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

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/Eczema/gene_data/GSE63741.csv +0 -0
  2. output/preprocess/Endometrioid_Cancer/clinical_data/GSE65986.csv +3 -3
  3. output/preprocess/Endometrioid_Cancer/code/GSE120490.py +164 -0
  4. output/preprocess/Endometrioid_Cancer/code/GSE40785.py +160 -0
  5. output/preprocess/Endometrioid_Cancer/code/GSE65986.py +168 -0
  6. output/preprocess/Endometrioid_Cancer/code/GSE66667.py +160 -0
  7. output/preprocess/Endometrioid_Cancer/code/GSE68600.py +159 -0
  8. output/preprocess/Endometrioid_Cancer/code/GSE73551.py +147 -0
  9. output/preprocess/Endometrioid_Cancer/code/GSE73614.py +181 -0
  10. output/preprocess/Endometrioid_Cancer/code/GSE73637.py +203 -0
  11. output/preprocess/Endometrioid_Cancer/code/GSE94523.py +172 -0
  12. output/preprocess/Endometrioid_Cancer/code/GSE94524.py +148 -0
  13. output/preprocess/Endometrioid_Cancer/code/TCGA.py +149 -0
  14. output/preprocess/Endometrioid_Cancer/cohort_info.json +1 -112
  15. output/preprocess/Endometriosis/GSE120103.csv +0 -0
  16. output/preprocess/Endometriosis/clinical_data/GSE120103.csv +2 -2
  17. output/preprocess/Endometriosis/clinical_data/GSE145701.csv +2 -2
  18. output/preprocess/Endometriosis/clinical_data/GSE73622.csv +3 -3
  19. output/preprocess/Endometriosis/code/GSE111974.py +127 -0
  20. output/preprocess/Endometriosis/code/GSE120103.py +192 -0
  21. output/preprocess/Endometriosis/code/GSE138297.py +155 -0
  22. output/preprocess/Endometriosis/code/GSE145701.py +195 -0
  23. output/preprocess/Endometriosis/code/GSE145702.py +197 -0
  24. output/preprocess/Endometriosis/code/GSE165004.py +148 -0
  25. output/preprocess/Endometriosis/code/GSE37837.py +169 -0
  26. output/preprocess/Endometriosis/code/GSE51981.py +193 -0
  27. output/preprocess/Endometriosis/code/GSE73622.py +244 -0
  28. output/preprocess/Endometriosis/code/GSE75427.py +133 -0
  29. output/preprocess/Endometriosis/code/TCGA.py +337 -0
  30. output/preprocess/Endometriosis/cohort_info.json +1 -112
  31. output/preprocess/Epilepsy/code/GSE123993.py +118 -0
  32. output/preprocess/Epilepsy/code/GSE143272.py +190 -0
  33. output/preprocess/Epilepsy/code/GSE199759.py +303 -0
  34. output/preprocess/Epilepsy/code/GSE273630.py +166 -0
  35. output/preprocess/Epilepsy/code/GSE29796.py +192 -0
  36. output/preprocess/Epilepsy/code/GSE42986.py +120 -0
  37. output/preprocess/Epilepsy/code/GSE63808.py +150 -0
  38. output/preprocess/Epilepsy/code/GSE64123.py +79 -0
  39. output/preprocess/Epilepsy/cohort_info.json +1 -112
  40. output/preprocess/Glioblastoma/code/GSE148949.py +264 -0
  41. output/preprocess/Glioblastoma/code/GSE159000.py +203 -0
  42. output/preprocess/Glioblastoma/code/GSE175700.py +220 -0
  43. output/preprocess/Glioblastoma/code/GSE178236.py +222 -0
  44. output/preprocess/Glioblastoma/code/GSE226976.py +191 -0
  45. output/preprocess/Glioblastoma/code/GSE249289.py +141 -0
  46. output/preprocess/Glioblastoma/code/GSE279426.py +135 -0
  47. output/preprocess/Glioblastoma/code/GSE39144.py +228 -0
  48. output/preprocess/Glioblastoma/code/TCGA.py +269 -0
  49. output/preprocess/Glucocorticoid_Sensitivity/GSE58715.csv +0 -0
  50. output/preprocess/Glucocorticoid_Sensitivity/clinical_data/GSE32962.csv +2 -3
output/preprocess/Eczema/gene_data/GSE63741.csv CHANGED
The diff for this file is too large to render. See raw diff
 
output/preprocess/Endometrioid_Cancer/clinical_data/GSE65986.csv CHANGED
@@ -1,3 +1,3 @@
1
- ,GSM1612097,GSM1612098,GSM1612099,GSM1612100,GSM1612101,GSM1612102,GSM1612103,GSM1612104,GSM1612105,GSM1612106,GSM1612107,GSM1612108,GSM1612109,GSM1612110,GSM1612111,GSM1612112,GSM1612113,GSM1612114,GSM1612115,GSM1612116,GSM1612117,GSM1612118,GSM1612119,GSM1612120,GSM1612121,GSM1612122,GSM1612123,GSM1612124,GSM1612125,GSM1612126,GSM1612127,GSM1612128,GSM1612129,GSM1612130,GSM1612131,GSM1612132,GSM1612133,GSM1612134,GSM1612135,GSM1612136,GSM1612137,GSM1612138,GSM1612139,GSM1612140,GSM1612141,GSM1612142,GSM1612143,GSM1612144,GSM1612145,GSM1612146,GSM1612147,GSM1612148,GSM1612149,GSM1612150,GSM1612151
2
- Endometrioid_Cancer,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,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
3
- Age,64.0,57.0,59.0,50.0,52.0,66.0,67.0,37.0,53.0,46.0,57.0,51.0,55.0,39.0,71.0,54.0,64.0,53.0,45.0,80.0,55.0,64.0,74.0,67.0,39.0,43.0,39.0,49.0,61.0,64.0,61.0,32.0,69.0,45.0,52.0,74.0,33.0,41.0,71.0,67.0,58.0,58.0,44.0,56.0,56.0,69.0,49.0,74.0,56.0,58.0,68.0,64.0,63.0,38.0,62.0
 
1
+ GSM1612097,GSM1612098,GSM1612099,GSM1612100,GSM1612101,GSM1612102,GSM1612103,GSM1612104,GSM1612105,GSM1612106,GSM1612107,GSM1612108,GSM1612109,GSM1612110,GSM1612111,GSM1612112,GSM1612113,GSM1612114,GSM1612115,GSM1612116,GSM1612117,GSM1612118,GSM1612119,GSM1612120,GSM1612121,GSM1612122,GSM1612123,GSM1612124,GSM1612125,GSM1612126,GSM1612127,GSM1612128,GSM1612129,GSM1612130,GSM1612131,GSM1612132,GSM1612133,GSM1612134,GSM1612135,GSM1612136,GSM1612137,GSM1612138,GSM1612139,GSM1612140,GSM1612141,GSM1612142,GSM1612143,GSM1612144,GSM1612145,GSM1612146,GSM1612147,GSM1612148,GSM1612149,GSM1612150,GSM1612151
2
+ 0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,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
3
+ 64.0,57.0,59.0,50.0,52.0,66.0,67.0,37.0,53.0,46.0,57.0,51.0,55.0,39.0,71.0,54.0,64.0,53.0,45.0,80.0,55.0,64.0,74.0,67.0,39.0,43.0,39.0,49.0,61.0,64.0,61.0,32.0,69.0,45.0,52.0,74.0,33.0,41.0,71.0,67.0,58.0,58.0,44.0,56.0,56.0,69.0,49.0,74.0,56.0,58.0,68.0,64.0,63.0,38.0,62.0
output/preprocess/Endometrioid_Cancer/code/GSE120490.py ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Endometrioid_Cancer"
6
+ cohort = "GSE120490"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Endometrioid_Cancer"
10
+ in_cohort_dir = "../DATA/GEO/Endometrioid_Cancer/GSE120490"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z2/preprocess/Endometrioid_Cancer/GSE120490.csv"
14
+ out_gene_data_file = "./output/z2/preprocess/Endometrioid_Cancer/gene_data/GSE120490.csv"
15
+ out_clinical_data_file = "./output/z2/preprocess/Endometrioid_Cancer/clinical_data/GSE120490.csv"
16
+ json_path = "./output/z2/preprocess/Endometrioid_Cancer/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ # 1. Gene Expression Data Availability
40
+ is_gene_available = True # Affymetrix U133 Plus 2.0 microarray platform indicates gene expression data
41
+
42
+ # 2. Variable Availability and Data Type Conversion
43
+ trait_row = 0 # 'matastasis: No/Yes' relates to cancer metastasis status
44
+ age_row = None # No age information available in sample characteristics
45
+ gender_row = None # No gender information available (endometrial cancer typically affects females)
46
+
47
+ def convert_trait(value):
48
+ """Convert metastasis status to binary: No=0, Yes=1"""
49
+ if value is None:
50
+ return None
51
+ value_str = str(value).split(':')[-1].strip().lower()
52
+ if value_str == 'no':
53
+ return 0
54
+ elif value_str == 'yes':
55
+ return 1
56
+ else:
57
+ return None
58
+
59
+ def convert_age(value):
60
+ """Age conversion function (not used as age data not available)"""
61
+ return None
62
+
63
+ def convert_gender(value):
64
+ """Gender conversion function (not used as gender data not available)"""
65
+ return None
66
+
67
+ # 3. Save Metadata
68
+ is_trait_available = trait_row is not None
69
+ save_cohort_info = validate_and_save_cohort_info(
70
+ is_final=False,
71
+ cohort=cohort,
72
+ info_path=json_path,
73
+ is_gene_available=is_gene_available,
74
+ is_trait_available=is_trait_available
75
+ )
76
+
77
+ # 4. Clinical Feature Extraction
78
+ if is_trait_available:
79
+ selected_clinical_data = geo_select_clinical_features(
80
+ clinical_df=clinical_data,
81
+ trait=trait,
82
+ trait_row=trait_row,
83
+ convert_trait=convert_trait,
84
+ age_row=age_row,
85
+ convert_age=convert_age,
86
+ gender_row=gender_row,
87
+ convert_gender=convert_gender
88
+ )
89
+
90
+ print("Preview of selected clinical data:")
91
+ print(preview_df(selected_clinical_data))
92
+
93
+ # Save clinical data
94
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
95
+ selected_clinical_data.to_csv(out_clinical_data_file)
96
+ print(f"Clinical data saved to {out_clinical_data_file}")
97
+
98
+ # Step 3: Gene Data Extraction
99
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
100
+ gene_data = get_genetic_data(matrix_file)
101
+
102
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
103
+ print(gene_data.index[:20])
104
+
105
+ # Step 4: Gene Identifier Review
106
+ # Analyze the gene identifiers from the previous step output
107
+ gene_identifiers = ['1007_s_at', '1053_at', '117_at', '121_at', '1255_g_at', '1294_at',
108
+ '1316_at', '1320_at', '1405_i_at', '1431_at', '1438_at', '1487_at',
109
+ '1494_f_at', '1552256_a_at', '1552257_a_at', '1552258_at', '1552261_at',
110
+ '1552263_at', '1552264_a_at', '1552266_at']
111
+
112
+ print("Sample gene identifiers:")
113
+ for identifier in gene_identifiers[:10]:
114
+ print(f" {identifier}")
115
+
116
+ # These identifiers follow the Affymetrix probe ID pattern with suffixes like "_at", "_s_at", "_a_at", etc.
117
+ # They are not human gene symbols (which would be like TP53, BRCA1, EGFR, etc.)
118
+ # Therefore, they require mapping to gene symbols
119
+
120
+ 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
+ # 1. Identify mapping columns: 'ID' contains probe IDs, 'Gene Symbol' contains gene symbols
132
+ probe_col = 'ID'
133
+ gene_col = 'Gene Symbol'
134
+
135
+ # 2. Get gene mapping dataframe
136
+ gene_mapping = get_gene_mapping(gene_annotation, probe_col, gene_col)
137
+
138
+ # 3. Apply gene mapping to convert probe-level measurements to gene expression data
139
+ gene_data = apply_gene_mapping(gene_data, gene_mapping)
140
+
141
+ print(f"Gene expression data shape after mapping: {gene_data.shape}")
142
+ print("Sample gene symbols:")
143
+ print(gene_data.index[:10].tolist())
144
+
145
+ # Step 7: Data Normalization and Linking
146
+ # 1. Normalize the obtained gene data with the 'normalize_gene_symbols_in_index' function from the library.
147
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
148
+ normalized_gene_data.to_csv(out_gene_data_file)
149
+
150
+ # 2. Link the clinical and genetic data with the 'geo_link_clinical_genetic_data' function from the library.
151
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_data, normalized_gene_data)
152
+
153
+ # 3. Handle missing values in the linked data
154
+ linked_data = handle_missing_values(linked_data, trait)
155
+
156
+ # 4. Determine whether the trait and some demographic features are severely biased, and remove biased features.
157
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
158
+
159
+ # 5. Conduct quality check and save the cohort information.
160
+ is_usable = validate_and_save_cohort_info(True, cohort, json_path, True, True, is_trait_biased, unbiased_linked_data)
161
+
162
+ # 6. If the linked data is usable, save it as a CSV file to 'out_data_file'.
163
+ if is_usable:
164
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Endometrioid_Cancer/code/GSE40785.py ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Endometrioid_Cancer"
6
+ cohort = "GSE40785"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Endometrioid_Cancer"
10
+ in_cohort_dir = "../DATA/GEO/Endometrioid_Cancer/GSE40785"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z2/preprocess/Endometrioid_Cancer/GSE40785.csv"
14
+ out_gene_data_file = "./output/z2/preprocess/Endometrioid_Cancer/gene_data/GSE40785.csv"
15
+ out_clinical_data_file = "./output/z2/preprocess/Endometrioid_Cancer/clinical_data/GSE40785.csv"
16
+ json_path = "./output/z2/preprocess/Endometrioid_Cancer/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ import pandas as pd
40
+
41
+ # 1. Gene Expression Data Availability
42
+ is_gene_available = True # RNA expression data from Illumina platform
43
+
44
+ # 2. Variable Availability and Data Type Conversion
45
+
46
+ # 2.1 Data Availability
47
+ trait_row = 1 # histology information is in key 1
48
+ age_row = None # no age information available
49
+ gender_row = None # no gender information available
50
+
51
+ # 2.2 Data Type Conversion
52
+ def convert_trait(value):
53
+ """Convert histology to binary endometrioid cancer (1) vs others (0)"""
54
+ if value is None:
55
+ return None
56
+
57
+ # Extract value after colon
58
+ if ':' in str(value):
59
+ histology = str(value).split(':', 1)[1].strip()
60
+ else:
61
+ histology = str(value).strip()
62
+
63
+ # Check if it's endometrioid
64
+ if 'Endometrioid' in histology:
65
+ return 1
66
+ else:
67
+ return 0
68
+
69
+ def convert_age(value):
70
+ """Age conversion function (not used as age data not available)"""
71
+ return None
72
+
73
+ def convert_gender(value):
74
+ """Gender conversion function (not used as gender data not available)"""
75
+ return None
76
+
77
+ # 3. Save Metadata
78
+ validate_and_save_cohort_info(
79
+ is_final=False,
80
+ cohort=cohort,
81
+ info_path=json_path,
82
+ is_gene_available=is_gene_available,
83
+ is_trait_available=trait_row is not None
84
+ )
85
+
86
+ # 4. Clinical Feature Extraction
87
+ if trait_row is not None:
88
+ selected_clinical_data = geo_select_clinical_features(
89
+ clinical_data, trait, trait_row, convert_trait,
90
+ age_row, convert_age, gender_row, convert_gender
91
+ )
92
+
93
+ print("Selected clinical data preview:")
94
+ print(preview_df(selected_clinical_data))
95
+
96
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
97
+ selected_clinical_data.to_csv(out_clinical_data_file)
98
+
99
+ # Step 3: Gene Data Extraction
100
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
101
+ gene_data = get_genetic_data(matrix_file)
102
+
103
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
104
+ print(gene_data.index[:20])
105
+
106
+ # Step 4: Gene Identifier Review
107
+ # Review the gene identifiers from the previous step output
108
+ # The identifiers follow the pattern 'ILMN_' followed by numbers
109
+ # These are Illumina probe IDs, not human gene symbols
110
+ # Human gene symbols would be names like TP53, BRCA1, MYC, etc.
111
+
112
+ print("Gene identifiers observed: ILMN_1343291, ILMN_1343295, ILMN_1651199, etc.")
113
+ print("These are Illumina probe IDs that need to be mapped to gene symbols.")
114
+
115
+ requires_gene_mapping = True
116
+
117
+ # Step 5: Gene Annotation
118
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
119
+ gene_annotation = get_gene_annotation(soft_file)
120
+
121
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
122
+ print("Gene annotation preview:")
123
+ print(preview_df(gene_annotation))
124
+
125
+ # Step 6: Gene Identifier Mapping
126
+ # 1. Identify the relevant columns in gene annotation
127
+ # 'ID' column contains Illumina probe IDs matching the gene expression data
128
+ # 'Symbol' column contains the gene symbols
129
+ prob_col = 'ID'
130
+ gene_col = 'Symbol'
131
+
132
+ # 2. Get gene mapping dataframe
133
+ gene_mapping = get_gene_mapping(gene_annotation, prob_col, gene_col)
134
+
135
+ # 3. Convert probe-level measurements to gene expression data
136
+ gene_data = apply_gene_mapping(gene_data, gene_mapping)
137
+
138
+ print(f"Gene expression data shape after mapping: {gene_data.shape}")
139
+ print(f"First few gene symbols: {list(gene_data.index[:10])}")
140
+
141
+ # Step 7: Data Normalization and Linking
142
+ # 1. Normalize the obtained gene data with the 'normalize_gene_symbols_in_index' function from the library.
143
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
144
+ normalized_gene_data.to_csv(out_gene_data_file)
145
+
146
+ # 2. Link the clinical and genetic data with the 'geo_link_clinical_genetic_data' function from the library.
147
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_data, normalized_gene_data)
148
+
149
+ # 3. Handle missing values in the linked data
150
+ linked_data = handle_missing_values(linked_data, trait)
151
+
152
+ # 4. Determine whether the trait and some demographic features are severely biased, and remove biased features.
153
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
154
+
155
+ # 5. Conduct quality check and save the cohort information.
156
+ is_usable = validate_and_save_cohort_info(True, cohort, json_path, True, True, is_trait_biased, unbiased_linked_data)
157
+
158
+ # 6. If the linked data is usable, save it as a CSV file to 'out_data_file'.
159
+ if is_usable:
160
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Endometrioid_Cancer/code/GSE65986.py ADDED
@@ -0,0 +1,168 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Endometrioid_Cancer"
6
+ cohort = "GSE65986"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Endometrioid_Cancer"
10
+ in_cohort_dir = "../DATA/GEO/Endometrioid_Cancer/GSE65986"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z2/preprocess/Endometrioid_Cancer/GSE65986.csv"
14
+ out_gene_data_file = "./output/z2/preprocess/Endometrioid_Cancer/gene_data/GSE65986.csv"
15
+ out_clinical_data_file = "./output/z2/preprocess/Endometrioid_Cancer/clinical_data/GSE65986.csv"
16
+ json_path = "./output/z2/preprocess/Endometrioid_Cancer/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ # 1. Gene Expression Data Availability
40
+ is_gene_available = True # This dataset uses Affymetrix U133plus2 array for gene expression
41
+
42
+ # 2. Variable Availability and Data Type Conversion
43
+
44
+ # 2.1 Data Availability
45
+ trait_row = 0 # histology field contains Endometrioid vs other cancer types
46
+ age_row = 1 # age field contains age values
47
+ gender_row = None # no gender information available in sample characteristics
48
+
49
+ # 2.2 Data Type Conversion Functions
50
+
51
+ def convert_trait(value):
52
+ """Convert trait to binary: 1 for Endometrioid, 0 for others"""
53
+ if value is None:
54
+ return None
55
+ # Extract value after colon
56
+ val = value.split(':')[-1].strip() if ':' in value else value.strip()
57
+ if val == 'Endometrioid':
58
+ return 1
59
+ elif val in ['Clear', 'Serous']:
60
+ return 0
61
+ else:
62
+ return None
63
+
64
+ def convert_age(value):
65
+ """Convert age to continuous numeric value"""
66
+ if value is None:
67
+ return None
68
+ # Extract value after colon
69
+ val = value.split(':')[-1].strip() if ':' in value else value.strip()
70
+ try:
71
+ return float(val)
72
+ except (ValueError, TypeError):
73
+ return None
74
+
75
+ def convert_gender(value):
76
+ """Not applicable - gender data not available"""
77
+ return None
78
+
79
+ # 3. Save Metadata
80
+ is_trait_available = trait_row is not None
81
+ save_result = validate_and_save_cohort_info(
82
+ is_final=False,
83
+ cohort=cohort,
84
+ info_path=json_path,
85
+ is_gene_available=is_gene_available,
86
+ is_trait_available=is_trait_available
87
+ )
88
+
89
+ # 4. Clinical Feature Extraction
90
+ if trait_row is not None:
91
+ selected_clinical_data = geo_select_clinical_features(
92
+ clinical_data, trait, trait_row, convert_trait,
93
+ age_row, convert_age, gender_row, convert_gender
94
+ )
95
+
96
+ # Preview the output dataframe
97
+ print("Preview of selected clinical data:")
98
+ print(preview_df(selected_clinical_data))
99
+
100
+ # Save to CSV file
101
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
102
+ selected_clinical_data.to_csv(out_clinical_data_file, index=False)
103
+ print(f"Clinical data saved to {out_clinical_data_file}")
104
+
105
+ # Step 3: Gene Data Extraction
106
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
107
+ gene_data = get_genetic_data(matrix_file)
108
+
109
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
110
+ print(gene_data.index[:20])
111
+
112
+ # Step 4: Gene Identifier Review
113
+ print("Sample gene identifiers from the dataset:")
114
+ print(gene_data.index[:20].tolist())
115
+
116
+ # These identifiers follow Affymetrix probe ID format (numbers + suffixes like _at, _s_at, _g_at, _i_at, _a_at)
117
+ # They are not human gene symbols, which would be in format like BRCA1, TP53, etc.
118
+ # Therefore, they need to be mapped to gene symbols
119
+
120
+ 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
+ # 1. Identify the correct columns for mapping
132
+ # 'ID' contains the probe identifiers matching the gene expression data
133
+ # 'Gene Symbol' contains the gene symbols we want to map to
134
+ probe_col = 'ID'
135
+ gene_col = 'Gene Symbol'
136
+
137
+ # 2. Get gene mapping dataframe
138
+ gene_mapping = get_gene_mapping(gene_annotation, probe_col, gene_col)
139
+
140
+ # 3. Apply gene mapping to convert probe-level to gene-level expression data
141
+ gene_data = apply_gene_mapping(gene_data, gene_mapping)
142
+
143
+ print(f"Original probe data shape: {get_genetic_data(matrix_file).shape}")
144
+ print(f"Mapped gene data shape: {gene_data.shape}")
145
+ print(f"First few gene symbols: {gene_data.index[:10].tolist()}")
146
+
147
+ # Step 7: Data Normalization and Linking
148
+ # 1. Normalize the obtained gene data with the 'normalize_gene_symbols_in_index' function from the library.
149
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
150
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
151
+ normalized_gene_data.to_csv(out_gene_data_file)
152
+
153
+ # 2. Link the clinical and genetic data with the 'geo_link_clinical_genetic_data' function from the library.
154
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_data, normalized_gene_data)
155
+
156
+ # 3. Handle missing values in the linked data
157
+ linked_data = handle_missing_values(linked_data, trait)
158
+
159
+ # 4. Determine whether the trait and some demographic features are severely biased, and remove biased features.
160
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
161
+
162
+ # 5. Conduct quality check and save the cohort information.
163
+ is_usable = validate_and_save_cohort_info(True, cohort, json_path, True, True, is_trait_biased, unbiased_linked_data)
164
+
165
+ # 6. If the linked data is usable, save it as a CSV file to 'out_data_file'.
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/Endometrioid_Cancer/code/GSE66667.py ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Endometrioid_Cancer"
6
+ cohort = "GSE66667"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Endometrioid_Cancer"
10
+ in_cohort_dir = "../DATA/GEO/Endometrioid_Cancer/GSE66667"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z2/preprocess/Endometrioid_Cancer/GSE66667.csv"
14
+ out_gene_data_file = "./output/z2/preprocess/Endometrioid_Cancer/gene_data/GSE66667.csv"
15
+ out_clinical_data_file = "./output/z2/preprocess/Endometrioid_Cancer/clinical_data/GSE66667.csv"
16
+ json_path = "./output/z2/preprocess/Endometrioid_Cancer/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ # 1. Gene Expression Data Availability
40
+ is_gene_available = True # Microarrays were employed to elucidate global transcription
41
+
42
+ # 2. Variable Availability and Data Type Conversion
43
+
44
+ # 2.1 Data Availability
45
+ trait_row = 0 # histology information available, including 'Endometrioid'
46
+ age_row = None # No age information in sample characteristics
47
+ gender_row = None # No gender information in sample characteristics
48
+
49
+ # 2.2 Data Type Conversion Functions
50
+ def convert_trait(value):
51
+ """Convert histology to binary: 1 for Endometrioid, 0 for others"""
52
+ if value is None:
53
+ return None
54
+ # Extract value after colon
55
+ if ':' in str(value):
56
+ histology_type = str(value).split(':')[1].strip()
57
+ else:
58
+ histology_type = str(value).strip()
59
+
60
+ return 1 if histology_type == 'Endometrioid' else 0
61
+
62
+ def convert_age(value):
63
+ """Age conversion function (not used since age_row is None)"""
64
+ return None
65
+
66
+ def convert_gender(value):
67
+ """Gender conversion function (not used since gender_row is None)"""
68
+ return None
69
+
70
+ # 3. Save Metadata
71
+ is_trait_available = trait_row is not None
72
+ save_cohort_info = validate_and_save_cohort_info(
73
+ is_final=False,
74
+ cohort=cohort,
75
+ info_path=json_path,
76
+ is_gene_available=is_gene_available,
77
+ is_trait_available=is_trait_available
78
+ )
79
+
80
+ # 4. Clinical Feature Extraction
81
+ if trait_row is not None:
82
+ selected_clinical_data = geo_select_clinical_features(
83
+ clinical_df=clinical_data,
84
+ trait=trait,
85
+ trait_row=trait_row,
86
+ convert_trait=convert_trait,
87
+ age_row=age_row,
88
+ convert_age=convert_age,
89
+ gender_row=gender_row,
90
+ convert_gender=convert_gender
91
+ )
92
+
93
+ # Preview the output
94
+ print("Clinical data preview:")
95
+ print(preview_df(selected_clinical_data))
96
+
97
+ # Save to CSV
98
+ selected_clinical_data.to_csv(out_clinical_data_file)
99
+ print(f"Clinical data saved to {out_clinical_data_file}")
100
+
101
+ # Step 3: Gene Data Extraction
102
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
103
+ gene_data = get_genetic_data(matrix_file)
104
+
105
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
106
+ print(gene_data.index[:20])
107
+
108
+ # Step 4: Gene Identifier Review
109
+ # These identifiers appear to be Affymetrix probe set IDs (e.g., '1007_s_at', '1053_at')
110
+ # They follow the typical pattern of numbers followed by probe set suffixes like '_at', '_s_at', '_a_at'
111
+ # Human gene symbols would be alphabetic names like 'BRCA1', 'TP53', 'EGFR'
112
+ # Therefore, these probe IDs need to be mapped to human gene symbols
113
+
114
+ requires_gene_mapping = True
115
+
116
+ # Step 5: Gene Annotation
117
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
118
+ gene_annotation = get_gene_annotation(soft_file)
119
+
120
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
121
+ print("Gene annotation preview:")
122
+ print(preview_df(gene_annotation))
123
+
124
+ # Step 6: Gene Identifier Mapping
125
+ # 1. Identify the columns for mapping
126
+ # From the preview, 'ID' contains the probe identifiers (same as gene_data index)
127
+ # 'Gene Symbol' contains the gene symbols we need to map to
128
+ prob_col = 'ID'
129
+ gene_col = 'Gene Symbol'
130
+
131
+ # 2. Get gene mapping dataframe
132
+ gene_mapping = get_gene_mapping(gene_annotation, prob_col, gene_col)
133
+
134
+ # 3. Apply gene mapping to convert probe-level data to gene expression data
135
+ gene_data = apply_gene_mapping(gene_data, gene_mapping)
136
+
137
+ print(f"Original probe data shape: {get_genetic_data(matrix_file).shape}")
138
+ print(f"Mapped gene data shape: {gene_data.shape}")
139
+ print(f"First 10 gene symbols: {list(gene_data.index[:10])}")
140
+
141
+ # Step 7: Data Normalization and Linking
142
+ # 1. Normalize the obtained gene data with the 'normalize_gene_symbols_in_index' function from the library.
143
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
144
+ normalized_gene_data.to_csv(out_gene_data_file)
145
+
146
+ # 2. Link the clinical and genetic data with the 'geo_link_clinical_genetic_data' function from the library.
147
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_data, normalized_gene_data)
148
+
149
+ # 3. Handle missing values in the linked data
150
+ linked_data = handle_missing_values(linked_data, trait)
151
+
152
+ # 4. Determine whether the trait and some demographic features are severely biased, and remove biased features.
153
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
154
+
155
+ # 5. Conduct quality check and save the cohort information.
156
+ is_usable = validate_and_save_cohort_info(True, cohort, json_path, True, True, is_trait_biased, unbiased_linked_data)
157
+
158
+ # 6. If the linked data is usable, save it as a CSV file to 'out_data_file'.
159
+ if is_usable:
160
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Endometrioid_Cancer/code/GSE68600.py ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Endometrioid_Cancer"
6
+ cohort = "GSE68600"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Endometrioid_Cancer"
10
+ in_cohort_dir = "../DATA/GEO/Endometrioid_Cancer/GSE68600"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z2/preprocess/Endometrioid_Cancer/GSE68600.csv"
14
+ out_gene_data_file = "./output/z2/preprocess/Endometrioid_Cancer/gene_data/GSE68600.csv"
15
+ out_clinical_data_file = "./output/z2/preprocess/Endometrioid_Cancer/clinical_data/GSE68600.csv"
16
+ json_path = "./output/z2/preprocess/Endometrioid_Cancer/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ # 1. Gene Expression Data Availability
40
+ is_gene_available = True # This is an Affymetrix gene expression microarray dataset
41
+
42
+ # 2. Variable Availability and Data Type Conversion
43
+
44
+ # 2.1 Data Availability
45
+ trait_row = 4 # histology information is in key 4
46
+ age_row = None # No age information available
47
+ gender_row = None # All samples are female (constant), not useful
48
+
49
+ # 2.2 Data Type Conversion Functions
50
+
51
+ def convert_trait(value):
52
+ """Convert histology to binary (0/1) for endometrioid cancer presence"""
53
+ if ':' in value:
54
+ histology = value.split(':')[1].strip().lower()
55
+ # Check if endometrioid is mentioned in the histology
56
+ if 'endometrioid' in histology:
57
+ return 1
58
+ else:
59
+ return 0
60
+ return None
61
+
62
+ def convert_age(value):
63
+ """Convert age - not applicable since age data is not available"""
64
+ return None
65
+
66
+ def convert_gender(value):
67
+ """Convert gender - not applicable since all samples are female"""
68
+ return None
69
+
70
+ # 3. Save Metadata
71
+ is_trait_available = trait_row is not None
72
+ is_usable = validate_and_save_cohort_info(
73
+ is_final=False,
74
+ cohort=cohort,
75
+ info_path=json_path,
76
+ is_gene_available=is_gene_available,
77
+ is_trait_available=is_trait_available
78
+ )
79
+
80
+ # 4. Clinical Feature Extraction
81
+ if trait_row is not None:
82
+ selected_clinical_data = geo_select_clinical_features(
83
+ clinical_data,
84
+ trait,
85
+ trait_row,
86
+ convert_trait,
87
+ age_row,
88
+ convert_age,
89
+ gender_row,
90
+ convert_gender
91
+ )
92
+
93
+ print("Preview of selected clinical data:")
94
+ print(preview_df(selected_clinical_data))
95
+
96
+ # Save clinical data
97
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
98
+ selected_clinical_data.to_csv(out_clinical_data_file)
99
+ print(f"Clinical data saved to {out_clinical_data_file}")
100
+
101
+ # Step 3: Gene Data Extraction
102
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
103
+ gene_data = get_genetic_data(matrix_file)
104
+
105
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
106
+ print(gene_data.index[:20])
107
+
108
+ # Step 4: Gene Identifier Review
109
+ # Examine the gene identifiers shown in the previous step output
110
+ # The identifiers follow patterns like 'A28102_at', 'AB000114_at', 'AB000381_s_at'
111
+ # These are Affymetrix microarray probe set identifiers, not human gene symbols
112
+ # Human gene symbols would be names like 'BRCA1', 'TP53', 'EGFR', etc.
113
+ # The '_at' and '_s_at' suffixes are characteristic of Affymetrix probe nomenclature
114
+
115
+ requires_gene_mapping = True
116
+
117
+ # Step 5: Gene Annotation
118
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
119
+ gene_annotation = get_gene_annotation(soft_file)
120
+
121
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
122
+ print("Gene annotation preview:")
123
+ print(preview_df(gene_annotation))
124
+
125
+ # Step 6: Gene Identifier Mapping
126
+ # 1. Based on the analysis, 'ID' column contains probe identifiers matching gene expression data,
127
+ # and 'Gene Symbol' column contains the human gene symbols we need
128
+ prob_col = 'ID'
129
+ gene_col = 'Gene Symbol'
130
+
131
+ # 2. Extract gene mapping dataframe with probe ID to gene symbol mapping
132
+ gene_mapping = get_gene_mapping(gene_annotation, prob_col, gene_col)
133
+
134
+ # 3. Apply gene mapping to convert probe-level measurements to gene expression data
135
+ gene_data = apply_gene_mapping(gene_data, gene_mapping)
136
+
137
+ print(f"Gene expression data shape after mapping: {gene_data.shape}")
138
+ print(f"First 10 gene symbols: {list(gene_data.index[:10])}")
139
+
140
+ # Step 7: Data Normalization and Linking
141
+ # 1. Normalize the obtained gene data with the 'normalize_gene_symbols_in_index' function from the library.
142
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
143
+ normalized_gene_data.to_csv(out_gene_data_file)
144
+
145
+ # 2. Link the clinical and genetic data with the 'geo_link_clinical_genetic_data' function from the library.
146
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_data, normalized_gene_data)
147
+
148
+ # 3. Handle missing values in the linked data
149
+ linked_data = handle_missing_values(linked_data, trait)
150
+
151
+ # 4. Determine whether the trait and some demographic features are severely biased, and remove biased features.
152
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
153
+
154
+ # 5. Conduct quality check and save the cohort information.
155
+ is_usable = validate_and_save_cohort_info(True, cohort, json_path, True, True, is_trait_biased, unbiased_linked_data)
156
+
157
+ # 6. If the linked data is usable, save it as a CSV file to 'out_data_file'.
158
+ if is_usable:
159
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Endometrioid_Cancer/code/GSE73551.py ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Endometrioid_Cancer"
6
+ cohort = "GSE73551"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Endometrioid_Cancer"
10
+ in_cohort_dir = "../DATA/GEO/Endometrioid_Cancer/GSE73551"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z2/preprocess/Endometrioid_Cancer/GSE73551.csv"
14
+ out_gene_data_file = "./output/z2/preprocess/Endometrioid_Cancer/gene_data/GSE73551.csv"
15
+ out_clinical_data_file = "./output/z2/preprocess/Endometrioid_Cancer/clinical_data/GSE73551.csv"
16
+ json_path = "./output/z2/preprocess/Endometrioid_Cancer/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ # 1. Gene Expression Data Availability
40
+ is_gene_available = True # This appears to be gene expression data for compositional analysis
41
+
42
+ # 2. Variable Availability and Data Type Conversion
43
+
44
+ # 2.1 Data Availability
45
+ trait_row = 0 # Cell type information is in row 0, includes ENDOMETRIOID
46
+ age_row = None # No age information available
47
+ gender_row = None # No gender information available
48
+
49
+ # 2.2 Data Type Conversion
50
+ def convert_trait(value):
51
+ """Convert cell type to binary: 1 for ENDOMETRIOID, 0 for others"""
52
+ if pd.isna(value):
53
+ return None
54
+ value_str = str(value).upper()
55
+ if ':' in value_str:
56
+ value_str = value_str.split(':', 1)[1].strip()
57
+ return 1 if 'ENDOMETRIOID' in value_str else 0
58
+
59
+ def convert_age(value):
60
+ """Convert age to continuous (not available in this dataset)"""
61
+ return None
62
+
63
+ def convert_gender(value):
64
+ """Convert gender to binary (not available in this dataset)"""
65
+ return None
66
+
67
+ # 3. Save Metadata
68
+ is_trait_available = trait_row is not None
69
+ validate_and_save_cohort_info(is_final=False, cohort=cohort, info_path=json_path,
70
+ is_gene_available=is_gene_available,
71
+ is_trait_available=is_trait_available)
72
+
73
+ # 4. Clinical Feature Extraction
74
+ if trait_row is not None:
75
+ selected_clinical_data = geo_select_clinical_features(clinical_data, trait, trait_row, convert_trait,
76
+ age_row, convert_age, gender_row, convert_gender)
77
+ print("Preview of selected clinical data:")
78
+ print(preview_df(selected_clinical_data))
79
+
80
+ # Save clinical data
81
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
82
+ selected_clinical_data.to_csv(out_clinical_data_file)
83
+ print(f"Clinical data saved to {out_clinical_data_file}")
84
+
85
+ # Step 3: Gene Data Extraction
86
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
87
+ gene_data = get_genetic_data(matrix_file)
88
+
89
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
90
+ print(gene_data.index[:20])
91
+
92
+ # Step 4: Gene Identifier Review
93
+ # Examine the gene identifiers to determine if mapping is required
94
+ print("Gene identifiers observed:")
95
+ print("Index(['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13',")
96
+ print(" '14', '15', '16', '17', '18', '19', '20'],")
97
+ print(" dtype='object', name='ID')")
98
+ print("\nThese are numerical identifiers, not human gene symbols.")
99
+ print("Human gene symbols are typically alphanumeric (e.g., TP53, BRCA1, EGFR).")
100
+ print("These numerical IDs likely represent probe IDs or platform-specific identifiers.")
101
+
102
+ requires_gene_mapping = True
103
+
104
+ # Step 5: Gene Annotation
105
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
106
+ gene_annotation = get_gene_annotation(soft_file)
107
+
108
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
109
+ print("Gene annotation preview:")
110
+ print(preview_df(gene_annotation))
111
+
112
+ # Step 6: Gene Identifier Mapping
113
+ # 1. Identify the correct columns for mapping
114
+ # The 'ID' column matches the gene identifiers in gene expression data
115
+ # The 'GeneSymbol' column contains the actual gene symbols
116
+ prob_col = 'ID'
117
+ gene_col = 'GeneSymbol'
118
+
119
+ # 2. Get gene mapping dataframe using the get_gene_mapping function
120
+ gene_mapping = get_gene_mapping(gene_annotation, prob_col, gene_col)
121
+
122
+ # 3. Apply gene mapping to convert probe-level data to gene expression data
123
+ gene_data = apply_gene_mapping(gene_data, gene_mapping)
124
+
125
+ print(f"Gene expression data shape after mapping: {gene_data.shape}")
126
+ print(f"First 10 genes: {list(gene_data.index[:10])}")
127
+
128
+ # Step 7: Data Normalization and Linking
129
+ # 1. Normalize the obtained gene data with the 'normalize_gene_symbols_in_index' function from the library.
130
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
131
+ normalized_gene_data.to_csv(out_gene_data_file)
132
+
133
+ # 2. Link the clinical and genetic data with the 'geo_link_clinical_genetic_data' function from the library.
134
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_data, normalized_gene_data)
135
+
136
+ # 3. Handle missing values in the linked data
137
+ linked_data = handle_missing_values(linked_data, trait)
138
+
139
+ # 4. Determine whether the trait and some demographic features are severely biased, and remove biased features.
140
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
141
+
142
+ # 5. Conduct quality check and save the cohort information.
143
+ is_usable = validate_and_save_cohort_info(True, cohort, json_path, True, True, is_trait_biased, unbiased_linked_data)
144
+
145
+ # 6. If the linked data is usable, save it as a CSV file to 'out_data_file'.
146
+ if is_usable:
147
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Endometrioid_Cancer/code/GSE73614.py ADDED
@@ -0,0 +1,181 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Endometrioid_Cancer"
6
+ cohort = "GSE73614"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Endometrioid_Cancer"
10
+ in_cohort_dir = "../DATA/GEO/Endometrioid_Cancer/GSE73614"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z2/preprocess/Endometrioid_Cancer/GSE73614.csv"
14
+ out_gene_data_file = "./output/z2/preprocess/Endometrioid_Cancer/gene_data/GSE73614.csv"
15
+ out_clinical_data_file = "./output/z2/preprocess/Endometrioid_Cancer/clinical_data/GSE73614.csv"
16
+ json_path = "./output/z2/preprocess/Endometrioid_Cancer/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ # 1. Gene Expression Data Availability
40
+ is_gene_available = True
41
+
42
+ # 2. Variable Availability and Data Type Conversion
43
+
44
+ # 2.1 Data Availability
45
+ trait_row = None # No trait information available in sample characteristics
46
+ age_row = None # No age information available in sample characteristics
47
+ gender_row = None # No gender information available in sample characteristics
48
+
49
+ # 2.2 Data Type Conversion
50
+ def convert_trait(value):
51
+ """Convert trait values to binary (0 for non-endometrioid, 1 for endometrioid)"""
52
+ if value is None:
53
+ return None
54
+ value_str = str(value).lower()
55
+ if 'endometrioid' in value_str:
56
+ return 1
57
+ else:
58
+ return 0
59
+
60
+ def convert_age(value):
61
+ """Convert age to continuous values"""
62
+ if value is None:
63
+ return None
64
+ try:
65
+ if ':' in str(value):
66
+ age_str = str(value).split(':')[1].strip()
67
+ else:
68
+ age_str = str(value).strip()
69
+ return float(age_str)
70
+ except (ValueError, IndexError):
71
+ return None
72
+
73
+ def convert_gender(value):
74
+ """Convert gender to binary (0 for female, 1 for male)"""
75
+ if value is None:
76
+ return None
77
+ value_str = str(value).lower()
78
+ if ':' in value_str:
79
+ value_str = value_str.split(':')[1].strip()
80
+
81
+ if 'female' in value_str or 'f' == value_str:
82
+ return 0
83
+ elif 'male' in value_str or 'm' == value_str:
84
+ return 1
85
+ else:
86
+ return None
87
+
88
+ # 3. Save Metadata
89
+ is_trait_available = trait_row is not None
90
+ save_cohort_info = 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
+ # 4. Clinical Feature Extraction
99
+ # Skip this step since trait_row is None (clinical data not available)
100
+
101
+ # Step 3: Gene Data Extraction
102
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
103
+ gene_data = get_genetic_data(matrix_file)
104
+
105
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
106
+ print(gene_data.index[:20])
107
+
108
+ # Step 4: Gene Identifier Review
109
+ # Examine the gene identifiers from the previous step
110
+ gene_identifiers_sample = ['A_23_P100001', 'A_23_P100011', 'A_23_P100022', 'A_23_P100056',
111
+ 'A_23_P100074', 'A_23_P100092', 'A_23_P100103', 'A_23_P100111',
112
+ 'A_23_P100127', 'A_23_P100133', 'A_23_P100141', 'A_23_P100156',
113
+ 'A_23_P100177', 'A_23_P100189', 'A_23_P100196', 'A_23_P100203',
114
+ 'A_23_P100220', 'A_23_P100240', 'A_23_P10025', 'A_23_P100263']
115
+
116
+ print("Sample gene identifiers:")
117
+ for i, identifier in enumerate(gene_identifiers_sample[:5]):
118
+ print(f" {identifier}")
119
+
120
+ # Analysis: These identifiers follow the pattern "A_23_P" + numbers
121
+ # This is the standard format for Agilent microarray probe IDs
122
+ # The "A_23_P" prefix indicates Agilent platform probe identifiers
123
+ # These are not human gene symbols (which would be like BRCA1, TP53, etc.)
124
+ # Therefore, they need to be mapped to gene symbols for meaningful analysis
125
+
126
+ print("\nAnalysis: These are Agilent microarray probe IDs (A_23_P prefix)")
127
+ print("They are not human gene symbols and require mapping to gene symbols.")
128
+
129
+ requires_gene_mapping = True
130
+
131
+ # Step 5: Gene Annotation
132
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
133
+ gene_annotation = get_gene_annotation(soft_file)
134
+
135
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
136
+ print("Gene annotation preview:")
137
+ print(preview_df(gene_annotation))
138
+
139
+ # Step 6: Gene Identifier Mapping
140
+ # 1. Identify the mapping columns
141
+ # Gene identifiers in expression data match 'ID' column in annotation
142
+ # Gene symbols are in 'GENE_SYMBOL' column
143
+ prob_col = 'ID'
144
+ gene_col = 'GENE_SYMBOL'
145
+
146
+ # 2. Get gene mapping dataframe
147
+ gene_mapping = get_gene_mapping(gene_annotation, prob_col, gene_col)
148
+
149
+ # 3. Apply gene mapping to convert probe-level to gene expression data
150
+ gene_data = apply_gene_mapping(gene_data, gene_mapping)
151
+
152
+ print(f"Gene expression data shape after mapping: {gene_data.shape}")
153
+ print(f"First 5 gene symbols: {list(gene_data.index[:5])}")
154
+
155
+ # Step 7: Data Normalization and Linking
156
+ import os
157
+
158
+ # 1. Normalize the obtained gene data with the 'normalize_gene_symbols_in_index' function from the library.
159
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
160
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
161
+ normalized_gene_data.to_csv(out_gene_data_file)
162
+
163
+ # 2. Since no clinical data is available (trait_row was None), create empty clinical dataframe
164
+ empty_clinical_data = pd.DataFrame()
165
+ linked_data = geo_link_clinical_genetic_data(empty_clinical_data, normalized_gene_data)
166
+
167
+ # 5. Conduct quality check and save the cohort information
168
+ os.makedirs(os.path.dirname(json_path), exist_ok=True)
169
+ is_usable = validate_and_save_cohort_info(
170
+ is_final=True,
171
+ cohort=cohort,
172
+ info_path=json_path,
173
+ is_gene_available=True,
174
+ is_trait_available=False,
175
+ is_biased=False, # Placeholder value since no trait data available
176
+ df=linked_data,
177
+ note="INFO: Dataset contains gene expression data but no trait information available for analysis"
178
+ )
179
+
180
+ # 6. Since no trait data is available, the dataset is not usable - do not save linked data
181
+ print("Dataset not saved - no trait information available for associational study")
output/preprocess/Endometrioid_Cancer/code/GSE73637.py ADDED
@@ -0,0 +1,203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Endometrioid_Cancer"
6
+ cohort = "GSE73637"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Endometrioid_Cancer"
10
+ in_cohort_dir = "../DATA/GEO/Endometrioid_Cancer/GSE73637"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z2/preprocess/Endometrioid_Cancer/GSE73637.csv"
14
+ out_gene_data_file = "./output/z2/preprocess/Endometrioid_Cancer/gene_data/GSE73637.csv"
15
+ out_clinical_data_file = "./output/z2/preprocess/Endometrioid_Cancer/clinical_data/GSE73637.csv"
16
+ json_path = "./output/z2/preprocess/Endometrioid_Cancer/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ # 1. Gene Expression Data Availability
40
+ is_gene_available = True
41
+
42
+ # 2.1 Data Availability
43
+ trait_row = 3 # histopathology data contains endometrioid cancer information
44
+ age_row = None # Not available for cell lines
45
+ gender_row = None # Not available for cell lines
46
+
47
+ # 2.2 Data Type Conversion functions
48
+ def convert_trait(value):
49
+ """Convert histopathology to binary endometrioid cancer status"""
50
+ if value is None:
51
+ return None
52
+ # Extract value after colon
53
+ if ':' in str(value):
54
+ histology = str(value).split(':')[1].strip()
55
+ else:
56
+ histology = str(value).strip()
57
+
58
+ # Check if it contains "Endometrioid" (including "Endometroid" variant)
59
+ if "Endometrioid" in histology or "Endometroid" in histology:
60
+ return 1
61
+ else:
62
+ return 0
63
+
64
+ def convert_age(value):
65
+ """Age conversion function (not used since age_row is None)"""
66
+ return None
67
+
68
+ def convert_gender(value):
69
+ """Gender conversion function (not used since gender_row is None)"""
70
+ return None
71
+
72
+ # 3. Save Metadata
73
+ is_trait_available = trait_row is not None
74
+ validate_and_save_cohort_info(is_final=False, cohort=cohort, info_path=json_path,
75
+ is_gene_available=is_gene_available, is_trait_available=is_trait_available)
76
+
77
+ # 4. Clinical Feature Extraction
78
+ if trait_row is not None:
79
+ selected_clinical_data = geo_select_clinical_features(clinical_data, trait, trait_row, convert_trait,
80
+ age_row, convert_age, gender_row, convert_gender)
81
+ print("Clinical data extracted:")
82
+ print(preview_df(selected_clinical_data))
83
+
84
+ # Save clinical data
85
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
86
+ selected_clinical_data.to_csv(out_clinical_data_file)
87
+
88
+ # Step 3: Gene Data Extraction
89
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
90
+ gene_data = get_genetic_data(matrix_file)
91
+
92
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
93
+ print(gene_data.index[:20])
94
+
95
+ # Step 4: Gene Identifier Review
96
+ # Examine the gene identifiers from the previous step output
97
+ gene_identifiers = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20']
98
+
99
+ print("Sample gene identifiers:", gene_identifiers[:10])
100
+ print("These appear to be numeric probe/array identifiers, not human gene symbols")
101
+ print("Human gene symbols are typically alphanumeric like BRCA1, TP53, GAPDH, etc.")
102
+ print("These numeric identifiers will need to be mapped to actual gene symbols")
103
+
104
+ requires_gene_mapping = True
105
+
106
+ # Step 5: Gene Annotation
107
+ # First, let's examine the SOFT file structure to understand what we're dealing with
108
+ print("Examining SOFT file structure:")
109
+ with gzip.open(soft_file, 'rt') as f:
110
+ lines = []
111
+ for i, line in enumerate(f):
112
+ lines.append(line.strip())
113
+ if i >= 50: # Read first 50 lines
114
+ break
115
+
116
+ # Show first 20 lines to understand the structure
117
+ for i, line in enumerate(lines[:20]):
118
+ print(f"Line {i}: {line[:100]}...") # Show first 100 chars of each line
119
+
120
+ print("\n" + "="*50)
121
+
122
+ # Look for gene annotation section - typically starts after platform info
123
+ annotation_start = None
124
+ for i, line in enumerate(lines):
125
+ if line.startswith('!platform_table_begin'):
126
+ annotation_start = i + 1
127
+ print(f"Found annotation section starting at line {annotation_start}")
128
+ break
129
+
130
+ if annotation_start:
131
+ print("Sample annotation lines:")
132
+ for i in range(annotation_start, min(annotation_start + 10, len(lines))):
133
+ if i < len(lines):
134
+ print(f"Line {i}: {lines[i]}")
135
+
136
+ # Try alternative approach to get gene annotation
137
+ try:
138
+ with gzip.open(soft_file, 'rt') as f:
139
+ content = f.read()
140
+
141
+ # Find the platform table section
142
+ if '!platform_table_begin' in content and '!platform_table_end' in content:
143
+ start_marker = '!platform_table_begin'
144
+ end_marker = '!platform_table_end'
145
+ start_idx = content.find(start_marker) + len(start_marker)
146
+ end_idx = content.find(end_marker)
147
+
148
+ table_content = content[start_idx:end_idx].strip()
149
+
150
+ # Parse as CSV
151
+ gene_annotation = pd.read_csv(io.StringIO(table_content), delimiter='\t', low_memory=False)
152
+
153
+ print("\nSuccessfully extracted gene annotation data!")
154
+ print("Gene annotation preview:")
155
+ print(preview_df(gene_annotation))
156
+
157
+ else:
158
+ print("Could not find platform table markers in SOFT file")
159
+
160
+ except Exception as e:
161
+ print(f"Alternative parsing also failed: {e}")
162
+ # If all parsing fails, we may need to work without gene annotation
163
+ gene_annotation = None
164
+
165
+ # Step 6: Gene Identifier Mapping
166
+ # 1. Identify the columns for gene identifiers and gene symbols
167
+ # The 'ID' column matches the gene expression data identifiers (numeric: 1, 2, 3, ...)
168
+ # The 'GeneSymbol' column contains the actual gene symbols (PRPF8, CAPNS1, etc.)
169
+
170
+ # 2. Get gene mapping dataframe
171
+ gene_mapping = get_gene_mapping(gene_annotation, 'ID', 'GeneSymbol')
172
+
173
+ # 3. Apply gene mapping to convert probe-level measurements to gene expression data
174
+ gene_data = apply_gene_mapping(gene_data, gene_mapping)
175
+
176
+ print(f"Gene expression data shape after mapping: {gene_data.shape}")
177
+ print(f"Sample gene symbols: {list(gene_data.index[:10])}")
178
+
179
+ # Step 7: Data Normalization and Linking
180
+ # 1. Normalize the obtained gene data with the 'normalize_gene_symbols_in_index' function from the library.
181
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
182
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
183
+ normalized_gene_data.to_csv(out_gene_data_file)
184
+
185
+ # 2. Link the clinical and genetic data with the 'geo_link_clinical_genetic_data' function from the library.
186
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_data, normalized_gene_data)
187
+
188
+ # 3. Handle missing values in the linked data
189
+ linked_data = handle_missing_values(linked_data, trait)
190
+
191
+ # 4. Determine whether the trait and some demographic features are severely biased, and remove biased features.
192
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
193
+
194
+ # 5. Conduct quality check and save the cohort information.
195
+ is_usable = validate_and_save_cohort_info(True, cohort, json_path, True, True, is_trait_biased, unbiased_linked_data)
196
+
197
+ # 6. If the linked data is usable, save it as a CSV file to 'out_data_file'.
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
+ print(f"Successfully saved processed data to {out_data_file}")
202
+ else:
203
+ print("Dataset is not usable for analysis - not saved")
output/preprocess/Endometrioid_Cancer/code/GSE94523.py ADDED
@@ -0,0 +1,172 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Endometrioid_Cancer"
6
+ cohort = "GSE94523"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Endometrioid_Cancer"
10
+ in_cohort_dir = "../DATA/GEO/Endometrioid_Cancer/GSE94523"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z2/preprocess/Endometrioid_Cancer/GSE94523.csv"
14
+ out_gene_data_file = "./output/z2/preprocess/Endometrioid_Cancer/gene_data/GSE94523.csv"
15
+ out_clinical_data_file = "./output/z2/preprocess/Endometrioid_Cancer/clinical_data/GSE94523.csv"
16
+ json_path = "./output/z2/preprocess/Endometrioid_Cancer/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ # 1. Gene Expression Data Availability
40
+ is_gene_available = True # Series mentions "Microarray Expression" and "Gene expression profiling"
41
+
42
+ # 2. Variable Availability and Data Type Conversion
43
+
44
+ # 2.1 Data Availability
45
+ trait_row = None # Only one unique value 'tissue: endometrioid adenocarcinoma', which is constant
46
+ age_row = None # No age information available in sample characteristics
47
+ gender_row = None # No gender information available in sample characteristics
48
+
49
+ # 2.2 Data Type Conversion
50
+ def convert_trait(value):
51
+ """Convert trait values to binary (0/1)"""
52
+ if value is None:
53
+ return None
54
+ value = str(value).split(':')[-1].strip().lower()
55
+ if 'endometrioid' in value or 'adenocarcinoma' in value:
56
+ return 1
57
+ else:
58
+ return 0
59
+
60
+ def convert_age(value):
61
+ """Convert age to continuous numeric values"""
62
+ if value is None:
63
+ return None
64
+ try:
65
+ value = str(value).split(':')[-1].strip()
66
+ return float(value)
67
+ except:
68
+ return None
69
+
70
+ def convert_gender(value):
71
+ """Convert gender to binary (0=female, 1=male)"""
72
+ if value is None:
73
+ return None
74
+ value = str(value).split(':')[-1].strip().lower()
75
+ if 'female' in value or 'f' in value:
76
+ return 0
77
+ elif 'male' in value or 'm' in value:
78
+ return 1
79
+ else:
80
+ return None
81
+
82
+ # 3. Save Metadata
83
+ is_trait_available = trait_row is not None
84
+ save_cohort_info = validate_and_save_cohort_info(
85
+ is_final=False,
86
+ cohort=cohort,
87
+ info_path=json_path,
88
+ is_gene_available=is_gene_available,
89
+ is_trait_available=is_trait_available
90
+ )
91
+
92
+ # 4. Clinical Feature Extraction
93
+ # Skipping this step since trait_row is None (no clinical data available)
94
+
95
+ # Step 3: Gene Data Extraction
96
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
97
+ gene_data = get_genetic_data(matrix_file)
98
+
99
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
100
+ print(gene_data.index[:20])
101
+
102
+ # Step 4: Gene Identifier Review
103
+ # Examine the gene identifiers from the previous step output
104
+ gene_identifiers = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20']
105
+
106
+ # Check if these look like human gene symbols
107
+ # Gene symbols are typically alphanumeric strings with letters, not just numbers
108
+ # Examples: TP53, BRCA1, EGFR, MYC, etc.
109
+ print("Sample gene identifiers:", gene_identifiers[:10])
110
+
111
+ # These are clearly numeric identifiers (as strings), not gene symbols
112
+ # Gene symbols would contain letters and be more descriptive
113
+ # These appear to be probe IDs or platform-specific identifiers
114
+
115
+ requires_gene_mapping = True
116
+
117
+ # Step 5: Gene Annotation
118
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
119
+ gene_annotation = get_gene_annotation(soft_file)
120
+
121
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
122
+ print("Gene annotation preview:")
123
+ print(preview_df(gene_annotation))
124
+
125
+ # Step 6: Gene Identifier Mapping
126
+ # 1. Identify mapping columns: 'ID' matches gene expression identifiers, 'HUGO' contains gene symbols
127
+ prob_col = 'ID'
128
+ gene_col = 'HUGO'
129
+
130
+ # 2. Get gene mapping dataframe using the library function
131
+ gene_mapping = get_gene_mapping(gene_annotation, prob_col, gene_col)
132
+
133
+ # 3. Apply gene mapping to convert probe-level measurements to gene expression data
134
+ gene_data = apply_gene_mapping(gene_data, gene_mapping)
135
+
136
+ print(f"Gene expression data shape after mapping: {gene_data.shape}")
137
+ print(f"First few gene symbols: {gene_data.index[:10].tolist()}")
138
+
139
+ # Step 7: Data Normalization and Linking
140
+ # 1. Normalize the obtained gene data with the 'normalize_gene_symbols_in_index' function from the library.
141
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
142
+ normalized_gene_data.to_csv(out_gene_data_file)
143
+
144
+ # 2. Since no clinical data is available (trait_row = None from Step 2), create empty clinical dataframe
145
+ # and link only genetic data
146
+ clinical_data_empty = pd.DataFrame()
147
+ linked_data = normalized_gene_data.T # Transpose to have samples as rows
148
+
149
+ # 3. Since no trait data is available, skip missing value handling for clinical features
150
+ # Only handle missing values in genetic data
151
+ linked_data = linked_data.fillna(linked_data.mean())
152
+
153
+ # 4. Since no trait data exists, the dataset is biased/unusable for associative studies
154
+ # All samples have the same constant trait value (endometrioid adenocarcinoma)
155
+ is_trait_biased = True
156
+ unbiased_linked_data = linked_data
157
+
158
+ # 5. Conduct quality check and save the cohort information
159
+ is_usable = validate_and_save_cohort_info(
160
+ is_final=True,
161
+ cohort=cohort,
162
+ info_path=json_path,
163
+ is_gene_available=True,
164
+ is_trait_available=False, # No usable trait data available
165
+ is_biased=is_trait_biased,
166
+ df=unbiased_linked_data,
167
+ note="INFO: Dataset contains only constant trait values (all endometrioid adenocarcinoma), not suitable for associative studies"
168
+ )
169
+
170
+ # 6. Since dataset is not usable, do not save the linked data file
171
+ if is_usable:
172
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Endometrioid_Cancer/code/GSE94524.py ADDED
@@ -0,0 +1,148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Endometrioid_Cancer"
6
+ cohort = "GSE94524"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Endometrioid_Cancer"
10
+ in_cohort_dir = "../DATA/GEO/Endometrioid_Cancer/GSE94524"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z2/preprocess/Endometrioid_Cancer/GSE94524.csv"
14
+ out_gene_data_file = "./output/z2/preprocess/Endometrioid_Cancer/gene_data/GSE94524.csv"
15
+ out_clinical_data_file = "./output/z2/preprocess/Endometrioid_Cancer/clinical_data/GSE94524.csv"
16
+ json_path = "./output/z2/preprocess/Endometrioid_Cancer/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ # 1. Gene Expression Data Availability
40
+ is_gene_available = True # The study focuses on differential enhancer activity, suggesting gene expression data
41
+
42
+ # 2. Variable Availability and Data Type Conversion
43
+
44
+ # 2.1 Data Availability
45
+ # trait: Only one unique value 'tissue: endometrioid adenocarcinoma' - constant feature, not useful
46
+ trait_row = None
47
+ age_row = None # No age information available
48
+ gender_row = None # No gender information available
49
+
50
+ # 2.2 Data Type Conversion
51
+ def convert_trait(value):
52
+ """Convert trait values to binary"""
53
+ if value is None:
54
+ return None
55
+ return None # Not used since trait_row is None
56
+
57
+ def convert_age(value):
58
+ """Convert age values to continuous"""
59
+ if value is None:
60
+ return None
61
+ return None # Not used since age_row is None
62
+
63
+ def convert_gender(value):
64
+ """Convert gender values to binary (0=female, 1=male)"""
65
+ if value is None:
66
+ return None
67
+ return None # Not used since gender_row is None
68
+
69
+ # 3. Save Metadata
70
+ is_trait_available = trait_row is not None
71
+ validate_and_save_cohort_info(is_final=False, cohort=cohort, info_path=json_path,
72
+ is_gene_available=is_gene_available,
73
+ is_trait_available=is_trait_available)
74
+
75
+ # 4. Clinical Feature Extraction
76
+ # Skip this step since trait_row is None (no clinical data available)
77
+
78
+ # Step 3: Gene Data Extraction
79
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
80
+ gene_data = get_genetic_data(matrix_file)
81
+
82
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
83
+ print(gene_data.index[:20])
84
+
85
+ # Step 4: Gene Identifier Review
86
+ print("Examining gene identifiers...")
87
+ print("Sample identifiers:", gene_data.index[:10].tolist())
88
+
89
+ # These are numeric identifiers (1, 2, 3, etc.), not human gene symbols
90
+ # Human gene symbols are typically alphanumeric strings like BRCA1, TP53, GAPDH, etc.
91
+ # These numeric IDs likely represent probe IDs or other database identifiers that need mapping
92
+
93
+ requires_gene_mapping = True
94
+
95
+ # Step 5: Gene Annotation
96
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
97
+ gene_annotation = get_gene_annotation(soft_file)
98
+
99
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
100
+ print("Gene annotation preview:")
101
+ print(preview_df(gene_annotation))
102
+
103
+ # Step 6: Gene Identifier Mapping
104
+ # 1. Identify the mapping columns
105
+ # 'ID' column matches the gene expression data identifiers (numeric IDs)
106
+ # 'HUGO' column contains gene symbols, though it has some NaN values
107
+ prob_col = 'ID'
108
+ gene_col = 'HUGO'
109
+
110
+ # 2. Get gene mapping dataframe
111
+ gene_mapping = get_gene_mapping(gene_annotation, prob_col, gene_col)
112
+
113
+ # 3. Apply gene mapping to convert probe-level data to gene expression data
114
+ gene_data = apply_gene_mapping(gene_data, gene_mapping)
115
+
116
+ # Normalize gene symbols to ensure consistency
117
+ gene_data = normalize_gene_symbols_in_index(gene_data)
118
+
119
+ print(f"Gene expression data shape after mapping: {gene_data.shape}")
120
+ print(f"Sample gene names: {gene_data.index[:10].tolist()}")
121
+
122
+ # Step 7: Data Normalization and Linking
123
+ # 1. Normalize the obtained gene data and save it
124
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
125
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
126
+ normalized_gene_data.to_csv(out_gene_data_file)
127
+
128
+ # Since no clinical data with variable traits is available (trait_row was None in Step 2),
129
+ # this dataset is not suitable for association studies
130
+ print("No variable clinical trait data available - dataset not suitable for association studies")
131
+
132
+ # Create empty dataframe to represent unavailable linked data
133
+ linked_data = pd.DataFrame()
134
+
135
+ # 5. Conduct final quality validation
136
+ is_usable = validate_and_save_cohort_info(
137
+ is_final=True,
138
+ cohort=cohort,
139
+ info_path=json_path,
140
+ is_gene_available=True,
141
+ is_trait_available=False,
142
+ is_biased=True, # Dataset is biased/unusable due to constant trait values
143
+ df=linked_data,
144
+ note="INFO: Dataset contains only constant trait values (all endometrioid adenocarcinoma), no variable clinical features for association analysis"
145
+ )
146
+
147
+ # 6. Since the dataset is not usable for association studies, do not save linked data file
148
+ print(f"Dataset usability: {is_usable}")
output/preprocess/Endometrioid_Cancer/code/TCGA.py ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Endometrioid_Cancer"
6
+
7
+ # Input paths
8
+ tcga_root_dir = "../DATA/TCGA"
9
+
10
+ # Output paths
11
+ out_data_file = "./output/z2/preprocess/Endometrioid_Cancer/TCGA.csv"
12
+ out_gene_data_file = "./output/z2/preprocess/Endometrioid_Cancer/gene_data/TCGA.csv"
13
+ out_clinical_data_file = "./output/z2/preprocess/Endometrioid_Cancer/clinical_data/TCGA.csv"
14
+ json_path = "./output/z2/preprocess/Endometrioid_Cancer/cohort_info.json"
15
+
16
+
17
+ # Step 1: Initial Data Loading
18
+ # Select the most relevant subdirectory for Endometrioid Cancer
19
+ selected_cohort = "TCGA_Endometrioid_Cancer_(UCEC)"
20
+ cohort_path = os.path.join(tcga_root_dir, selected_cohort)
21
+
22
+ print(f"Selected cohort: {selected_cohort}")
23
+
24
+ # Get file paths for clinical and genetic data
25
+ clinical_file_path, genetic_file_path = tcga_get_relevant_filepaths(cohort_path)
26
+
27
+ print(f"Clinical data file: {clinical_file_path}")
28
+ print(f"Genetic data file: {genetic_file_path}")
29
+
30
+ # Load clinical data
31
+ clinical_data = pd.read_csv(clinical_file_path, index_col=0, sep='\t')
32
+
33
+ # Load genetic data
34
+ genetic_data = pd.read_csv(genetic_file_path, index_col=0, sep='\t')
35
+
36
+ print(f"\nClinical data shape: {clinical_data.shape}")
37
+ print(f"Genetic data shape: {genetic_data.shape}")
38
+
39
+ print(f"\nClinical data column names:")
40
+ print(clinical_data.columns.tolist())
41
+
42
+ # Step 2: Find Candidate Demographic Features
43
+ # Identify candidate demographic columns
44
+ candidate_age_cols = ['age_at_initial_pathologic_diagnosis', 'days_to_birth']
45
+ candidate_gender_cols = ['gender']
46
+
47
+ # Load clinical data to extract and preview candidate columns
48
+ clinical_file_path, genetic_file_path = tcga_get_relevant_filepaths(os.path.join(tcga_root_dir, "TCGA_Endometrioid_Cancer_(UCEC)"))
49
+ clinical_df = pd.read_csv(clinical_file_path, sep='\t', index_col=0)
50
+
51
+ # Extract age candidate columns
52
+ if candidate_age_cols:
53
+ age_data = clinical_df[candidate_age_cols]
54
+ print("Age candidate columns preview:")
55
+ print(preview_df(age_data, n=5))
56
+ print()
57
+
58
+ # Extract gender candidate columns
59
+ if candidate_gender_cols:
60
+ gender_data = clinical_df[candidate_gender_cols]
61
+ print("Gender candidate columns preview:")
62
+ print(preview_df(gender_data, n=5))
63
+
64
+ # Step 3: Select Demographic Features
65
+ # Based on the previous step output, select the best columns
66
+ # Age candidate columns had: age_at_initial_pathologic_diagnosis (direct age values) and days_to_birth (negative values, some missing)
67
+ # Gender candidate columns had: gender (clear FEMALE/MALE values)
68
+
69
+ # Choose age column - age_at_initial_pathologic_diagnosis has direct age values with no missing data
70
+ age_col = 'age_at_initial_pathologic_diagnosis'
71
+
72
+ # Choose gender column - gender has clear gender values
73
+ gender_col = 'gender'
74
+
75
+ print(f"Chosen age column: {age_col}")
76
+ print(f"Chosen gender column: {gender_col}")
77
+
78
+ # Step 4: Feature Engineering and Validation
79
+ # Extract and standardize clinical features
80
+ clinical_features = tcga_select_clinical_features(
81
+ clinical_data,
82
+ trait=trait,
83
+ age_col=age_col,
84
+ gender_col=gender_col
85
+ )
86
+
87
+ print(f"Clinical features shape: {clinical_features.shape}")
88
+ print(f"Clinical features columns: {clinical_features.columns.tolist()}")
89
+
90
+ # Normalize gene symbols in genetic data
91
+ normalized_genetic_data = normalize_gene_symbols_in_index(genetic_data)
92
+ print(f"Normalized genetic data shape: {normalized_genetic_data.shape}")
93
+
94
+ # Save normalized genetic data
95
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
96
+ normalized_genetic_data.to_csv(out_gene_data_file)
97
+ print(f"Saved normalized genetic data to {out_gene_data_file}")
98
+
99
+ # Link clinical and genetic data - transpose genetic data first to have samples as rows
100
+ genetic_data_transposed = normalized_genetic_data.T
101
+ print(f"Transposed genetic data shape: {genetic_data_transposed.shape}")
102
+
103
+ # Align by common sample IDs and concatenate
104
+ common_samples = clinical_features.index.intersection(genetic_data_transposed.index)
105
+ print(f"Common samples between clinical and genetic data: {len(common_samples)}")
106
+
107
+ clinical_aligned = clinical_features.loc[common_samples]
108
+ genetic_aligned = genetic_data_transposed.loc[common_samples]
109
+
110
+ linked_data = pd.concat([clinical_aligned, genetic_aligned], axis=1)
111
+ print(f"Linked data shape: {linked_data.shape}")
112
+
113
+ # Handle missing values systematically
114
+ linked_data = handle_missing_values(linked_data, trait)
115
+ print(f"Data shape after handling missing values: {linked_data.shape}")
116
+
117
+ # Check if features are severely biased and remove biased demographic features
118
+ trait_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)
119
+ print(f"Final data shape: {linked_data.shape}")
120
+ print(f"Final columns: {linked_data.columns.tolist()[:10]}...") # Show first 10 columns
121
+
122
+ # Validate data quality and determine if dataset is usable
123
+ is_gene_available = len([col for col in linked_data.columns if col not in [trait, 'Age', 'Gender']]) > 0
124
+ is_trait_available = trait in linked_data.columns and not linked_data[trait].isna().all()
125
+
126
+ # Final validation and save cohort info
127
+ is_usable = validate_and_save_cohort_info(
128
+ is_final=True,
129
+ cohort="TCGA",
130
+ info_path=json_path,
131
+ is_gene_available=is_gene_available,
132
+ is_trait_available=is_trait_available,
133
+ is_biased=trait_biased,
134
+ df=linked_data,
135
+ note="INFO: TCGA Endometrioid Cancer cohort processed successfully"
136
+ )
137
+
138
+ # Save clinical data
139
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
140
+ clinical_features.to_csv(out_clinical_data_file)
141
+ print(f"Saved clinical data to {out_clinical_data_file}")
142
+
143
+ # Save linked data only if usable
144
+ if is_usable:
145
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
146
+ linked_data.to_csv(out_data_file)
147
+ print(f"Dataset is usable. Saved linked data to {out_data_file}")
148
+ else:
149
+ print("Dataset is not usable. Linked data was not saved.")
output/preprocess/Endometrioid_Cancer/cohort_info.json CHANGED
@@ -1,112 +1 @@
1
- {
2
- "GSE94524": {
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": 111
11
- },
12
- "GSE94523": {
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": 111
21
- },
22
- "GSE73637": {
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": false,
29
- "has_gender": false,
30
- "sample_size": 52
31
- },
32
- "GSE73614": {
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
- "GSE73551": {
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": 50
51
- },
52
- "GSE68600": {
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": 113
61
- },
62
- "GSE66667": {
63
- "is_usable": false,
64
- "is_gene_available": true,
65
- "is_trait_available": true,
66
- "is_available": true,
67
- "is_biased": true,
68
- "has_age": false,
69
- "has_gender": false,
70
- "sample_size": 36
71
- },
72
- "GSE65986": {
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": true,
79
- "has_gender": false,
80
- "sample_size": 55
81
- },
82
- "GSE40785": {
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": 37
91
- },
92
- "GSE120490": {
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": 145
101
- },
102
- "TCGA": {
103
- "is_usable": true,
104
- "is_gene_available": true,
105
- "is_trait_available": true,
106
- "is_available": true,
107
- "is_biased": false,
108
- "has_age": true,
109
- "has_gender": false,
110
- "sample_size": 201
111
- }
112
- }
 
1
+ {"GSE94524": {"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: Dataset contains only constant trait values (all endometrioid adenocarcinoma), no variable clinical features for association analysis"}, "GSE94523": {"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: Dataset contains only constant trait values (all endometrioid adenocarcinoma), not suitable for associative studies"}, "GSE73637": {"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": 52, "note": ""}, "GSE73614": {"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: Dataset contains gene expression data but no trait information available for analysis"}, "GSE73551": {"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": 50, "note": ""}, "GSE68600": {"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": 113, "note": ""}, "GSE66667": {"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": 36, "note": ""}, "GSE65986": {"is_usable": true, "is_gene_available": true, "is_trait_available": true, "is_available": true, "is_biased": false, "has_age": true, "has_gender": false, "sample_size": 55, "note": ""}, "GSE40785": {"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": 37, "note": ""}, "GSE120490": {"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": 145, "note": ""}, "TCGA": {"is_usable": true, "is_gene_available": true, "is_trait_available": true, "is_available": true, "is_biased": false, "has_age": true, "has_gender": false, "sample_size": 201, "note": "INFO: TCGA Endometrioid Cancer cohort processed successfully"}}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
output/preprocess/Endometriosis/GSE120103.csv ADDED
The diff for this file is too large to render. See raw diff
 
output/preprocess/Endometriosis/clinical_data/GSE120103.csv CHANGED
@@ -1,2 +1,2 @@
1
- 0,1,2,3
2
- 0.0,1.0,0.0,1.0
 
1
+ ,GSM3393491,GSM3393492,GSM3393493,GSM3393494,GSM3393495,GSM3393496,GSM3393497,GSM3393498,GSM3393499,GSM3393500,GSM3393501,GSM3393502,GSM3393503,GSM3393504,GSM3393505,GSM3393506,GSM3393507,GSM3393508,GSM3393509,GSM3393510,GSM3393511,GSM3393512,GSM3393513,GSM3393514,GSM3393515,GSM3393516,GSM3393517,GSM3393518,GSM3393519,GSM3393520,GSM3393521,GSM3393522,GSM3393523,GSM3393524,GSM3393525,GSM3393526
2
+ Endometriosis,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,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
output/preprocess/Endometriosis/clinical_data/GSE145701.csv CHANGED
@@ -1,2 +1,2 @@
1
- ,0,1,2,3,4,5,6,7,8,9,10,11
2
- Endometriosis,0.0,1.0,1.0,,,,,,,,,
 
1
+ ,GSM4331199,GSM4331200,GSM4331201,GSM4331202,GSM4331203,GSM4331204,GSM4331205,GSM4331206,GSM4331207,GSM4331208,GSM4331209,GSM4331210,GSM4331211,GSM4331212,GSM4331213,GSM4331214,GSM4331215,GSM4331216,GSM4331217,GSM4331218,GSM4331219,GSM4331220,GSM4331221,GSM4331222,GSM4331223,GSM4331224,GSM4331225,GSM4331226,GSM4331227,GSM4331228,GSM4331229,GSM4331230,GSM4331231,GSM4331232,GSM4331233,GSM4331234,GSM4331235,GSM4331236,GSM4331237,GSM4331238,GSM4331239,GSM4331240,GSM4331241,GSM4331242,GSM4331243,GSM4331244,GSM4331245,GSM4331246
2
+ Endometriosis,0.0,0.0,0.0,0.0,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
output/preprocess/Endometriosis/clinical_data/GSE73622.csv CHANGED
@@ -1,3 +1,3 @@
1
- ,Sample_1,Sample_2
2
- Endometriosis,1.0,1.0
3
- Age,29.0,39.0
 
1
+ GSM1899589,GSM1899590,GSM1899591,GSM1899592,GSM1899593,GSM1899594,GSM1899595,GSM1899596,GSM1899597,GSM1899598,GSM1899599,GSM1899600,GSM1899601,GSM1899602,GSM1899603,GSM1899604,GSM1899605,GSM1899606,GSM1899607,GSM1899608,GSM1899609,GSM1899610,GSM1899611,GSM1899612,GSM1899613,GSM1899614,GSM1899615,GSM1899616,GSM1899617,GSM1899618,GSM1899619,GSM1899620,GSM1899621,GSM1899622,GSM1899623,GSM1899624,GSM1899625,GSM1899626,GSM1899627,GSM1899628,GSM1899629,GSM1899630,GSM1899631,GSM1899632,GSM1899633,GSM1899634,GSM1899635,GSM1899636,GSM1899637,GSM1899638
2
+ 1.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0
3
+ 29.0,39.0,47.0,35.0,50.0,27.0,21.0,31.0,26.0,29.0,29.0,36.0,31.0,47.0,35.0,24.0,28.0,28.0,41.0,29.0,31.0,36.0,47.0,24.0,28.0,27.0,21.0,29.0,31.0,36.0,28.0,27.0,28.0,21.0,29.0,31.0,36.0,47.0,24.0,28.0,28.0,21.0,29.0,31.0,36.0,47.0,24.0,28.0,28.0,21.0
output/preprocess/Endometriosis/code/GSE111974.py ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Endometriosis"
6
+ cohort = "GSE111974"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Endometriosis"
10
+ in_cohort_dir = "../DATA/GEO/Endometriosis/GSE111974"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z3/preprocess/Endometriosis/GSE111974.csv"
14
+ out_gene_data_file = "./output/z3/preprocess/Endometriosis/gene_data/GSE111974.csv"
15
+ out_clinical_data_file = "./output/z3/preprocess/Endometriosis/clinical_data/GSE111974.csv"
16
+ json_path = "./output/z3/preprocess/Endometriosis/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ # Determine gene and trait availability based on provided background and characteristics
40
+ is_gene_available = True # RNA expression profiling implies gene expression data is available
41
+ trait_row = None # No Endometriosis status available; dataset focuses on RIF vs fertile controls
42
+ age_row = None # No age information in sample characteristics
43
+ gender_row = None # No gender information in sample characteristics
44
+
45
+ is_trait_available = trait_row is not None
46
+
47
+ # Conversion functions
48
+ def _parse_after_colon(x):
49
+ if x is None:
50
+ return None
51
+ try:
52
+ s = str(x)
53
+ except Exception:
54
+ return None
55
+ parts = s.split(":", 1)
56
+ val = parts[1] if len(parts) == 2 else parts[0]
57
+ return val.strip()
58
+
59
+ def convert_trait(x):
60
+ # Binary: Endometriosis case = 1, control = 0
61
+ val = _parse_after_colon(x)
62
+ if val is None:
63
+ return None
64
+ v = val.strip().lower()
65
+ # Positive indications
66
+ positives = {"endometriosis", "endo", "case"}
67
+ if any(p in v for p in positives):
68
+ # If the phrase explicitly negates endometriosis, handle below
69
+ if "no endometriosis" in v or "without endometriosis" in v:
70
+ return 0
71
+ return 1
72
+ # Negative/control indications
73
+ negatives = {"control", "healthy", "no endometriosis", "without endometriosis"}
74
+ if any(n in v for n in negatives):
75
+ return 0
76
+ return None
77
+
78
+ def convert_age(x):
79
+ # Continuous: extract first number as age in years
80
+ val = _parse_after_colon(x)
81
+ if val is None:
82
+ return None
83
+ import re
84
+ m = re.search(r"[-+]?\d*\.?\d+", val)
85
+ if not m:
86
+ return None
87
+ try:
88
+ return float(m.group())
89
+ except Exception:
90
+ return None
91
+
92
+ def convert_gender(x):
93
+ # Binary: female=0, male=1
94
+ val = _parse_after_colon(x)
95
+ if val is None:
96
+ return None
97
+ v = val.strip().lower()
98
+ if v in {"female", "f", "woman", "women"}:
99
+ return 0
100
+ if v in {"male", "m", "man", "men"}:
101
+ return 1
102
+ return None
103
+
104
+ # Save initial metadata
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
+ # Clinical feature extraction is skipped because trait_row is None
114
+ if trait_row is not None:
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
+ preview = preview_df(selected_clinical_df, n=5)
126
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
127
+ selected_clinical_df.to_csv(out_clinical_data_file)
output/preprocess/Endometriosis/code/GSE120103.py ADDED
@@ -0,0 +1,192 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Endometriosis"
6
+ cohort = "GSE120103"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Endometriosis"
10
+ in_cohort_dir = "../DATA/GEO/Endometriosis/GSE120103"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z3/preprocess/Endometriosis/GSE120103.csv"
14
+ out_gene_data_file = "./output/z3/preprocess/Endometriosis/gene_data/GSE120103.csv"
15
+ out_clinical_data_file = "./output/z3/preprocess/Endometriosis/clinical_data/GSE120103.csv"
16
+ json_path = "./output/z3/preprocess/Endometriosis/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 # Whole genome expression arrays (mRNA) per background info
45
+
46
+ # 2) Variable availability and converters
47
+ trait_row = 1 # 'sample group' encodes Endometriosis vs Control
48
+ age_row = None # No age information found
49
+ gender_row = None # Gender present but constant (all Female), thus not useful
50
+
51
+ def _extract_value(x):
52
+ if x is None:
53
+ return None
54
+ s = str(x)
55
+ if ':' in s:
56
+ s = s.split(':', 1)[1]
57
+ return s.strip()
58
+
59
+ def convert_trait(x):
60
+ v = _extract_value(x)
61
+ if not v:
62
+ return None
63
+ vl = v.lower()
64
+ # Cases (Endometriosis)
65
+ if 'endometriosis' in vl:
66
+ return 1
67
+ # Controls (No Endometriosis)
68
+ if 'disease free' in vl or 'disease-free' in vl or 'without endometriosis' in vl or 'control' in vl:
69
+ return 0
70
+ # Fallback by group labels if present
71
+ if 'group 2' in vl:
72
+ return 1
73
+ if 'group 1' in vl:
74
+ return 0
75
+ return None
76
+
77
+ def convert_age(x):
78
+ v = _extract_value(x)
79
+ if not v:
80
+ return None
81
+ # Extract a number possibly with decimal (e.g., '35', '35.0', '35 years')
82
+ m = re.search(r'(\d+(\.\d+)?)', v)
83
+ if m:
84
+ try:
85
+ return float(m.group(1))
86
+ except Exception:
87
+ return None
88
+ return None
89
+
90
+ def convert_gender(x):
91
+ v = _extract_value(x)
92
+ if not v:
93
+ return None
94
+ vl = v.lower()
95
+ if vl in {'f', 'female', 'woman', 'women'}:
96
+ return 0
97
+ if vl in {'m', 'male', 'man', 'men'}:
98
+ return 1
99
+ return None
100
+
101
+ # 3) Initial filtering metadata save
102
+ is_trait_available = trait_row is not None
103
+ _ = validate_and_save_cohort_info(
104
+ is_final=False,
105
+ cohort=cohort,
106
+ info_path=json_path,
107
+ is_gene_available=is_gene_available,
108
+ is_trait_available=is_trait_available
109
+ )
110
+
111
+ # 4) Clinical feature extraction (only if trait available)
112
+ if is_trait_available:
113
+ selected_clinical_df = geo_select_clinical_features(
114
+ clinical_df=clinical_data,
115
+ trait=trait,
116
+ trait_row=trait_row,
117
+ convert_trait=convert_trait,
118
+ age_row=age_row,
119
+ convert_age=convert_age,
120
+ gender_row=gender_row,
121
+ convert_gender=convert_gender
122
+ )
123
+ preview = preview_df(selected_clinical_df)
124
+ print(preview)
125
+
126
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
127
+ selected_clinical_df.to_csv(out_clinical_data_file)
128
+
129
+ # Step 3: Gene Data Extraction
130
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
131
+ gene_data = get_genetic_data(matrix_file)
132
+
133
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
134
+ print(gene_data.index[:20])
135
+
136
+ # Step 4: Gene Identifier Review
137
+ print("requires_gene_mapping = True")
138
+
139
+ # Step 5: Gene Annotation
140
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
141
+ gene_annotation = get_gene_annotation(soft_file)
142
+
143
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
144
+ print("Gene annotation preview:")
145
+ print(preview_df(gene_annotation))
146
+
147
+ # Step 6: Gene Identifier Mapping
148
+ # 1. Decide the identifier and gene symbol columns based on previews:
149
+ # - Probe/ID column: 'ID' matches expression data identifiers like 'A_23_P100001'
150
+ # - Gene symbol column: 'GENE_SYMBOL'
151
+
152
+ # 2. Build the mapping dataframe
153
+ mapping_df = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='GENE_SYMBOL')
154
+
155
+ # 3. Apply mapping to convert probe-level data to gene-level expression
156
+ gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
157
+
158
+ # Step 7: Data Normalization and Linking
159
+ import os
160
+
161
+ # 1. Normalize gene symbols and save
162
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
163
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
164
+ normalized_gene_data.to_csv(out_gene_data_file)
165
+
166
+ # 2. Link clinical and genetic data
167
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
168
+
169
+ # 3. Handle missing values
170
+ linked_data = handle_missing_values(linked_data, trait)
171
+
172
+ # 4. Assess bias and drop biased covariates if any
173
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
174
+
175
+ # 5. Final validation and save cohort info
176
+ note = ("INFO: Gender was constant (all female) and excluded; Age not available in annotations. "
177
+ "Probe-to-gene mapping used GENE_SYMBOL; gene symbols normalized with NCBI synonyms.")
178
+ is_usable = validate_and_save_cohort_info(
179
+ is_final=True,
180
+ cohort=cohort,
181
+ info_path=json_path,
182
+ is_gene_available=True,
183
+ is_trait_available=True,
184
+ is_biased=is_trait_biased,
185
+ df=unbiased_linked_data,
186
+ note=note
187
+ )
188
+
189
+ # 6. Save linked data only 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/Endometriosis/code/GSE138297.py ADDED
@@ -0,0 +1,155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Endometriosis"
6
+ cohort = "GSE138297"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Endometriosis"
10
+ in_cohort_dir = "../DATA/GEO/Endometriosis/GSE138297"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z3/preprocess/Endometriosis/GSE138297.csv"
14
+ out_gene_data_file = "./output/z3/preprocess/Endometriosis/gene_data/GSE138297.csv"
15
+ out_clinical_data_file = "./output/z3/preprocess/Endometriosis/clinical_data/GSE138297.csv"
16
+ json_path = "./output/z3/preprocess/Endometriosis/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 (microarray on biopsies -> gene expression)
42
+ is_gene_available = True
43
+
44
+ # 2) Variable availability from the sample characteristics:
45
+ # Trait (Endometriosis) is not present; dataset is IBS FMT trial -> not available for current trait
46
+ trait_row = None
47
+ # Age and Gender rows identified from the dictionary
48
+ age_row = 3
49
+ gender_row = 1
50
+
51
+ # 2.2) Converters
52
+ def _after_colon(x):
53
+ s = str(x)
54
+ return s.split(":", 1)[1].strip() if ":" in s else s.strip()
55
+
56
+ def convert_trait(x):
57
+ # Binary: 1 = Endometriosis present (case), 0 = control
58
+ v = _after_colon(x).lower()
59
+ if v in {"1", "yes", "case", "patient", "disease"}:
60
+ return 1
61
+ if v in {"0", "no", "control", "healthy", "normal"}:
62
+ return 0
63
+ # keyword-based heuristic
64
+ if "endometriosis" in v or re.search(r"\bendo\b", v):
65
+ return 1
66
+ if "non-endometriosis" in v or "nonendo" in v or "non endo" in v:
67
+ return 0
68
+ return None
69
+
70
+ def convert_age(x):
71
+ v = _after_colon(x)
72
+ m = re.search(r"-?\d+\.?\d*", v)
73
+ if m:
74
+ try:
75
+ val = float(m.group())
76
+ return int(val) if val.is_integer() else val
77
+ except Exception:
78
+ return None
79
+ return None
80
+
81
+ def convert_gender(x):
82
+ # Binary: female -> 0, male -> 1
83
+ v = _after_colon(x).lower()
84
+ # Dataset encodes female=1, male=0; invert to our standard
85
+ if v in {"0", "1"}:
86
+ try:
87
+ num = int(v)
88
+ return 1 if num == 0 else 0 # male(0)->1, female(1)->0
89
+ except Exception:
90
+ pass
91
+ if "male" in v:
92
+ return 1
93
+ if "female" in v:
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 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
+ _ = preview_df(selected_clinical_df)
120
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
121
+ selected_clinical_df.to_csv(out_clinical_data_file)
122
+
123
+ # Step 3: Gene Data Extraction
124
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
125
+ gene_data = get_genetic_data(matrix_file)
126
+
127
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
128
+ print(gene_data.index[:20])
129
+
130
+ # Step 4: Gene Identifier Review
131
+ # Based on the provided gene identifiers (numeric probe-like IDs), these are not human gene symbols.
132
+ requires_gene_mapping = True
133
+ print(f"requires_gene_mapping = {requires_gene_mapping}")
134
+
135
+ # Step 5: Gene Annotation
136
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
137
+ gene_annotation = get_gene_annotation(soft_file)
138
+
139
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
140
+ print("Gene annotation preview:")
141
+ print(preview_df(gene_annotation))
142
+
143
+ # Step 6: Gene Identifier Mapping
144
+ # Decide columns for probe IDs and gene symbols from the annotation dataframe
145
+ probe_id_col = 'ID' if 'ID' in gene_annotation.columns else ('probeset_id' if 'probeset_id' in gene_annotation.columns else None)
146
+ gene_symbol_col = 'gene_assignment' if 'gene_assignment' in gene_annotation.columns else ('mrna_assignment' if 'mrna_assignment' in gene_annotation.columns else None)
147
+
148
+ if probe_id_col is None or gene_symbol_col is None:
149
+ raise ValueError("Required columns for mapping not found in gene annotation.")
150
+
151
+ # 2. Build mapping dataframe
152
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=probe_id_col, gene_col=gene_symbol_col)
153
+
154
+ # 3. Apply mapping to convert probe-level data to gene-level expression
155
+ gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
output/preprocess/Endometriosis/code/GSE145701.py ADDED
@@ -0,0 +1,195 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Endometriosis"
6
+ cohort = "GSE145701"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Endometriosis"
10
+ in_cohort_dir = "../DATA/GEO/Endometriosis/GSE145701"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z3/preprocess/Endometriosis/GSE145701.csv"
14
+ out_gene_data_file = "./output/z3/preprocess/Endometriosis/gene_data/GSE145701.csv"
15
+ out_clinical_data_file = "./output/z3/preprocess/Endometriosis/clinical_data/GSE145701.csv"
16
+ json_path = "./output/z3/preprocess/Endometriosis/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
41
+
42
+ # 1. Gene Expression Data Availability
43
+ # Affymetrix Human Gene 1.0 ST arrays indicate gene expression microarray data.
44
+ is_gene_available = True
45
+
46
+ # 2. Variable Availability and Data Type Conversion
47
+
48
+ # Keys identified from the provided Sample Characteristics Dictionary:
49
+ # 0: gender (but all Female -> constant -> not available)
50
+ # 2: disease state (Normal, Endometriosis Stage I/IV) -> trait
51
+ trait_row: Optional[int] = 2
52
+ age_row: Optional[int] = None
53
+ gender_row: Optional[int] = None
54
+
55
+ def _extract_value(x):
56
+ if x is None:
57
+ return None
58
+ if not isinstance(x, str):
59
+ x = str(x)
60
+ # Split on ':' and take the part after the last colon to be robust
61
+ parts = x.split(':', 1)
62
+ val = parts[1] if len(parts) > 1 else parts[0]
63
+ return val.strip()
64
+
65
+ def convert_trait(x):
66
+ """
67
+ Binary: 0 = control/normal; 1 = endometriosis (any stage).
68
+ Maps disease state strings accordingly.
69
+ """
70
+ val = _extract_value(x)
71
+ if val is None or val == '':
72
+ return None
73
+ low = val.lower()
74
+ # Normal controls
75
+ if 'normal' in low or 'nup' in low:
76
+ return 0
77
+ # Endometriosis (any stage)
78
+ if 'endometriosis' in low:
79
+ return 1
80
+ return None
81
+
82
+ def convert_age(x):
83
+ # Age not available in this dataset
84
+ return None
85
+
86
+ def convert_gender(x):
87
+ """
88
+ Binary gender mapping: female->0, male->1.
89
+ Not used here since gender is constant (all female), but provided for completeness.
90
+ """
91
+ val = _extract_value(x)
92
+ if val is None or val == '':
93
+ return None
94
+ low = val.lower()
95
+ if low in {'female', 'f', 'woman', 'women'}:
96
+ return 0
97
+ if low in {'male', 'm', 'man', 'men'}:
98
+ return 1
99
+ return None
100
+
101
+ # 3. Save Metadata (initial filtering)
102
+ is_trait_available = trait_row is not None
103
+ _ = validate_and_save_cohort_info(
104
+ is_final=False,
105
+ cohort=cohort,
106
+ info_path=json_path,
107
+ is_gene_available=is_gene_available,
108
+ is_trait_available=is_trait_available
109
+ )
110
+
111
+ # 4. Clinical Feature Extraction (only if trait_row is available)
112
+ if trait_row is not None:
113
+ selected_clinical_df = geo_select_clinical_features(
114
+ clinical_df=clinical_data,
115
+ trait=trait,
116
+ trait_row=trait_row,
117
+ convert_trait=convert_trait,
118
+ age_row=age_row,
119
+ convert_age=convert_age,
120
+ gender_row=gender_row,
121
+ convert_gender=convert_gender
122
+ )
123
+ preview = preview_df(selected_clinical_df)
124
+ print("Clinical features preview:", preview)
125
+
126
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
127
+ # Preserve index to keep feature names
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
+ # The observed identifiers (e.g., '7892501') are numeric probe IDs (e.g., Illumina), not human gene symbols.
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 for probe IDs and gene symbols in the annotation
152
+ id_col = 'ID' if 'ID' in gene_annotation.columns else gene_annotation.columns[0]
153
+ gene_symbol_col_candidates = ['gene_assignment', 'mrna_assignment', 'GB_LIST']
154
+ gene_col = next((c for c in gene_symbol_col_candidates if c in gene_annotation.columns), None)
155
+ if gene_col is None:
156
+ raise ValueError("No suitable gene symbol column found in gene_annotation.")
157
+
158
+ # Build the mapping dataframe (probe ID -> gene annotation text)
159
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=id_col, gene_col=gene_col)
160
+
161
+ # Apply mapping to convert probe-level data to gene-level data
162
+ # Preserve original probe-level data, then overwrite gene_data with gene-level expression as required
163
+ probe_level_df = gene_data
164
+ gene_data = apply_gene_mapping(probe_level_df, mapping_df)
165
+
166
+ # Step 7: Data Normalization and Linking
167
+ import os
168
+
169
+ # 1. Normalize gene symbols and save gene data
170
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
171
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
172
+ normalized_gene_data.to_csv(out_gene_data_file)
173
+
174
+ # 2. Link clinical and genetic data (use the correct variable name from Step 2)
175
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
176
+
177
+ # Optional sanity check
178
+ print("Normalized gene data shape:", normalized_gene_data.shape)
179
+ print("Linked data shape before missing handling:", linked_data.shape)
180
+
181
+ # 3. Handle missing values in the linked data
182
+ linked_data = handle_missing_values(linked_data, trait)
183
+
184
+ # 4. Determine bias and remove biased demographic features
185
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
186
+
187
+ # 5. Final quality validation and saving cohort info
188
+ is_usable = validate_and_save_cohort_info(
189
+ True, cohort, json_path, True, True, is_trait_biased, unbiased_linked_data
190
+ )
191
+
192
+ # 6. Conditionally save linked data
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/Endometriosis/code/GSE145702.py ADDED
@@ -0,0 +1,197 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Endometriosis"
6
+ cohort = "GSE145702"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Endometriosis"
10
+ in_cohort_dir = "../DATA/GEO/Endometriosis/GSE145702"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z3/preprocess/Endometriosis/GSE145702.csv"
14
+ out_gene_data_file = "./output/z3/preprocess/Endometriosis/gene_data/GSE145702.csv"
15
+ out_clinical_data_file = "./output/z3/preprocess/Endometriosis/clinical_data/GSE145702.csv"
16
+ json_path = "./output/z3/preprocess/Endometriosis/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ # Step 1: Determine gene expression availability
40
+ is_gene_available = True # Based on series context indicating gene transcription; not miRNA-only or methylation-only.
41
+
42
+ # Step 2: Variable availability and conversion functions
43
+ # Sample Characteristics Dictionary suggests:
44
+ # - trait (Endometriosis) at row 2: ['disease state: Normal', 'disease state: Endometriosis Stage I', 'disease state: Endometriosis Stage IV']
45
+ # - age: not available
46
+ # - gender: only 'Female' => constant, treat as unavailable
47
+
48
+ trait_row = 2
49
+ age_row = None
50
+ gender_row = None
51
+
52
+ def _extract_value(x):
53
+ if x is None:
54
+ return None
55
+ s = str(x)
56
+ if ':' in s:
57
+ s = s.split(':', 1)[1]
58
+ return s.strip()
59
+
60
+ def convert_trait(x):
61
+ v = _extract_value(x)
62
+ if v is None or v == '':
63
+ return None
64
+ vl = v.lower()
65
+ # Heuristic: any mention of endometriosis indicates case; normal/control indicates control
66
+ if 'normal' in vl or 'control' in vl:
67
+ return 0
68
+ if 'endometriosis' in vl or 'endo' in vl:
69
+ return 1
70
+ return None
71
+
72
+ def convert_age(x):
73
+ v = _extract_value(x)
74
+ if v is None or v == '':
75
+ return None
76
+ # Extract first numeric value as age (e.g., "35 years")
77
+ try:
78
+ import re
79
+ m = re.search(r'(\d+(\.\d+)?)', v)
80
+ return float(m.group(1)) if m else None
81
+ except Exception:
82
+ return None
83
+
84
+ def convert_gender(x):
85
+ v = _extract_value(x)
86
+ if v is None or v == '':
87
+ return None
88
+ vl = v.lower()
89
+ if vl.startswith('f'):
90
+ return 0
91
+ if vl.startswith('m'):
92
+ return 1
93
+ return None
94
+
95
+ # Step 3: Initial filtering metadata save
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
+ # Step 4: Clinical feature extraction (only if trait is available)
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=None,
114
+ gender_row=gender_row,
115
+ convert_gender=None
116
+ )
117
+ preview = preview_df(selected_clinical_df)
118
+ print(preview)
119
+
120
+ import os
121
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
122
+ selected_clinical_df.to_csv(out_clinical_data_file)
123
+
124
+ # Step 3: Gene Data Extraction
125
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
126
+ gene_data = get_genetic_data(matrix_file)
127
+
128
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
129
+ print(gene_data.index[:20])
130
+
131
+ # Step 4: Gene Identifier Review
132
+ print("requires_gene_mapping = True")
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
+ # Map probe IDs to gene symbols and convert probe-level data to gene-level data
144
+
145
+ # 1. Decide columns: probe identifiers are in 'ID' and gene symbols info is in 'gene_assignment'
146
+ probe_col = 'ID'
147
+ gene_col = 'gene_assignment'
148
+
149
+ # 2. Build mapping dataframe from annotation
150
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=probe_col, gene_col=gene_col)
151
+
152
+ # 3. Apply mapping to convert probe-level expression to gene-level expression
153
+ probe_data = gene_data # preserve original probe-level data
154
+ gene_data = apply_gene_mapping(expression_df=probe_data, mapping_df=mapping_df)
155
+
156
+ # Step 7: Data Normalization and Linking
157
+ import os
158
+
159
+ # Ensure we have the clinical features in memory; otherwise load from the saved CSV
160
+ try:
161
+ selected_clinical_df
162
+ except NameError:
163
+ selected_clinical_df = pd.read_csv(out_clinical_data_file, index_col=0)
164
+
165
+ # 1. Normalize gene symbols and save
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
+ # 2. Link clinical and genetic data
171
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
172
+
173
+ # 3. Handle missing values
174
+ linked_data = handle_missing_values(linked_data, trait)
175
+
176
+ # 4. Bias checking and removal of biased demographic features
177
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
178
+
179
+ # 5. Final validation and save cohort info
180
+ note = ("INFO: Gender effectively constant female and Age unavailable in this cohort. "
181
+ "Samples are eutopic endometrial stromal fibroblasts with hormone treatments; "
182
+ "trait derived from 'disease state'.")
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/Endometriosis/code/GSE165004.py ADDED
@@ -0,0 +1,148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Endometriosis"
6
+ cohort = "GSE165004"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Endometriosis"
10
+ in_cohort_dir = "../DATA/GEO/Endometriosis/GSE165004"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z3/preprocess/Endometriosis/GSE165004.csv"
14
+ out_gene_data_file = "./output/z3/preprocess/Endometriosis/gene_data/GSE165004.csv"
15
+ out_clinical_data_file = "./output/z3/preprocess/Endometriosis/clinical_data/GSE165004.csv"
16
+ json_path = "./output/z3/preprocess/Endometriosis/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 (RNA expression study -> likely gene expression data)
42
+ is_gene_available = True
43
+
44
+ # 2) Variable availability and converters
45
+ # Based on sample characteristics:
46
+ # {0: ['subject status/group: Control', 'subject status/group: patient with RPL', 'subject status/group: patient with UIF'],
47
+ # 1: ['tissue: Endometrial tissue']}
48
+ # No endometriosis group; study explicitly excluded endometriosis -> trait would be constant negative. No age/gender fields listed.
49
+ trait_row = None # Constantly absent for Endometriosis in this cohort
50
+ age_row = None # Not provided
51
+ gender_row = None # Not provided (all participants are women; constant feature and not explicitly recorded)
52
+
53
+ def _after_colon(x: str) -> str:
54
+ if x is None:
55
+ return ""
56
+ s = str(x)
57
+ parts = s.split(":", 1)
58
+ return parts[1].strip() if len(parts) == 2 else s.strip()
59
+
60
+ def convert_trait(x):
61
+ # Binary: Endometriosis present (1) vs. absent (0)
62
+ val = _after_colon(x).lower()
63
+ if not val:
64
+ return None
65
+ # Positive if explicit endometriosis present
66
+ if "endometriosis" in val or "endometriotic" in val:
67
+ return 1
68
+ # Negative if clearly a non-endometriosis cohort label
69
+ if any(k in val for k in ["control", "rpl", "recurrent pregnancy loss", "uif", "ui", "unexplained infertility"]):
70
+ return 0
71
+ # If the string is clearly unrelated metadata (e.g., tissue), return None
72
+ if any(k in val for k in ["tissue", "endometrial tissue"]):
73
+ return None
74
+ return None
75
+
76
+ def convert_age(x):
77
+ # Continuous: extract numeric age if present
78
+ val = _after_colon(x)
79
+ if not val:
80
+ return None
81
+ m = re.search(r"[-+]?\d*\.?\d+", val)
82
+ return float(m.group()) if m else None
83
+
84
+ def convert_gender(x):
85
+ # Binary: female=0, male=1
86
+ val = _after_colon(x).lower()
87
+ if not val:
88
+ return None
89
+ if "female" in val or val == "f":
90
+ return 0
91
+ if "male" in val or val == "m":
92
+ return 1
93
+ return None
94
+
95
+ # 3) Save metadata with 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 (skip because trait_row is None)
106
+ if trait_row is not None and 'clinical_data' in globals():
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
+ _ = preview_df(selected_clinical_df)
118
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
119
+ selected_clinical_df.to_csv(out_clinical_data_file, index=False)
120
+
121
+ # Step 3: Gene Data Extraction
122
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
123
+ gene_data = get_genetic_data(matrix_file)
124
+
125
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
126
+ print(gene_data.index[:20])
127
+
128
+ # Step 4: Gene Identifier Review
129
+ print("requires_gene_mapping = True")
130
+
131
+ # Step 5: Gene Annotation
132
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
133
+ gene_annotation = get_gene_annotation(soft_file)
134
+
135
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
136
+ print("Gene annotation preview:")
137
+ print(preview_df(gene_annotation))
138
+
139
+ # Step 6: Gene Identifier Mapping
140
+ # Determine the appropriate columns for mapping: probe IDs and gene symbols
141
+ probe_col = 'ID'
142
+ gene_symbol_col = 'GENE_SYMBOL'
143
+
144
+ # 2. Create the mapping dataframe from annotation
145
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=probe_col, gene_col=gene_symbol_col)
146
+
147
+ # 3. Apply the mapping to convert probe-level data to gene-level expression
148
+ gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
output/preprocess/Endometriosis/code/GSE37837.py ADDED
@@ -0,0 +1,169 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Endometriosis"
6
+ cohort = "GSE37837"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Endometriosis"
10
+ in_cohort_dir = "../DATA/GEO/Endometriosis/GSE37837"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z3/preprocess/Endometriosis/GSE37837.csv"
14
+ out_gene_data_file = "./output/z3/preprocess/Endometriosis/gene_data/GSE37837.csv"
15
+ out_clinical_data_file = "./output/z3/preprocess/Endometriosis/clinical_data/GSE37837.csv"
16
+ json_path = "./output/z3/preprocess/Endometriosis/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 # Agilent whole human genome oligo microarray => gene expression data
43
+
44
+ # 2. Variable Availability and Data Type Conversion
45
+
46
+ # Trait: Endometriosis - all subjects are endometriosis patients; no controls => not available
47
+ trait_row = None
48
+
49
+ # Age: available at key 0
50
+ age_row = 0
51
+
52
+ # Gender: only "female (fertile)" => constant => not available
53
+ gender_row = None
54
+
55
+ def _after_colon(s: str) -> str:
56
+ if s is None:
57
+ return ""
58
+ parts = str(s).split(":", 1)
59
+ return parts[1].strip() if len(parts) == 2 else str(s).strip()
60
+
61
+ def convert_trait(x):
62
+ v = _after_colon(x).lower()
63
+ if not v:
64
+ return None
65
+ # Generic heuristics (not used here since trait_row is None)
66
+ if any(k in v for k in ["control", "healthy", "normal", "no endometriosis"]):
67
+ return 0
68
+ if any(k in v for k in ["endometriosis", "endometrioma", "case", "patient"]):
69
+ return 1
70
+ return None
71
+
72
+ def convert_age(x):
73
+ v = _after_colon(x)
74
+ if not v:
75
+ return None
76
+ nums = re.findall(r"[-+]?\d*\.?\d+", v)
77
+ if not nums:
78
+ return None
79
+ try:
80
+ return float(nums[0])
81
+ except Exception:
82
+ return None
83
+
84
+ def convert_gender(x):
85
+ v = _after_colon(x).lower()
86
+ if not v:
87
+ return None
88
+ if "female" in v or v == "f":
89
+ return 0
90
+ if "male" in v 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 (skip because trait_row is None)
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
+ selected_clinical_df.to_csv(out_clinical_data_file, index=True)
118
+
119
+ # Step 3: Gene Data Extraction
120
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
121
+ gene_data = get_genetic_data(matrix_file)
122
+
123
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
124
+ print(gene_data.index[:20])
125
+
126
+ # Step 4: Gene Identifier Review
127
+ requires_gene_mapping = True
128
+ print(f"requires_gene_mapping = {requires_gene_mapping}")
129
+
130
+ # Step 5: Gene Annotation
131
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
132
+ gene_annotation = get_gene_annotation(soft_file)
133
+
134
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
135
+ print("Gene annotation preview:")
136
+ print(preview_df(gene_annotation))
137
+
138
+ # Step 6: Gene Identifier Mapping
139
+ # 1-2. Decide identifier and gene symbol columns, and create mapping dataframe
140
+ probe_col = 'ID' # Matches probe identifiers like 'A_23_P100001' in gene_data index
141
+ gene_symbol_col = 'GENE_SYMBOL' # Contains human gene symbols
142
+
143
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=probe_col, gene_col=gene_symbol_col)
144
+
145
+ # 3. Apply mapping to convert probe-level data to gene-level expression
146
+ gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
147
+
148
+ # Step 7: Data Normalization and Linking
149
+ # 1. Normalize the obtained gene data and save
150
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
151
+ normalized_gene_data.to_csv(out_gene_data_file)
152
+
153
+ # Since trait data is unavailable for this cohort (Step 2), skip linking and downstream steps.
154
+ is_trait_available = False
155
+ note = "WARNING: Trait not available (all subjects are endometriosis patients; no control/trait labels)."
156
+
157
+ # 5. Final metadata logging. Pass gene data (transposed) just to avoid abnormality override.
158
+ is_usable = validate_and_save_cohort_info(
159
+ is_final=True,
160
+ cohort=cohort,
161
+ info_path=json_path,
162
+ is_gene_available=True,
163
+ is_trait_available=is_trait_available,
164
+ is_biased=False,
165
+ df=normalized_gene_data.T,
166
+ note=note
167
+ )
168
+
169
+ # 6. Do not save linked data since trait is unavailable and dataset is not usable for association analysis.
output/preprocess/Endometriosis/code/GSE51981.py ADDED
@@ -0,0 +1,193 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Endometriosis"
6
+ cohort = "GSE51981"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Endometriosis"
10
+ in_cohort_dir = "../DATA/GEO/Endometriosis/GSE51981"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z3/preprocess/Endometriosis/GSE51981.csv"
14
+ out_gene_data_file = "./output/z3/preprocess/Endometriosis/gene_data/GSE51981.csv"
15
+ out_clinical_data_file = "./output/z3/preprocess/Endometriosis/clinical_data/GSE51981.csv"
16
+ json_path = "./output/z3/preprocess/Endometriosis/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ # Step 1: Determine gene expression data availability based on series design
40
+ is_gene_available = True # Whole genome microarrays indicate gene expression data
41
+
42
+ # Step 2: Variable availability and conversion functions
43
+ # From the Sample Characteristics Dictionary:
44
+ # - Trait (Endometriosis status) is at key 1 with values "Endometriosis" vs "Non-Endometriosis"
45
+ trait_row = 1
46
+
47
+ # Age and Gender are not present; study population is women and likely constant/absent in metadata here.
48
+ age_row = None
49
+ gender_row = None
50
+
51
+ def _extract_value(x):
52
+ if x is None:
53
+ return None
54
+ if isinstance(x, str):
55
+ parts = x.split(":", 1)
56
+ return parts[1].strip() if len(parts) == 2 else x.strip()
57
+ return x
58
+
59
+ def convert_trait(x):
60
+ val = _extract_value(x)
61
+ if val is None:
62
+ return None
63
+ s = str(val).strip().lower()
64
+ # Map common representations to binary
65
+ if s in {"endometriosis", "endo", "case", "yes", "y", "1"}:
66
+ return 1
67
+ if s in {"non-endometriosis", "no endometriosis", "control", "no", "n", "0"}:
68
+ return 0
69
+ return None
70
+
71
+ def convert_age(x):
72
+ # Not used (age_row is None), but provided for completeness
73
+ val = _extract_value(x)
74
+ if val is None:
75
+ return None
76
+ s = str(val).lower()
77
+ # Extract first numeric token as age
78
+ import re
79
+ m = re.search(r"(\d+(\.\d+)?)", s)
80
+ if m:
81
+ try:
82
+ return float(m.group(1))
83
+ except Exception:
84
+ return None
85
+ return None
86
+
87
+ def convert_gender(x):
88
+ # Not used (gender_row is None), but provided for completeness
89
+ val = _extract_value(x)
90
+ if val is None:
91
+ return None
92
+ s = str(val).strip().lower()
93
+ if s in {"female", "f", "woman", "women"}:
94
+ return 0
95
+ if s in {"male", "m", "man", "men"}:
96
+ return 1
97
+ return None
98
+
99
+ # Step 3: Save initial metadata (initial filtering)
100
+ is_trait_available = trait_row is not None
101
+ _ = validate_and_save_cohort_info(
102
+ is_final=False,
103
+ cohort=cohort,
104
+ info_path=json_path,
105
+ is_gene_available=is_gene_available,
106
+ is_trait_available=is_trait_available
107
+ )
108
+
109
+ # Step 4: Clinical feature extraction (only if trait data is available)
110
+ if trait_row is not None:
111
+ selected_clinical_df = geo_select_clinical_features(
112
+ clinical_df=clinical_data,
113
+ trait=trait,
114
+ trait_row=trait_row,
115
+ convert_trait=convert_trait,
116
+ age_row=age_row,
117
+ convert_age=convert_age,
118
+ gender_row=gender_row,
119
+ convert_gender=convert_gender
120
+ )
121
+ preview = preview_df(selected_clinical_df, n=5)
122
+ print("Preview of selected clinical features:", preview)
123
+
124
+ # Save clinical features
125
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
126
+ selected_clinical_df.to_csv(out_clinical_data_file)
127
+
128
+ # Step 3: Gene Data Extraction
129
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
130
+ gene_data = get_genetic_data(matrix_file)
131
+
132
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
133
+ print(gene_data.index[:20])
134
+
135
+ # Step 4: Gene Identifier Review
136
+ requires_gene_mapping = True
137
+ print(f"requires_gene_mapping = {requires_gene_mapping}")
138
+
139
+ # Step 5: Gene Annotation
140
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
141
+ gene_annotation = get_gene_annotation(soft_file)
142
+
143
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
144
+ print("Gene annotation preview:")
145
+ print(preview_df(gene_annotation))
146
+
147
+ # Step 6: Gene Identifier Mapping
148
+ # Decide the appropriate columns for probe IDs and gene symbols based on the preview:
149
+ # Probe ID column: "ID"
150
+ # Gene symbol column: "Gene Symbol"
151
+
152
+ # 2. Get mapping dataframe
153
+ mapping_df = get_gene_mapping(gene_annotation, prob_col="ID", gene_col="Gene Symbol")
154
+
155
+ # 3. Apply mapping to convert probe-level data to gene-level expression
156
+ gene_data = apply_gene_mapping(gene_data, mapping_df)
157
+
158
+ # Step 7: Data Normalization and Linking
159
+ # 1. Normalize the obtained gene data and save
160
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
161
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
162
+ normalized_gene_data.to_csv(out_gene_data_file)
163
+
164
+ # Ensure clinical dataframe is available (fallback to loading from saved CSV if needed)
165
+ try:
166
+ selected_clinical_df # noqa: F401
167
+ except NameError:
168
+ selected_clinical_df = pd.read_csv(out_clinical_data_file, index_col=0)
169
+
170
+ # 2. Link the clinical and genetic data
171
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
172
+
173
+ # 3. Handle missing values in the linked data
174
+ linked_data = handle_missing_values(linked_data, trait)
175
+
176
+ # 4. Determine whether the trait and demographic features are severely biased, and remove biased features.
177
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
178
+
179
+ # 5. Conduct quality check and save the cohort information.
180
+ note = (
181
+ f"INFO: Probes mapped to gene symbols and normalized by NCBI synonyms. "
182
+ f"Age and Gender unavailable in clinical data. "
183
+ f"Linked samples: {len(unbiased_linked_data)}; "
184
+ f"Features (incl. trait): {len(unbiased_linked_data.columns)}."
185
+ )
186
+ is_usable = validate_and_save_cohort_info(
187
+ True, cohort, json_path, True, True, is_trait_biased, unbiased_linked_data, note
188
+ )
189
+
190
+ # 6. If the linked data is usable, save it
191
+ if is_usable:
192
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
193
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Endometriosis/code/GSE73622.py ADDED
@@ -0,0 +1,244 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Endometriosis"
6
+ cohort = "GSE73622"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Endometriosis"
10
+ in_cohort_dir = "../DATA/GEO/Endometriosis/GSE73622"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z3/preprocess/Endometriosis/GSE73622.csv"
14
+ out_gene_data_file = "./output/z3/preprocess/Endometriosis/gene_data/GSE73622.csv"
15
+ out_clinical_data_file = "./output/z3/preprocess/Endometriosis/clinical_data/GSE73622.csv"
16
+ json_path = "./output/z3/preprocess/Endometriosis/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 # Transcriptome analysis indicates mRNA gene expression data
45
+
46
+ # 2) Variable availability
47
+ trait_row = 0 # disease: No Endometriosis / Endometriosis
48
+ age_row = 3 # age: numbers
49
+ gender_row = None # Endometrial tissue from women; gender is constant (female) and not explicitly recorded -> not available
50
+
51
+ # 2.2) Converters
52
+ def _after_colon(value):
53
+ if value is None:
54
+ return None
55
+ s = str(value)
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(value):
61
+ v = _after_colon(value)
62
+ if v is None:
63
+ return None
64
+ vl = v.strip().lower()
65
+ # Positive cases
66
+ if vl in {"endometriosis", "case"} or ("endo" in vl and "no" not in vl):
67
+ return 1
68
+ # Controls/negatives
69
+ if vl in {"no endometriosis", "control"} or ("no" in vl and "endometriosis" in vl):
70
+ return 0
71
+ return None
72
+
73
+ def convert_age(value):
74
+ v = _after_colon(value)
75
+ if v is None:
76
+ return None
77
+ # Extract first integer/float in the string
78
+ m = re.search(r"[-+]?\d*\.?\d+", v)
79
+ if not m:
80
+ return None
81
+ try:
82
+ num = float(m.group())
83
+ return num
84
+ except Exception:
85
+ return None
86
+
87
+ def convert_gender(value):
88
+ v = _after_colon(value)
89
+ if v is None:
90
+ return None
91
+ vl = v.strip().lower()
92
+ # Female -> 0, Male -> 1
93
+ if vl in {"female", "f", "woman", "women"}:
94
+ return 0
95
+ if vl in {"male", "m", "man", "men"}:
96
+ return 1
97
+ return None
98
+
99
+ # 3) Save metadata (initial filtering)
100
+ is_trait_available = trait_row is not None
101
+ _ = validate_and_save_cohort_info(
102
+ is_final=False,
103
+ cohort=cohort,
104
+ info_path=json_path,
105
+ is_gene_available=is_gene_available,
106
+ is_trait_available=is_trait_available
107
+ )
108
+
109
+ # 4) Clinical feature extraction (only if trait_row is available)
110
+ if trait_row is not None:
111
+ selected_clinical_df = geo_select_clinical_features(
112
+ clinical_df=clinical_data,
113
+ trait=trait,
114
+ trait_row=trait_row,
115
+ convert_trait=convert_trait,
116
+ age_row=age_row,
117
+ convert_age=convert_age,
118
+ gender_row=gender_row,
119
+ convert_gender=convert_gender if gender_row is not None else None
120
+ )
121
+ preview = preview_df(selected_clinical_df)
122
+ print(preview)
123
+
124
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
125
+ selected_clinical_df.to_csv(out_clinical_data_file, index=False)
126
+
127
+ # Step 3: Gene Data Extraction
128
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
129
+ gene_data = get_genetic_data(matrix_file)
130
+
131
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
132
+ print(gene_data.index[:20])
133
+
134
+ # Step 4: Gene Identifier Review
135
+ import os
136
+ import re
137
+ import pandas as pd
138
+
139
+ def is_symbol_like(s: str) -> bool:
140
+ # Heuristics: human gene symbols are typically alphanumeric with letters, may include '-' or '.',
141
+ # rarely include underscores, and are not purely numeric. Exclude common non-symbol prefixes.
142
+ s = s.strip()
143
+ if not s or s.isdigit():
144
+ return False
145
+ if "_" in s:
146
+ return False
147
+ if any(s.upper().startswith(p) for p in ["ENSG", "ENST", "NM_", "XM_", "NR_", "ILMN", "AFFX", "A_"]):
148
+ return False
149
+ return bool(re.match(r"^[A-Za-z][A-Za-z0-9\-.]{1,}$", s))
150
+
151
+ requires_gene_mapping = True # default to conservative choice
152
+
153
+ if os.path.exists(out_gene_data_file):
154
+ try:
155
+ gdf = pd.read_csv(out_gene_data_file, index_col=0)
156
+ ids = gdf.index.astype(str).tolist()
157
+ sample_ids = ids[: min(200, len(ids))]
158
+ if sample_ids:
159
+ symbol_like_count = sum(is_symbol_like(x) for x in sample_ids)
160
+ digit_only_count = sum(x.isdigit() for x in sample_ids)
161
+ # Decide based on majority pattern
162
+ if symbol_like_count / len(sample_ids) >= 0.6:
163
+ requires_gene_mapping = False
164
+ elif digit_only_count / len(sample_ids) >= 0.6:
165
+ requires_gene_mapping = True
166
+ else:
167
+ # If mixed, require mapping to ensure consistency
168
+ requires_gene_mapping = True
169
+ except Exception:
170
+ # If reading fails, keep conservative default
171
+ requires_gene_mapping = True
172
+
173
+ print(f"requires_gene_mapping = {str(requires_gene_mapping)}")
174
+
175
+ # Step 5: Gene Annotation
176
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
177
+ gene_annotation = get_gene_annotation(soft_file)
178
+
179
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
180
+ print("Gene annotation preview:")
181
+ print(preview_df(gene_annotation))
182
+
183
+ # Step 6: Gene Identifier Mapping
184
+ # Decide columns for mapping based on annotation preview:
185
+ # - Probe/ID column: 'ID' (matches numeric probe IDs seen in gene_data index)
186
+ # - Gene symbol information: 'gene_assignment' (contains gene symbols in the annotation text)
187
+
188
+ gene_col = 'gene_assignment' if 'gene_assignment' in gene_annotation.columns else 'mrna_assignment'
189
+
190
+ # Build mapping dataframe
191
+ mapping_df = get_gene_mapping(gene_annotation, prob_col='ID', gene_col=gene_col)
192
+
193
+ # Apply mapping to convert probe-level data to gene-level data
194
+ gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
195
+
196
+ # Step 7: Data Normalization and Linking
197
+ import os
198
+ import pandas as pd
199
+
200
+ # 1. Normalize the obtained gene data and save
201
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
202
+ pre_norm_gene_count = gene_data.shape[0] if isinstance(gene_data, pd.DataFrame) else 0
203
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
204
+ normalized_gene_data.to_csv(out_gene_data_file)
205
+
206
+ # 2. Link the clinical and genetic data
207
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
208
+
209
+ # 3. Handle missing values in the linked data
210
+ linked_data = handle_missing_values(linked_data, trait)
211
+
212
+ # 4. Determine whether the trait and some demographic features are severely biased, and remove biased features
213
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
214
+ is_trait_biased = bool(is_trait_biased)
215
+
216
+ # Flags for final validation (ensure native Python bools)
217
+ is_gene_available_flag = bool(normalized_gene_data.shape[0] > 0)
218
+ is_trait_available_flag = bool((trait in selected_clinical_df.index) and bool(selected_clinical_df.loc[trait].notna().any()))
219
+
220
+ # Prepare note
221
+ note = (
222
+ f"INFO: Probes mapped to genes. Genes before normalization: {int(pre_norm_gene_count)}, "
223
+ f"after normalization: {int(normalized_gene_data.shape[0])}. "
224
+ f"Samples before filtering: {int(selected_clinical_df.shape[1])}, "
225
+ f"after filtering: {int(unbiased_linked_data.shape[0])}. "
226
+ f"Gender not available (all female)."
227
+ )
228
+
229
+ # 5. Conduct quality check and save the cohort information
230
+ is_usable = validate_and_save_cohort_info(
231
+ is_final=True,
232
+ cohort=cohort,
233
+ info_path=json_path,
234
+ is_gene_available=is_gene_available_flag,
235
+ is_trait_available=is_trait_available_flag,
236
+ is_biased=is_trait_biased,
237
+ df=unbiased_linked_data,
238
+ note=note
239
+ )
240
+
241
+ # 6. If the linked data is usable, save it as a CSV file
242
+ if is_usable:
243
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
244
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Endometriosis/code/GSE75427.py ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Endometriosis"
6
+ cohort = "GSE75427"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Endometriosis"
10
+ in_cohort_dir = "../DATA/GEO/Endometriosis/GSE75427"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z3/preprocess/Endometriosis/GSE75427.csv"
14
+ out_gene_data_file = "./output/z3/preprocess/Endometriosis/gene_data/GSE75427.csv"
15
+ out_clinical_data_file = "./output/z3/preprocess/Endometriosis/clinical_data/GSE75427.csv"
16
+ json_path = "./output/z3/preprocess/Endometriosis/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 (from series title: "Expression profiles ...")
44
+ is_gene_available = True
45
+
46
+ # 2) Variable availability and converters inferred from the sample characteristics dictionary shown:
47
+ # {0: ['cell type: proliferative phase normal endometrium'],
48
+ # 1: ['gender: Female'],
49
+ # 2: ['age: 37y', 'age: 47y', 'age: 53y', 'age: 41y'],
50
+ # 3: ['treatment: 12d 10% charcoal-stripped heat-inactivated FBS', 'treatment: 12d dibutyryl-cAMP and dienogest']}
51
+
52
+ # - Trait (Endometriosis): Only "cell type: proliferative phase normal endometrium" is present -> constant -> not available.
53
+ trait_row = None
54
+
55
+ # - Age: multiple values available under key 2.
56
+ age_row = 2
57
+
58
+ # - Gender: only 'Female' under key 1 -> constant -> not available.
59
+ gender_row = None
60
+
61
+ def _after_colon(x: str) -> str:
62
+ if x is None:
63
+ return ""
64
+ # handle values that may not contain a colon
65
+ parts = str(x).split(":", 1)
66
+ return parts[1].strip() if len(parts) == 2 else str(x).strip()
67
+
68
+ # 2.2 Converters
69
+ def convert_trait(x):
70
+ # Binary: case (Endometriosis) = 1, control = 0
71
+ v = _after_colon(x).lower()
72
+ if not v:
73
+ return None
74
+ # Heuristics for case vs control
75
+ case_markers = ["endometriosis", "endometriotic", "ecsc", "ectopic", "lesion", "ovarian endometrioma"]
76
+ control_markers = ["normal", "nesc", "control", "healthy", "non-endometriosis", "euploid"]
77
+ if any(m in v for m in case_markers):
78
+ return 1
79
+ if any(m in v for m in control_markers):
80
+ return 0
81
+ return None
82
+
83
+ def convert_age(x):
84
+ # Continuous: years
85
+ v = _after_colon(x)
86
+ if not v:
87
+ return None
88
+ # extract first number (int or float)
89
+ m = re.search(r"(\d+(\.\d+)?)", v)
90
+ if not m:
91
+ return None
92
+ try:
93
+ val = float(m.group(1))
94
+ return val
95
+ except Exception:
96
+ return None
97
+
98
+ def convert_gender(x):
99
+ # Binary: female -> 0, male -> 1
100
+ v = _after_colon(x).lower()
101
+ if not v:
102
+ return None
103
+ if v in ["f", "female"]:
104
+ return 0
105
+ if v in ["m", "male"]:
106
+ return 1
107
+ return None
108
+
109
+ # 3) Save metadata (initial filtering)
110
+ is_trait_available = trait_row is not None
111
+ _ = validate_and_save_cohort_info(
112
+ is_final=False,
113
+ cohort=cohort,
114
+ info_path=json_path,
115
+ is_gene_available=is_gene_available,
116
+ is_trait_available=is_trait_available
117
+ )
118
+
119
+ # 4) Clinical feature extraction (skip if trait not available)
120
+ if trait_row is not None:
121
+ selected_clinical_df = geo_select_clinical_features(
122
+ clinical_df=clinical_data,
123
+ trait=trait,
124
+ trait_row=trait_row,
125
+ convert_trait=convert_trait,
126
+ age_row=age_row,
127
+ convert_age=convert_age,
128
+ gender_row=gender_row,
129
+ convert_gender=convert_gender
130
+ )
131
+ clinical_preview = preview_df(selected_clinical_df, n=5)
132
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
133
+ selected_clinical_df.to_csv(out_clinical_data_file)
output/preprocess/Endometriosis/code/TCGA.py ADDED
@@ -0,0 +1,337 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Endometriosis"
6
+
7
+ # Input paths
8
+ tcga_root_dir = "../DATA/TCGA"
9
+
10
+ # Output paths
11
+ out_data_file = "./output/z3/preprocess/Endometriosis/TCGA.csv"
12
+ out_gene_data_file = "./output/z3/preprocess/Endometriosis/gene_data/TCGA.csv"
13
+ out_clinical_data_file = "./output/z3/preprocess/Endometriosis/clinical_data/TCGA.csv"
14
+ json_path = "./output/z3/preprocess/Endometriosis/cohort_info.json"
15
+
16
+
17
+ # Step 1: Initial Data Loading
18
+ import os
19
+ import pandas as pd
20
+
21
+ # List available TCGA subdirectories
22
+ subdirs = [d for d in os.listdir(tcga_root_dir) if os.path.isdir(os.path.join(tcga_root_dir, d))]
23
+
24
+ # Scoring-based selection for directories related to Endometriosis
25
+ keywords = [
26
+ ("endometrioid", 5),
27
+ ("endometri", 4),
28
+ ("endometrial", 3),
29
+ ("uterine", 2),
30
+ ("ovarian", 2),
31
+ ("ovary", 2),
32
+ ]
33
+ best_dir = None
34
+ best_score = 0
35
+ for d in subdirs:
36
+ name = d.lower()
37
+ score = sum(weight for kw, weight in keywords if kw in name)
38
+ if score > best_score:
39
+ best_score = score
40
+ best_dir = d
41
+
42
+ if best_dir is None or best_score == 0:
43
+ # No suitable directory found; record and stop further processing
44
+ print("No suitable TCGA cohort directory found for the trait. Skipping.")
45
+ validate_and_save_cohort_info(
46
+ is_final=False,
47
+ cohort="TCGA",
48
+ info_path=json_path,
49
+ is_gene_available=False,
50
+ is_trait_available=False
51
+ )
52
+ else:
53
+ print(f"Selected TCGA cohort directory: {best_dir}")
54
+ cohort_dir = os.path.join(tcga_root_dir, best_dir)
55
+
56
+ # Identify clinical and genetic files
57
+ clinical_fp, genetic_fp = tcga_get_relevant_filepaths(cohort_dir)
58
+ print(f"Clinical file: {clinical_fp}")
59
+ print(f"Genetic file: {genetic_fp}")
60
+
61
+ # Load data
62
+ clinical_df = pd.read_csv(clinical_fp, sep='\t', index_col=0, low_memory=False)
63
+ genetic_df = pd.read_csv(genetic_fp, sep='\t', index_col=0, low_memory=False)
64
+
65
+ # Print clinical column names for further analysis
66
+ print(list(clinical_df.columns))
67
+
68
+ # Step 2: Find Candidate Demographic Features
69
+ import os
70
+ import re
71
+ import pandas as pd
72
+
73
+ # Locate clinical file
74
+ cohort_dir = os.path.join(tcga_root_dir, "TCGA_Endometrioid_Cancer_(UCEC)")
75
+ clinical_file_path, _ = tcga_get_relevant_filepaths(cohort_dir)
76
+
77
+ # Load clinical DataFrame
78
+ try:
79
+ clinical_df = pd.read_csv(clinical_file_path, sep="\t", index_col=0, dtype=str)
80
+ except Exception:
81
+ clinical_df = pd.read_csv(clinical_file_path, sep=",", index_col=0, dtype=str)
82
+
83
+ def token_match(s: str, token: str) -> bool:
84
+ # Match token as a standalone word or underscore-separated token
85
+ return re.search(rf'(?<![A-Za-z0-9]){re.escape(token)}(?![A-Za-z0-9])', s) is not None
86
+
87
+ candidate_age_cols = []
88
+ candidate_gender_cols = []
89
+
90
+ for c in clinical_df.columns:
91
+ cl = c.lower()
92
+ # Age candidates: 'age' as a token, plus specific whitelist like 'days_to_birth'
93
+ if token_match(cl, 'age') or cl == 'days_to_birth':
94
+ candidate_age_cols.append(c)
95
+ # Gender candidates: 'gender' or 'sex' as tokens
96
+ if token_match(cl, 'gender') or token_match(cl, 'sex'):
97
+ candidate_gender_cols.append(c)
98
+
99
+ # Print candidates in the required strict format
100
+ print(f"candidate_age_cols = {candidate_age_cols}")
101
+ print(f"candidate_gender_cols = {candidate_gender_cols}")
102
+
103
+ # Preview extracted data (first 5 values) as dictionaries
104
+ if candidate_age_cols:
105
+ age_preview = preview_df(clinical_df[candidate_age_cols], n=5)
106
+ print(age_preview)
107
+
108
+ if candidate_gender_cols:
109
+ gender_preview = preview_df(clinical_df[candidate_gender_cols], n=5)
110
+ print(gender_preview)
111
+
112
+ # Step 3: Select Demographic Features
113
+ # Select the most suitable demographic columns based on preview dictionaries (if available) and simple heuristics.
114
+
115
+ # Try to retrieve preview dictionaries created in previous steps
116
+ def _get_preview_dict(possible_names):
117
+ for name in possible_names:
118
+ if name in globals() and isinstance(globals()[name], dict):
119
+ return globals()[name]
120
+ return None
121
+
122
+ age_preview_dict = _get_preview_dict([
123
+ 'age_preview_dict', 'age_values_dict', 'age_candidate_dict', 'age_dict', 'candidate_age_dict'
124
+ ])
125
+ gender_preview_dict = _get_preview_dict([
126
+ 'gender_preview_dict', 'gender_values_dict', 'gender_candidate_dict', 'gender_dict', 'candidate_gender_dict'
127
+ ])
128
+
129
+ def _to_list(v):
130
+ if v is None:
131
+ return []
132
+ if isinstance(v, list):
133
+ return v
134
+ try:
135
+ return list(v)
136
+ except Exception:
137
+ return [v]
138
+
139
+ import math
140
+ import re
141
+
142
+ def _extract_number(x):
143
+ if x is None:
144
+ return None
145
+ s = str(x).strip()
146
+ if s.lower() in ("nan", "na", "none", ""):
147
+ return None
148
+ m = re.search(r'-?\d+\.?\d*', s)
149
+ if m:
150
+ try:
151
+ return float(m.group())
152
+ except Exception:
153
+ return None
154
+ return None
155
+
156
+ def _evaluate_age_column(col, preview_vals):
157
+ # Returns (valid_age_count, non_missing_count, total_count, preference_bonus)
158
+ vals = _to_list(preview_vals)
159
+ total = len(vals)
160
+ non_missing = 0
161
+ valid = 0
162
+ for v in vals:
163
+ num = _extract_number(v)
164
+ if num is None:
165
+ continue
166
+ non_missing += 1
167
+ # If this looks like days_to_birth (often negative), convert to years
168
+ if ('day' in col.lower()) or ('birth' in col.lower()):
169
+ age_years = abs(num) / 365.25
170
+ else:
171
+ age_years = num
172
+ if 0 < age_years < 120:
173
+ valid += 1
174
+ # Preference bonus for clearer column names
175
+ bonus = 0.0
176
+ col_lower = col.lower()
177
+ if 'age' in col_lower:
178
+ bonus += 1.0
179
+ if 'days' in col_lower or 'birth' in col_lower:
180
+ bonus += 0.2
181
+ return valid, non_missing, total, bonus
182
+
183
+ def _evaluate_gender_column(col, preview_vals):
184
+ # Returns (valid_gender_count, non_missing_count, total_count)
185
+ vals = _to_list(preview_vals)
186
+ total = len(vals)
187
+ non_missing = 0
188
+ valid = 0
189
+ for v in vals:
190
+ if v is None:
191
+ continue
192
+ s = str(v).strip().lower()
193
+ if s in ("nan", "na", "none", ""):
194
+ continue
195
+ non_missing += 1
196
+ if s in ("male", "female", "m", "f", "0", "1"):
197
+ valid += 1
198
+ return valid, non_missing, total
199
+
200
+ # Attempt to fetch previews from dicts; if unavailable and clinical_df exists, create previews from clinical_df
201
+ def _get_preview_for_col(col, preview_dict):
202
+ if preview_dict and isinstance(preview_dict.get(col, None), list):
203
+ return preview_dict[col]
204
+ # Fallback: sample from clinical_df if available
205
+ if 'clinical_df' in globals():
206
+ try:
207
+ return clinical_df[col].head(5).tolist()
208
+ except Exception:
209
+ return []
210
+ return []
211
+
212
+ # Initialize selections
213
+ age_col = None
214
+ gender_col = None
215
+
216
+ # Select age column
217
+ age_candidates = candidate_age_cols if 'candidate_age_cols' in globals() else []
218
+ best_age_score = (-1, -1, -1, -1.0) # tuple to compare: (valid, non_missing, total, bonus)
219
+ best_age_col = None
220
+
221
+ if isinstance(age_candidates, list) and len(age_candidates) > 0:
222
+ for col in age_candidates:
223
+ preview = _get_preview_for_col(col, age_preview_dict)
224
+ valid, non_missing, total, bonus = _evaluate_age_column(col, preview)
225
+ score = (valid, non_missing, total, bonus)
226
+ if score > best_age_score:
227
+ best_age_score = score
228
+ best_age_col = col
229
+
230
+ # Decide if best candidate is acceptable
231
+ valid, non_missing, total, bonus = best_age_score
232
+ if total > 0 and valid >= max(1, min(3, non_missing)): # require at least some valid values in preview
233
+ age_col = best_age_col
234
+ else:
235
+ age_col = None
236
+ else:
237
+ age_col = None
238
+
239
+ # Select gender column
240
+ gender_candidates = candidate_gender_cols if 'candidate_gender_cols' in globals() else []
241
+ best_gender_score = (-1, -1, -1) # (valid, non_missing, total)
242
+ best_gender_col = None
243
+
244
+ if isinstance(gender_candidates, list) and len(gender_candidates) > 0:
245
+ for col in gender_candidates:
246
+ preview = _get_preview_for_col(col, gender_preview_dict)
247
+ valid, non_missing, total = _evaluate_gender_column(col, preview)
248
+ score = (valid, non_missing, total)
249
+ if score > best_gender_score:
250
+ best_gender_score = score
251
+ best_gender_col = col
252
+
253
+ valid_g, non_missing_g, total_g = best_gender_score
254
+ if total_g > 0 and valid_g >= max(1, min(3, non_missing_g)):
255
+ gender_col = best_gender_col
256
+ else:
257
+ gender_col = None
258
+ else:
259
+ gender_col = None
260
+
261
+ # Explicitly print chosen columns and preview info
262
+ def _print_preview_info(col, preview_dict):
263
+ print(col)
264
+ if col is None:
265
+ print("None")
266
+ return
267
+ preview_vals = _get_preview_for_col(col, preview_dict)
268
+ if preview_vals:
269
+ print(preview_vals)
270
+ else:
271
+ print("Preview unavailable")
272
+
273
+ print("Selected age_col and preview:")
274
+ _print_preview_info(age_col, age_preview_dict)
275
+
276
+ print("Selected gender_col and preview:")
277
+ _print_preview_info(gender_col, gender_preview_dict)
278
+
279
+ # Step 4: Feature Engineering and Validation
280
+ import os
281
+ import pandas as pd
282
+
283
+ # 1) Extract and standardize clinical features (trait, age, gender)
284
+ selected_clinical_df = tcga_select_clinical_features(
285
+ clinical_df,
286
+ trait=trait,
287
+ age_col=age_col if 'age_col' in globals() else None,
288
+ gender_col=gender_col if 'gender_col' in globals() else None
289
+ )
290
+
291
+ # 2) Normalize gene symbols, drop unrecognized, aggregate duplicates; save normalized gene data
292
+ gene_df_norm = normalize_gene_symbols_in_index(genetic_df.copy())
293
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
294
+ gene_df_norm.to_csv(out_gene_data_file)
295
+
296
+ # 3) Link clinical and genetic data on sample IDs
297
+ common_samples = selected_clinical_df.index.intersection(gene_df_norm.columns)
298
+ linked_data = pd.concat(
299
+ [selected_clinical_df.loc[common_samples], gene_df_norm.T.loc[common_samples]],
300
+ axis=1
301
+ )
302
+
303
+ # 4) Handle missing values systematically
304
+ processed_df = handle_missing_values(linked_data.copy(), trait_col=trait)
305
+
306
+ # 5) Determine bias in trait and demographic features; remove biased demographics
307
+ trait_biased, processed_df = judge_and_remove_biased_features(processed_df, trait)
308
+
309
+ # 6) Final validation and save cohort info
310
+ # Explicitly cast to native Python bools to avoid JSON serialization issues
311
+ is_gene_available = bool((gene_df_norm.shape[0] > 0) and (len(common_samples) > 0))
312
+ is_trait_available = bool((trait in linked_data.columns) and bool(linked_data[trait].notna().any()))
313
+ trait_biased = bool(trait_biased)
314
+
315
+ # Note about cohort and trait distribution before processing
316
+ try:
317
+ trait_counts = linked_data[trait].value_counts(dropna=True).to_dict()
318
+ except Exception:
319
+ trait_counts = {}
320
+
321
+ note = f"INFO: Cohort=TCGA UCEC; common_samples={int(len(common_samples))}; trait_counts={trait_counts}."
322
+
323
+ is_usable = validate_and_save_cohort_info(
324
+ is_final=True,
325
+ cohort="TCGA",
326
+ info_path=json_path,
327
+ is_gene_available=is_gene_available,
328
+ is_trait_available=is_trait_available,
329
+ is_biased=trait_biased,
330
+ df=processed_df,
331
+ note=note
332
+ )
333
+
334
+ # 7) Save linked data only if usable
335
+ if is_usable:
336
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
337
+ processed_df.to_csv(out_data_file)
output/preprocess/Endometriosis/cohort_info.json CHANGED
@@ -1,112 +1 @@
1
- {
2
- "GSE75427": {
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": true,
9
- "has_gender": false,
10
- "sample_size": 8
11
- },
12
- "GSE73622": {
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
- "GSE51981": {
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": false,
29
- "has_gender": false,
30
- "sample_size": 148
31
- },
32
- "GSE37837": {
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
- "GSE165004": {
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": 72
51
- },
52
- "GSE145702": {
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": 48
61
- },
62
- "GSE145701": {
63
- "is_usable": false,
64
- "is_gene_available": false,
65
- "is_trait_available": false,
66
- "is_available": false,
67
- "is_biased": null,
68
- "has_age": null,
69
- "has_gender": null,
70
- "sample_size": null
71
- },
72
- "GSE138297": {
73
- "is_usable": false,
74
- "is_gene_available": true,
75
- "is_trait_available": false,
76
- "is_available": false,
77
- "is_biased": null,
78
- "has_age": null,
79
- "has_gender": null,
80
- "sample_size": null
81
- },
82
- "GSE120103": {
83
- "is_usable": false,
84
- "is_gene_available": false,
85
- "is_trait_available": false,
86
- "is_available": false,
87
- "is_biased": null,
88
- "has_age": null,
89
- "has_gender": null,
90
- "sample_size": null
91
- },
92
- "GSE111974": {
93
- "is_usable": false,
94
- "is_gene_available": true,
95
- "is_trait_available": false,
96
- "is_available": false,
97
- "is_biased": null,
98
- "has_age": null,
99
- "has_gender": null,
100
- "sample_size": null
101
- },
102
- "TCGA": {
103
- "is_usable": true,
104
- "is_gene_available": true,
105
- "is_trait_available": true,
106
- "is_available": true,
107
- "is_biased": false,
108
- "has_age": true,
109
- "has_gender": false,
110
- "sample_size": 201
111
- }
112
- }
 
1
+ {"GSE75427": {"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}, "GSE73622": {"is_usable": true, "is_gene_available": true, "is_trait_available": true, "is_available": true, "is_biased": false, "has_age": true, "has_gender": false, "sample_size": 50, "note": "INFO: Probes mapped to genes. Genes before normalization: 117474, after normalization: 24229. Samples before filtering: 50, after filtering: 50. Gender not available (all female)."}, "GSE51981": {"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": 148, "note": "INFO: Probes mapped to gene symbols and normalized by NCBI synonyms. Age and Gender unavailable in clinical data. Linked samples: 148; Features (incl. trait): 19846."}, "GSE37837": {"is_usable": false, "is_gene_available": true, "is_trait_available": false, "is_available": false, "is_biased": null, "has_age": null, "has_gender": null, "sample_size": null, "note": "WARNING: Trait not available (all subjects are endometriosis patients; no control/trait labels)."}, "GSE165004": {"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}, "GSE145702": {"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: Gender effectively constant female and Age unavailable in this cohort. Samples are eutopic endometrial stromal fibroblasts with hormone treatments; trait derived from 'disease state'."}, "GSE145701": {"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": ""}, "GSE138297": {"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}, "GSE120103": {"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": 36, "note": "INFO: Gender was constant (all female) and excluded; Age not available in annotations. Probe-to-gene mapping used GENE_SYMBOL; gene symbols normalized with NCBI synonyms."}, "GSE111974": {"is_usable": false, "is_gene_available": true, "is_trait_available": false, "is_available": false, "is_biased": null, "has_age": null, "has_gender": null, "sample_size": null, "note": null}, "TCGA": {"is_usable": true, "is_gene_available": true, "is_trait_available": true, "is_available": true, "is_biased": false, "has_age": true, "has_gender": false, "sample_size": 201, "note": "INFO: Cohort=TCGA UCEC; common_samples=201; trait_counts={1: 177, 0: 24}."}}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
output/preprocess/Epilepsy/code/GSE123993.py ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Epilepsy"
6
+ cohort = "GSE123993"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Epilepsy"
10
+ in_cohort_dir = "../DATA/GEO/Epilepsy/GSE123993"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z3/preprocess/Epilepsy/GSE123993.csv"
14
+ out_gene_data_file = "./output/z3/preprocess/Epilepsy/gene_data/GSE123993.csv"
15
+ out_clinical_data_file = "./output/z3/preprocess/Epilepsy/clinical_data/GSE123993.csv"
16
+ json_path = "./output/z3/preprocess/Epilepsy/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 HuGene 2.1 ST arrays indicate gene expression data
41
+ # Trait of interest is Epilepsy; this dataset is a vitamin D supplementation study with no epilepsy phenotype recorded
42
+ trait_row = None
43
+
44
+ # No explicit age field in the sample characteristics; background says all >65 (constant, not useful)
45
+ age_row = None
46
+
47
+ # Gender is available under 'Sex'
48
+ gender_row = 1
49
+
50
+ # Step 2: Define converters
51
+ import re
52
+ import pandas as pd
53
+
54
+ def _after_colon(val: str) -> str:
55
+ if val is None:
56
+ return ""
57
+ s = str(val)
58
+ parts = s.split(":", 1)
59
+ return parts[1].strip() if len(parts) == 2 else s.strip()
60
+
61
+ def convert_trait(x):
62
+ # Binary mapping for Epilepsy trait if present in other datasets; not used here (trait_row is None)
63
+ v = _after_colon(x).lower()
64
+ if v in {"epilepsy", "epileptic", "case", "patient", "seizure", "seizures"}:
65
+ return 1
66
+ if v in {"control", "healthy", "normal", "non-epilepsy", "none", "na"}:
67
+ return 0
68
+ return None
69
+
70
+ def convert_age(x):
71
+ # Continuous mapping; extract numeric age in years if present
72
+ v = _after_colon(x)
73
+ if not v:
74
+ return None
75
+ # Find a number (integer or float)
76
+ m = re.search(r"(\d+(?:\.\d+)?)", v)
77
+ if not m:
78
+ return None
79
+ try:
80
+ return float(m.group(1))
81
+ except Exception:
82
+ return None
83
+
84
+ def convert_gender(x):
85
+ # Binary mapping: female->0, male->1
86
+ v = _after_colon(x).lower()
87
+ if v in {"male", "m"}:
88
+ return 1
89
+ if v in {"female", "f"}:
90
+ return 0
91
+ return None
92
+
93
+ # Step 3: Initial filtering and save metadata
94
+ is_trait_available = trait_row is not None
95
+ _ = validate_and_save_cohort_info(
96
+ is_final=False,
97
+ cohort=cohort,
98
+ info_path=json_path,
99
+ is_gene_available=is_gene_available,
100
+ is_trait_available=is_trait_available
101
+ )
102
+
103
+ # Step 4: Clinical feature extraction (skip if trait not available)
104
+ if trait_row is not None:
105
+ selected_clinical_df = geo_select_clinical_features(
106
+ clinical_df=clinical_data,
107
+ trait=trait,
108
+ trait_row=trait_row,
109
+ convert_trait=convert_trait,
110
+ age_row=age_row,
111
+ convert_age=convert_age if age_row is not None else None,
112
+ gender_row=gender_row,
113
+ convert_gender=convert_gender if gender_row is not None else None
114
+ )
115
+ clinical_preview = preview_df(selected_clinical_df, n=5)
116
+ # Save clinical data
117
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
118
+ selected_clinical_df.to_csv(out_clinical_data_file, index=False)
output/preprocess/Epilepsy/code/GSE143272.py ADDED
@@ -0,0 +1,190 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Epilepsy"
6
+ cohort = "GSE143272"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Epilepsy"
10
+ in_cohort_dir = "../DATA/GEO/Epilepsy/GSE143272"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z3/preprocess/Epilepsy/GSE143272.csv"
14
+ out_gene_data_file = "./output/z3/preprocess/Epilepsy/gene_data/GSE143272.csv"
15
+ out_clinical_data_file = "./output/z3/preprocess/Epilepsy/clinical_data/GSE143272.csv"
16
+ json_path = "./output/z3/preprocess/Epilepsy/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ import os
40
+
41
+ # 1) Assess gene expression data availability (mRNA expression per background info)
42
+ is_gene_available = True
43
+
44
+ # 2) Identify rows for trait, age, and gender based on the provided Sample Characteristics Dictionary
45
+ trait_row = 2 # 'epilepsy type: -/Idiopathic/Cryptogenic/Symptomatic'
46
+ age_row = 0 # 'age (in years): <number>'
47
+ gender_row = 1 # 'Sex: Male/Female'
48
+
49
+ # 2.2) Define conversion functions
50
+ def _extract_value(x):
51
+ if x is None:
52
+ return None
53
+ parts = str(x).split(":", 1)
54
+ val = parts[1] if len(parts) > 1 else parts[0]
55
+ return val.strip()
56
+
57
+ def convert_trait(x):
58
+ val = _extract_value(x)
59
+ if val is None:
60
+ return None
61
+ v = val.strip().lower()
62
+ # Map to epilepsy presence: 1 for any specified epilepsy type, 0 for '-' or controls
63
+ if v in {"-", "", "na", "n/a", "control", "healthy", "normal"}:
64
+ return 0
65
+ if any(k in v for k in ["idiopathic", "cryptogenic", "symptomatic", "epilepsy"]):
66
+ return 1
67
+ return None
68
+
69
+ def convert_age(x):
70
+ val = _extract_value(x)
71
+ if val is None:
72
+ return None
73
+ val = val.strip()
74
+ try:
75
+ return float(val)
76
+ except Exception:
77
+ return None
78
+
79
+ def convert_gender(x):
80
+ val = _extract_value(x)
81
+ if val is None:
82
+ return None
83
+ v = val.strip().lower()
84
+ if v in {"female", "f"}:
85
+ return 0
86
+ if v in {"male", "m"}:
87
+ return 1
88
+ return None
89
+
90
+ # 3) Save initial metadata (filtering) using the library
91
+ is_trait_available = trait_row is not None
92
+ _ = validate_and_save_cohort_info(
93
+ is_final=False,
94
+ cohort=cohort,
95
+ info_path=json_path,
96
+ is_gene_available=is_gene_available,
97
+ is_trait_available=is_trait_available
98
+ )
99
+
100
+ # 4) Clinical Feature Extraction (only if trait data is available)
101
+ if trait_row is not None:
102
+ selected_clinical_df = geo_select_clinical_features(
103
+ clinical_df=clinical_data,
104
+ trait=trait,
105
+ trait_row=trait_row,
106
+ convert_trait=convert_trait,
107
+ age_row=age_row,
108
+ convert_age=convert_age,
109
+ gender_row=gender_row,
110
+ convert_gender=convert_gender
111
+ )
112
+ preview = preview_df(selected_clinical_df)
113
+ print(preview)
114
+ # Save clinical data
115
+ os.makedirs(os.path.dirname(out_clinical_data_file), 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
+ # ILMN_* are Illumina probe IDs (array probes), not human gene symbols; mapping is required.
127
+ print("requires_gene_mapping = True")
128
+
129
+ # Step 5: Gene Annotation
130
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
131
+ gene_annotation = get_gene_annotation(soft_file)
132
+
133
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
134
+ print("Gene annotation preview:")
135
+ print(preview_df(gene_annotation))
136
+
137
+ # Step 6: Gene Identifier Mapping
138
+ # Decide columns for mapping: probe IDs and gene symbols
139
+ probe_id_col_candidates = ['ID', 'Probe_Id', 'Array_Address_Id']
140
+ gene_symbol_col_candidates = ['Symbol', 'ILMN_Gene', 'Gene Symbol', 'GeneSymbol', 'Gene_Symbol']
141
+
142
+ probe_col = next((c for c in probe_id_col_candidates if c in gene_annotation.columns), None)
143
+ gene_col = next((c for c in gene_symbol_col_candidates if c in gene_annotation.columns), None)
144
+
145
+ if probe_col is None or gene_col is None:
146
+ raise ValueError("Could not find appropriate columns for probe IDs and gene symbols in the annotation.")
147
+
148
+ # Build mapping dataframe
149
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=probe_col, gene_col=gene_col)
150
+
151
+ # Apply mapping to convert probe-level data (existing gene_data) to gene-level data
152
+ gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
153
+
154
+ # Step 7: Data Normalization and Linking
155
+ import os
156
+
157
+ # 1. Normalize the obtained gene data and save
158
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
159
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
160
+ normalized_gene_data.to_csv(out_gene_data_file)
161
+
162
+ # 2. Link the clinical and genetic data
163
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
164
+
165
+ # 3. Handle missing values
166
+ linked_data = handle_missing_values(linked_data, trait)
167
+
168
+ # 4. Determine 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 (cast to native bools to avoid JSON issues)
172
+ is_gene_available_final = bool((normalized_gene_data.shape[0] > 0) and (normalized_gene_data.shape[1] > 0))
173
+ is_trait_available_final = bool((trait in linked_data.columns) and bool(linked_data[trait].notna().any()))
174
+ note = "INFO: ILMN probe IDs mapped to gene symbols via SOFT (ID->Symbol). Trait derived from 'epilepsy type'; age and gender included."
175
+
176
+ is_usable = validate_and_save_cohort_info(
177
+ is_final=True,
178
+ cohort=cohort,
179
+ info_path=json_path,
180
+ is_gene_available=is_gene_available_final,
181
+ is_trait_available=is_trait_available_final,
182
+ is_biased=bool(is_trait_biased),
183
+ df=unbiased_linked_data,
184
+ note=note
185
+ )
186
+
187
+ # 6. Save linked data if usable
188
+ if is_usable:
189
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
190
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Epilepsy/code/GSE199759.py ADDED
@@ -0,0 +1,303 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Epilepsy"
6
+ cohort = "GSE199759"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Epilepsy"
10
+ in_cohort_dir = "../DATA/GEO/Epilepsy/GSE199759"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z3/preprocess/Epilepsy/GSE199759.csv"
14
+ out_gene_data_file = "./output/z3/preprocess/Epilepsy/gene_data/GSE199759.csv"
15
+ out_clinical_data_file = "./output/z3/preprocess/Epilepsy/clinical_data/GSE199759.csv"
16
+ json_path = "./output/z3/preprocess/Epilepsy/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ import re
40
+
41
+ # 1) Gene expression availability based on background information
42
+ is_gene_available = True # Agilent LncRNA+mRNA Human Gene Expression Microarray V3.0 suggests mRNA expression data is available.
43
+
44
+ # 2) Variable availability based on the provided Sample Characteristics Dictionary
45
+ trait_row = None # No explicit epilepsy status in the provided characteristics; groups (GRE vs GNE) not listed.
46
+ age_row = 2 # 'age: ...y'
47
+ gender_row = 1 # 'gender: Male/Female'
48
+
49
+ # 2.2) Conversion functions
50
+ def _after_colon(val):
51
+ if val is None:
52
+ return None
53
+ parts = str(val).split(":", 1)
54
+ return parts[1].strip() if len(parts) > 1 else str(val).strip()
55
+
56
+ def convert_trait(x):
57
+ """
58
+ Generic epilepsy status converter (not used here since trait_row is None).
59
+ Maps epilepsy-related indications to binary: epilepsy=1, non-epilepsy=0.
60
+ """
61
+ v = _after_colon(x)
62
+ if v is None:
63
+ return None
64
+ v_low = v.lower()
65
+ # Heuristics for GRE vs GNE if ever encountered
66
+ if any(k in v_low for k in ["gre", "with epilepsy", "epilepsy", "glioma-related epilepsy"]):
67
+ if any(k in v_low for k in ["gne", "without epilepsy", "no epilepsy"]):
68
+ return None # Ambiguous
69
+ return 1
70
+ if any(k in v_low for k in ["gne", "without epilepsy", "no epilepsy", "nonepilepsy", "non-epilepsy"]):
71
+ return 0
72
+ return None
73
+
74
+ def convert_age(x):
75
+ v = _after_colon(x)
76
+ if v is None:
77
+ return None
78
+ # Extract integer/float from strings like "47y", "47", "47 years"
79
+ nums = re.findall(r"\d+\.?\d*", v)
80
+ if not nums:
81
+ return None
82
+ try:
83
+ val = float(nums[0])
84
+ return int(val) if val.is_integer() else val
85
+ except Exception:
86
+ return None
87
+
88
+ def convert_gender(x):
89
+ v = _after_colon(x)
90
+ if v is None:
91
+ return None
92
+ v_low = v.lower()
93
+ if "male" in v_low:
94
+ return 1
95
+ if "female" in v_low:
96
+ return 0
97
+ return None
98
+
99
+ # 3) Save metadata (initial filtering)
100
+ is_trait_available = trait_row is not None
101
+ _ = validate_and_save_cohort_info(
102
+ is_final=False,
103
+ cohort=cohort,
104
+ info_path=json_path,
105
+ is_gene_available=is_gene_available,
106
+ is_trait_available=is_trait_available
107
+ )
108
+
109
+ # 4) Clinical Feature Extraction (skip because trait_row is None)
110
+ # If trait_row were available:
111
+ # selected_clinical_df = geo_select_clinical_features(
112
+ # clinical_df=clinical_data,
113
+ # trait=trait,
114
+ # trait_row=trait_row,
115
+ # convert_trait=convert_trait,
116
+ # age_row=age_row,
117
+ # convert_age=convert_age,
118
+ # gender_row=gender_row,
119
+ # convert_gender=convert_gender
120
+ # )
121
+ # preview = preview_df(selected_clinical_df)
122
+ # selected_clinical_df.to_csv(out_clinical_data_file, index=True)
123
+
124
+ # Step 3: Gene Data Extraction
125
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
126
+ gene_data = get_genetic_data(matrix_file)
127
+
128
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
129
+ print(gene_data.index[:20])
130
+
131
+ # Step 4: Gene Identifier Review
132
+ print("requires_gene_mapping = True")
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
+ import os
144
+ import pandas as pd
145
+
146
+ # 1) Identify the correct SOFT (platform) file and the appropriate columns for probe IDs and gene symbols
147
+ soft_files = [os.path.join(in_cohort_dir, f) for f in os.listdir(in_cohort_dir) if 'soft' in f.lower()]
148
+
149
+ best_soft = None
150
+ best_probe_col = None
151
+ best_symbol_col = None
152
+ best_match_count = -1 # number of probes matched to gene_data.index
153
+
154
+ # Use a subset of probe IDs for quick matching
155
+ probe_index = pd.Index(gene_data.index.astype(str))
156
+ subset_probe = probe_index[:min(5000, len(probe_index))]
157
+
158
+ # Candidate columns to prioritize for gene symbols
159
+ symbol_priority = [
160
+ 'Gene Symbol', 'GENE_SYMBOL', 'GeneSymbol', 'Symbol', 'SYMBOL', 'gene_symbol',
161
+ 'GENESYMBOL', 'Gene Name', 'GENE_NAME', 'gene_assignment', 'DESCRIPTION',
162
+ 'Description', 'Entrez Gene Symbol', 'ENTREZ_GENE_SYMBOL'
163
+ ]
164
+
165
+ for sf in soft_files:
166
+ try:
167
+ ann = get_gene_annotation(sf)
168
+ if ann is None or not isinstance(ann, pd.DataFrame) or ann.empty:
169
+ continue
170
+
171
+ # Identify which column in this annotation best matches our probe IDs
172
+ probe_col_candidate = None
173
+ probe_match_counts = {}
174
+ for col in ann.columns:
175
+ try:
176
+ match_count = ann[col].astype(str).isin(subset_probe).sum()
177
+ probe_match_counts[col] = match_count
178
+ except Exception:
179
+ continue
180
+
181
+ if not probe_match_counts:
182
+ continue
183
+
184
+ # Choose the column with maximum matches
185
+ candidate_col, candidate_count = max(probe_match_counts.items(), key=lambda x: x[1])
186
+
187
+ # Require at least some reasonable overlap to consider this platform relevant
188
+ if candidate_count > best_match_count and candidate_count > 0:
189
+ # Find a gene symbol column in this annotation
190
+ symbol_col = None
191
+ # First try priority list
192
+ for c in symbol_priority:
193
+ if c in ann.columns:
194
+ symbol_col = c
195
+ break
196
+ # If none from priority list, choose the column with the most extractable human symbols
197
+ if symbol_col is None:
198
+ non_empty_counts = {}
199
+ for col in ann.columns:
200
+ try:
201
+ symbols_extracted = ann[col].astype(str).map(extract_human_gene_symbols)
202
+ non_empty_counts[col] = symbols_extracted.map(lambda x: len(x) > 0).sum()
203
+ except Exception:
204
+ continue
205
+ if non_empty_counts:
206
+ symbol_col = max(non_empty_counts.items(), key=lambda x: x[1])[0]
207
+
208
+ if symbol_col is not None:
209
+ best_soft = sf
210
+ best_probe_col = candidate_col
211
+ best_symbol_col = symbol_col
212
+ best_match_count = candidate_count
213
+ except Exception:
214
+ continue
215
+
216
+ # 2) Build mapping dataframe and 3) apply mapping to convert probe-level data to gene-level data
217
+ if best_soft is not None and best_probe_col is not None and best_symbol_col is not None:
218
+ selected_annotation = get_gene_annotation(best_soft)
219
+ mapping_df = get_gene_mapping(selected_annotation, prob_col=best_probe_col, gene_col=best_symbol_col)
220
+ gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
221
+ else:
222
+ # If no suitable mapping was found, keep gene_data unchanged (probe-level) to avoid crashing downstream steps.
223
+ # This branch should be rare; it indicates annotation mismatch (e.g., miRNA platform vs mRNA probes).
224
+ gene_data = gene_data
225
+
226
+ # Step 7: Data Normalization and Linking
227
+ import os
228
+ import pandas as pd
229
+
230
+ # 1. Normalize gene symbols and save gene matrix
231
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
232
+
233
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
234
+ normalized_gene_data.to_csv(out_gene_data_file)
235
+
236
+ # Helper flags and note assembly
237
+ is_gene_available_fin = not normalized_gene_data.empty
238
+ notes = []
239
+ if not is_gene_available_fin:
240
+ notes.append("WARNING: Normalized gene matrix is empty after symbol normalization; "
241
+ "probe->gene mapping likely failed due to platform annotation mismatch (e.g., miRNA vs mRNA).")
242
+
243
+ linked_data = None # default
244
+
245
+ # 2-6. Proceed only if clinical features were extracted (i.e., selected_clinical_data exists and contains the trait)
246
+ if 'selected_clinical_data' in globals() and isinstance(selected_clinical_data, pd.DataFrame) and not selected_clinical_data.empty:
247
+ try:
248
+ # 2. Link clinical and genetic data
249
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_data, normalized_gene_data)
250
+
251
+ # 3. Handle missing values
252
+ linked_data = handle_missing_values(linked_data, trait)
253
+
254
+ # 4. Bias checking and removal of biased covariates
255
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
256
+
257
+ # 5. Final validation and metadata saving
258
+ os.makedirs(os.path.dirname(json_path), exist_ok=True)
259
+ is_usable = validate_and_save_cohort_info(
260
+ is_final=True,
261
+ cohort=cohort,
262
+ info_path=json_path,
263
+ is_gene_available=is_gene_available_fin,
264
+ is_trait_available=True,
265
+ is_biased=is_trait_biased,
266
+ df=unbiased_linked_data,
267
+ note=(" ".join(notes) if notes else "INFO: Clinical features linked and processed.")
268
+ )
269
+
270
+ # 6. Save linked data only if usable
271
+ if is_usable:
272
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
273
+ unbiased_linked_data.to_csv(out_data_file)
274
+
275
+ except Exception as e:
276
+ # If anything fails during linking due to unexpected shapes/availability, record as unavailable
277
+ notes.append(f"ERROR: Linking/processing failed with error: {e}")
278
+ os.makedirs(os.path.dirname(json_path), exist_ok=True)
279
+ _ = validate_and_save_cohort_info(
280
+ is_final=True,
281
+ cohort=cohort,
282
+ info_path=json_path,
283
+ is_gene_available=is_gene_available_fin,
284
+ is_trait_available=False,
285
+ is_biased=False,
286
+ df=pd.DataFrame(),
287
+ note=" ".join(notes)
288
+ )
289
+ else:
290
+ # Trait not available (as in this cohort), skip linking and mark dataset unusable
291
+ notes.append("INFO: Clinical trait labels (Epilepsy) not available in series matrix; "
292
+ "skipping linking and marking dataset as unusable.")
293
+ os.makedirs(os.path.dirname(json_path), exist_ok=True)
294
+ _ = validate_and_save_cohort_info(
295
+ is_final=True,
296
+ cohort=cohort,
297
+ info_path=json_path,
298
+ is_gene_available=is_gene_available_fin,
299
+ is_trait_available=False,
300
+ is_biased=False,
301
+ df=pd.DataFrame(),
302
+ note=" ".join(notes)
303
+ )
output/preprocess/Epilepsy/code/GSE273630.py ADDED
@@ -0,0 +1,166 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Epilepsy"
6
+ cohort = "GSE273630"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Epilepsy"
10
+ in_cohort_dir = "../DATA/GEO/Epilepsy/GSE273630"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z3/preprocess/Epilepsy/GSE273630.csv"
14
+ out_gene_data_file = "./output/z3/preprocess/Epilepsy/gene_data/GSE273630.csv"
15
+ out_clinical_data_file = "./output/z3/preprocess/Epilepsy/clinical_data/GSE273630.csv"
16
+ json_path = "./output/z3/preprocess/Epilepsy/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ # Step 1: Determine gene expression availability
40
+ is_gene_available = True # NanoString digital transcript panel indicates gene expression data
41
+
42
+ # Step 2: Variable availability and conversion functions
43
+
44
+ # Availability from the provided Sample Characteristics Dictionary and background info:
45
+ # - Trait (Epilepsy): Excluded by design; no sample-level field -> not available
46
+ # - Age: No per-sample age field provided -> not available
47
+ # - Gender: All participants are males by design (constant) -> not available
48
+ trait_row = None
49
+ age_row = None
50
+ gender_row = None
51
+
52
+ # Conversion functions (defined for interface completeness; they won't be used since rows are None)
53
+ def _extract_value(cell):
54
+ if cell is None:
55
+ return None
56
+ if isinstance(cell, str):
57
+ parts = cell.split(":", 1)
58
+ return parts[1].strip() if len(parts) == 2 else cell.strip()
59
+ return cell
60
+
61
+ def convert_trait(x):
62
+ # Map epilepsy-related information to binary (0/1); default to None if unknown
63
+ val = _extract_value(x)
64
+ if val is None:
65
+ return None
66
+ s = str(val).strip().lower()
67
+ # Positive indications
68
+ positive_kw = ["epilep", "seizure", "ictal", "sz"]
69
+ # Negative phrases
70
+ negative_kw = ["no epilepsy", "non-epilep", "without epilepsy", "seizure-free", "no seizure", "none"]
71
+ if any(k in s for k in negative_kw):
72
+ return 0
73
+ if any(k in s for k in positive_kw):
74
+ # avoid false positives if explicitly negated
75
+ if "no " in s or "not " in s:
76
+ return 0
77
+ return 1
78
+ return None
79
+
80
+ def convert_age(x):
81
+ val = _extract_value(x)
82
+ if val is None:
83
+ return None
84
+ s = str(val)
85
+ # Extract first number (integer or float)
86
+ import re
87
+ m = re.search(r"(-?\d+\.?\d*)", s)
88
+ if m:
89
+ try:
90
+ return float(m.group(1))
91
+ except:
92
+ return None
93
+ return None
94
+
95
+ def convert_gender(x):
96
+ val = _extract_value(x)
97
+ if val is None:
98
+ return None
99
+ s = str(val).strip().lower()
100
+ if s in ["male", "m", "man", "boy"]:
101
+ return 1
102
+ if s in ["female", "f", "woman", "girl"]:
103
+ return 0
104
+ # Try to infer from single letters embedded
105
+ if "male" in s:
106
+ return 1
107
+ if "female" in s:
108
+ return 0
109
+ return None
110
+
111
+ # Step 3: Save metadata using initial filtering
112
+ is_trait_available = trait_row is not None
113
+ _ = validate_and_save_cohort_info(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
+ # Step 4: Clinical feature extraction
120
+ # Skipped because trait_row is None (no clinical trait data available for Epilepsy in this dataset)
121
+
122
+ # Step 3: Gene Data Extraction
123
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
124
+ gene_data = get_genetic_data(matrix_file)
125
+
126
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
127
+ print(gene_data.index[:20])
128
+
129
+ # Step 4: Gene Identifier Review
130
+ requires_gene_mapping = False
131
+ print(f"requires_gene_mapping = {requires_gene_mapping}")
132
+
133
+ # Step 5: Data Normalization and Linking
134
+ # 1. Normalize the obtained gene data and save
135
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
136
+ normalized_gene_data.to_csv(out_gene_data_file)
137
+
138
+ # 2-6. Proceed only if clinical data with trait exists (guard safely via locals().get)
139
+ if (locals().get('selected_clinical_data') is not None) and (locals().get('trait_row') is not None):
140
+ # Link clinical and genetic data
141
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_data, normalized_gene_data)
142
+
143
+ # Handle missing values
144
+ linked_data = handle_missing_values(linked_data, trait)
145
+
146
+ # Bias check and remove biased demographic features
147
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
148
+
149
+ # Final validation and save cohort info
150
+ is_usable = validate_and_save_cohort_info(
151
+ is_final=True,
152
+ cohort=cohort,
153
+ info_path=json_path,
154
+ is_gene_available=True,
155
+ is_trait_available=True,
156
+ is_biased=is_trait_biased,
157
+ df=unbiased_linked_data,
158
+ note="INFO: Clinical features extracted and linked successfully."
159
+ )
160
+
161
+ # Save linked data only if usable
162
+ if is_usable:
163
+ unbiased_linked_data.to_csv(out_data_file)
164
+ else:
165
+ # No clinical trait data available; only gene data saved in this step
166
+ print("No clinical trait data available; skipping linking and final validation for this cohort.")
output/preprocess/Epilepsy/code/GSE29796.py ADDED
@@ -0,0 +1,192 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Epilepsy"
6
+ cohort = "GSE29796"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Epilepsy"
10
+ in_cohort_dir = "../DATA/GEO/Epilepsy/GSE29796"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z3/preprocess/Epilepsy/GSE29796.csv"
14
+ out_gene_data_file = "./output/z3/preprocess/Epilepsy/gene_data/GSE29796.csv"
15
+ out_clinical_data_file = "./output/z3/preprocess/Epilepsy/clinical_data/GSE29796.csv"
16
+ json_path = "./output/z3/preprocess/Epilepsy/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 # Expression profiling of human glial cells; not miRNA/methylation only.
45
+
46
+ # 2) Variable Availability
47
+ # From the provided characteristics dictionary, epilepsy appears under "pathology" at key 1.
48
+ trait_row = 1
49
+ age_row = None
50
+ gender_row = None
51
+
52
+ # 2.2) Data Type Conversion
53
+
54
+ def _after_colon(x):
55
+ if x is None:
56
+ return None
57
+ s = str(x).strip()
58
+ if ':' in s:
59
+ s = s.split(':', 1)[1]
60
+ return s.strip()
61
+
62
+ def convert_trait(x):
63
+ val = _after_colon(x)
64
+ if val is None or val == '':
65
+ return None
66
+ v = val.strip().lower()
67
+ # Treat common unknown tokens as missing
68
+ if v in {'na', 'n/a', 'unknown', 'not available', 'nan', 'none', 'missing', 'null', 'undetermined'}:
69
+ return None
70
+ # Positive if explicitly labeled epilepsy; otherwise negative.
71
+ if v in {'epilepsy', 'epileptic'}:
72
+ return 1
73
+ # For other pathologies (tumor types etc.), map to 0
74
+ return 0
75
+
76
+ def convert_age(x):
77
+ val = _after_colon(x)
78
+ if val is None or val == '':
79
+ return None
80
+ m = re.search(r"[-+]?\d*\.?\d+", str(val))
81
+ return float(m.group()) if m else None
82
+
83
+ def convert_gender(x):
84
+ val = _after_colon(x)
85
+ if val is None or val == '':
86
+ return None
87
+ v = val.strip().lower()
88
+ if v in {'female', 'f', 'woman', 'women', 'girl'}:
89
+ return 0
90
+ if v in {'male', 'm', 'man', 'men', 'boy'}:
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 (only if trait is available)
105
+ if trait_row is not None:
106
+ selected_clinical_df = geo_select_clinical_features(
107
+ clinical_df=clinical_data,
108
+ trait=trait,
109
+ trait_row=trait_row,
110
+ convert_trait=convert_trait,
111
+ age_row=age_row,
112
+ convert_age=convert_age,
113
+ gender_row=gender_row,
114
+ convert_gender=convert_gender
115
+ )
116
+ # Preview and save
117
+ preview = preview_df(selected_clinical_df)
118
+ print(preview)
119
+ # Ensure output directory exists and save
120
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
121
+ selected_clinical_df.to_csv(out_clinical_data_file)
122
+
123
+ # Step 3: Gene Data Extraction
124
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
125
+ gene_data = get_genetic_data(matrix_file)
126
+
127
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
128
+ print(gene_data.index[:20])
129
+
130
+ # Step 4: Gene Identifier Review
131
+ 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 appropriate columns in the annotation for mapping:
144
+ # - Probe/feature identifiers: 'ID' (matches gene_data index like '1007_s_at')
145
+ # - Gene symbols: 'Gene Symbol'
146
+ mapping_df = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='Gene Symbol')
147
+
148
+ # Apply mapping to convert probe-level data to gene-level expression
149
+ gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
150
+
151
+ # Step 7: Data Normalization and Linking
152
+ import os
153
+
154
+ # 1. Normalize gene symbols and save gene data
155
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
156
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
157
+ normalized_gene_data.to_csv(out_gene_data_file)
158
+
159
+ # 2. Link the clinical and genetic data
160
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
161
+
162
+ # 3. Handle missing values
163
+ linked_data = handle_missing_values(linked_data, trait)
164
+
165
+ # 4. Bias check and remove biased demographic features
166
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
167
+
168
+ # 5. Final validation and save cohort info
169
+ covariate_cols = [trait] + [c for c in ['Age', 'Gender'] if c in unbiased_linked_data.columns]
170
+ gene_cols_present = [c for c in unbiased_linked_data.columns if c not in covariate_cols]
171
+
172
+ # Ensure Python-native bools for JSON serialization
173
+ is_gene_available_final = bool(len(gene_cols_present) > 0)
174
+ is_trait_available_final = bool((trait in unbiased_linked_data.columns) and bool(unbiased_linked_data[trait].notna().any()))
175
+
176
+ note = ("INFO: Trait (Epilepsy) inferred from 'pathology' field; Affymetrix probe IDs mapped to gene symbols using "
177
+ "platform annotation, then normalized via NCBI gene synonym table. Missing values handled per protocol.")
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_final,
183
+ is_trait_available=is_trait_available_final,
184
+ is_biased=bool(is_trait_biased),
185
+ df=unbiased_linked_data,
186
+ note=note
187
+ )
188
+
189
+ # 6. Save linked dataset if usable
190
+ if is_usable:
191
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
192
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Epilepsy/code/GSE42986.py ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Epilepsy"
6
+ cohort = "GSE42986"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Epilepsy"
10
+ in_cohort_dir = "../DATA/GEO/Epilepsy/GSE42986"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z3/preprocess/Epilepsy/GSE42986.csv"
14
+ out_gene_data_file = "./output/z3/preprocess/Epilepsy/gene_data/GSE42986.csv"
15
+ out_clinical_data_file = "./output/z3/preprocess/Epilepsy/clinical_data/GSE42986.csv"
16
+ json_path = "./output/z3/preprocess/Epilepsy/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 Exon 1.0 ST -> mRNA expression, not miRNA/methylation
43
+
44
+ # 2) Variable availability based on provided Sample Characteristics Dictionary
45
+ trait_row = None # No epilepsy-related field available in this dataset
46
+ age_row = 3 # 'age (years): ...'
47
+ gender_row = 2 # 'gender: F/M'
48
+
49
+ # 2.2) Conversion functions
50
+ def _after_colon(x):
51
+ if x is None:
52
+ return None
53
+ s = str(x)
54
+ if ':' in s:
55
+ s = s.split(':', 1)[1].strip()
56
+ return s.strip()
57
+
58
+ def convert_trait(x):
59
+ # Trait is Epilepsy; dataset does not provide epilepsy info -> return None unless explicitly stated
60
+ s = _after_colon(x)
61
+ if s is None:
62
+ return None
63
+ sl = s.lower()
64
+ if 'epilepsy' in sl or 'epileptic' in sl:
65
+ return 1
66
+ if 'control' in sl or 'healthy' in sl or 'non-epilepsy' in sl or 'non-epileptic' in sl or 'no epilepsy' in sl:
67
+ return 0
68
+ return None
69
+
70
+ def convert_age(x):
71
+ s = _after_colon(x)
72
+ if s is None:
73
+ return None
74
+ sl = s.lower()
75
+ if sl in {'na', 'n/a', 'not obtained', 'unknown', ''}:
76
+ return None
77
+ s = s.replace('years', '').strip()
78
+ try:
79
+ return float(s)
80
+ except Exception:
81
+ m = re.search(r'[-+]?\d*\.?\d+', s)
82
+ return float(m.group()) if m else None
83
+
84
+ def convert_gender(x):
85
+ s = _after_colon(x)
86
+ if s is None:
87
+ return None
88
+ sl = s.lower()
89
+ if sl in {'f', 'female', 'woman', 'women', 'girl'}:
90
+ return 0
91
+ if sl in {'m', 'male', 'man', 'men', 'boy'}:
92
+ return 1
93
+ return None
94
+
95
+ # 3) Initial filtering and save metadata
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 (skip because trait_row is None)
106
+ # If trait_row becomes available in future steps, uncomment below:
107
+ # if trait_row is not None:
108
+ # selected_clinical_df = geo_select_clinical_features(
109
+ # clinical_df=clinical_data,
110
+ # trait=trait,
111
+ # trait_row=trait_row,
112
+ # convert_trait=convert_trait,
113
+ # age_row=age_row,
114
+ # convert_age=convert_age,
115
+ # gender_row=gender_row,
116
+ # convert_gender=convert_gender
117
+ # )
118
+ # _ = preview_df(selected_clinical_df)
119
+ # os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
120
+ # selected_clinical_df.to_csv(out_clinical_data_file)
output/preprocess/Epilepsy/code/GSE63808.py ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Epilepsy"
6
+ cohort = "GSE63808"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Epilepsy"
10
+ in_cohort_dir = "../DATA/GEO/Epilepsy/GSE63808"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z3/preprocess/Epilepsy/GSE63808.csv"
14
+ out_gene_data_file = "./output/z3/preprocess/Epilepsy/gene_data/GSE63808.csv"
15
+ out_clinical_data_file = "./output/z3/preprocess/Epilepsy/clinical_data/GSE63808.csv"
16
+ json_path = "./output/z3/preprocess/Epilepsy/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 # Series describes mRNA expression in human hippocampus biopsies; not miRNA-only or methylation.
43
+
44
+ # 2) Variable Availability and Data Type Conversion
45
+
46
+ # From the provided characteristics:
47
+ # {0: ['tissue: hippocampal formation'], 1: ['phenotype: epilepsy']}
48
+ # - Trait appears constant ("epilepsy") with no controls -> not usable for association.
49
+ # - Age/Gender not present.
50
+ trait_row = None
51
+ age_row = None
52
+ gender_row = None
53
+
54
+ # Data type choices
55
+ trait_type = 'binary'
56
+ age_type = 'continuous'
57
+ gender_type = 'binary'
58
+
59
+ def _after_colon(x):
60
+ if x is None:
61
+ return None
62
+ s = str(x)
63
+ parts = s.split(':', 1)
64
+ return parts[1].strip() if len(parts) == 2 else s.strip()
65
+
66
+ def convert_trait(x):
67
+ """Map epilepsy-related statuses to binary: control=0, epilepsy/TLE=1; unknown -> None."""
68
+ val = _after_colon(x)
69
+ if val is None or val == '':
70
+ return None
71
+ v = val.lower()
72
+ # Positive (epilepsy) indicators
73
+ pos_terms = [
74
+ 'epilepsy', 'temporal lobe epilepsy', 'tle', 'seizure', 'patient', 'case',
75
+ 'pharmacoresistant', 'intractable'
76
+ ]
77
+ # Negative (control) indicators
78
+ neg_terms = ['control', 'healthy', 'non-epilepsy', 'nonepilepsy', 'normal', 'non epilepsy']
79
+ if any(t in v for t in pos_terms):
80
+ return 1
81
+ if any(t in v for t in neg_terms):
82
+ return 0
83
+ # binary flags like "yes"/"no"
84
+ if v in {'yes', 'y', 'true', '1'}:
85
+ return 1
86
+ if v in {'no', 'n', 'false', '0'}:
87
+ return 0
88
+ return None
89
+
90
+ def convert_age(x):
91
+ """Extract age in years as float. Supports 'years' or 'months' (converted to years)."""
92
+ val = _after_colon(x)
93
+ if val is None or val == '':
94
+ return None
95
+ v = val.lower()
96
+ # Find first numeric token
97
+ m = re.search(r'(\d+(?:\.\d+)?)', v)
98
+ if not m:
99
+ return None
100
+ num = float(m.group(1))
101
+ # Determine unit
102
+ if any(u in v for u in ['month', 'months', 'mo', 'mth', 'mths']):
103
+ return round(num / 12.0, 3)
104
+ # Default to years if unspecified or contains year terms
105
+ return num
106
+
107
+ def convert_gender(x):
108
+ """Map gender to binary: female=0, male=1; unknown -> None."""
109
+ val = _after_colon(x)
110
+ if val is None or val == '':
111
+ return None
112
+ v = val.strip().lower()
113
+ # Common mappings
114
+ if v in {'male', 'm', 'man', 'boy'}:
115
+ return 1
116
+ if v in {'female', 'f', 'woman', 'girl'}:
117
+ return 0
118
+ # Sometimes coded as 0/1 or True/False
119
+ if v in {'1', 'true'}:
120
+ return 1
121
+ if v in {'0', 'false'}:
122
+ return 0
123
+ return None
124
+
125
+ # 3) Save Metadata (initial filtering)
126
+ is_trait_available = trait_row is not None
127
+ _ = validate_and_save_cohort_info(
128
+ is_final=False,
129
+ cohort=cohort,
130
+ info_path=json_path,
131
+ is_gene_available=is_gene_available,
132
+ is_trait_available=is_trait_available
133
+ )
134
+
135
+ # 4) Clinical Feature Extraction (skip because trait_row is None)
136
+ if (trait_row is not None) and ('clinical_data' in globals()):
137
+ selected_clinical_df = geo_select_clinical_features(
138
+ clinical_df=clinical_data,
139
+ trait=trait,
140
+ trait_row=trait_row,
141
+ convert_trait=convert_trait,
142
+ age_row=age_row,
143
+ convert_age=convert_age if age_row is not None else None,
144
+ gender_row=gender_row,
145
+ convert_gender=convert_gender if gender_row is not None else None
146
+ )
147
+ _ = preview_df(selected_clinical_df)
148
+ # Save clinical features
149
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
150
+ selected_clinical_df.to_csv(out_clinical_data_file)
output/preprocess/Epilepsy/code/GSE64123.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Epilepsy"
6
+ cohort = "GSE64123"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Epilepsy"
10
+ in_cohort_dir = "../DATA/GEO/Epilepsy/GSE64123"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z3/preprocess/Epilepsy/GSE64123.csv"
14
+ out_gene_data_file = "./output/z3/preprocess/Epilepsy/gene_data/GSE64123.csv"
15
+ out_clinical_data_file = "./output/z3/preprocess/Epilepsy/clinical_data/GSE64123.csv"
16
+ json_path = "./output/z3/preprocess/Epilepsy/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ # Determine data availability based on provided background and sample characteristics
40
+ is_gene_available = True # Gene expression profiling is likely (hESC neurotox assay with multiple time points/exposures)
41
+ trait_row = None # No human Epilepsy phenotype; dataset is drug exposure in hESCs
42
+ age_row = None # Not human subject data
43
+ gender_row = None # Not human subject data
44
+
45
+ # Converters (not used since corresponding rows are None)
46
+ def _extract_after_colon(x):
47
+ if x is None:
48
+ return None
49
+ s = str(x)
50
+ if ":" in s:
51
+ return s.split(":", 1)[1].strip()
52
+ return s.strip()
53
+
54
+ def convert_trait(x):
55
+ # No epilepsy trait available in this cohort
56
+ _ = _extract_after_colon(x)
57
+ return None
58
+
59
+ def convert_age(x):
60
+ # No human age data
61
+ _ = _extract_after_colon(x)
62
+ return None
63
+
64
+ def convert_gender(x):
65
+ # No human gender data
66
+ _ = _extract_after_colon(x)
67
+ return None
68
+
69
+ # Initial filtering and save metadata
70
+ is_trait_available = trait_row is not None
71
+ _ = validate_and_save_cohort_info(
72
+ is_final=False,
73
+ cohort=cohort,
74
+ info_path=json_path,
75
+ is_gene_available=is_gene_available,
76
+ is_trait_available=is_trait_available
77
+ )
78
+
79
+ # Clinical feature extraction is skipped because trait_row is None (no clinical data available)
output/preprocess/Epilepsy/cohort_info.json CHANGED
@@ -1,112 +1 @@
1
- {
2
- "GSE74571": {
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
- "GSE65106": {
13
- "is_usable": true,
14
- "is_gene_available": true,
15
- "is_trait_available": true,
16
- "is_available": true,
17
- "is_biased": false,
18
- "has_age": true,
19
- "has_gender": false,
20
- "sample_size": 59
21
- },
22
- "GSE64123": {
23
- "is_usable": false,
24
- "is_gene_available": false,
25
- "is_trait_available": false,
26
- "is_available": false,
27
- "is_biased": null,
28
- "has_age": null,
29
- "has_gender": null,
30
- "sample_size": null
31
- },
32
- "GSE63808": {
33
- "is_usable": false,
34
- "is_gene_available": true,
35
- "is_trait_available": true,
36
- "is_available": true,
37
- "is_biased": true,
38
- "has_age": false,
39
- "has_gender": false,
40
- "sample_size": 129
41
- },
42
- "GSE42986": {
43
- "is_usable": false,
44
- "is_gene_available": false,
45
- "is_trait_available": false,
46
- "is_available": false,
47
- "is_biased": null,
48
- "has_age": null,
49
- "has_gender": null,
50
- "sample_size": null
51
- },
52
- "GSE29796": {
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": 72
61
- },
62
- "GSE273630": {
63
- "is_usable": false,
64
- "is_gene_available": false,
65
- "is_trait_available": false,
66
- "is_available": false,
67
- "is_biased": null,
68
- "has_age": null,
69
- "has_gender": null,
70
- "sample_size": null
71
- },
72
- "GSE199759": {
73
- "is_usable": false,
74
- "is_gene_available": false,
75
- "is_trait_available": false,
76
- "is_available": false,
77
- "is_biased": null,
78
- "has_age": null,
79
- "has_gender": null,
80
- "sample_size": null
81
- },
82
- "GSE143272": {
83
- "is_usable": true,
84
- "is_gene_available": true,
85
- "is_trait_available": true,
86
- "is_available": true,
87
- "is_biased": false,
88
- "has_age": true,
89
- "has_gender": true,
90
- "sample_size": 142
91
- },
92
- "GSE123993": {
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": true,
100
- "sample_size": 44
101
- },
102
- "TCGA": {
103
- "is_usable": true,
104
- "is_gene_available": true,
105
- "is_trait_available": true,
106
- "is_available": true,
107
- "is_biased": false,
108
- "has_age": true,
109
- "has_gender": true,
110
- "sample_size": 702
111
- }
112
- }
 
1
+ {"GSE74571": {"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}, "GSE65106": {"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 'Epilepsy' is not recorded in this ASD cohort; clinical linking skipped."}, "GSE64123": {"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}, "GSE63808": {"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}, "GSE42986": {"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}, "GSE29796": {"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": 72, "note": "INFO: Trait (Epilepsy) inferred from 'pathology' field; Affymetrix probe IDs mapped to gene symbols using platform annotation, then normalized via NCBI gene synonym table. Missing values handled per protocol."}, "GSE273630": {"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}, "GSE199759": {"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": "WARNING: Normalized gene matrix is empty after symbol normalization; probe->gene mapping likely failed due to platform annotation mismatch (e.g., miRNA vs mRNA). INFO: Clinical trait labels (Epilepsy) not available in series matrix; skipping linking and marking dataset as unusable."}, "GSE143272": {"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": 142, "note": "INFO: ILMN probe IDs mapped to gene symbols via SOFT (ID->Symbol). Trait derived from 'epilepsy type'; age and gender included."}, "GSE123993": {"is_usable": false, "is_gene_available": true, "is_trait_available": false, "is_available": false, "is_biased": null, "has_age": null, "has_gender": null, "sample_size": null, "note": null}, "TCGA": {"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/Glioblastoma/code/GSE148949.py ADDED
@@ -0,0 +1,264 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Glioblastoma"
6
+ cohort = "GSE148949"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Glioblastoma"
10
+ in_cohort_dir = "../DATA/GEO/Glioblastoma/GSE148949"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z3/preprocess/Glioblastoma/GSE148949.csv"
14
+ out_gene_data_file = "./output/z3/preprocess/Glioblastoma/gene_data/GSE148949.csv"
15
+ out_clinical_data_file = "./output/z3/preprocess/Glioblastoma/clinical_data/GSE148949.csv"
16
+ json_path = "./output/z3/preprocess/Glioblastoma/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ import os
22
+
23
+ # 1. Identify the paths to the SOFT file and the matrix file, ensuring they belong to the target cohort
24
+ files = os.listdir(in_cohort_dir)
25
+
26
+ # Prefer files that include the cohort accession explicitly
27
+ soft_candidates = [f for f in files if ('soft' in f.lower()) and (cohort.lower() in f.lower())]
28
+ matrix_candidates = [f for f in files if ('series_matrix' in f.lower()) and (cohort.lower() in f.lower())]
29
+
30
+ # Fallbacks if strict matching fails
31
+ if not soft_candidates:
32
+ soft_candidates = [f for f in files if 'soft' in f.lower()]
33
+ if not matrix_candidates:
34
+ matrix_candidates = [f for f in files if 'matrix' in f.lower()]
35
+
36
+ assert len(soft_candidates) > 0 and len(matrix_candidates) > 0, "SOFT or matrix files not found in cohort directory."
37
+
38
+ soft_file = os.path.join(in_cohort_dir, soft_candidates[0])
39
+ matrix_file = os.path.join(in_cohort_dir, matrix_candidates[0])
40
+
41
+ # Assert that chosen files likely correspond to the cohort
42
+ assert cohort.lower() in os.path.basename(soft_file).lower() or 'soft' in os.path.basename(soft_file).lower()
43
+ assert cohort.lower() in os.path.basename(matrix_file).lower() or 'matrix' in os.path.basename(matrix_file).lower()
44
+
45
+ print(f"Selected SOFT file: {soft_file}")
46
+ print(f"Selected matrix file: {matrix_file}")
47
+
48
+ # 2. Read the matrix file to obtain background information and sample characteristics data
49
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
50
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
51
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
52
+
53
+ # 3. Improve readability of clinical feature overview by setting meaningful row labels
54
+ clinical_named = clinical_data.copy()
55
+ if clinical_named.shape[1] > 0:
56
+ # Use the first column as row labels and drop it from data
57
+ clinical_named.index = clinical_named.iloc[:, 0]
58
+ clinical_named = clinical_named.drop(columns=clinical_named.columns[0])
59
+
60
+ # Obtain the sample characteristics dictionary with a concise cap on unique values per feature
61
+ sample_characteristics_dict = get_unique_values_by_row(clinical_named, max_len=20)
62
+
63
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
64
+ print("Background Information:")
65
+ print(background_info)
66
+ print("Sample Characteristics Dictionary:")
67
+ print(sample_characteristics_dict)
68
+
69
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
70
+ # Step 1: Determine gene expression availability based on background info
71
+ # The series uses 2-channel whole human genome Agilent microarrays (mRNA), so gene expression data is available.
72
+ is_gene_available = True
73
+
74
+ # Step 2: Variable availability and conversion functions
75
+ # From the provided sample characteristics, there is no per-sample human clinical information (only a single descriptive line).
76
+ # Therefore, trait (Glioblastoma status), age, and gender are not available.
77
+ trait_row = None
78
+ age_row = None
79
+ gender_row = None
80
+
81
+ # Define conversion functions (will not be used since corresponding rows are None).
82
+ def convert_trait(x):
83
+ # Not available; return None
84
+ return None
85
+
86
+ def convert_age(x):
87
+ # Not available; return None
88
+ return None
89
+
90
+ def convert_gender(x):
91
+ # Not available; return None
92
+ return None
93
+
94
+ # Step 3: Save metadata with 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
+ # Step 4: Clinical Feature Extraction (skip because trait_row is None)
105
+ # If trait_row were available:
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
+ # selected_clinical_df.to_csv(out_clinical_data_file, index=True)
118
+
119
+ # Step 3: Gene Data Extraction
120
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
121
+ gene_data = get_genetic_data(matrix_file)
122
+
123
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
124
+ print(gene_data.index[:20])
125
+
126
+ # Step 4: Gene Identifier Review
127
+ print("requires_gene_mapping = True")
128
+
129
+ # Step 5: Gene Annotation
130
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
131
+ gene_annotation = get_gene_annotation(soft_file)
132
+
133
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
134
+ print("Gene annotation preview:")
135
+ print(preview_df(gene_annotation))
136
+
137
+ # Step 6: Gene Identifier Mapping
138
+ import gzip
139
+ import io
140
+ import pandas as pd
141
+
142
+ # Prepare expression ID set
143
+ expr_ids = set(gene_data.index.astype(str).str.strip())
144
+
145
+ # Parse platform annotation tables from the family SOFT
146
+ platform_tables = []
147
+ capture = False
148
+ buf = []
149
+
150
+ with gzip.open(soft_file, 'rt', errors='ignore') as f:
151
+ for line in f:
152
+ line = line.rstrip('\n')
153
+ if line.startswith('!platform_table_begin'):
154
+ capture = True
155
+ buf = []
156
+ continue
157
+ if line.startswith('!platform_table_end') and capture:
158
+ capture = False
159
+ table_str = '\n'.join(buf)
160
+ try:
161
+ df = pd.read_csv(io.StringIO(table_str), sep='\t', dtype=str, on_bad_lines='skip', low_memory=False)
162
+ platform_tables.append(df)
163
+ except Exception as e:
164
+ print(f"Failed to parse a platform table: {e}")
165
+ continue
166
+ if capture:
167
+ buf.append(line)
168
+
169
+ # If no platform table could be parsed, raise informative error
170
+ if len(platform_tables) == 0:
171
+ raise ValueError("No platform annotation tables were found in the SOFT file between !platform_table_begin/end.")
172
+
173
+ # Identify the best matching table and identifier column by overlap with expression IDs
174
+ best = {'table_idx': None, 'id_col': None, 'overlap': -1}
175
+ overlap_matrix = []
176
+
177
+ for ti, df in enumerate(platform_tables):
178
+ for col in df.columns:
179
+ col_values = set(df[col].dropna().astype(str).str.strip())
180
+ overlap = len(expr_ids.intersection(col_values))
181
+ overlap_matrix.append((ti, col, overlap))
182
+ if overlap > best['overlap']:
183
+ best = {'table_idx': ti, 'id_col': col, 'overlap': overlap}
184
+
185
+ # Print overlap summary for transparency
186
+ print("Overlap counts (table_index, column, overlap):")
187
+ for ti, col, ov in sorted(overlap_matrix, key=lambda x: (-x[2], x[0], x[1]))[:20]:
188
+ print(f"{ti}, {col}, {ov}")
189
+
190
+ # Validate that we have a meaningful overlap
191
+ if best['overlap'] <= 0 or best['table_idx'] is None or best['id_col'] is None:
192
+ raise ValueError(
193
+ "Failed to find any overlap between expression IDs and platform annotation columns. "
194
+ "Cannot proceed with mapping when requires_gene_mapping = True."
195
+ )
196
+
197
+ selected_table = platform_tables[best['table_idx']]
198
+ id_col = best['id_col']
199
+ print(f"Selected table index: {best['table_idx']}")
200
+ print(f"Selected ID column: {id_col} with overlap {best['overlap']}")
201
+
202
+ # Choose a gene symbol column
203
+ preferred_gene_cols = [
204
+ 'Gene Symbol', 'GENE_SYMBOL', 'Gene symbol', 'SYMBOL', 'Symbol', 'GeneSymbol',
205
+ 'GENE SYMBOL', 'ORF', 'GENE', 'Gene', 'Gene Name', 'GENE_NAME', 'GENE NAME', 'Gene Description',
206
+ 'GENE_DESCRIPTION', 'DESCRIPTION', 'Gene title', 'GENE TITLE', 'GB_ACC', 'RefSeq Accession'
207
+ ]
208
+ gene_col = None
209
+ for cand in preferred_gene_cols:
210
+ if cand in selected_table.columns:
211
+ gene_col = cand
212
+ break
213
+
214
+ # If no preferred column found, heuristically select the column that yields the most extractable human symbols
215
+ if gene_col is None:
216
+ def score_gene_column(series: pd.Series) -> int:
217
+ # Count rows where we can extract at least one human gene symbol
218
+ return series.dropna().astype(str).apply(lambda s: len(extract_human_gene_symbols(s)) > 0).sum()
219
+ scores = {col: score_gene_column(selected_table[col]) for col in selected_table.columns if col != id_col}
220
+ # Pick the column with highest score
221
+ if len(scores) > 0:
222
+ gene_col = max(scores, key=scores.get)
223
+ else:
224
+ raise ValueError("No suitable gene symbol column could be identified in the platform table.")
225
+
226
+ print(f"Selected Gene Symbol column: {gene_col}")
227
+
228
+ # Build mapping and ensure overlap isn’t trivial
229
+ mapping_df = get_gene_mapping(selected_table, prob_col=id_col, gene_col=gene_col)
230
+
231
+ mapped_id_overlap = len(set(mapping_df['ID']).intersection(expr_ids))
232
+ print(f"Mapping ID overlap with expression IDs: {mapped_id_overlap}")
233
+
234
+ if mapped_id_overlap <= 0:
235
+ raise ValueError(
236
+ f"Constructed mapping has no overlap with expression IDs using id_col={id_col} and gene_col={gene_col}."
237
+ )
238
+
239
+ # Apply mapping to convert probe-level to gene-level
240
+ mapped_gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
241
+
242
+ # Validate that the mapping produced gene-level data
243
+ if mapped_gene_data.shape[0] == 0:
244
+ raise ValueError("Mapping produced an empty gene expression matrix. Aborting to avoid using unmapped probe data.")
245
+
246
+ print(f"Mapped probes: {mapped_id_overlap}")
247
+ print(f"Resulting genes: {mapped_gene_data.shape[0]}")
248
+
249
+ # Replace gene_data with mapped gene-level data
250
+ gene_data = mapped_gene_data
251
+
252
+ # Step 7: Data Normalization and Linking
253
+ # 1. Normalize gene symbols and save gene-level data
254
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
255
+ normalized_gene_data.to_csv(out_gene_data_file)
256
+
257
+ # 2-6. No clinical/trait data available for this cohort; record availability without triggering final validation
258
+ _ = validate_and_save_cohort_info(
259
+ is_final=False,
260
+ cohort=cohort,
261
+ info_path=json_path,
262
+ is_gene_available=True,
263
+ is_trait_available=False
264
+ )
output/preprocess/Glioblastoma/code/GSE159000.py ADDED
@@ -0,0 +1,203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Glioblastoma"
6
+ cohort = "GSE159000"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Glioblastoma"
10
+ in_cohort_dir = "../DATA/GEO/Glioblastoma/GSE159000"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z3/preprocess/Glioblastoma/GSE159000.csv"
14
+ out_gene_data_file = "./output/z3/preprocess/Glioblastoma/gene_data/GSE159000.csv"
15
+ out_clinical_data_file = "./output/z3/preprocess/Glioblastoma/clinical_data/GSE159000.csv"
16
+ json_path = "./output/z3/preprocess/Glioblastoma/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 # Title indicates "Gene expression profiles"
43
+
44
+ # 2) Variable availability and conversion functions
45
+
46
+ # Trait (Glioblastoma): all samples are GBM patients (constant), so not available
47
+ trait_row = None
48
+
49
+ def convert_trait(x):
50
+ # Map disease status to binary: control/normal=0, GBM/case=1
51
+ if x is None:
52
+ return None
53
+ val = str(x)
54
+ if ':' in val:
55
+ val = val.split(':', 1)[1]
56
+ v = val.strip().lower()
57
+ if v in {'gbm', 'glioblastoma', 'glioblastoma multiforme', 'case', 'tumor', 'tumour', 'cancer', 'patient', 'yes'}:
58
+ return 1
59
+ if v in {'control', 'normal', 'non-tumor', 'non tumour', 'non-tumour', 'healthy', 'adjacent normal', 'no'}:
60
+ return 0
61
+ return None
62
+
63
+ # Age: available at row 2, continuous
64
+ age_row = 2
65
+
66
+ def convert_age(x):
67
+ if x is None:
68
+ return None
69
+ s = str(x)
70
+ if ':' in s:
71
+ s = s.split(':', 1)[1]
72
+ s = s.strip()
73
+ m = re.search(r'[-+]?\d*\.?\d+', s)
74
+ if not m:
75
+ return None
76
+ try:
77
+ return float(m.group())
78
+ except Exception:
79
+ return None
80
+
81
+ # Gender: available at row 1, binary (female=0, male=1)
82
+ gender_row = 1
83
+
84
+ def convert_gender(x):
85
+ if x is None:
86
+ return None
87
+ s = str(x)
88
+ if ':' in s:
89
+ s = s.split(':', 1)[1]
90
+ v = s.strip().lower()
91
+ if v in {'f', 'female', 'woman', 'girl'}:
92
+ return 0
93
+ if v in {'m', 'male', 'man', 'boy'}:
94
+ return 1
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 were available, we would extract and save clinical features as 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 = preview_df(selected_clinical_df, n=5)
121
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
122
+ selected_clinical_df.to_csv(out_clinical_data_file)
123
+
124
+ # Step 3: Gene Data Extraction
125
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
126
+ gene_data = get_genetic_data(matrix_file)
127
+
128
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
129
+ print(gene_data.index[:20])
130
+
131
+ # Step 4: Gene Identifier Review
132
+ print("requires_gene_mapping = True")
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
+ # Ensure required dataframes are available
144
+ if 'gene_annotation' not in locals():
145
+ gene_annotation = get_gene_annotation(soft_file)
146
+ if 'gene_data' not in locals():
147
+ gene_data = get_genetic_data(matrix_file)
148
+
149
+ # 1-2) Decide mapping columns and extract mapping dataframe
150
+ # Probe IDs in expression data are Illumina IDs like 'ILMN_...' which match the 'ID' column in annotation.
151
+ # Gene symbols are in the 'Symbol' column based on the preview.
152
+ prob_col = 'ID'
153
+ gene_col = 'Symbol'
154
+ gene_mapping = get_gene_mapping(gene_annotation, prob_col=prob_col, gene_col=gene_col)
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=gene_mapping)
158
+
159
+ # Step 7: Data Normalization and Linking
160
+ # 1. Normalize gene symbols and save gene-level data
161
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
162
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
163
+ normalized_gene_data.to_csv(out_gene_data_file)
164
+
165
+ # 2. Link clinical and genetic data only if clinical features exist
166
+ linked_data = None
167
+ if 'selected_clinical_data' in locals() and isinstance(selected_clinical_data, pd.DataFrame):
168
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_data, normalized_gene_data)
169
+
170
+ # 3-4. Handle missing values and bias checks only if linked data is available
171
+ if linked_data is not None:
172
+ linked_data = handle_missing_values(linked_data, trait)
173
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
174
+
175
+ # 5. Final validation and save cohort info (clinical data available)
176
+ is_usable = validate_and_save_cohort_info(
177
+ is_final=True,
178
+ cohort=cohort,
179
+ info_path=json_path,
180
+ is_gene_available=True,
181
+ is_trait_available=True,
182
+ is_biased=is_trait_biased,
183
+ df=unbiased_linked_data,
184
+ note="INFO: Linked clinical and genetic data; performed missing value handling and bias checks."
185
+ )
186
+
187
+ # 6. Save linked data only if usable
188
+ if is_usable:
189
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
190
+ unbiased_linked_data.to_csv(out_data_file)
191
+
192
+ else:
193
+ # Trait/clinical data not available; record this and skip linking/imputation
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=False,
200
+ is_biased=False, # Placeholder; not used since is_available will be False
201
+ df=normalized_gene_data, # Provide non-empty df to avoid false gene unavailability
202
+ note="INFO: Trait not available; clinical linking skipped."
203
+ )
output/preprocess/Glioblastoma/code/GSE175700.py ADDED
@@ -0,0 +1,220 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Glioblastoma"
6
+ cohort = "GSE175700"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Glioblastoma"
10
+ in_cohort_dir = "../DATA/GEO/Glioblastoma/GSE175700"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z3/preprocess/Glioblastoma/GSE175700.csv"
14
+ out_gene_data_file = "./output/z3/preprocess/Glioblastoma/gene_data/GSE175700.csv"
15
+ out_clinical_data_file = "./output/z3/preprocess/Glioblastoma/clinical_data/GSE175700.csv"
16
+ json_path = "./output/z3/preprocess/Glioblastoma/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ import re
40
+ import pandas as pd
41
+
42
+ # 1) Gene expression data availability
43
+ # Background indicates microarray-based transcriptome profiling on U87 glioblastoma cell line.
44
+ is_gene_available = True
45
+
46
+ # 2) Variable availability inferred from Sample Characteristics Dictionary:
47
+ # {0: ['tissue: brain'], 1: ['Sex: male']}
48
+ # - Trait (Glioblastoma): not explicitly available and is constant (U87 glioblastoma cell line) -> not usable.
49
+ # - Age: not available.
50
+ # - Gender: constant 'male' -> not usable.
51
+ trait_row = None
52
+ age_row = None
53
+ gender_row = None
54
+
55
+ # 2.2) Converters
56
+ def _extract_value(x):
57
+ if x is None or (isinstance(x, float) and pd.isna(x)):
58
+ return None
59
+ s = str(x)
60
+ v = s.split(":", 1)[1] if ":" in s else s
61
+ v = v.strip()
62
+ if v == "" or v.lower() in {"na", "n/a", "null", "none", "unknown", "not available", "not applicable", "?"}:
63
+ return None
64
+ return v
65
+
66
+ def convert_trait(x):
67
+ v = _extract_value(x)
68
+ if v is None:
69
+ return None
70
+ vl = v.lower()
71
+ # Map to binary: presence of glioblastoma (or glioma/GBM/U87) = 1, otherwise 0
72
+ positive_markers = ["glioblastoma", "gbm", "glioma", "u87"]
73
+ negative_markers = ["normal", "healthy", "control", "non-tumor", "non tumour", "noncancer", "non-cancer"]
74
+ if any(m in vl for m in positive_markers):
75
+ return 1
76
+ if any(m in vl for m in negative_markers):
77
+ return 0
78
+ # If ambiguous (e.g., treatment labels only), return None
79
+ return None
80
+
81
+ def convert_age(x):
82
+ v = _extract_value(x)
83
+ if v is None:
84
+ return None
85
+ # Extract first number as age (years)
86
+ m = re.search(r"(\d+(\.\d+)?)", v)
87
+ if not m:
88
+ return None
89
+ try:
90
+ return float(m.group(1))
91
+ except Exception:
92
+ return None
93
+
94
+ def convert_gender(x):
95
+ v = _extract_value(x)
96
+ if v is None:
97
+ return None
98
+ vl = v.lower()
99
+ if vl in {"female", "f", "woman", "girl"}:
100
+ return 0
101
+ if vl in {"male", "m", "man", "boy"}:
102
+ return 1
103
+ return None
104
+
105
+ # 3) Initial filtering and save metadata
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: skipped because trait_row is None (no usable clinical trait data)
116
+ # If trait_row becomes available in future, uncomment the following:
117
+ # selected_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_df)
128
+ # selected_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
+ 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
+ # Determine appropriate columns for probe IDs and gene symbols from the annotation dataframe
150
+ probe_id_candidates = ['probeset_id', 'ID', 'transcript_cluster_id', 'probe_id', 'PROBESET_ID']
151
+ gene_symbol_candidates = ['gene_assignment', 'Gene Symbol', 'gene_symbol', 'gene', 'mrna_assignment', 'symbol']
152
+
153
+ probe_col = next((c for c in probe_id_candidates if c in gene_annotation.columns), None)
154
+ gene_col = next((c for c in gene_symbol_candidates if c in gene_annotation.columns), None)
155
+
156
+ if probe_col is None or gene_col is None:
157
+ missing = []
158
+ if probe_col is None:
159
+ missing.append('probe identifier column')
160
+ if gene_col is None:
161
+ missing.append('gene symbol column')
162
+ raise ValueError(f"Could not find required column(s) in gene annotation: {', '.join(missing)}")
163
+
164
+ # 2) Build mapping dataframe
165
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=probe_col, gene_col=gene_col)
166
+
167
+ # 3) Apply mapping to convert probe-level data to gene-level data
168
+ gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
169
+
170
+ # Step 7: Data Normalization and Linking
171
+ import os
172
+ import pandas as pd
173
+
174
+ # 1) Normalize gene symbols and save gene-level expression
175
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
176
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
177
+ normalized_gene_data.to_csv(out_gene_data_file)
178
+
179
+ # 2) Link clinical and genetic data only if clinical features were extracted previously and trait is available
180
+ linked_data = None
181
+ clinical_var = None
182
+ if 'selected_clinical_data' in globals() and isinstance(selected_clinical_data, pd.DataFrame):
183
+ clinical_var = selected_clinical_data
184
+ elif 'selected_df' in globals() and isinstance(selected_df, pd.DataFrame):
185
+ clinical_var = selected_df
186
+
187
+ if clinical_var is not None and ('trait_row' in globals() and trait_row is not None):
188
+ linked_data = geo_link_clinical_genetic_data(clinical_var, normalized_gene_data)
189
+
190
+ # 3) Handle missing values
191
+ linked_data = handle_missing_values(linked_data, trait)
192
+
193
+ # 4) Bias assessment
194
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
195
+
196
+ # 5) Final validation and save cohort info
197
+ is_usable = validate_and_save_cohort_info(
198
+ is_final=True,
199
+ cohort=cohort,
200
+ info_path=json_path,
201
+ is_gene_available=True,
202
+ is_trait_available=True,
203
+ is_biased=is_trait_biased,
204
+ df=unbiased_linked_data,
205
+ note="INFO: Clinical trait data present and linked."
206
+ )
207
+
208
+ # 6) Save linked data only if usable
209
+ if is_usable:
210
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
211
+ unbiased_linked_data.to_csv(out_data_file)
212
+ else:
213
+ # No usable clinical trait data; record metadata with initial filtering only.
214
+ validate_and_save_cohort_info(
215
+ is_final=False,
216
+ cohort=cohort,
217
+ info_path=json_path,
218
+ is_gene_available=True,
219
+ is_trait_available=False
220
+ )
output/preprocess/Glioblastoma/code/GSE178236.py ADDED
@@ -0,0 +1,222 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Glioblastoma"
6
+ cohort = "GSE178236"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Glioblastoma"
10
+ in_cohort_dir = "../DATA/GEO/Glioblastoma/GSE178236"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z3/preprocess/Glioblastoma/GSE178236.csv"
14
+ out_gene_data_file = "./output/z3/preprocess/Glioblastoma/gene_data/GSE178236.csv"
15
+ out_clinical_data_file = "./output/z3/preprocess/Glioblastoma/clinical_data/GSE178236.csv"
16
+ json_path = "./output/z3/preprocess/Glioblastoma/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 # Genome-wide gene expression profiling indicated in background info
41
+
42
+ # Step 2: Variable availability and converters based on Sample Characteristics Dictionary
43
+ # From the dictionary:
44
+ # 1 -> gender, 2 -> age; Trait (Glioblastoma) is constant across samples -> not usable
45
+ trait_row = None
46
+ age_row = 2
47
+ gender_row = 1
48
+
49
+ def _extract_after_colon(x):
50
+ if x is None:
51
+ return None
52
+ if isinstance(x, str):
53
+ parts = x.split(":", 1)
54
+ val = parts[1].strip() if len(parts) > 1 else x.strip()
55
+ val = val.strip().strip('"').strip("'")
56
+ return val if val != "" else None
57
+ return x
58
+
59
+ def convert_trait(x):
60
+ # Not used since trait_row is None; define robustly if needed
61
+ v = _extract_after_colon(x)
62
+ if v is None:
63
+ return None
64
+ v_low = str(v).lower()
65
+ # Map glioblastoma-related indications to 1, others to 0 (if ever used)
66
+ if "glioblastoma" in v_low or "gbm" in v_low:
67
+ return 1
68
+ if v_low in {"control", "normal", "healthy"}:
69
+ return 0
70
+ return None
71
+
72
+ def convert_age(x):
73
+ v = _extract_after_colon(x)
74
+ if v is None:
75
+ return None
76
+ v_low = str(v).lower()
77
+ if v_low in {"na", "n/a", "nan", "none", "unknown", ""}:
78
+ return None
79
+ # Keep only digits and potential decimal point
80
+ try:
81
+ return float(v)
82
+ except Exception:
83
+ # Try to parse integers embedded in strings
84
+ import re
85
+ nums = re.findall(r"[-+]?\d*\.?\d+", v_low)
86
+ if nums:
87
+ try:
88
+ return float(nums[0])
89
+ except Exception:
90
+ return None
91
+ return None
92
+
93
+ def convert_gender(x):
94
+ v = _extract_after_colon(x)
95
+ if v is None:
96
+ return None
97
+ v_low = str(v).lower().strip()
98
+ if v_low in {"male", "m"}:
99
+ return 1
100
+ if v_low in {"female", "f"}:
101
+ return 0
102
+ if v_low in {"na", "n/a", "nan", "none", "unknown", ""}:
103
+ return None
104
+ return None
105
+
106
+ # Step 3: Save metadata (initial filtering)
107
+ is_trait_available = trait_row is not None
108
+ _ = validate_and_save_cohort_info(
109
+ is_final=False,
110
+ cohort=cohort,
111
+ info_path=json_path,
112
+ is_gene_available=is_gene_available,
113
+ is_trait_available=is_trait_available
114
+ )
115
+
116
+ # Step 4: Clinical Feature Extraction (skip because trait_row is None)
117
+ # If trait_row were available, we would extract and save clinical features like below:
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_df(selected_clinical_df)
130
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
131
+ selected_clinical_df.to_csv(out_clinical_data_file, index=True)
132
+
133
+ # Step 3: Gene Data Extraction
134
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
135
+ gene_data = get_genetic_data(matrix_file)
136
+
137
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
138
+ print(gene_data.index[:20])
139
+
140
+ # Step 4: Gene Identifier Review
141
+ requires_gene_mapping = True
142
+ print(f"requires_gene_mapping = {requires_gene_mapping}")
143
+
144
+ # Step 5: Gene Annotation
145
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
146
+ gene_annotation = get_gene_annotation(soft_file)
147
+
148
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
149
+ print("Gene annotation preview:")
150
+ print(preview_df(gene_annotation))
151
+
152
+ # Step 6: Gene Identifier Mapping
153
+ # Identify the appropriate columns for probe IDs and gene symbols
154
+ probe_col = 'ID' # Matches ILMN_* probe IDs seen in the expression data
155
+ gene_col = 'Symbol' # Gene symbols column in the annotation
156
+
157
+ # Build the probe-to-gene mapping dataframe
158
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=probe_col, gene_col=gene_col)
159
+
160
+ # Apply mapping to convert probe-level data to gene-level expression
161
+ probe_data = gene_data # keep original probe-level data
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 gene-level data
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
+ # Determine trait availability based on previous steps
173
+ trait_available = ('trait_row' in globals()) and (trait_row is not None)
174
+
175
+ if trait_available:
176
+ # Ensure clinical features are extracted before linking
177
+ selected_clinical_data = geo_select_clinical_features(
178
+ clinical_df=clinical_data,
179
+ trait=trait,
180
+ trait_row=trait_row,
181
+ convert_trait=convert_trait,
182
+ age_row=age_row if 'age_row' in globals() else None,
183
+ convert_age=convert_age if 'convert_age' in globals() else None,
184
+ gender_row=gender_row if 'gender_row' in globals() else None,
185
+ convert_gender=convert_gender if 'convert_gender' in globals() else None
186
+ )
187
+
188
+ # 2. Link the clinical and genetic data
189
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_data, normalized_gene_data)
190
+
191
+ # 3. Handle missing values
192
+ linked_data = handle_missing_values(linked_data, trait)
193
+
194
+ # 4. Bias checks (trait determines usability; biased covariates are dropped)
195
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
196
+
197
+ # 5. Final validation and save cohort info
198
+ is_usable = validate_and_save_cohort_info(
199
+ is_final=True,
200
+ cohort=cohort,
201
+ info_path=json_path,
202
+ is_gene_available=True,
203
+ is_trait_available=True,
204
+ is_biased=is_trait_biased,
205
+ df=unbiased_linked_data,
206
+ note="INFO: Proceeded with full preprocessing; clinical features extracted and linked."
207
+ )
208
+
209
+ # 6. Save linked data only if usable
210
+ if is_usable:
211
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
212
+ unbiased_linked_data.to_csv(out_data_file)
213
+
214
+ else:
215
+ # Trait not available; cannot proceed with linking or final validation
216
+ _ = validate_and_save_cohort_info(
217
+ is_final=False,
218
+ cohort=cohort,
219
+ info_path=json_path,
220
+ is_gene_available=True,
221
+ is_trait_available=False
222
+ )
output/preprocess/Glioblastoma/code/GSE226976.py ADDED
@@ -0,0 +1,191 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Glioblastoma"
6
+ cohort = "GSE226976"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Glioblastoma"
10
+ in_cohort_dir = "../DATA/GEO/Glioblastoma/GSE226976"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z3/preprocess/Glioblastoma/GSE226976.csv"
14
+ out_gene_data_file = "./output/z3/preprocess/Glioblastoma/gene_data/GSE226976.csv"
15
+ out_clinical_data_file = "./output/z3/preprocess/Glioblastoma/clinical_data/GSE226976.csv"
16
+ json_path = "./output/z3/preprocess/Glioblastoma/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ # Step 1: Determine gene expression availability based on background info
40
+ is_gene_available = True # "Gene expression data for samples included in this trial..."
41
+
42
+ # Step 2: Variable availability and converters
43
+ # Sample Characteristics only has one constant field: {0: ['sample type: recurrent glioma']}
44
+ # No varying trait/age/gender information is available.
45
+ trait_row = None
46
+ age_row = None
47
+ gender_row = None
48
+
49
+ # Converters (robust implementations, though not used since rows are None)
50
+ def _after_colon(x: str) -> str:
51
+ if x is None:
52
+ return ""
53
+ parts = str(x).split(":", 1)
54
+ return parts[1].strip() if len(parts) == 2 else str(x).strip()
55
+
56
+ def convert_trait(x):
57
+ v = _after_colon(x).lower()
58
+ if v == "":
59
+ return None
60
+ # Map glioblastoma/GBM to 1, other gliomas to 0
61
+ if any(k in v for k in ["glioblastoma", "gbm", "grade iv"]):
62
+ return 1
63
+ if "glioma" in v:
64
+ return 0
65
+ return None
66
+
67
+ def convert_age(x):
68
+ v = _after_colon(x)
69
+ if not v:
70
+ return None
71
+ # Extract first number as age
72
+ import re
73
+ m = re.search(r"(\d+(\.\d+)?)", v)
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
+ v = _after_colon(x).lower()
83
+ if not v:
84
+ return None
85
+ if v in ["male", "m", "man"]:
86
+ return 1
87
+ if v in ["female", "f", "woman"]:
88
+ return 0
89
+ return None
90
+
91
+ # Step 3: Save metadata (initial filtering)
92
+ is_trait_available = trait_row is not None
93
+ _ = validate_and_save_cohort_info(
94
+ is_final=False,
95
+ cohort=cohort,
96
+ info_path=json_path,
97
+ is_gene_available=is_gene_available,
98
+ is_trait_available=is_trait_available
99
+ )
100
+
101
+ # Step 4: Clinical feature extraction (skip because trait_row is None)
102
+ # If trait_row were available, we would extract and save clinical features:
103
+ if trait_row is not None:
104
+ selected_clinical_df = geo_select_clinical_features(
105
+ clinical_df=clinical_data,
106
+ trait=trait,
107
+ trait_row=trait_row,
108
+ convert_trait=convert_trait,
109
+ age_row=age_row,
110
+ convert_age=convert_age,
111
+ gender_row=gender_row,
112
+ convert_gender=convert_gender
113
+ )
114
+ clinical_preview = preview_df(selected_clinical_df, n=5)
115
+ os.makedirs(os.path.dirname(out_clinical_data_file), 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
+ # The displayed identifiers (e.g., A2M, AKT1, APOE) are standard human gene symbols (HGNC).
127
+ requires_gene_mapping = False
128
+ print(f"requires_gene_mapping = {requires_gene_mapping}")
129
+
130
+ # Step 5: Data Normalization and Linking
131
+ import os
132
+
133
+ # 1) Normalize gene symbols and save gene expression matrix
134
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
135
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
136
+ normalized_gene_data.to_csv(out_gene_data_file)
137
+
138
+ # 2) Link clinical and genetic data if trait is available; otherwise skip linking
139
+ linked_data = None
140
+ is_trait_available = ('trait_row' in locals()) and (trait_row is not None)
141
+
142
+ if is_trait_available:
143
+ # Build clinical dataframe (in case not created previously)
144
+ selected_clinical_data = geo_select_clinical_features(
145
+ clinical_df=clinical_data,
146
+ trait=trait,
147
+ trait_row=trait_row,
148
+ convert_trait=convert_trait,
149
+ age_row=age_row,
150
+ convert_age=convert_age,
151
+ gender_row=gender_row,
152
+ convert_gender=convert_gender
153
+ )
154
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_data, normalized_gene_data)
155
+
156
+ # 3) Handle missing values using the specified rules
157
+ linked_data = handle_missing_values(linked_data, trait)
158
+
159
+ # 4) Judge bias and drop biased demographics
160
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
161
+
162
+ # 5) Final validation and metadata
163
+ is_usable = validate_and_save_cohort_info(
164
+ is_final=True,
165
+ cohort=cohort,
166
+ info_path=json_path,
167
+ is_gene_available=True,
168
+ is_trait_available=True,
169
+ is_biased=is_trait_biased,
170
+ df=unbiased_linked_data,
171
+ note="INFO: Linked clinical and genetic data; performed QC and bias checks."
172
+ )
173
+
174
+ # 6) Save linked data only if usable
175
+ if is_usable:
176
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
177
+ unbiased_linked_data.to_csv(out_data_file)
178
+
179
+ else:
180
+ # No trait available: skip linking, validate metadata using gene data only
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=False,
187
+ is_biased=False, # Ignored since trait not available
188
+ df=normalized_gene_data.T, # So sample_size can still be recorded
189
+ note="INFO: Trait not available in sample characteristics; saved normalized gene expression only."
190
+ )
191
+ # Do not save out_data_file when trait is unavailable
output/preprocess/Glioblastoma/code/GSE249289.py ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Glioblastoma"
6
+ cohort = "GSE249289"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Glioblastoma"
10
+ in_cohort_dir = "../DATA/GEO/Glioblastoma/GSE249289"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z3/preprocess/Glioblastoma/GSE249289.csv"
14
+ out_gene_data_file = "./output/z3/preprocess/Glioblastoma/gene_data/GSE249289.csv"
15
+ out_clinical_data_file = "./output/z3/preprocess/Glioblastoma/clinical_data/GSE249289.csv"
16
+ json_path = "./output/z3/preprocess/Glioblastoma/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 # Title and summary indicate gene expression profiling
43
+
44
+ # 2) Variable availability and converters
45
+ # From Sample Characteristics Dictionary:
46
+ # 0: tissue: Brain (constant, not useful)
47
+ # 1: Sex: Male/Female
48
+ # 2: age: values
49
+ # 3: tumorsphere IDs (irrelevant for current variables)
50
+ # 4: culture platform (not the trait of interest)
51
+ trait_row = None # Trait (Glioblastoma) is constant across samples, thus not available for association
52
+ age_row = 2
53
+ gender_row = 1
54
+
55
+ def convert_trait(x):
56
+ # Not used since trait_row is None; return None for safety
57
+ return None
58
+
59
+ def convert_age(x):
60
+ if x is None:
61
+ return None
62
+ s = str(x).strip()
63
+ if ':' in s:
64
+ s = s.split(':', 1)[1].strip()
65
+ # Remove common age unit words
66
+ s = re.sub(r'\b(years?|yrs?|yo)\b', '', s, flags=re.IGNORECASE).strip()
67
+ m = re.search(r'(\d+(\.\d+)?)', s)
68
+ if not m:
69
+ return None
70
+ val = float(m.group(1))
71
+ # Prefer integer when appropriate
72
+ return int(val) if abs(val - int(val)) < 1e-6 else val
73
+
74
+ def convert_gender(x):
75
+ if x is None:
76
+ return None
77
+ s = str(x).strip()
78
+ if ':' in s:
79
+ s = s.split(':', 1)[1].strip()
80
+ s_low = s.lower()
81
+ if s_low in {'male', 'm', 'man'}:
82
+ return 1
83
+ if s_low in {'female', 'f', 'woman'}:
84
+ return 0
85
+ return None
86
+
87
+ # 3) Save metadata with initial filtering
88
+ is_trait_available = trait_row is not None
89
+ _ = validate_and_save_cohort_info(
90
+ is_final=False,
91
+ cohort=cohort,
92
+ info_path=json_path,
93
+ is_gene_available=is_gene_available,
94
+ is_trait_available=is_trait_available
95
+ )
96
+
97
+ # 4) Clinical Feature Extraction (skip because trait_row is None)
98
+ if trait_row is not None:
99
+ selected_clinical_df = geo_select_clinical_features(
100
+ clinical_df=clinical_data,
101
+ trait=trait,
102
+ trait_row=trait_row,
103
+ convert_trait=convert_trait,
104
+ age_row=age_row,
105
+ convert_age=convert_age,
106
+ gender_row=gender_row,
107
+ convert_gender=convert_gender
108
+ )
109
+ clinical_preview = preview_df(selected_clinical_df)
110
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
111
+ selected_clinical_df.to_csv(out_clinical_data_file)
112
+
113
+ # Step 3: Gene Data Extraction
114
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
115
+ gene_data = get_genetic_data(matrix_file)
116
+
117
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
118
+ print(gene_data.index[:20])
119
+
120
+ # Step 4: Gene Identifier Review
121
+ print("requires_gene_mapping = True")
122
+
123
+ # Step 5: Gene Annotation
124
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
125
+ gene_annotation = get_gene_annotation(soft_file)
126
+
127
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
128
+ print("Gene annotation preview:")
129
+ print(preview_df(gene_annotation))
130
+
131
+ # Step 6: Gene Identifier Mapping
132
+ # Identify columns for probe IDs and gene symbols based on annotation preview:
133
+ # Probe ID column: 'ID' matches probe identifiers like 'ILMN_1343291'
134
+ # Gene symbol column: 'Symbol' contains gene symbols / descriptive strings from which symbols can be extracted
135
+
136
+ # 1-2) Build mapping dataframe from annotation
137
+ mapping_df = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='Symbol')
138
+
139
+ # 3) Apply mapping to convert probe-level data to gene-level expression
140
+ probe_data = gene_data # keep original probe-level data
141
+ gene_data = apply_gene_mapping(expression_df=probe_data, mapping_df=mapping_df)
output/preprocess/Glioblastoma/code/GSE279426.py ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Glioblastoma"
6
+ cohort = "GSE279426"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Glioblastoma"
10
+ in_cohort_dir = "../DATA/GEO/Glioblastoma/GSE279426"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z3/preprocess/Glioblastoma/GSE279426.csv"
14
+ out_gene_data_file = "./output/z3/preprocess/Glioblastoma/gene_data/GSE279426.csv"
15
+ out_clinical_data_file = "./output/z3/preprocess/Glioblastoma/clinical_data/GSE279426.csv"
16
+ json_path = "./output/z3/preprocess/Glioblastoma/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
+ from typing import Optional, Union
41
+
42
+ # 1) Gene expression availability
43
+ is_gene_available = True # Series title/summary indicate mRNA expression data, not miRNA/methylation.
44
+
45
+ # 2) Variable availability based on Sample Characteristics Dictionary:
46
+ # Keys observed:
47
+ # 0: name_in_pmid_21471286 (IDs)
48
+ # 1: alternative_name (IDs)
49
+ # 2: treatment_gefitinib (T0/T1/T2)
50
+ # 3: type (human/xenograft)
51
+ # 4: egfr_amplification (A0/A1)
52
+ # 5: disease (GBM) [constant]
53
+ trait_row = None # No case/control or equivalent for "Glioblastoma"; disease is constant GBM.
54
+ age_row = None # No age field present.
55
+ gender_row = None # No gender field present.
56
+
57
+ # 2.2) Data type conversion functions (defined for interface completeness; they will not be used since rows are None)
58
+ def _after_colon(x: str) -> Optional[str]:
59
+ if x is None:
60
+ return None
61
+ if isinstance(x, str):
62
+ parts = x.split(":", 1)
63
+ return parts[1].strip() if len(parts) == 2 else x.strip()
64
+ return None
65
+
66
+ def convert_trait(x: str) -> Optional[int]:
67
+ """
68
+ Map disease or related indicators to binary if applicable:
69
+ - glioblastoma/gbm -> 1
70
+ - normal/control/non-disease -> 0
71
+ Unknowns -> None
72
+ """
73
+ v = _after_colon(x)
74
+ if v is None:
75
+ return None
76
+ vl = v.lower()
77
+ # Common disease indicators
78
+ if any(k in vl for k in ["glioblastoma", "gbm"]):
79
+ return 1
80
+ if any(k in vl for k in ["normal", "control", "healthy", "non-disease", "non disease"]):
81
+ return 0
82
+ # If field is treatment (T0/T1/T2) or other irrelevant fields, we cannot infer trait robustly
83
+ return None
84
+
85
+ def convert_age(x: str) -> Optional[float]:
86
+ v = _after_colon(x)
87
+ if v is None:
88
+ return None
89
+ # Extract number (years assumed if unspecified)
90
+ m = re.search(r"(\d+(\.\d+)?)", v)
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(x: str) -> Optional[int]:
99
+ v = _after_colon(x)
100
+ if v is None:
101
+ return None
102
+ vl = v.strip().lower()
103
+ # Standardize common gender representations
104
+ if vl in ["male", "m", "man"]:
105
+ return 1
106
+ if vl in ["female", "f", "woman", "women"]:
107
+ return 0
108
+ return None
109
+
110
+ # 3) Save initial metadata (trait availability determined by trait_row is None)
111
+ is_trait_available = trait_row is not None
112
+ _ = validate_and_save_cohort_info(
113
+ is_final=False,
114
+ cohort=cohort,
115
+ info_path=json_path,
116
+ is_gene_available=is_gene_available,
117
+ is_trait_available=is_trait_available
118
+ )
119
+
120
+ # 4) Clinical Feature Extraction
121
+ # Skipped because trait_row is None (no clinical trait data available for the target trait).
122
+ # If trait_row were available, we would run:
123
+ # selected_clinical_df = geo_select_clinical_features(
124
+ # clinical_df=clinical_data,
125
+ # trait=trait,
126
+ # trait_row=trait_row,
127
+ # convert_trait=convert_trait,
128
+ # age_row=age_row,
129
+ # convert_age=convert_age,
130
+ # gender_row=gender_row,
131
+ # convert_gender=convert_gender
132
+ # )
133
+ # preview = preview_df(selected_clinical_df)
134
+ # os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
135
+ # selected_clinical_df.to_csv(out_clinical_data_file, index=True)
output/preprocess/Glioblastoma/code/GSE39144.py ADDED
@@ -0,0 +1,228 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Glioblastoma"
6
+ cohort = "GSE39144"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Glioblastoma"
10
+ in_cohort_dir = "../DATA/GEO/Glioblastoma/GSE39144"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z3/preprocess/Glioblastoma/GSE39144.csv"
14
+ out_gene_data_file = "./output/z3/preprocess/Glioblastoma/gene_data/GSE39144.csv"
15
+ out_clinical_data_file = "./output/z3/preprocess/Glioblastoma/clinical_data/GSE39144.csv"
16
+ json_path = "./output/z3/preprocess/Glioblastoma/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
+ # Platform: Affymetrix Human Genome U133 Plus 2.0 Array (mRNA expression), so gene data is available.
45
+ is_gene_available = True
46
+
47
+ # 2. Variable Availability and Data Type Conversion
48
+
49
+ # Choose keys (rows) for variables based on Sample Characteristics Dictionary
50
+ # Trait (Glioblastoma): inferred from 'cell type: glioma-initiating cells ...' under key 0
51
+ trait_row = 0
52
+
53
+ # Age: age information is inconsistently embedded in 'source' text and not reliably available across samples
54
+ age_row = None
55
+
56
+ # Gender: dedicated gender row exists at key 2
57
+ gender_row = 2
58
+
59
+ # Conversion functions
60
+ def _after_colon(x: str) -> str:
61
+ if x is None:
62
+ return ''
63
+ s = str(x)
64
+ parts = s.split(':', 1)
65
+ return parts[1].strip() if len(parts) == 2 else s.strip()
66
+
67
+ def convert_trait(x):
68
+ """
69
+ Map to binary: Glioblastoma (glioma-initiating cells / glioblastoma tissues) -> 1; others -> 0.
70
+ Heuristic: presence of keywords indicates glioblastoma-derived samples.
71
+ """
72
+ if x is None:
73
+ return None
74
+ val = _after_colon(x).lower()
75
+ if any(k in val for k in ['glioblastoma', 'glioma-initiating']):
76
+ return 1
77
+ # For this series, non-glioma entries include iPSC/ESC/NSC/tissues; treat as controls.
78
+ return 0
79
+
80
+ def convert_age(x):
81
+ """
82
+ Not used (age_row=None). If needed, attempts to parse '36-year-old' as 36.
83
+ Gestational weeks or pooled/unknown will return None.
84
+ """
85
+ if x is None:
86
+ return None
87
+ val = _after_colon(x).lower()
88
+ # Parse patterns like '36-year-old'
89
+ m = re.search(r'(\d+)\s*-\s*year\s*-\s*old|(\d+)\s*year\s*old|(\d+)\s*years?\s*old', val)
90
+ if m:
91
+ # Extract the first non-None capturing group
92
+ for g in m.groups():
93
+ if g is not None:
94
+ try:
95
+ return float(g)
96
+ except Exception:
97
+ pass
98
+ # Do not convert gestational weeks or other formats
99
+ return None
100
+
101
+ def convert_gender(x):
102
+ """
103
+ Map gender to binary: female -> 0, male -> 1.
104
+ Pooled or mixed sexes -> None.
105
+ """
106
+ if x is None:
107
+ return None
108
+ val = _after_colon(x).strip().lower()
109
+ if val in ['female']:
110
+ return 0
111
+ if val in ['male']:
112
+ return 1
113
+ if val in ['pooled male']:
114
+ return 1
115
+ if val in ['pooled female']:
116
+ return 0
117
+ if val in ['pooled', 'male and female', 'female and male']:
118
+ return None
119
+ # If unexpected text contains male/female exclusively
120
+ if 'male' in val and 'female' not in val:
121
+ return 1
122
+ if 'female' in val and 'male' not in val:
123
+ return 0
124
+ return None
125
+
126
+ # 3. Save Metadata (initial filtering)
127
+ is_trait_available = trait_row is not None
128
+ _ = validate_and_save_cohort_info(
129
+ is_final=False,
130
+ cohort=cohort,
131
+ info_path=json_path,
132
+ is_gene_available=is_gene_available,
133
+ is_trait_available=is_trait_available
134
+ )
135
+
136
+ # 4. Clinical Feature Extraction (only if trait data is available)
137
+ if trait_row is not None:
138
+ selected_clinical_df = geo_select_clinical_features(
139
+ clinical_df=clinical_data,
140
+ trait=trait,
141
+ trait_row=trait_row,
142
+ convert_trait=convert_trait,
143
+ age_row=age_row,
144
+ convert_age=convert_age,
145
+ gender_row=gender_row,
146
+ convert_gender=convert_gender
147
+ )
148
+ # Preview and save
149
+ preview = preview_df(selected_clinical_df, n=5)
150
+ print("Clinical features preview:", preview)
151
+
152
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
153
+ selected_clinical_df.to_csv(out_clinical_data_file)
154
+
155
+ # Step 3: Gene Data Extraction
156
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
157
+ gene_data = get_genetic_data(matrix_file)
158
+
159
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
160
+ print(gene_data.index[:20])
161
+
162
+ # Step 4: Gene Identifier Review
163
+ print("requires_gene_mapping = True")
164
+
165
+ # Step 5: Gene Annotation
166
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
167
+ gene_annotation = get_gene_annotation(soft_file)
168
+
169
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
170
+ print("Gene annotation preview:")
171
+ print(preview_df(gene_annotation))
172
+
173
+ # Step 6: Gene Identifier Mapping
174
+ # Determine the appropriate columns for mapping based on the annotation preview:
175
+ # - Probe identifiers: 'ID' (matches expression data index like '1007_s_at')
176
+ # - Gene symbols: 'Gene Symbol'
177
+
178
+ # 1-2. Build the mapping dataframe
179
+ prob_col = 'ID'
180
+ gene_col = 'Gene Symbol'
181
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=prob_col, gene_col=gene_col)
182
+
183
+ # 3. Apply mapping to convert probe-level data to gene-level expression
184
+ gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
185
+
186
+ # Step 7: Data Normalization and Linking
187
+ import os
188
+ import pandas as pd
189
+
190
+ # Ensure clinical features are available in the session; reload from disk if necessary
191
+ if 'selected_clinical_df' not in locals():
192
+ selected_clinical_df = pd.read_csv(out_clinical_data_file, index_col=0)
193
+
194
+ # 1. Normalize gene symbols and save
195
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
196
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
197
+ normalized_gene_data.to_csv(out_gene_data_file)
198
+
199
+ # 2. Link clinical and genetic data
200
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
201
+
202
+ # 3. Handle missing values
203
+ linked_data = handle_missing_values(linked_data, trait)
204
+
205
+ # 4. Judge trait/demographic bias and drop biased demographics
206
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
207
+
208
+ # 5. Final validation and save cohort info
209
+ # Cast to native Python bools to avoid JSON serialization issues
210
+ is_gene_available = bool((normalized_gene_data.shape[0] > 0) and (normalized_gene_data.shape[1] > 0))
211
+ is_trait_available = bool((trait in selected_clinical_df.index) and bool(selected_clinical_df.loc[trait].notna().any()))
212
+
213
+ note = "INFO: Age not available; gender partially missing/pooled; trait inferred from cell type keywords."
214
+ is_usable = validate_and_save_cohort_info(
215
+ is_final=True,
216
+ cohort=cohort,
217
+ info_path=json_path,
218
+ is_gene_available=is_gene_available,
219
+ is_trait_available=is_trait_available,
220
+ is_biased=bool(is_trait_biased),
221
+ df=unbiased_linked_data,
222
+ note=note
223
+ )
224
+
225
+ # 6. Save linked data if usable
226
+ if is_usable:
227
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
228
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Glioblastoma/code/TCGA.py ADDED
@@ -0,0 +1,269 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Glioblastoma"
6
+
7
+ # Input paths
8
+ tcga_root_dir = "../DATA/TCGA"
9
+
10
+ # Output paths
11
+ out_data_file = "./output/z3/preprocess/Glioblastoma/TCGA.csv"
12
+ out_gene_data_file = "./output/z3/preprocess/Glioblastoma/gene_data/TCGA.csv"
13
+ out_clinical_data_file = "./output/z3/preprocess/Glioblastoma/clinical_data/TCGA.csv"
14
+ json_path = "./output/z3/preprocess/Glioblastoma/cohort_info.json"
15
+
16
+
17
+ # Step 1: Initial Data Loading
18
+ import os
19
+ import pandas as pd
20
+
21
+ # 1) Select the most specific cohort directory for Glioblastoma
22
+ preferred_dirs = [
23
+ 'TCGA_Glioblastoma_(GBM)',
24
+ 'TCGA_lower_grade_glioma_and_glioblastoma_(GBMLGG)',
25
+ 'TCGA_Lower_Grade_Glioma_(LGG)'
26
+ ]
27
+
28
+ available_dirs = [d for d in os.listdir(tcga_root_dir) if os.path.isdir(os.path.join(tcga_root_dir, d))]
29
+ selected_cohort_dir_name = None
30
+ for d in preferred_dirs:
31
+ if d in available_dirs:
32
+ selected_cohort_dir_name = d
33
+ break
34
+
35
+ if selected_cohort_dir_name is None:
36
+ print("No suitable TCGA subdirectory found for Glioblastoma. Skipping this trait.")
37
+ else:
38
+ cohort_dir = os.path.join(tcga_root_dir, selected_cohort_dir_name)
39
+
40
+ # 2) Identify clinical and genetic file paths
41
+ clinical_file_path, genetic_file_path = tcga_get_relevant_filepaths(cohort_dir)
42
+
43
+ # 3) Load both files as DataFrames
44
+ clinical_df = pd.read_csv(clinical_file_path, sep='\t', index_col=0, compression='infer', low_memory=False)
45
+ genetic_df = pd.read_csv(genetic_file_path, sep='\t', index_col=0, compression='infer', low_memory=False)
46
+
47
+ # 4) Print clinical column names
48
+ print(list(clinical_df.columns))
49
+
50
+ # Step 2: Find Candidate Demographic Features
51
+ import os
52
+ import pandas as pd
53
+
54
+ # Locate the GBM cohort directory under the TCGA root
55
+ cohort_dirs = [os.path.join(tcga_root_dir, d) for d in os.listdir(tcga_root_dir)
56
+ if os.path.isdir(os.path.join(tcga_root_dir, d)) and 'gbm' in d.lower()]
57
+ if not cohort_dirs:
58
+ raise FileNotFoundError("Could not find a GBM cohort directory under tcga_root_dir.")
59
+ cohort_dir = cohort_dirs[0]
60
+
61
+ # Get clinical and genetic file paths
62
+ clinical_file_path, genetic_file_path = tcga_get_relevant_filepaths(cohort_dir)
63
+
64
+ # Load clinical data
65
+ clinical_df = pd.read_csv(clinical_file_path, sep='\t', index_col=0, dtype=str)
66
+
67
+ # Identify candidate columns for age and gender
68
+ cols_lower = {c: c.lower() for c in clinical_df.columns}
69
+ candidate_age_cols = []
70
+ candidate_gender_cols = []
71
+
72
+ for c, cl in cols_lower.items():
73
+ # Age-related: include 'age' (but not 'stage') and 'birth'
74
+ if ('age' in cl and 'stage' not in cl) or ('birth' in cl):
75
+ candidate_age_cols.append(c)
76
+ # Gender-related: include 'gender' or 'sex'
77
+ if ('gender' in cl) or (cl == 'sex') or (cl.startswith('sex_')) or ('_sex' in cl):
78
+ candidate_gender_cols.append(c)
79
+
80
+ # Print candidate lists in the required strict format
81
+ print(f"candidate_age_cols = {candidate_age_cols}")
82
+ print(f"candidate_gender_cols = {candidate_gender_cols}")
83
+
84
+ # Extract and preview candidate columns (first 5 values) as dictionaries
85
+ if candidate_age_cols:
86
+ age_preview = preview_df(clinical_df[candidate_age_cols], n=5)
87
+ print(age_preview)
88
+
89
+ if candidate_gender_cols:
90
+ gender_preview = preview_df(clinical_df[candidate_gender_cols], n=5)
91
+ print(gender_preview)
92
+
93
+ # Step 3: Select Demographic Features
94
+ import re
95
+ import math
96
+
97
+ # Helper functions
98
+ def is_missing(v):
99
+ if v is None:
100
+ return True
101
+ if isinstance(v, float):
102
+ return math.isnan(v)
103
+ if isinstance(v, str):
104
+ return v.strip().lower() in ("", "na", "nan", "null", "none")
105
+ return False
106
+
107
+ def find_preview_dict(candidate_keys):
108
+ best_dict = None
109
+ best_match_count = -1
110
+ for name, obj in globals().items():
111
+ if isinstance(obj, dict) and len(obj) > 0:
112
+ keys = list(obj.keys())
113
+ if all(isinstance(k, str) for k in keys) and all(isinstance(obj[k], list) for k in keys):
114
+ match_count = sum(1 for k in keys if k in candidate_keys)
115
+ if match_count > best_match_count and match_count > 0:
116
+ best_match_count = match_count
117
+ best_dict = obj
118
+ return best_dict
119
+
120
+ def extract_number(s):
121
+ # Use same logic as tcga_convert_age if available; otherwise fallback
122
+ try:
123
+ return tcga_convert_age(s)
124
+ except Exception:
125
+ pass
126
+ m = re.search(r'\d+', str(s))
127
+ return int(m.group()) if m else None
128
+
129
+ def choose_age_col(age_dict, candidate_cols):
130
+ if not age_dict:
131
+ return None
132
+ best_col = None
133
+ best_plausible = -1
134
+ best_present = -1
135
+ for col in candidate_cols:
136
+ if col not in age_dict:
137
+ continue
138
+ vals = age_dict[col]
139
+ nums = [extract_number(v) for v in vals if not is_missing(v)]
140
+ present = len(nums)
141
+ plausible = sum(1 for n in nums if n is not None and 0 < n <= 120)
142
+ # Prefer columns with more plausible ages; tie-breaker: more present values
143
+ if plausible > best_plausible or (plausible == best_plausible and present > best_present):
144
+ best_plausible = plausible
145
+ best_present = present
146
+ best_col = col
147
+ # Require at least moderate data quality in the preview
148
+ if best_col is None:
149
+ return None
150
+ if best_plausible < 3 and best_present < 3:
151
+ return None
152
+ return best_col
153
+
154
+ def choose_gender_col(gender_dict, candidate_cols):
155
+ if not gender_dict:
156
+ return None
157
+ best_col = None
158
+ best_valid = -1
159
+ for col in candidate_cols:
160
+ if col not in gender_dict:
161
+ continue
162
+ vals = gender_dict[col]
163
+ valid = 0
164
+ present = 0
165
+ for v in vals:
166
+ if is_missing(v):
167
+ continue
168
+ present += 1
169
+ s = str(v).strip().lower()
170
+ if s in ("female", "male", "f", "m"):
171
+ valid += 1
172
+ # Prefer more valid recognized entries
173
+ if valid > best_valid:
174
+ best_valid = valid
175
+ best_col = col
176
+ if best_col is None:
177
+ return None
178
+ # Require at least 3 recognized values in preview
179
+ if best_valid < 3:
180
+ return None
181
+ return best_col
182
+
183
+ # Retrieve the preview dictionaries produced in prior steps
184
+ age_preview_dict = find_preview_dict(candidate_age_cols) if 'candidate_age_cols' in globals() else None
185
+ gender_preview_dict = find_preview_dict(candidate_gender_cols) if 'candidate_gender_cols' in globals() else None
186
+
187
+ # Select columns
188
+ age_col = choose_age_col(age_preview_dict, candidate_age_cols) if age_preview_dict else None
189
+ gender_col = choose_gender_col(gender_preview_dict, candidate_gender_cols) if gender_preview_dict else None
190
+
191
+ # Explicitly print chosen information
192
+ print("Chosen age_col:", age_col)
193
+ if age_col and age_preview_dict:
194
+ print("Sample values for age_col:", age_preview_dict.get(age_col))
195
+
196
+ print("Chosen gender_col:", gender_col)
197
+ if gender_col and gender_preview_dict:
198
+ print("Sample values for gender_col:", gender_preview_dict.get(gender_col))
199
+
200
+ # Step 4: Feature Engineering and Validation
201
+ import os
202
+ import pandas as pd
203
+
204
+ # 1) Extract and standardize clinical features (trait, optional age, gender)
205
+ selected_clinical_df = tcga_select_clinical_features(
206
+ clinical_df,
207
+ trait=trait,
208
+ age_col=age_col if 'age_col' in globals() else None,
209
+ gender_col=gender_col if 'gender_col' in globals() else None
210
+ )
211
+
212
+ # Optionally save standardized clinical features for reference
213
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
214
+ selected_clinical_df.to_csv(out_clinical_data_file)
215
+
216
+ # 2) Normalize gene symbols and save normalized gene expression
217
+ genetic_df_numeric = genetic_df.apply(pd.to_numeric, errors='coerce')
218
+ normalized_gene_df = normalize_gene_symbols_in_index(genetic_df_numeric.copy())
219
+
220
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
221
+ normalized_gene_df.to_csv(out_gene_data_file)
222
+
223
+ # 3) Link clinical and genetic data on sample IDs
224
+ common_samples = selected_clinical_df.index.intersection(normalized_gene_df.columns)
225
+ linked_data = pd.concat(
226
+ [selected_clinical_df.loc[common_samples], normalized_gene_df[common_samples].T],
227
+ axis=1
228
+ )
229
+
230
+ # 4) Handle missing values systematically
231
+ processed_df = handle_missing_values(linked_data, trait_col=trait)
232
+
233
+ # 5) Determine bias in trait and demographic features; drop biased demographics
234
+ trait_biased, processed_df = judge_and_remove_biased_features(processed_df, trait=trait)
235
+
236
+ # 6) Final validation and save cohort info
237
+ cohort_name = os.path.basename(cohort_dir) if 'cohort_dir' in globals() else (
238
+ selected_cohort_dir_name if 'selected_cohort_dir_name' in globals() else 'TCGA_Glioblastoma_(GBM)'
239
+ )
240
+
241
+ # Cast to native Python bool to avoid numpy.bool_ serialization issues
242
+ is_gene_available = bool((normalized_gene_df.shape[0] > 0) and (normalized_gene_df.shape[1] > 0))
243
+ is_trait_available = bool(selected_clinical_df[trait].notna().any())
244
+ trait_biased = bool(trait_biased)
245
+
246
+ covariates_present = [c for c in ['Age', 'Gender'] if c in processed_df.columns]
247
+ gene_cols_in_processed = [c for c in processed_df.columns if c not in [trait, 'Age', 'Gender']]
248
+ note = (
249
+ f"INFO: Cohort={cohort_name}; age_col={age_col if 'age_col' in globals() else None}; "
250
+ f"gender_col={gender_col if 'gender_col' in globals() else None}; "
251
+ f"linked_samples={len(common_samples)}; final_samples={len(processed_df)}; "
252
+ f"covariates={covariates_present}; final_gene_count={len(gene_cols_in_processed)}."
253
+ )
254
+
255
+ is_usable = validate_and_save_cohort_info(
256
+ is_final=True,
257
+ cohort=str(cohort_name),
258
+ info_path=json_path,
259
+ is_gene_available=is_gene_available,
260
+ is_trait_available=is_trait_available,
261
+ is_biased=trait_biased,
262
+ df=processed_df,
263
+ note=str(note)
264
+ )
265
+
266
+ # 7) Save linked data if usable
267
+ if is_usable:
268
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
269
+ processed_df.to_csv(out_data_file)
output/preprocess/Glucocorticoid_Sensitivity/GSE58715.csv CHANGED
The diff for this file is too large to render. See raw diff
 
output/preprocess/Glucocorticoid_Sensitivity/clinical_data/GSE32962.csv CHANGED
@@ -1,3 +1,2 @@
1
- GSM816393,GSM816394,GSM816395,GSM816396,GSM816397,GSM816398,GSM816399,GSM816400,GSM816401,GSM816402,GSM816403,GSM816404,GSM816405,GSM816406,GSM816407,GSM816408,GSM816409,GSM816410,GSM816411,GSM816412,GSM816413,GSM816414,GSM816415,GSM816416,GSM816417,GSM816418,GSM816419,GSM816420,GSM816421,GSM816422,GSM816423,GSM816424,GSM816425,GSM816426,GSM816427,GSM816428,GSM816429,GSM816430,GSM816431,GSM816432,GSM816433,GSM816434,GSM816435
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,0.0,0.0,0.0,0.0,0.0,0.0,0.0,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
- 0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5
 
1
+ ,GSM816393,GSM816394,GSM816395,GSM816396,GSM816397,GSM816398,GSM816399,GSM816400,GSM816401,GSM816402,GSM816403,GSM816404,GSM816405,GSM816406,GSM816407,GSM816408,GSM816409,GSM816410,GSM816411,GSM816412,GSM816413,GSM816414,GSM816415,GSM816416,GSM816417,GSM816418,GSM816419,GSM816420,GSM816421,GSM816422,GSM816423,GSM816424,GSM816425,GSM816426,GSM816427,GSM816428,GSM816429,GSM816430,GSM816431,GSM816432,GSM816433,GSM816434,GSM816435
2
+ Glucocorticoid_Sensitivity,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,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