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

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/HIV_Resistance/clinical_data/GSE33580.csv +1 -1
  2. output/preprocess/HIV_Resistance/code/GSE117748.py +139 -0
  3. output/preprocess/HIV_Resistance/code/GSE33580.py +205 -0
  4. output/preprocess/HIV_Resistance/code/GSE46599.py +187 -0
  5. output/preprocess/HIV_Resistance/code/TCGA.py +56 -0
  6. output/preprocess/HIV_Resistance/cohort_info.json +1 -42
  7. output/preprocess/Hemochromatosis/code/GSE159676.py +178 -0
  8. output/preprocess/Hemochromatosis/code/GSE50579.py +216 -0
  9. output/preprocess/Hemochromatosis/code/TCGA.py +60 -0
  10. output/preprocess/Hemochromatosis/gene_data/GSE159676.csv +0 -0
  11. output/preprocess/Hepatitis/GSE114783.csv +0 -0
  12. output/preprocess/Hepatitis/GSE45032.csv +0 -0
  13. output/preprocess/Hepatitis/clinical_data/GSE114783.csv +1 -1
  14. output/preprocess/Hepatitis/clinical_data/GSE124719.csv +2 -3
  15. output/preprocess/Hepatitis/clinical_data/GSE125860.csv +2 -4
  16. output/preprocess/Hepatitis/clinical_data/GSE159676.csv +1 -1
  17. output/preprocess/Hepatitis/clinical_data/GSE45032.csv +4 -4
  18. output/preprocess/Hepatitis/clinical_data/GSE66843.csv +2 -2
  19. output/preprocess/Hepatitis/code/GSE114783.py +268 -0
  20. output/preprocess/Hepatitis/code/GSE124719.py +221 -0
  21. output/preprocess/Hepatitis/code/GSE125860.py +213 -0
  22. output/preprocess/Hepatitis/code/GSE152738.py +130 -0
  23. output/preprocess/Hepatitis/code/GSE159676.py +199 -0
  24. output/preprocess/Hepatitis/code/GSE168049.py +219 -0
  25. output/preprocess/Hepatitis/code/GSE45032.py +198 -0
  26. output/preprocess/Hepatitis/code/GSE66843.py +193 -0
  27. output/preprocess/Hepatitis/code/GSE85550.py +196 -0
  28. output/preprocess/Hepatitis/code/GSE97475.py +323 -0
  29. output/preprocess/Hepatitis/code/TCGA.py +289 -0
  30. output/preprocess/Hepatitis/cohort_info.json +1 -112
  31. output/preprocess/Hepatitis/gene_data/GSE114783.csv +0 -0
  32. output/preprocess/High-Density_Lipoprotein_Deficiency/code/GSE34945.py +130 -0
  33. output/preprocess/High-Density_Lipoprotein_Deficiency/code/TCGA.py +72 -0
  34. output/preprocess/High-Density_Lipoprotein_Deficiency/cohort_info.json +1 -22
  35. output/preprocess/Huntingtons_Disease/clinical_data/GSE26927.csv +4 -4
  36. output/preprocess/Huntingtons_Disease/clinical_data/GSE34721.csv +3 -3
  37. output/preprocess/Huntingtons_Disease/code/GSE135589.py +190 -0
  38. output/preprocess/Huntingtons_Disease/code/GSE154141.py +507 -0
  39. output/preprocess/Huntingtons_Disease/code/GSE26927.py +193 -0
  40. output/preprocess/Huntingtons_Disease/code/GSE34201.py +190 -0
  41. output/preprocess/Huntingtons_Disease/code/GSE34721.py +203 -0
  42. output/preprocess/Huntingtons_Disease/code/GSE71220.py +136 -0
  43. output/preprocess/Huntingtons_Disease/code/GSE95843.py +147 -0
  44. output/preprocess/Huntingtons_Disease/code/TCGA.py +75 -0
  45. output/preprocess/Huntingtons_Disease/cohort_info.json +1 -82
  46. output/preprocess/Hutchinson-Gilford_Progeria_Syndrome/clinical_data/GSE84351.csv +3 -3
  47. output/preprocess/Hutchinson-Gilford_Progeria_Syndrome/code/GSE84351.py +348 -0
  48. output/preprocess/Hutchinson-Gilford_Progeria_Syndrome/code/GSE84360.py +222 -0
  49. output/preprocess/Hutchinson-Gilford_Progeria_Syndrome/code/TCGA.py +68 -0
  50. output/preprocess/Hutchinson-Gilford_Progeria_Syndrome/cohort_info.json +1 -32
output/preprocess/HIV_Resistance/clinical_data/GSE33580.csv CHANGED
@@ -1,2 +1,2 @@
1
  ,GSM830155,GSM830156,GSM830157,GSM830158,GSM830159,GSM830160,GSM830161,GSM830162,GSM830163,GSM830164,GSM830165,GSM830166,GSM830167,GSM830168,GSM830169,GSM830170,GSM830171,GSM830172,GSM830173,GSM830174,GSM830175,GSM830176,GSM830177,GSM830178,GSM830179,GSM830180,GSM830181,GSM830182,GSM830183,GSM830184,GSM830185,GSM830186,GSM830187,GSM830188,GSM830189,GSM830190,GSM830191,GSM830192,GSM830193,GSM830194,GSM830195,GSM830196,GSM830197,GSM830198,GSM830199,GSM830200,GSM830201,GSM830202,GSM830203,GSM830204,GSM830205,GSM830206,GSM830207,GSM830208,GSM830209,GSM830210,GSM830211,GSM830212,GSM830213,GSM830214,GSM830215,GSM830216,GSM830217,GSM830218,GSM830219,GSM830220,GSM830221,GSM830222,GSM830223,GSM830224,GSM830225,GSM830226,GSM830227,GSM830228,GSM830229,GSM830230,GSM830231,GSM830232,GSM830233,GSM830234,GSM830235,GSM830236,GSM830237,GSM830238,GSM830239,GSM830240
2
- HIV_Resistance,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
 
1
  ,GSM830155,GSM830156,GSM830157,GSM830158,GSM830159,GSM830160,GSM830161,GSM830162,GSM830163,GSM830164,GSM830165,GSM830166,GSM830167,GSM830168,GSM830169,GSM830170,GSM830171,GSM830172,GSM830173,GSM830174,GSM830175,GSM830176,GSM830177,GSM830178,GSM830179,GSM830180,GSM830181,GSM830182,GSM830183,GSM830184,GSM830185,GSM830186,GSM830187,GSM830188,GSM830189,GSM830190,GSM830191,GSM830192,GSM830193,GSM830194,GSM830195,GSM830196,GSM830197,GSM830198,GSM830199,GSM830200,GSM830201,GSM830202,GSM830203,GSM830204,GSM830205,GSM830206,GSM830207,GSM830208,GSM830209,GSM830210,GSM830211,GSM830212,GSM830213,GSM830214,GSM830215,GSM830216,GSM830217,GSM830218,GSM830219,GSM830220,GSM830221,GSM830222,GSM830223,GSM830224,GSM830225,GSM830226,GSM830227,GSM830228,GSM830229,GSM830230,GSM830231,GSM830232,GSM830233,GSM830234,GSM830235,GSM830236,GSM830237,GSM830238,GSM830239,GSM830240
2
+ HIV_Resistance,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0
output/preprocess/HIV_Resistance/code/GSE117748.py ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "HIV_Resistance"
6
+ cohort = "GSE117748"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/HIV_Resistance"
10
+ in_cohort_dir = "../DATA/GEO/HIV_Resistance/GSE117748"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z3/preprocess/HIV_Resistance/GSE117748.csv"
14
+ out_gene_data_file = "./output/z3/preprocess/HIV_Resistance/gene_data/GSE117748.csv"
15
+ out_clinical_data_file = "./output/z3/preprocess/HIV_Resistance/clinical_data/GSE117748.csv"
16
+ json_path = "./output/z3/preprocess/HIV_Resistance/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 (likely not suitable: cell-line based SuperSeries focused on microRNA)
42
+ is_gene_available = False
43
+
44
+ # 2) Variable availability from the provided Sample Characteristics Dictionary
45
+ trait_row = None # No HIV resistance info
46
+ age_row = None # No age info for human subjects
47
+ gender_row = None # No gender info for human subjects
48
+
49
+ # 2.2) Converters
50
+ def _after_colon(value):
51
+ if value is None:
52
+ return None
53
+ s = str(value)
54
+ if ':' in s:
55
+ s = s.split(':', 1)[1]
56
+ return s.strip()
57
+
58
+ def convert_trait(x):
59
+ # Binary: 1=resistant/protected, 0=non-resistant/susceptible. Unknown -> None
60
+ v = _after_colon(x)
61
+ if v is None or v == '':
62
+ return None
63
+ s = v.strip().lower()
64
+
65
+ # Positive/resistant indicators
66
+ pos_terms = [
67
+ 'hesn', 'hiv-exposed seronegative', 'exposed uninfected', 'exposed-uninfected',
68
+ 'resistant', 'non-susceptible', 'nonsusceptible', 'protected',
69
+ 'long-term nonprogressor', 'long term nonprogressor', 'ltnp',
70
+ 'elite controller', 'viremic controller'
71
+ ]
72
+ if any(term in s for term in pos_terms):
73
+ return 1
74
+
75
+ # Negative/susceptible indicators
76
+ neg_terms = [
77
+ 'susceptible', 'case', 'infected', 'seropositive', 'hiv positive', 'hiv-1 positive',
78
+ 'aids', 'progressor', 'rapid progressor'
79
+ ]
80
+ if any(term in s for term in neg_terms):
81
+ return 0
82
+
83
+ # Ambiguous terms: don't force mapping
84
+ amb_terms = ['control', 'healthy', 'hiv negative', 'hiv-1 negative', 'uninfected', 'naive']
85
+ if any(term in s for term in amb_terms):
86
+ return None
87
+
88
+ return None
89
+
90
+ def convert_age(x):
91
+ # Continuous numeric age in years, unknown -> None
92
+ v = _after_colon(x)
93
+ if v is None or v == '':
94
+ return None
95
+ s = v.lower()
96
+ m = re.search(r'(\d+(\.\d+)?)', s)
97
+ if m:
98
+ try:
99
+ return float(m.group(1))
100
+ except Exception:
101
+ return None
102
+ return None
103
+
104
+ def convert_gender(x):
105
+ # Binary: female->0, male->1, unknown -> None
106
+ v = _after_colon(x)
107
+ if v is None or v == '':
108
+ return None
109
+ s = v.strip().lower()
110
+ if s in ['male', 'm', 'man', 'boy']:
111
+ return 1
112
+ if s in ['female', 'f', 'woman', 'girl']:
113
+ return 0
114
+ return None
115
+
116
+ # 3) Initial filtering metadata save
117
+ is_trait_available = trait_row is not None
118
+ validate_and_save_cohort_info(
119
+ is_final=False,
120
+ cohort=cohort,
121
+ info_path=json_path,
122
+ is_gene_available=is_gene_available,
123
+ is_trait_available=is_trait_available
124
+ )
125
+
126
+ # 4) Clinical feature extraction (skip because trait_row is None)
127
+ # If trait_row were available:
128
+ # selected_clinical_df = geo_select_clinical_features(
129
+ # clinical_df=clinical_data,
130
+ # trait=trait,
131
+ # trait_row=trait_row,
132
+ # convert_trait=convert_trait,
133
+ # age_row=age_row,
134
+ # convert_age=convert_age,
135
+ # gender_row=gender_row,
136
+ # convert_gender=convert_gender
137
+ # )
138
+ # preview = preview_df(selected_clinical_df)
139
+ # selected_clinical_df.to_csv(out_clinical_data_file)
output/preprocess/HIV_Resistance/code/GSE33580.py ADDED
@@ -0,0 +1,205 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "HIV_Resistance"
6
+ cohort = "GSE33580"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/HIV_Resistance"
10
+ in_cohort_dir = "../DATA/GEO/HIV_Resistance/GSE33580"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z3/preprocess/HIV_Resistance/GSE33580.csv"
14
+ out_gene_data_file = "./output/z3/preprocess/HIV_Resistance/gene_data/GSE33580.csv"
15
+ out_clinical_data_file = "./output/z3/preprocess/HIV_Resistance/clinical_data/GSE33580.csv"
16
+ json_path = "./output/z3/preprocess/HIV_Resistance/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 # Affymetrix HGU133 Plus 2.0 microarray -> mRNA expression data
45
+
46
+ # 2) Variable availability
47
+ trait_row = 1 # 'hiv status: HIV resistant' vs 'hiv status: HIV negative'
48
+ age_row = None # Not provided
49
+ gender_row = None # All participants are women per background; constant feature -> treat as unavailable
50
+
51
+ # 2.2) Converters
52
+ def _after_colon(val):
53
+ if pd.isna(val):
54
+ return None
55
+ s = str(val)
56
+ if ':' in s:
57
+ s = s.split(':', 1)[1]
58
+ return s.strip()
59
+
60
+ def convert_trait(val):
61
+ v = _after_colon(val)
62
+ if v is None:
63
+ return None
64
+ x = v.lower().strip()
65
+ x = x.replace('-', ' ').replace('_', ' ')
66
+ # Positive (resistant) mappings
67
+ resistant_terms = {
68
+ 'hiv resistant', 'resistant', 'resistance',
69
+ 'hiv exposed uninfected', 'exposed uninfected', 'hiv exposed and uninfected',
70
+ 'eu', 'heu'
71
+ }
72
+ # Negative/control/susceptible mappings
73
+ control_terms = {
74
+ 'hiv negative', 'negative', 'control', 'controls',
75
+ 'susceptible', 'hiv susceptible', 'susceptible control', 'negative control'
76
+ }
77
+ # Normalize some common phrases
78
+ if 'resistant' in x or 'exposed' in x and 'uninfected' in x:
79
+ return 1
80
+ if 'hiv negative' in x or 'negative' == x or 'control' in x or 'susceptible' in x:
81
+ return 0
82
+ if x in resistant_terms:
83
+ return 1
84
+ if x in control_terms:
85
+ return 0
86
+ return None
87
+
88
+ def convert_age(val):
89
+ v = _after_colon(val)
90
+ if v is None:
91
+ return None
92
+ # extract first number
93
+ m = re.search(r'(\d+(\.\d+)?)', v)
94
+ if not m:
95
+ return None
96
+ try:
97
+ age = float(m.group(1))
98
+ if 0 < age < 120:
99
+ return age
100
+ except Exception:
101
+ pass
102
+ return None
103
+
104
+ def convert_gender(val):
105
+ v = _after_colon(val)
106
+ if v is None:
107
+ return None
108
+ x = v.lower().strip()
109
+ # Map female -> 0, male -> 1
110
+ if any(k in x for k in ['female', 'woman', 'women', 'girl', 'f']):
111
+ return 0
112
+ if any(k in x for k in ['male', 'man', 'men', 'boy', 'm']):
113
+ return 1
114
+ return None
115
+
116
+ # 3) Save metadata (initial filtering)
117
+ is_trait_available = trait_row is not None
118
+ _ = validate_and_save_cohort_info(
119
+ is_final=False,
120
+ cohort=cohort,
121
+ info_path=json_path,
122
+ is_gene_available=is_gene_available,
123
+ is_trait_available=is_trait_available
124
+ )
125
+
126
+ # 4) Clinical feature extraction (since trait_row is available)
127
+ selected_clinical_df = geo_select_clinical_features(
128
+ clinical_df=clinical_data,
129
+ trait=trait,
130
+ trait_row=trait_row,
131
+ convert_trait=convert_trait,
132
+ age_row=age_row,
133
+ convert_age=None,
134
+ gender_row=gender_row,
135
+ convert_gender=None
136
+ )
137
+
138
+ # Preview and save
139
+ _ = preview_df(selected_clinical_df, n=5)
140
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
141
+ selected_clinical_df.to_csv(out_clinical_data_file)
142
+
143
+ # Step 3: Gene Data Extraction
144
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
145
+ gene_data = get_genetic_data(matrix_file)
146
+
147
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
148
+ print(gene_data.index[:20])
149
+
150
+ # Step 4: Gene Identifier Review
151
+ print("requires_gene_mapping = True")
152
+
153
+ # Step 5: Gene Annotation
154
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
155
+ gene_annotation = get_gene_annotation(soft_file)
156
+
157
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
158
+ print("Gene annotation preview:")
159
+ print(preview_df(gene_annotation))
160
+
161
+ # Step 6: Gene Identifier Mapping
162
+ # Identify the appropriate columns in gene_annotation for probe IDs and gene symbols
163
+ probe_id_col = 'ID'
164
+ gene_symbol_col = 'Gene Symbol'
165
+
166
+ # Build mapping dataframe
167
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=probe_id_col, gene_col=gene_symbol_col)
168
+
169
+ # Apply mapping to convert probe-level data to gene-level expression
170
+ gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
171
+
172
+ # Step 7: Data Normalization and Linking
173
+ import os
174
+
175
+ # 1. Normalize gene symbols and save gene expression data
176
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
177
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
178
+ normalized_gene_data.to_csv(out_gene_data_file)
179
+
180
+ # 2. Link the clinical and genetic data
181
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
182
+
183
+ # 3. Handle missing values
184
+ linked_data = handle_missing_values(linked_data, trait)
185
+
186
+ # 4. Assess bias and remove biased demographic features if any
187
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
188
+
189
+ # 5. Final validation and metadata saving
190
+ note = "INFO: Age unavailable; Gender constant (all women) per series summary; only trait used as clinical covariate."
191
+ is_usable = validate_and_save_cohort_info(
192
+ is_final=True,
193
+ cohort=cohort,
194
+ info_path=json_path,
195
+ is_gene_available=True,
196
+ is_trait_available=True,
197
+ is_biased=is_trait_biased,
198
+ df=unbiased_linked_data,
199
+ note=note
200
+ )
201
+
202
+ # 6. Save linked data if usable
203
+ if is_usable:
204
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
205
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/HIV_Resistance/code/GSE46599.py ADDED
@@ -0,0 +1,187 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "HIV_Resistance"
6
+ cohort = "GSE46599"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/HIV_Resistance"
10
+ in_cohort_dir = "../DATA/GEO/HIV_Resistance/GSE46599"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z3/preprocess/HIV_Resistance/GSE46599.csv"
14
+ out_gene_data_file = "./output/z3/preprocess/HIV_Resistance/gene_data/GSE46599.csv"
15
+ out_clinical_data_file = "./output/z3/preprocess/HIV_Resistance/clinical_data/GSE46599.csv"
16
+ json_path = "./output/z3/preprocess/HIV_Resistance/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 # Whole-genome analysis of ISGs implies gene expression data (not miRNA-only or methylation-only)
41
+
42
+ # 2) Variable availability and converters
43
+ trait_row = 4 # 'resistance to hiv-1 following ifn treatment'
44
+ age_row = None
45
+ gender_row = None
46
+
47
+ def _extract_after_colon(x):
48
+ if x is None:
49
+ return None
50
+ try:
51
+ val = str(x)
52
+ except Exception:
53
+ return None
54
+ if ':' in val:
55
+ val = val.split(':', 1)[1]
56
+ val = val.strip()
57
+ if val == '' or val.lower() in {'na', 'nan', 'none', 'unknown', 'n/a'}:
58
+ return None
59
+ return val
60
+
61
+ def convert_trait(x):
62
+ v = _extract_after_colon(x)
63
+ if v is None:
64
+ return None
65
+ v_low = v.lower()
66
+ if 'untreated' in v_low:
67
+ return None
68
+ if 'resistant' in v_low and 'partially' not in v_low:
69
+ return 1
70
+ if 'permissive' in v_low or 'partially' in v_low:
71
+ return 0
72
+ return None
73
+
74
+ # Age and Gender not available in this dataset
75
+ def convert_age(x):
76
+ return None
77
+
78
+ def convert_gender(x):
79
+ return None
80
+
81
+ # 3) Save metadata (initial filtering)
82
+ is_trait_available = trait_row is not None
83
+ _ = validate_and_save_cohort_info(
84
+ is_final=False,
85
+ cohort=cohort,
86
+ info_path=json_path,
87
+ is_gene_available=is_gene_available,
88
+ is_trait_available=is_trait_available
89
+ )
90
+
91
+ # 4) Clinical feature extraction (only if trait is available)
92
+ if trait_row is not None:
93
+ selected_clinical_df = geo_select_clinical_features(
94
+ clinical_df=clinical_data,
95
+ trait=trait,
96
+ trait_row=trait_row,
97
+ convert_trait=convert_trait
98
+ )
99
+ preview = preview_df(selected_clinical_df)
100
+ print("Preview of selected clinical features:", preview)
101
+
102
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
103
+ selected_clinical_df.to_csv(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
+ observed_ids = [
114
+ 'ILMN_1343291', 'ILMN_1343295', 'ILMN_1651209', 'ILMN_1651228',
115
+ 'ILMN_1651229', 'ILMN_1651230', 'ILMN_1651232', 'ILMN_1651236',
116
+ 'ILMN_1651238', 'ILMN_1651253', 'ILMN_1651254', 'ILMN_1651259',
117
+ 'ILMN_1651260', 'ILMN_1651262', 'ILMN_1651268', 'ILMN_1651278',
118
+ 'ILMN_1651281', 'ILMN_1651282', 'ILMN_1651285', 'ILMN_1651286'
119
+ ]
120
+ requires_gene_mapping = any(id_.startswith('ILMN_') for id_ in observed_ids)
121
+ print(f"requires_gene_mapping = {requires_gene_mapping}")
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
+ # Decide annotation columns for probe IDs and gene symbols based on preview
133
+ probe_col = 'ID' # Matches probe identifiers like 'ILMN_1343291'
134
+ gene_symbol_col = 'Symbol' # Contains gene symbols
135
+
136
+ # 2) Build mapping dataframe
137
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=probe_col, gene_col=gene_symbol_col)
138
+
139
+ # 3) Apply mapping: convert probe-level data to gene-level expression
140
+ gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
141
+
142
+ # Step 7: Data Normalization and Linking
143
+ import os
144
+ import pandas as pd
145
+
146
+ # 1) Normalize gene symbols and save
147
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
148
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
149
+ normalized_gene_data.to_csv(out_gene_data_file)
150
+
151
+ # Ensure clinical features dataframe is available; if not in memory, load from saved CSV
152
+ if 'selected_clinical_df' not in globals() or selected_clinical_df is None:
153
+ if not os.path.exists(out_clinical_data_file):
154
+ raise FileNotFoundError(f"Clinical data file not found at: {out_clinical_data_file}")
155
+ selected_clinical_df = pd.read_csv(out_clinical_data_file, index_col=0)
156
+
157
+ # 2) Link clinical and genetic data
158
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
159
+
160
+ # Determine availability flags before filtering/imputation and cast to built-in bool
161
+ is_gene_available = bool((normalized_gene_data.shape[0] > 0) and (normalized_gene_data.shape[1] > 0))
162
+ is_trait_available = bool((trait in linked_data.columns) and (linked_data[trait].notna().any()))
163
+
164
+ # 3) Handle missing values
165
+ linked_data = handle_missing_values(linked_data, trait)
166
+
167
+ # 4) Bias checks and removal of biased demographic features
168
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
169
+ is_trait_biased = bool(is_trait_biased) # ensure JSON serializable
170
+
171
+ # 5) Final validation and save cohort metadata
172
+ note = "INFO: HIV resistance phenotype inferred from 'resistance to hiv-1 following ifn treatment'; untreated samples set to missing."
173
+ is_usable = validate_and_save_cohort_info(
174
+ is_final=True,
175
+ cohort=cohort,
176
+ info_path=json_path,
177
+ is_gene_available=bool(is_gene_available),
178
+ is_trait_available=bool(is_trait_available),
179
+ is_biased=bool(is_trait_biased),
180
+ df=unbiased_linked_data,
181
+ note=note
182
+ )
183
+
184
+ # 6) Save linked data if usable
185
+ if is_usable:
186
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
187
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/HIV_Resistance/code/TCGA.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "HIV_Resistance"
6
+
7
+ # Input paths
8
+ tcga_root_dir = "../DATA/TCGA"
9
+
10
+ # Output paths
11
+ out_data_file = "./output/z3/preprocess/HIV_Resistance/TCGA.csv"
12
+ out_gene_data_file = "./output/z3/preprocess/HIV_Resistance/gene_data/TCGA.csv"
13
+ out_clinical_data_file = "./output/z3/preprocess/HIV_Resistance/clinical_data/TCGA.csv"
14
+ json_path = "./output/z3/preprocess/HIV_Resistance/cohort_info.json"
15
+
16
+
17
+ # Step 1: Initial Data Loading
18
+ import os
19
+ import pandas as pd
20
+
21
+ # 1. Select the most appropriate TCGA cohort directory for the trait "HIV_Resistance"
22
+ subdirs = [d for d in os.listdir(tcga_root_dir) if os.path.isdir(os.path.join(tcga_root_dir, d))]
23
+ keywords = [
24
+ 'hiv', 'aids', 'antiretroviral', 'art', 'haart', 'retroviral',
25
+ 'viral load', 'viral_load', 'seroconversion', 'cd4', 'cd8',
26
+ 'immune deficiency', 'immunodeficiency'
27
+ ]
28
+
29
+ matched_dirs = [d for d in subdirs if any(kw in d.lower() for kw in keywords)]
30
+
31
+ selected_dir = None
32
+ if matched_dirs:
33
+ # Prefer the most specific match (choose the one with 'hiv' in name first, else the longest name)
34
+ hiv_matches = [d for d in matched_dirs if 'hiv' in d.lower()]
35
+ selected_dir = hiv_matches[0] if hiv_matches else sorted(matched_dirs, key=len, reverse=True)[0]
36
+
37
+ if selected_dir is None:
38
+ # No suitable cohort for HIV_Resistance in TCGA; record and skip further processing
39
+ validate_and_save_cohort_info(
40
+ is_final=False,
41
+ cohort="TCGA",
42
+ info_path=json_path,
43
+ is_gene_available=False,
44
+ is_trait_available=False
45
+ )
46
+ else:
47
+ # 2. Identify clinical and genetic file paths
48
+ cohort_dir = os.path.join(tcga_root_dir, selected_dir)
49
+ clinical_path, genetic_path = tcga_get_relevant_filepaths(cohort_dir)
50
+
51
+ # 3. Load both files as DataFrames
52
+ clinical_df = pd.read_csv(clinical_path, sep='\t', index_col=0, low_memory=False)
53
+ genetic_df = pd.read_csv(genetic_path, sep='\t', index_col=0, low_memory=False)
54
+
55
+ # 4. Print clinical column names
56
+ print(list(clinical_df.columns))
output/preprocess/HIV_Resistance/cohort_info.json CHANGED
@@ -1,42 +1 @@
1
- {
2
- "GSE46599": {
3
- "is_usable": true,
4
- "is_gene_available": true,
5
- "is_trait_available": true,
6
- "is_available": true,
7
- "is_biased": false,
8
- "has_age": false,
9
- "has_gender": false,
10
- "sample_size": 24
11
- },
12
- "GSE33580": {
13
- "is_usable": true,
14
- "is_gene_available": true,
15
- "is_trait_available": true,
16
- "is_available": true,
17
- "is_biased": false,
18
- "has_age": false,
19
- "has_gender": false,
20
- "sample_size": 86
21
- },
22
- "GSE117748": {
23
- "is_usable": false,
24
- "is_gene_available": true,
25
- "is_trait_available": true,
26
- "is_available": true,
27
- "is_biased": true,
28
- "has_age": false,
29
- "has_gender": false,
30
- "sample_size": 15
31
- },
32
- "TCGA": {
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": true,
39
- "has_gender": true,
40
- "sample_size": 48
41
- }
42
- }
 
1
+ {"GSE46599": {"is_usable": true, "is_gene_available": true, "is_trait_available": true, "is_available": true, "is_biased": false, "has_age": false, "has_gender": false, "sample_size": 24, "note": "INFO: HIV resistance phenotype inferred from 'resistance to hiv-1 following ifn treatment'; untreated samples set to missing."}, "GSE33580": {"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": 86, "note": "INFO: Age unavailable; Gender constant (all women) per series summary; only trait used as clinical covariate."}, "GSE117748": {"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}, "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/Hemochromatosis/code/GSE159676.py ADDED
@@ -0,0 +1,178 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Hemochromatosis"
6
+ cohort = "GSE159676"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Hemochromatosis"
10
+ in_cohort_dir = "../DATA/GEO/Hemochromatosis/GSE159676"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z3/preprocess/Hemochromatosis/GSE159676.csv"
14
+ out_gene_data_file = "./output/z3/preprocess/Hemochromatosis/gene_data/GSE159676.csv"
15
+ out_clinical_data_file = "./output/z3/preprocess/Hemochromatosis/clinical_data/GSE159676.csv"
16
+ json_path = "./output/z3/preprocess/Hemochromatosis/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ # 1) Determine data availability
40
+ is_gene_available = True # Affymetrix Human Gene 1.0 ST array -> mRNA expression data
41
+
42
+ # 2) Variable availability
43
+ trait_row = 0 # 'condition' field includes 'Haemochromatosis' among other conditions
44
+ age_row = None
45
+ gender_row = None
46
+
47
+ # 2.2) Converters
48
+ def _extract_value(cell):
49
+ if cell is None:
50
+ return None
51
+ s = str(cell)
52
+ parts = s.split(":", 1)
53
+ val = parts[1] if len(parts) > 1 else parts[0]
54
+ val = val.strip()
55
+ return val if val != "" else None
56
+
57
+ def convert_trait(cell):
58
+ val = _extract_value(cell)
59
+ if val is None:
60
+ return None
61
+ v = val.lower()
62
+ # Map presence of Hemochromatosis to 1; all other known conditions and healthy to 0
63
+ if "haemochromatosis" in v or "hemochromatosis" in v:
64
+ return 1
65
+ # For other conditions and healthy controls, this is a negative for the trait
66
+ return 0
67
+
68
+ def convert_age(cell):
69
+ val = _extract_value(cell)
70
+ if val is None:
71
+ return None
72
+ # Extract numeric age in years if present
73
+ import re
74
+ m = re.search(r'(\d+(\.\d+)?)', val)
75
+ if m:
76
+ try:
77
+ return float(m.group(1))
78
+ except Exception:
79
+ return None
80
+ return None
81
+
82
+ def convert_gender(cell):
83
+ val = _extract_value(cell)
84
+ if val is None:
85
+ return None
86
+ v = val.lower()
87
+ if v in {"female", "f", "woman", "women"}:
88
+ return 0
89
+ if v in {"male", "m", "man", "men"}:
90
+ return 1
91
+ return None
92
+
93
+ # 3) Save metadata (initial filtering)
94
+ is_trait_available = trait_row is not None
95
+ _ = validate_and_save_cohort_info(
96
+ is_final=False,
97
+ cohort=cohort,
98
+ info_path=json_path,
99
+ is_gene_available=is_gene_available,
100
+ is_trait_available=is_trait_available
101
+ )
102
+
103
+ # 4) Clinical feature extraction (only if trait_row is available)
104
+ if trait_row is not None:
105
+ selected_clinical_df = geo_select_clinical_features(
106
+ clinical_df=clinical_data,
107
+ trait=trait,
108
+ trait_row=trait_row,
109
+ convert_trait=convert_trait,
110
+ age_row=age_row,
111
+ convert_age=convert_age,
112
+ gender_row=gender_row,
113
+ convert_gender=convert_gender
114
+ )
115
+ # Preview and save
116
+ preview = preview_df(selected_clinical_df)
117
+ print("Preview of selected clinical features:", preview)
118
+
119
+ import os
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
+ print("requires_gene_mapping = True")
132
+
133
+ # Step 5: Gene Annotation
134
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
135
+ gene_annotation = get_gene_annotation(soft_file)
136
+
137
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
138
+ print("Gene annotation preview:")
139
+ print(preview_df(gene_annotation))
140
+
141
+ # Step 6: Gene Identifier Mapping
142
+ # 1) Decide the columns for mapping
143
+ probe_col = 'ID' # Matches the probe identifiers in gene_data index (e.g., '7896754')
144
+ gene_symbol_col = 'gene_assignment' # Contains gene symbols within descriptive strings
145
+
146
+ # 2) Build the mapping dataframe
147
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=probe_col, gene_col=gene_symbol_col)
148
+
149
+ # 3) Apply mapping to convert probe-level data to gene-level expression
150
+ gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
151
+
152
+ # Step 7: Data Normalization and Linking
153
+ import os
154
+
155
+ # 1. Normalize gene symbols and save gene-level data
156
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
157
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
158
+ normalized_gene_data.to_csv(out_gene_data_file)
159
+
160
+ # 2. Link clinical and genetic data
161
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
162
+
163
+ # 3. Handle missing values
164
+ linked_data = handle_missing_values(linked_data, trait)
165
+
166
+ # 4. Bias assessment and removal of biased demographics
167
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
168
+
169
+ # 5. Final validation and save cohort metadata
170
+ note = "INFO: Only trait available (no age/gender). Labels appear highly imbalanced for Hemochromatosis in this series."
171
+ is_usable = validate_and_save_cohort_info(
172
+ True, cohort, json_path, True, True, is_trait_biased, unbiased_linked_data, note
173
+ )
174
+
175
+ # 6. Save linked data if usable
176
+ if is_usable:
177
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
178
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Hemochromatosis/code/GSE50579.py ADDED
@@ -0,0 +1,216 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Hemochromatosis"
6
+ cohort = "GSE50579"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Hemochromatosis"
10
+ in_cohort_dir = "../DATA/GEO/Hemochromatosis/GSE50579"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z3/preprocess/Hemochromatosis/GSE50579.csv"
14
+ out_gene_data_file = "./output/z3/preprocess/Hemochromatosis/gene_data/GSE50579.csv"
15
+ out_clinical_data_file = "./output/z3/preprocess/Hemochromatosis/clinical_data/GSE50579.csv"
16
+ json_path = "./output/z3/preprocess/Hemochromatosis/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) Determine data availability
44
+ is_gene_available = True # "Expression profiling" with genome-wide gene expression
45
+ # Variables and their rows in the sample characteristics dictionary
46
+ trait_row = 1 # 'etiology' includes 'genetic hemochromatosis'
47
+ age_row = 5 # 'age (yrs)'
48
+ gender_row = 3 # 'gender'
49
+ is_trait_available = trait_row is not None
50
+
51
+ # 2) Conversion functions
52
+ def _after_colon(x):
53
+ if x is None or (isinstance(x, float) and pd.isna(x)):
54
+ return None
55
+ s = str(x)
56
+ parts = s.split(':', 1)
57
+ v = parts[1] if len(parts) > 1 else parts[0]
58
+ v = v.strip()
59
+ return v if v != '' else None
60
+
61
+ def convert_trait(x):
62
+ v = _after_colon(x)
63
+ if v is None:
64
+ return None
65
+ low = v.lower()
66
+ # Unknowns
67
+ if low in {'n.d.', 'nd', 'na', 'n/a', 'not determined', 'unknown', ''}:
68
+ return None
69
+ # Positive cases
70
+ if 'hemochromatosis' in low:
71
+ return 1
72
+ # Other etiologies -> control/reference for this trait
73
+ if any(k in low for k in ['cryptogenic', 'alcohol', 'hcv', 'hbv', 'alpha-1 antitrypsin']):
74
+ return 0
75
+ # Fallback: if it's some other described etiology, treat as non-hemochromatosis (0)
76
+ if low not in {'', 'n.d.'}:
77
+ return 0
78
+ return None
79
+
80
+ def convert_age(x):
81
+ v = _after_colon(x)
82
+ if v is None:
83
+ return None
84
+ low = v.lower()
85
+ if low in {'n.d.', 'nd', 'na', 'n/a', 'not determined', 'unknown', ''}:
86
+ return None
87
+ m = re.search(r'[-+]?\d*\.?\d+', v)
88
+ if m:
89
+ try:
90
+ return float(m.group(0))
91
+ except Exception:
92
+ return None
93
+ return None
94
+
95
+ def convert_gender(x):
96
+ v = _after_colon(x)
97
+ if v is None:
98
+ return None
99
+ low = v.lower()
100
+ if low in {'female', 'f'}:
101
+ return 0
102
+ if low in {'male', 'm'}:
103
+ return 1
104
+ if low in {'n.d.', 'nd', 'na', 'n/a', 'not determined', 'unknown', ''}:
105
+ return None
106
+ return None
107
+
108
+ # 3) Save initial metadata
109
+ _ = validate_and_save_cohort_info(
110
+ is_final=False,
111
+ cohort=cohort,
112
+ info_path=json_path,
113
+ is_gene_available=is_gene_available,
114
+ is_trait_available=is_trait_available
115
+ )
116
+
117
+ # 4) Clinical feature extraction (only if trait_row is available)
118
+ if trait_row is not None:
119
+ selected_clinical_df = geo_select_clinical_features(
120
+ clinical_df=clinical_data,
121
+ trait=trait,
122
+ trait_row=trait_row,
123
+ convert_trait=convert_trait,
124
+ age_row=age_row,
125
+ convert_age=convert_age,
126
+ gender_row=gender_row,
127
+ convert_gender=convert_gender
128
+ )
129
+
130
+ # Preview and save
131
+ preview = preview_df(selected_clinical_df)
132
+ print(preview)
133
+
134
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
135
+ selected_clinical_df.to_csv(out_clinical_data_file)
136
+
137
+ # Step 3: Gene Data Extraction
138
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
139
+ gene_data = get_genetic_data(matrix_file)
140
+
141
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
142
+ print(gene_data.index[:20])
143
+
144
+ # Step 4: Gene Identifier Review
145
+ print("requires_gene_mapping = True")
146
+
147
+ # Step 5: Gene Annotation
148
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
149
+ gene_annotation = get_gene_annotation(soft_file)
150
+
151
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
152
+ print("Gene annotation preview:")
153
+ print(preview_df(gene_annotation))
154
+
155
+ # Step 6: Gene Identifier Mapping
156
+ # Decide columns for probe IDs and gene symbols based on availability and content
157
+ id_candidates = ['ID', 'SPOT_ID']
158
+ symbol_candidates = ['GENE_SYMBOL', 'GENE', 'GENE_NAME']
159
+
160
+ probe_col = next((c for c in id_candidates if c in gene_annotation.columns), None)
161
+ if probe_col is None:
162
+ raise ValueError("No suitable probe ID column found in gene annotation.")
163
+
164
+ # Try symbol columns in order until we get a non-empty mapping
165
+ mapping_df = None
166
+ for sym_col in symbol_candidates:
167
+ if sym_col in gene_annotation.columns:
168
+ tmp_map = get_gene_mapping(gene_annotation, prob_col=probe_col, gene_col=sym_col)
169
+ if not tmp_map.empty:
170
+ mapping_df = tmp_map
171
+ break
172
+
173
+ if mapping_df is None or mapping_df.empty:
174
+ raise ValueError("No suitable gene symbol column produced a valid mapping from the annotation.")
175
+
176
+ # Apply mapping to convert probe-level data to gene-level expression
177
+ gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
178
+
179
+ # Step 7: Data Normalization and Linking
180
+ import os
181
+
182
+ # 1. Normalize the obtained gene data and save
183
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
184
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
185
+ normalized_gene_data.to_csv(out_gene_data_file)
186
+
187
+ # 2. Link the clinical and genetic data
188
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
189
+
190
+ # Optional debug previews
191
+ print(f"Shapes before missing-value handling -> clinical: {selected_clinical_df.shape}, "
192
+ f"gene: {normalized_gene_data.shape}, linked: {linked_data.shape}")
193
+
194
+ # 3. Handle missing values in the linked data
195
+ linked_data = handle_missing_values(linked_data, trait)
196
+ print(f"Shape after missing-value handling: {linked_data.shape}")
197
+
198
+ # 4. Determine whether the trait and some demographic features are severely biased, and remove biased demographics
199
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
200
+
201
+ # 5. Final validation and save cohort information
202
+ is_usable = validate_and_save_cohort_info(
203
+ is_final=True,
204
+ cohort=cohort,
205
+ info_path=json_path,
206
+ is_gene_available=True,
207
+ is_trait_available=True,
208
+ is_biased=is_trait_biased,
209
+ df=unbiased_linked_data,
210
+ note="INFO: Gene symbols normalized and data linked; standard GEO preprocessing pipeline applied."
211
+ )
212
+
213
+ # 6. Save usable linked data
214
+ if is_usable:
215
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
216
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Hemochromatosis/code/TCGA.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Hemochromatosis"
6
+
7
+ # Input paths
8
+ tcga_root_dir = "../DATA/TCGA"
9
+
10
+ # Output paths
11
+ out_data_file = "./output/z3/preprocess/Hemochromatosis/TCGA.csv"
12
+ out_gene_data_file = "./output/z3/preprocess/Hemochromatosis/gene_data/TCGA.csv"
13
+ out_clinical_data_file = "./output/z3/preprocess/Hemochromatosis/clinical_data/TCGA.csv"
14
+ json_path = "./output/z3/preprocess/Hemochromatosis/cohort_info.json"
15
+
16
+
17
+ # Step 1: Initial Data Loading
18
+ import os
19
+ import pandas as pd
20
+
21
+ # Step 1: Identify the most relevant TCGA cohort directory for Hemochromatosis
22
+ dir_candidates = []
23
+ if os.path.exists(tcga_root_dir):
24
+ for d in os.listdir(tcga_root_dir):
25
+ full_path = os.path.join(tcga_root_dir, d)
26
+ if os.path.isdir(full_path):
27
+ dir_candidates.append(d)
28
+
29
+ trait_keywords = ['hemochromatosis', 'haemochromatosis', 'iron overload', 'iron']
30
+ selected_dir = None
31
+ for d in dir_candidates:
32
+ name_l = d.lower()
33
+ if any(k in name_l for k in trait_keywords):
34
+ selected_dir = d
35
+ break
36
+
37
+ # If no suitable directory is found, skip this trait and mark as completed
38
+ if selected_dir is None:
39
+ _ = validate_and_save_cohort_info(
40
+ is_final=False,
41
+ cohort="TCGA",
42
+ info_path=json_path,
43
+ is_gene_available=False,
44
+ is_trait_available=False
45
+ )
46
+ print("No suitable TCGA cohort found for the trait 'Hemochromatosis'. Skipping.")
47
+ else:
48
+ # Step 2: Identify file paths for clinical and genetic data
49
+ cohort_dir = os.path.join(tcga_root_dir, selected_dir)
50
+ clinical_file_path, genetic_file_path = tcga_get_relevant_filepaths(cohort_dir)
51
+
52
+ # Step 3: Load both files as DataFrames
53
+ clinical_compression = 'gzip' if clinical_file_path.endswith('.gz') else None
54
+ genetic_compression = 'gzip' if genetic_file_path.endswith('.gz') else None
55
+
56
+ clinical_df = pd.read_csv(clinical_file_path, sep='\t', index_col=0, compression=clinical_compression, low_memory=False)
57
+ genetic_df = pd.read_csv(genetic_file_path, sep='\t', index_col=0, compression=genetic_compression, low_memory=False)
58
+
59
+ # Step 4: Print column names of the clinical data
60
+ print(list(clinical_df.columns))
output/preprocess/Hemochromatosis/gene_data/GSE159676.csv CHANGED
The diff for this file is too large to render. See raw diff
 
output/preprocess/Hepatitis/GSE114783.csv ADDED
The diff for this file is too large to render. See raw diff
 
output/preprocess/Hepatitis/GSE45032.csv ADDED
The diff for this file is too large to render. See raw diff
 
output/preprocess/Hepatitis/clinical_data/GSE114783.csv CHANGED
@@ -1,2 +1,2 @@
1
  ,GSM3150135,GSM3150136,GSM3150137,GSM3150138,GSM3150139,GSM3150140,GSM3150141,GSM3150142,GSM3150143,GSM3150144,GSM3150145,GSM3150146,GSM3150147,GSM3150148,GSM3150149,GSM3150150,GSM3150151,GSM3150152,GSM3150153,GSM3150154,GSM3150155,GSM3150156,GSM3150157,GSM3150158,GSM3150159,GSM3150160,GSM3150161,GSM3150162,GSM3150163,GSM3150164,GSM3150165,GSM3150166,GSM3150167,GSM3150168,GSM3150169,GSM3150170
2
- Hepatitis,1.0,1.0,0.0,0.0,1.0,0.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0
 
1
  ,GSM3150135,GSM3150136,GSM3150137,GSM3150138,GSM3150139,GSM3150140,GSM3150141,GSM3150142,GSM3150143,GSM3150144,GSM3150145,GSM3150146,GSM3150147,GSM3150148,GSM3150149,GSM3150150,GSM3150151,GSM3150152,GSM3150153,GSM3150154,GSM3150155,GSM3150156,GSM3150157,GSM3150158,GSM3150159,GSM3150160,GSM3150161,GSM3150162,GSM3150163,GSM3150164,GSM3150165,GSM3150166,GSM3150167,GSM3150168,GSM3150169,GSM3150170
2
+ Hepatitis,0.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,0.0,0.0,1.0,0.0,1.0,0.0,0.0,0.0,1.0,0.0,0.0,0.0,1.0,0.0,1.0,1.0,1.0,0.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0
output/preprocess/Hepatitis/clinical_data/GSE124719.csv CHANGED
@@ -1,4 +1,3 @@
1
  ,GSM3543875,GSM3543876,GSM3543877,GSM3543878,GSM3543879,GSM3543880,GSM3543881,GSM3543882,GSM3543883,GSM3543884,GSM3543885,GSM3543886,GSM3543887,GSM3543888,GSM3543889,GSM3543890,GSM3543891,GSM3543892,GSM3543893,GSM3543894,GSM3543895,GSM3543896,GSM3543897,GSM3543898,GSM3543899,GSM3543900,GSM3543901,GSM3543902,GSM3543903,GSM3543904,GSM3543905,GSM3543906,GSM3543907,GSM3543908,GSM3543909,GSM3543910,GSM3543911,GSM3543912,GSM3543913,GSM3543914,GSM3543915,GSM3543916,GSM3543917,GSM3543918,GSM3543919,GSM3543920,GSM3543921,GSM3543922,GSM3543923,GSM3543924,GSM3543925,GSM3543926,GSM3543927,GSM3543928,GSM3543929,GSM3543930,GSM3543931,GSM3543932,GSM3543933,GSM3543934,GSM3543935,GSM3543936,GSM3543937,GSM3543938,GSM3543939,GSM3543940,GSM3543941,GSM3543942,GSM3543943,GSM3543944,GSM3543945,GSM3543946,GSM3543947,GSM3543948,GSM3543949,GSM3543950,GSM3543951,GSM3543952,GSM3543953,GSM3543954,GSM3543955,GSM3543956,GSM3543957,GSM3543958,GSM3543959,GSM3543960,GSM3543961,GSM3543962,GSM3543963,GSM3543964,GSM3543965,GSM3543966,GSM3543967,GSM3543968,GSM3543969,GSM3543970,GSM3543971,GSM3543972,GSM3543973,GSM3543974,GSM3543975,GSM3543976,GSM3543977,GSM3543978,GSM3543979,GSM3543980,GSM3543981,GSM3543982,GSM3543983,GSM3543984,GSM3543985,GSM3543986,GSM3543987,GSM3543988,GSM3543989,GSM3543990,GSM3543991,GSM3543992,GSM3543993,GSM3543994,GSM3543995,GSM3543996,GSM3543997,GSM3543998,GSM3543999,GSM3544000,GSM3544001,GSM3544002,GSM3544003,GSM3544004,GSM3544005,GSM3544006,GSM3544007,GSM3544008,GSM3544009,GSM3544010,GSM3544011,GSM3544012,GSM3544013,GSM3544014,GSM3544015,GSM3544016,GSM3544017,GSM3544018,GSM3544019,GSM3544020,GSM3544021,GSM3544022,GSM3544023,GSM3544024,GSM3544025,GSM3544026,GSM3544027,GSM3544028,GSM3544029,GSM3544030,GSM3544031,GSM3544032,GSM3544033,GSM3544034,GSM3544035,GSM3544036,GSM3544037,GSM3544038,GSM3544039,GSM3544040,GSM3544041,GSM3544042,GSM3544043,GSM3544044,GSM3544045,GSM3544046,GSM3544047,GSM3544048,GSM3544049,GSM3544050,GSM3544051,GSM3544052,GSM3544053
2
- Hepatitis,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
3
- Age,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,28.0,28.0,21.0,21.0,25.0,25.0,29.0,29.0,19.0,19.0,23.0,23.0,24.0,24.0,21.0,21.0,22.0,24.0,24.0,31.0,31.0,33.0,33.0,22.0,22.0,19.0,19.0,27.0,27.0,32.0,32.0,29.0,29.0,29.0,29.0,23.0,23.0,25.0,25.0,22.0,22.0,21.0,21.0,21.0,21.0,25.0,25.0,20.0,20.0,27.0,22.0,22.0,20.0,33.0,33.0,18.0,18.0,36.0,36.0,21.0,21.0,28.0,28.0,21.0,21.0,23.0,23.0,25.0,25.0,22.0,22.0,18.0,18.0,23.0,23.0,23.0,23.0,21.0,21.0,22.0,22.0,21.0,21.0,32.0,32.0,23.0,23.0,22.0,27.0,20.0,,
4
- Gender,,,0.0,,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,,,,,,,,,,,,,,,,,,,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,,,,,,,0.0,0.0,,,,,0.0,0.0,,,0.0,0.0,0.0,0.0,0.0,0.0,,,,0.0,0.0,,,0.0,0.0,0.0,0.0,,,0.0,0.0,,,,,0.0,0.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,,
 
1
  ,GSM3543875,GSM3543876,GSM3543877,GSM3543878,GSM3543879,GSM3543880,GSM3543881,GSM3543882,GSM3543883,GSM3543884,GSM3543885,GSM3543886,GSM3543887,GSM3543888,GSM3543889,GSM3543890,GSM3543891,GSM3543892,GSM3543893,GSM3543894,GSM3543895,GSM3543896,GSM3543897,GSM3543898,GSM3543899,GSM3543900,GSM3543901,GSM3543902,GSM3543903,GSM3543904,GSM3543905,GSM3543906,GSM3543907,GSM3543908,GSM3543909,GSM3543910,GSM3543911,GSM3543912,GSM3543913,GSM3543914,GSM3543915,GSM3543916,GSM3543917,GSM3543918,GSM3543919,GSM3543920,GSM3543921,GSM3543922,GSM3543923,GSM3543924,GSM3543925,GSM3543926,GSM3543927,GSM3543928,GSM3543929,GSM3543930,GSM3543931,GSM3543932,GSM3543933,GSM3543934,GSM3543935,GSM3543936,GSM3543937,GSM3543938,GSM3543939,GSM3543940,GSM3543941,GSM3543942,GSM3543943,GSM3543944,GSM3543945,GSM3543946,GSM3543947,GSM3543948,GSM3543949,GSM3543950,GSM3543951,GSM3543952,GSM3543953,GSM3543954,GSM3543955,GSM3543956,GSM3543957,GSM3543958,GSM3543959,GSM3543960,GSM3543961,GSM3543962,GSM3543963,GSM3543964,GSM3543965,GSM3543966,GSM3543967,GSM3543968,GSM3543969,GSM3543970,GSM3543971,GSM3543972,GSM3543973,GSM3543974,GSM3543975,GSM3543976,GSM3543977,GSM3543978,GSM3543979,GSM3543980,GSM3543981,GSM3543982,GSM3543983,GSM3543984,GSM3543985,GSM3543986,GSM3543987,GSM3543988,GSM3543989,GSM3543990,GSM3543991,GSM3543992,GSM3543993,GSM3543994,GSM3543995,GSM3543996,GSM3543997,GSM3543998,GSM3543999,GSM3544000,GSM3544001,GSM3544002,GSM3544003,GSM3544004,GSM3544005,GSM3544006,GSM3544007,GSM3544008,GSM3544009,GSM3544010,GSM3544011,GSM3544012,GSM3544013,GSM3544014,GSM3544015,GSM3544016,GSM3544017,GSM3544018,GSM3544019,GSM3544020,GSM3544021,GSM3544022,GSM3544023,GSM3544024,GSM3544025,GSM3544026,GSM3544027,GSM3544028,GSM3544029,GSM3544030,GSM3544031,GSM3544032,GSM3544033,GSM3544034,GSM3544035,GSM3544036,GSM3544037,GSM3544038,GSM3544039,GSM3544040,GSM3544041,GSM3544042,GSM3544043,GSM3544044,GSM3544045,GSM3544046,GSM3544047,GSM3544048,GSM3544049,GSM3544050,GSM3544051,GSM3544052,GSM3544053
2
+ Hepatitis,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,0.0,0.0,1.0,1.0,0.0,0.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,0.0,0.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,1.0,1.0,0.0,0.0,1.0,1.0,0.0,1.0,0.0,0.0,0.0
3
+ Age,29.0,29.0,21.0,28.0,25.0,25.0,23.0,23.0,19.0,19.0,24.0,24.0,33.0,33.0,24.0,24.0,36.0,36.0,21.0,23.0,25.0,25.0,29.0,29.0,32.0,32.0,22.0,22.0,23.0,21.0,22.0,22.0,19.0,19.0,22.0,22.0,33.0,33.0,25.0,25.0,22.0,22.0,21.0,21.0,22.0,22.0,31.0,31.0,32.0,32.0,22.0,22.0,28.0,28.0,21.0,21.0,29.0,29.0,21.0,21.0,20.0,20.0,21.0,21.0,27.0,27.0,20.0,27.0,27.0,23.0,23.0,23.0,23.0,23.0,23.0,23.0,23.0,18.0,18.0,25.0,25.0,21.0,21.0,18.0,18.0,21.0,21.0,28.0,28.0,21.0,21.0,25.0,25.0,29.0,29.0,19.0,19.0,23.0,23.0,24.0,24.0,21.0,21.0,22.0,24.0,24.0,31.0,31.0,33.0,33.0,22.0,22.0,19.0,19.0,27.0,27.0,32.0,32.0,29.0,29.0,29.0,29.0,23.0,23.0,25.0,25.0,22.0,22.0,21.0,21.0,21.0,21.0,25.0,25.0,20.0,20.0,27.0,22.0,22.0,20.0,33.0,33.0,18.0,18.0,36.0,36.0,21.0,21.0,28.0,28.0,21.0,21.0,23.0,23.0,25.0,25.0,22.0,22.0,18.0,18.0,23.0,23.0,23.0,23.0,21.0,21.0,22.0,22.0,21.0,21.0,32.0,32.0,23.0,23.0,22.0,27.0,20.0,28.0,20.0
 
output/preprocess/Hepatitis/clinical_data/GSE125860.csv CHANGED
@@ -1,4 +1,2 @@
1
- ,7,17,18
2
- Hepatitis,26.712,72.0,
3
- Age,12.666,33.0,
4
- Gender,,,0.0
 
1
+ ,GSM3583371,GSM3583372,GSM3583373,GSM3583374,GSM3583375,GSM3583376,GSM3583377,GSM3583378,GSM3583379,GSM3583380,GSM3583381,GSM3583382,GSM3583383,GSM3583384,GSM3583385,GSM3583386,GSM3583387,GSM3583388,GSM3583389,GSM3583390,GSM3583391,GSM3583392,GSM3583393,GSM3583394,GSM3583395,GSM3583396,GSM3583397,GSM3583398,GSM3583399,GSM3583400,GSM3583401,GSM3583402,GSM3583403,GSM3583404,GSM3583405,GSM3583406,GSM3583407,GSM3583408,GSM3583409,GSM3583410,GSM3583411,GSM3583412,GSM3583413,GSM3583414,GSM3583415,GSM3583416,GSM3583417,GSM3583418,GSM3583419,GSM3583420,GSM3583421,GSM3583422,GSM3583423,GSM3583424,GSM3583425,GSM3583426,GSM3583427,GSM3583428,GSM3583429,GSM3583430,GSM3583431,GSM3583432,GSM3583433,GSM3583434,GSM3583435,GSM3583436,GSM3583437,GSM3583438,GSM3583439,GSM3583440,GSM3583441,GSM3583442,GSM3583443,GSM3583444,GSM3583445,GSM3583446,GSM3583447,GSM3583448,GSM3583449,GSM3583450,GSM3583451,GSM3583452,GSM3583453,GSM3583454,GSM3583455,GSM3583456,GSM3583457,GSM3583458,GSM3583459,GSM3583460,GSM3583461,GSM3583462,GSM3583463,GSM3583464,GSM3583465,GSM3583466,GSM3583467,GSM3583468,GSM3583469,GSM3583470,GSM3583471,GSM3583472,GSM3583473,GSM3583474,GSM3583475,GSM3583476,GSM3583477,GSM3583478,GSM3583479,GSM3583480,GSM3583481,GSM3583482,GSM3583483,GSM3583484,GSM3583485,GSM3583486,GSM3583487,GSM3583488,GSM3583489,GSM3583490,GSM3583491,GSM3583492,GSM3583493,GSM3583494,GSM3583495,GSM3583496,GSM3583497,GSM3583498,GSM3583499,GSM3583500,GSM3583501,GSM3583502,GSM3583503,GSM3583504,GSM3583505,GSM3583506,GSM3583507,GSM3583508,GSM3583509,GSM3583510,GSM3583511,GSM3583512,GSM3583513,GSM3583514,GSM3583515,GSM3583516,GSM3583517,GSM3583518,GSM3583519,GSM3583520,GSM3583521,GSM3583522,GSM3583523,GSM3583524,GSM3583525,GSM3583526,GSM3583527,GSM3583528,GSM3583529,GSM3583530,GSM3583531,GSM3583532,GSM3583533,GSM3583534,GSM3583535,GSM3583536,GSM3583537,GSM3583538,GSM3583539,GSM3583540,GSM3583541,GSM3583542,GSM3583543
2
+ Hepatitis,34.882,5.0,5.072,5.0,6.738,5.0,5.0,5.0,106.136,5.0,5.0,6.757,5.0,5.0,148.805,5.0,5.0,5.0,5.0,5.0,26.712,54.976,5.0,,142.442,5.0,67.995,9.376,5.0,5.0,5.0,19.557,78.414,5.0,5.0,5.0,16938.23,5.0,5.0,5.466,5.0,5.0,12.666,5.512,5.0,5.0,5.0,366.395,11.966,5.0,6.74,10.763,53.131,27.114,12.091,36.768,7.124,5.0,5.0,5.0,5.0,63.196,5416.394,7589.005,5.0,5.0,1120.902,5.0,5.0,46.87,30320.357,34.839,5.0,15.851,5.0,262.988,25.298,5.0,5.0,124.499,39.224,16.269,5.0,212.134,102.117,212.208,5.0,7.774,5.0,5.0,5.0,5.0,200.656,5.0,5.0,5.0,5.0,5.0,13.633,8.275,18.207,5.0,5.0,5.0,5.0,19.705,5.0,5.0,5.0,5.0,33.203,5.0,5.0,5.0,5.0,5.0,5.665,5.0,5.0,5.0,5.0,20.055,26.092,59.28,9661.057,5.0,36979.5,13.896,5.0,52.148,17311.4,5.0,62.815,5.0,172.776,5.0,48.631,5.0,5.0,5.0,5.0,5.0,317.022,5.887,291.133,5.0,2029.989,14.454,11.518,118.492,9.368,5.0,5.0,5.0,5.0,2936.73,15.003,5.0,5.0,34.028,5.0,8.414,5.0,11.406,5.0,8.471,90.739,5.0,5.0,11.444,5.0,1482.147,5.0
 
 
output/preprocess/Hepatitis/clinical_data/GSE159676.csv CHANGED
@@ -1,2 +1,2 @@
1
  ,GSM4837490,GSM4837491,GSM4837492,GSM4837493,GSM4837494,GSM4837495,GSM4837496,GSM4837497,GSM4837498,GSM4837499,GSM4837500,GSM4837501,GSM4837502,GSM4837503,GSM4837504,GSM4837505,GSM4837506,GSM4837507,GSM4837508,GSM4837509,GSM4837510,GSM4837511,GSM4837512,GSM4837513,GSM4837514,GSM4837515,GSM4837516,GSM4837517,GSM4837518,GSM4837519,GSM4837520,GSM4837521,GSM4837522
2
- Hepatitis,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
  ,GSM4837490,GSM4837491,GSM4837492,GSM4837493,GSM4837494,GSM4837495,GSM4837496,GSM4837497,GSM4837498,GSM4837499,GSM4837500,GSM4837501,GSM4837502,GSM4837503,GSM4837504,GSM4837505,GSM4837506,GSM4837507,GSM4837508,GSM4837509,GSM4837510,GSM4837511,GSM4837512,GSM4837513,GSM4837514,GSM4837515,GSM4837516,GSM4837517,GSM4837518,GSM4837519,GSM4837520,GSM4837521,GSM4837522
2
+ Hepatitis,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,0.0,1.0,0.0
output/preprocess/Hepatitis/clinical_data/GSE45032.csv CHANGED
@@ -1,4 +1,4 @@
1
- Sample_1,Sample_2,Sample_3,Sample_4,Sample_5,Sample_6,Sample_7,Sample_8,Sample_9,Sample_10,Sample_11,Sample_12,Sample_13,Sample_14,Sample_15,Sample_16,Sample_17,Sample_18,Sample_19,Sample_20,Sample_21,Sample_22,Sample_23,Sample_24,Sample_25,Sample_26,Sample_27
2
- 1.0,0.0,,,,,,,,,,,,,,,,,,,,,,,,,
3
- 67.0,56.0,76.0,79.0,66.0,70.0,68.0,72.0,62.0,55.0,71.0,73.0,74.0,61.0,54.0,64.0,59.0,69.0,25.0,41.0,50.0,58.0,49.0,63.0,60.0,52.0,51.0
4
- 1.0,0.0,,,,,,,,,,,,,,,,,,,,,,,,,
 
1
+ ,GSM1096016,GSM1096017,GSM1096018,GSM1096019,GSM1096020,GSM1096021,GSM1096022,GSM1096023,GSM1096024,GSM1096025,GSM1096026,GSM1096027,GSM1096028,GSM1096029,GSM1096030,GSM1096031,GSM1096032,GSM1096033,GSM1096034,GSM1096035,GSM1096036,GSM1096037,GSM1096038,GSM1096039,GSM1096040,GSM1096041,GSM1096042,GSM1096043,GSM1096044,GSM1096045,GSM1096046,GSM1096047,GSM1096048,GSM1096049,GSM1096050,GSM1096051,GSM1096052,GSM1096053,GSM1096054,GSM1096055,GSM1096056,GSM1096057,GSM1096058,GSM1096059,GSM1096060,GSM1096061,GSM1096062,GSM1096063
2
+ Hepatitis,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,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
3
+ Age,67.0,56.0,76.0,79.0,66.0,70.0,68.0,72.0,62.0,66.0,55.0,62.0,71.0,73.0,74.0,61.0,54.0,64.0,68.0,59.0,79.0,69.0,59.0,71.0,64.0,55.0,66.0,56.0,66.0,68.0,25.0,41.0,50.0,56.0,66.0,58.0,67.0,49.0,63.0,70.0,60.0,50.0,58.0,61.0,60.0,59.0,52.0,51.0
4
+ Gender,1.0,1.0,0.0,1.0,1.0,1.0,1.0,0.0,1.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,1.0,0.0,1.0,1.0,1.0,0.0,1.0,1.0,1.0,0.0,0.0,1.0,1.0,1.0,0.0,1.0,0.0,0.0,0.0,1.0,0.0,1.0,1.0,1.0,0.0,0.0,1.0,1.0,0.0,1.0,1.0,1.0
output/preprocess/Hepatitis/clinical_data/GSE66843.csv CHANGED
@@ -1,2 +1,2 @@
1
- ,GSM1633236,GSM1633237,GSM1633238,GSM1633239,GSM1633240,GSM1633241,GSM1633242,GSM1633243,GSM1633244,GSM1633245,GSM1633246,GSM1633247,GSM1633248,GSM1633249,GSM1633250,GSM1633251,GSM1633252
2
- Hepatitis,0.0,0.0,1.0,1.0,1.0,0.0,0.0,0.0,1.0,1.0,1.0,0.0,0.0,0.0,1.0,1.0,1.0
 
1
+ GSM1633236,GSM1633237,GSM1633238,GSM1633239,GSM1633240,GSM1633241,GSM1633242,GSM1633243,GSM1633244,GSM1633245,GSM1633246,GSM1633247,GSM1633248,GSM1633249,GSM1633250,GSM1633251,GSM1633252
2
+ 0.0,0.0,1.0,1.0,1.0,0.0,0.0,0.0,1.0,1.0,1.0,0.0,0.0,0.0,1.0,1.0,1.0
output/preprocess/Hepatitis/code/GSE114783.py ADDED
@@ -0,0 +1,268 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Hepatitis"
6
+ cohort = "GSE114783"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Hepatitis"
10
+ in_cohort_dir = "../DATA/GEO/Hepatitis/GSE114783"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z3/preprocess/Hepatitis/GSE114783.csv"
14
+ out_gene_data_file = "./output/z3/preprocess/Hepatitis/gene_data/GSE114783.csv"
15
+ out_clinical_data_file = "./output/z3/preprocess/Hepatitis/clinical_data/GSE114783.csv"
16
+ json_path = "./output/z3/preprocess/Hepatitis/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ import os
40
+
41
+ # 1. Gene Expression Data Availability
42
+ is_gene_available = True # "Microarray gene expression" on PBMCs suggests gene expression data is available.
43
+
44
+ # 2. Variable Availability and Data Type Conversion
45
+ # From the Sample Characteristics Dictionary, diagnosis is at key 0.
46
+ trait_row = 0
47
+ age_row = None # No age information available
48
+ gender_row = None # No gender information available
49
+
50
+ def _extract_value(x):
51
+ if x is None:
52
+ return None
53
+ if isinstance(x, (int, float)):
54
+ return str(x)
55
+ s = str(x).strip()
56
+ if ':' in s:
57
+ s = s.split(':', 1)[1]
58
+ return s.strip()
59
+
60
+ def convert_trait(x):
61
+ """
62
+ Binary mapping for 'Hepatitis':
63
+ - 1: chronic hepatitis B (active hepatitis)
64
+ - 0: healthy control, hepatitis B virus carrier, liver cirrhosis, hepatocellular carcinoma
65
+ Unknown/other -> None
66
+ """
67
+ val = _extract_value(x)
68
+ if val is None or val == '':
69
+ return None
70
+ v = val.lower()
71
+ if ('chronic hepatitis' in v) or (v.strip() == 'chb'):
72
+ return 1
73
+ if any(k in v for k in ['healthy control', 'hepatitis b virus carrier', 'hbv carrier',
74
+ 'liver cirrhosis', 'cirrhosis', 'hepatocellular carcinoma', 'hcc']):
75
+ return 0
76
+ return None
77
+
78
+ def convert_age(x):
79
+ val = _extract_value(x)
80
+ if val is None or val == '':
81
+ return None
82
+ import re
83
+ m = re.search(r'(\d+(\.\d+)?)', val)
84
+ if not m:
85
+ return None
86
+ try:
87
+ age = float(m.group(1))
88
+ return age
89
+ except Exception:
90
+ return None
91
+
92
+ def convert_gender(x):
93
+ val = _extract_value(x)
94
+ if val is None or val == '':
95
+ return None
96
+ v = val.lower()
97
+ if v in ['male', 'm', 'man']:
98
+ return 1
99
+ if v in ['female', 'f', 'woman', 'women']:
100
+ return 0
101
+ return None
102
+
103
+ # 3. Save Metadata (initial filtering)
104
+ is_trait_available = trait_row is not None
105
+ _ = validate_and_save_cohort_info(
106
+ is_final=False,
107
+ cohort=cohort,
108
+ info_path=json_path,
109
+ is_gene_available=is_gene_available,
110
+ is_trait_available=is_trait_available
111
+ )
112
+
113
+ # 4. Clinical Feature Extraction (only if clinical data available)
114
+ if is_trait_available:
115
+ assert 'clinical_data' in globals(), "clinical_data is required for clinical feature extraction but is not defined."
116
+ selected_clinical_df = geo_select_clinical_features(
117
+ clinical_df=clinical_data,
118
+ trait=trait,
119
+ trait_row=trait_row,
120
+ convert_trait=convert_trait,
121
+ age_row=age_row,
122
+ convert_age=convert_age,
123
+ gender_row=gender_row,
124
+ convert_gender=convert_gender
125
+ )
126
+ clinical_preview = preview_df(selected_clinical_df)
127
+ print(clinical_preview)
128
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
129
+ selected_clinical_df.to_csv(out_clinical_data_file)
130
+
131
+ # Step 3: Gene Data Extraction
132
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
133
+ gene_data = get_genetic_data(matrix_file)
134
+
135
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
136
+ print(gene_data.index[:20])
137
+
138
+ # Step 4: Gene Identifier Review
139
+ # Based on the observed identifiers (e.g., AB000409), which are GenBank accessions, mapping to human gene symbols is required.
140
+ requires_gene_mapping = True
141
+ print(f"requires_gene_mapping = {requires_gene_mapping}")
142
+
143
+ # Step 5: Gene Annotation
144
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
145
+ gene_annotation = get_gene_annotation(soft_file)
146
+
147
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
148
+ print("Gene annotation preview:")
149
+ print(preview_df(gene_annotation))
150
+
151
+ # Step 6: Gene Identifier Mapping
152
+ import re
153
+
154
+ # Determine which annotation column matches the gene/probe identifiers in gene_data
155
+ annot_cols = list(gene_annotation.columns)
156
+ expr_ids = set(gene_data.index.astype(str))
157
+
158
+ best_id_col = None
159
+ best_overlap = -1
160
+ for col in annot_cols:
161
+ col_vals = set(gene_annotation[col].astype(str).str.strip())
162
+ overlap = len(expr_ids & col_vals)
163
+ if overlap > best_overlap:
164
+ best_overlap = overlap
165
+ best_id_col = col
166
+
167
+ # Try to find a gene symbol column
168
+ symbol_candidates = [c for c in annot_cols if 'symbol' in str(c).lower()]
169
+ gene_symbol_col = symbol_candidates[0] if len(symbol_candidates) > 0 else None
170
+
171
+ if gene_symbol_col is not None:
172
+ # Use existing library functions when a proper symbol column exists
173
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=best_id_col, gene_col=gene_symbol_col)
174
+ gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
175
+ else:
176
+ # Fallback: aggregate by Entrez Gene IDs (GENE_ID) when gene symbols are unavailable
177
+ if 'GENE_ID' not in gene_annotation.columns:
178
+ raise ValueError("No gene symbol column or GENE_ID column found in the annotation to perform mapping.")
179
+
180
+ def split_gene_ids(val: str):
181
+ s = str(val).strip()
182
+ if s.lower() in ['', 'nan', 'none']:
183
+ return []
184
+ # Single numeric (possibly with .0)
185
+ if re.fullmatch(r'\d+(\.0)?', s):
186
+ return [s.split('.', 1)[0]]
187
+ # Split on common delimiters
188
+ parts = re.split(r'[;,/| ]+', s)
189
+ ids = []
190
+ for p in parts:
191
+ p = p.strip()
192
+ if p == '' or p.lower() == 'na':
193
+ continue
194
+ if re.fullmatch(r'\d+(\.0)?', p):
195
+ p = p.split('.', 1)[0]
196
+ if re.fullmatch(r'\d+', p):
197
+ ids.append(p)
198
+ return list(dict.fromkeys(ids))
199
+
200
+ # Build mapping df using probe ID and Entrez Gene ID
201
+ mapping_df = gene_annotation[[best_id_col, 'GENE_ID']].dropna().copy()
202
+ mapping_df[best_id_col] = mapping_df[best_id_col].astype(str).str.strip()
203
+
204
+ # Keep only probes present in expression data
205
+ mapping_df = mapping_df[mapping_df[best_id_col].isin(gene_data.index)]
206
+
207
+ # Split gene IDs and explode
208
+ mapping_df['Gene'] = mapping_df['GENE_ID'].apply(split_gene_ids)
209
+ mapping_df['num_genes'] = mapping_df['Gene'].apply(lambda lst: len(lst))
210
+ mapping_df = mapping_df.explode('Gene')
211
+ mapping_df = mapping_df.dropna(subset=['Gene'])
212
+ mapping_df = mapping_df[mapping_df['Gene'] != '']
213
+ mapping_df = mapping_df.set_index(best_id_col)
214
+
215
+ # Join with expression and distribute values across multiple genes per probe
216
+ merged_df = mapping_df.join(gene_data, how='inner')
217
+ expr_cols = [c for c in merged_df.columns if c not in ['GENE_ID', 'Gene', 'num_genes']]
218
+ merged_df[expr_cols] = merged_df[expr_cols].div(merged_df['num_genes'].replace(0, 1), axis=0)
219
+
220
+ # Sum to gene-level using Entrez IDs as gene labels
221
+ gene_data = merged_df.groupby('Gene')[expr_cols].sum()
222
+
223
+ # Step 7: Data Normalization and Linking
224
+ import os
225
+
226
+ # 1. Normalize gene symbols; fallback if normalization drops almost all rows (likely Entrez IDs rather than symbols)
227
+ try:
228
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data.copy())
229
+ retention_ratio = (len(normalized_gene_data) / len(gene_data)) if len(gene_data) > 0 else 0.0
230
+ if normalized_gene_data.empty or retention_ratio < 0.05:
231
+ normalized_gene_data = gene_data.copy()
232
+ norm_note = f"INFO: Gene symbol normalization yielded low retention (ratio={retention_ratio:.4f}); retained original identifiers (likely Entrez IDs)."
233
+ else:
234
+ norm_note = f"INFO: Gene symbols normalized using synonym map (retention_ratio={retention_ratio:.4f})."
235
+ except Exception as e:
236
+ # If normalization fails for any reason, keep original gene_data
237
+ normalized_gene_data = gene_data.copy()
238
+ norm_note = f"WARNING: Gene symbol normalization failed ({e}); retained original identifiers (likely Entrez IDs)."
239
+
240
+ # Ensure output directory exists and save normalized gene data
241
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
242
+ normalized_gene_data.to_csv(out_gene_data_file)
243
+
244
+ # 2. Link the clinical and genetic data
245
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
246
+
247
+ # 3. Handle missing values
248
+ linked_data = handle_missing_values(linked_data, trait)
249
+
250
+ # 4. Check bias and remove biased demographic features if needed
251
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
252
+
253
+ # 5. Final validation and save cohort info
254
+ is_usable = validate_and_save_cohort_info(
255
+ is_final=True,
256
+ cohort=cohort,
257
+ info_path=json_path,
258
+ is_gene_available=True,
259
+ is_trait_available=True,
260
+ is_biased=is_trait_biased,
261
+ df=unbiased_linked_data,
262
+ note=norm_note
263
+ )
264
+
265
+ # 6. Save linked data if usable
266
+ if is_usable:
267
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
268
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Hepatitis/code/GSE124719.py ADDED
@@ -0,0 +1,221 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Hepatitis"
6
+ cohort = "GSE124719"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Hepatitis"
10
+ in_cohort_dir = "../DATA/GEO/Hepatitis/GSE124719"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z3/preprocess/Hepatitis/GSE124719.csv"
14
+ out_gene_data_file = "./output/z3/preprocess/Hepatitis/gene_data/GSE124719.csv"
15
+ out_clinical_data_file = "./output/z3/preprocess/Hepatitis/clinical_data/GSE124719.csv"
16
+ json_path = "./output/z3/preprocess/Hepatitis/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
+ from typing import Optional
42
+ import pandas as pd
43
+
44
+ # 1) Gene expression availability
45
+ is_gene_available = True # Gene expression arrays in blood and muscle are described in the series.
46
+
47
+ # 2) Variable availability and conversion functions
48
+
49
+ # Identify rows from the sample characteristics dictionary:
50
+ # - Trait (Hepatitis-related): use treatment assignment -> row 1 ('treatment: FENDRIXE' (HepB), 'FLUADE', 'PLACEBOE')
51
+ trait_row = 1
52
+
53
+ # - Age: explicit age values -> row 11 (primary), with backup values in row 7
54
+ age_row = 11
55
+ backup_age_row = 7
56
+
57
+ # - Gender: all subjects are male (rows 6/10 show only male), so it's constant -> not available
58
+ gender_row = None
59
+
60
+ # Conversion helpers
61
+ def _after_colon(val: str) -> Optional[str]:
62
+ if not isinstance(val, str):
63
+ return None
64
+ parts = val.split(":", 1)
65
+ s = parts[1] if len(parts) > 1 else parts[0]
66
+ s = s.strip()
67
+ return s if s else None
68
+
69
+ def convert_trait(val):
70
+ """
71
+ Binary: 1 = Hepatitis B vaccine (FENDRIX/FENDRIXE/HBV/HepB), 0 = others (FLUADE/influenza, PLACEBOE/saline).
72
+ Unknown -> None
73
+ """
74
+ s = _after_colon(val)
75
+ if s is None:
76
+ return None
77
+ sl = s.lower().strip()
78
+ # Exact token checks
79
+ if sl in {"fendrix", "fendrixe"}:
80
+ return 1
81
+ if sl in {"flua", "fluae", "fluade", "placebo", "placeboe", "saline"}:
82
+ return 0
83
+ # Heuristic fallbacks
84
+ if ("fendrix" in sl) or ("hepb" in sl) or ("hbv" in sl) or ("hepatitis" in sl):
85
+ return 1
86
+ if ("placebo" in sl) or ("saline" in sl) or ("flua" in sl) or ("influenza" in sl) or ("flu" in sl):
87
+ return 0
88
+ return None
89
+
90
+ def convert_age(val):
91
+ """
92
+ Continuous (years). Extract leading numeric from strings like 'age: 21y' -> 21.0
93
+ Unknown -> None
94
+ """
95
+ s = _after_colon(val)
96
+ if s is None:
97
+ return None
98
+ m = re.search(r'(\d+(\.\d+)?)', s)
99
+ if not m:
100
+ return None
101
+ try:
102
+ return float(m.group(1))
103
+ except Exception:
104
+ return None
105
+
106
+ def convert_gender(val):
107
+ """
108
+ Binary: female -> 0, male -> 1, Unknown -> None
109
+ Note: Gender is constant (all male) in this cohort, so this function won't be used.
110
+ """
111
+ s = _after_colon(val)
112
+ if s is None:
113
+ return None
114
+ sl = s.lower()
115
+ if "male" in sl or sl == "m":
116
+ return 1
117
+ if "female" in sl or sl == "f":
118
+ return 0
119
+ return None
120
+
121
+ # 3) Save metadata (initial filtering)
122
+ is_trait_available = trait_row is not None
123
+ _ = validate_and_save_cohort_info(
124
+ is_final=False,
125
+ cohort=cohort,
126
+ info_path=json_path,
127
+ is_gene_available=is_gene_available,
128
+ is_trait_available=is_trait_available
129
+ )
130
+
131
+ # 4) Clinical feature extraction
132
+ if trait_row is not None:
133
+ clinical_features = geo_select_clinical_features(
134
+ clinical_df=clinical_data,
135
+ trait=trait,
136
+ trait_row=trait_row,
137
+ convert_trait=convert_trait,
138
+ age_row=age_row,
139
+ convert_age=convert_age,
140
+ gender_row=gender_row,
141
+ convert_gender=convert_gender
142
+ )
143
+ # Fill missing ages using backup row (row 7)
144
+ try:
145
+ backup_age_series = clinical_data.loc[backup_age_row].apply(convert_age)
146
+ backup_age_series = pd.to_numeric(backup_age_series, errors='coerce')
147
+ if "Age" in clinical_features.index:
148
+ clinical_features.loc["Age"] = clinical_features.loc["Age"].fillna(backup_age_series)
149
+ except Exception:
150
+ # If backup filling fails, proceed with original ages
151
+ pass
152
+
153
+ preview = preview_df(clinical_features, n=5)
154
+ print(preview)
155
+ # Save clinical features
156
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
157
+ clinical_features.to_csv(out_clinical_data_file)
158
+
159
+ # Step 3: Gene Data Extraction
160
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
161
+ gene_data = get_genetic_data(matrix_file)
162
+
163
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
164
+ print(gene_data.index[:20])
165
+
166
+ # Step 4: Gene Identifier Review
167
+ print("requires_gene_mapping = True")
168
+
169
+ # Step 5: Gene Annotation
170
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
171
+ gene_annotation = get_gene_annotation(soft_file)
172
+
173
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
174
+ print("Gene annotation preview:")
175
+ print(preview_df(gene_annotation))
176
+
177
+ # Step 6: Gene Identifier Mapping
178
+ # Decide on identifier and gene symbol columns based on previews:
179
+ id_col = 'ID' # Matches the probe/row identifiers in gene_data
180
+ gene_symbol_col = 'GENE_SYMBOL' # Contains human gene symbols
181
+
182
+ # 2) Build mapping dataframe
183
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=id_col, gene_col=gene_symbol_col)
184
+
185
+ # 3) Apply mapping to convert probe-level measurements to gene-level expression
186
+ gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
187
+
188
+ # Step 7: Data Normalization and Linking
189
+ import os
190
+
191
+ # 1. Normalize gene symbols and save normalized gene expression data
192
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
193
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
194
+ normalized_gene_data.to_csv(out_gene_data_file)
195
+
196
+ # 2. Link the clinical and genetic data
197
+ linked_data = geo_link_clinical_genetic_data(clinical_features, normalized_gene_data)
198
+
199
+ # 3. Handle missing values in the linked data
200
+ linked_data = handle_missing_values(linked_data, trait)
201
+
202
+ # 4. Determine whether the trait and demographic features are severely biased
203
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
204
+
205
+ # 5. Final validation and save cohort information
206
+ note = "INFO: All participants are male; Gender not available. Trait defined as HepB vaccine (FENDRIX/FENDRIXE) vs others."
207
+ is_usable = validate_and_save_cohort_info(
208
+ is_final=True,
209
+ cohort=cohort,
210
+ info_path=json_path,
211
+ is_gene_available=True,
212
+ is_trait_available=True,
213
+ is_biased=is_trait_biased,
214
+ df=unbiased_linked_data,
215
+ note=note
216
+ )
217
+
218
+ # 6. Save the linked data if usable
219
+ if is_usable:
220
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
221
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Hepatitis/code/GSE125860.py ADDED
@@ -0,0 +1,213 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Hepatitis"
6
+ cohort = "GSE125860"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Hepatitis"
10
+ in_cohort_dir = "../DATA/GEO/Hepatitis/GSE125860"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z3/preprocess/Hepatitis/GSE125860.csv"
14
+ out_gene_data_file = "./output/z3/preprocess/Hepatitis/gene_data/GSE125860.csv"
15
+ out_clinical_data_file = "./output/z3/preprocess/Hepatitis/clinical_data/GSE125860.csv"
16
+ json_path = "./output/z3/preprocess/Hepatitis/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 # Affymetrix transcriptomic profiling mentioned in background
43
+
44
+ # 2) Variable availability and converters based on provided sample characteristics
45
+ # From the provided dictionary, we select:
46
+ # - Trait (Hepatitis): use "hepatitis b average concentration (post-vax)" at key 7 as continuous
47
+ trait_row = 7
48
+
49
+ # Age/Gender not observed in the provided sample characteristics snippet
50
+ age_row = None
51
+ gender_row = None
52
+
53
+ def _extract_after_colon(x):
54
+ if x is None:
55
+ return None
56
+ s = str(x)
57
+ if ':' in s:
58
+ s = s.split(':', 1)[1]
59
+ s = s.strip()
60
+ return s if s != '' else None
61
+
62
+ def convert_trait(x):
63
+ v = _extract_after_colon(x)
64
+ if v is None:
65
+ return None
66
+ v_low = v.strip().lower()
67
+ if v_low in {'na', 'n/a', 'none', ''}:
68
+ return None
69
+ # Handle inequality values like "<5" or ">10"
70
+ if v_low.startswith('<') or v_low.startswith('>'):
71
+ num_str = v_low[1:].strip()
72
+ try:
73
+ # Map to the threshold value itself for a conservative approximation
74
+ return float(num_str)
75
+ except:
76
+ pass
77
+ # Try direct float conversion
78
+ try:
79
+ return float(v_low)
80
+ except:
81
+ # Fallback: extract any numeric substring
82
+ m = re.search(r'[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?', v_low)
83
+ if m:
84
+ try:
85
+ return float(m.group(0))
86
+ except:
87
+ return None
88
+ return None
89
+
90
+ def convert_age(x):
91
+ v = _extract_after_colon(x)
92
+ if v is None:
93
+ return None
94
+ v_low = v.strip().lower()
95
+ if v_low in {'na', 'n/a', 'none', ''}:
96
+ return None
97
+ # Extract numeric age (years)
98
+ m = re.search(r'[-+]?\d*\.?\d+', v_low)
99
+ if m:
100
+ try:
101
+ return float(m.group(0))
102
+ except:
103
+ return None
104
+ return None
105
+
106
+ def convert_gender(x):
107
+ v = _extract_after_colon(x)
108
+ if v is None:
109
+ return None
110
+ v_low = v.strip().lower()
111
+ if v_low in {'female', 'f', 'woman', 'women'}:
112
+ return 0
113
+ if v_low in {'male', 'm', 'man', 'men'}:
114
+ return 1
115
+ return None
116
+
117
+ # 3) Save metadata (initial filtering)
118
+ is_trait_available = trait_row is not None
119
+ _ = validate_and_save_cohort_info(
120
+ is_final=False,
121
+ cohort=cohort,
122
+ info_path=json_path,
123
+ is_gene_available=is_gene_available,
124
+ is_trait_available=is_trait_available
125
+ )
126
+
127
+ # 4) Clinical feature extraction (only if trait_row is available)
128
+ if is_trait_available:
129
+ selected_clinical_df = geo_select_clinical_features(
130
+ clinical_df=clinical_data,
131
+ trait=trait,
132
+ trait_row=trait_row,
133
+ convert_trait=convert_trait,
134
+ age_row=age_row,
135
+ convert_age=convert_age,
136
+ gender_row=gender_row,
137
+ convert_gender=convert_gender
138
+ )
139
+ preview = preview_df(selected_clinical_df)
140
+ print(preview)
141
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
142
+ selected_clinical_df.to_csv(out_clinical_data_file)
143
+
144
+ # Step 3: Gene Data Extraction
145
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
146
+ gene_data = get_genetic_data(matrix_file)
147
+
148
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
149
+ print(gene_data.index[:20])
150
+
151
+ # Step 4: Gene Identifier Review
152
+ # Based on the observed identifiers (e.g., 'AFFX-BioB-3_at'), these are Affymetrix probe set/control IDs, not human gene symbols.
153
+ requires_gene_mapping = True
154
+ print(f"requires_gene_mapping = {requires_gene_mapping}")
155
+
156
+ # Step 5: Gene Annotation
157
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
158
+ gene_annotation = get_gene_annotation(soft_file)
159
+
160
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
161
+ print("Gene annotation preview:")
162
+ print(preview_df(gene_annotation))
163
+
164
+ # Step 6: Gene Identifier Mapping
165
+ # Decide identifier and gene symbol columns based on annotation preview
166
+ probe_col = 'ID' # Matches probe IDs like 'AFFX-BioB-3_at'
167
+ gene_symbol_col = 'GeneSymbol' # Gene symbols column
168
+
169
+ # 2. Build mapping dataframe
170
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=probe_col, gene_col=gene_symbol_col)
171
+
172
+ # 3. Apply mapping to convert probe-level data to gene-level data
173
+ gene_data = apply_gene_mapping(gene_data, mapping_df)
174
+
175
+ # Optional normalization of gene symbols to standardized symbols and aggregation
176
+ gene_data = normalize_gene_symbols_in_index(gene_data)
177
+
178
+ # Step 7: Data Normalization and Linking
179
+ import os
180
+
181
+ # 1. Normalize gene symbols (already done in Step 6); just save to file safely.
182
+ normalized_gene_data = gene_data
183
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
184
+ normalized_gene_data.to_csv(out_gene_data_file)
185
+
186
+ # 2. Link the clinical and genetic data
187
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
188
+
189
+ # 3. Handle missing values
190
+ linked_data = handle_missing_values(linked_data, trait)
191
+
192
+ # 4. Determine bias and remove biased demographic features if necessary
193
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
194
+
195
+ # 5. Final validation and save cohort info
196
+ note = ("INFO: Probe-to-gene mapping applied and gene symbols normalized in Step 6; "
197
+ "age and gender not available in this series; trait is continuous HBV post-vaccination "
198
+ "antibody concentration (mIU/mL) with left-censored values (e.g., '<5') mapped to the threshold.")
199
+ is_usable = validate_and_save_cohort_info(
200
+ is_final=True,
201
+ cohort=cohort,
202
+ info_path=json_path,
203
+ is_gene_available=True,
204
+ is_trait_available=True,
205
+ is_biased=is_trait_biased,
206
+ df=unbiased_linked_data,
207
+ note=note
208
+ )
209
+
210
+ # 6. Save linked data if usable
211
+ if is_usable:
212
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
213
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Hepatitis/code/GSE152738.py ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Hepatitis"
6
+ cohort = "GSE152738"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Hepatitis"
10
+ in_cohort_dir = "../DATA/GEO/Hepatitis/GSE152738"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z3/preprocess/Hepatitis/GSE152738.csv"
14
+ out_gene_data_file = "./output/z3/preprocess/Hepatitis/gene_data/GSE152738.csv"
15
+ out_clinical_data_file = "./output/z3/preprocess/Hepatitis/clinical_data/GSE152738.csv"
16
+ json_path = "./output/z3/preprocess/Hepatitis/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 U133 Plus 2 arrays -> mRNA expression
43
+
44
+ # 2) Variable availability based on provided sample characteristics
45
+ # Sample Characteristics Dictionary:
46
+ # {0: ['age stage: Old (>40 years)', 'age stage: Young (<40 years)'], 1: ['tissue: liver']}
47
+ trait_row = None # Hepatitis status not available in this dataset
48
+ age_row = 0 # Age stage available (Old vs Young)
49
+ gender_row = None # No gender information
50
+
51
+ # 2.2) Converters
52
+ def _extract_after_colon(x):
53
+ if x is None:
54
+ return None
55
+ if isinstance(x, str):
56
+ parts = x.split(":", 1)
57
+ val = parts[1] if len(parts) > 1 else parts[0]
58
+ return val.strip()
59
+ return x
60
+
61
+ def convert_trait(x):
62
+ # Binary: 1 = hepatitis present, 0 = no hepatitis, None = unknown
63
+ val = _extract_after_colon(x)
64
+ if val is None:
65
+ return None
66
+ s = str(val).lower()
67
+
68
+ # Strong positives
69
+ positive_keywords = [
70
+ 'hepatitis', 'hbv', 'hcv', 'hep b', 'hep c', 'b virus', 'c virus', 'viral hepatitis'
71
+ ]
72
+ # Strong negatives
73
+ negative_keywords = [
74
+ 'healthy', 'control', 'non-hepatitis', 'no hepatitis', 'hbv-', 'hcv-', 'negative', 'no hcv', 'no hbv'
75
+ ]
76
+
77
+ # If both appear (unlikely), prioritize explicit negatives first
78
+ if any(k in s for k in negative_keywords):
79
+ return 0
80
+ if any(k in s for k in positive_keywords):
81
+ return 1
82
+
83
+ return None
84
+
85
+ def convert_age(x):
86
+ # Binary: 1 = Older (>=40 or contains 'old'), 0 = Younger (<40 or contains 'young'), None = unknown
87
+ val = _extract_after_colon(x)
88
+ if val is None:
89
+ return None
90
+ s = str(val).lower()
91
+
92
+ if 'old' in s:
93
+ return 1
94
+ if 'young' in s:
95
+ return 0
96
+
97
+ # Try to parse a numeric age if present
98
+ nums = re.findall(r'\d+(?:\.\d+)?', s)
99
+ if nums:
100
+ try:
101
+ age_val = float(nums[0])
102
+ return 1 if age_val >= 40 else 0
103
+ except Exception:
104
+ pass
105
+
106
+ return None
107
+
108
+ def convert_gender(x):
109
+ # Binary: 1 = male, 0 = female, None = unknown
110
+ val = _extract_after_colon(x)
111
+ if val is None:
112
+ return None
113
+ s = str(val).lower()
114
+ if 'male' in s and 'female' not in s:
115
+ return 1
116
+ if 'female' in s and 'male' not in s:
117
+ return 0
118
+ return None
119
+
120
+ # 3) Save initial metadata
121
+ is_trait_available = trait_row is not None
122
+ _ = validate_and_save_cohort_info(
123
+ is_final=False,
124
+ cohort=cohort,
125
+ info_path=json_path,
126
+ is_gene_available=is_gene_available,
127
+ is_trait_available=is_trait_available
128
+ )
129
+
130
+ # 4) Clinical feature extraction is skipped because trait_row is None
output/preprocess/Hepatitis/code/GSE159676.py ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Hepatitis"
6
+ cohort = "GSE159676"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Hepatitis"
10
+ in_cohort_dir = "../DATA/GEO/Hepatitis/GSE159676"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z3/preprocess/Hepatitis/GSE159676.csv"
14
+ out_gene_data_file = "./output/z3/preprocess/Hepatitis/gene_data/GSE159676.csv"
15
+ out_clinical_data_file = "./output/z3/preprocess/Hepatitis/clinical_data/GSE159676.csv"
16
+ json_path = "./output/z3/preprocess/Hepatitis/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ # Step: Dataset Analysis and Clinical Feature Extraction for GSE159676
40
+
41
+ import os
42
+
43
+ # 1) Gene expression availability
44
+ is_gene_available = True # Affymetrix Human Gene 1.0 ST array indicates mRNA expression data
45
+
46
+ # 2) Variable availability and converters
47
+ # From the provided Sample Characteristics Dictionary, only key 0 ("condition") is available and variable.
48
+ trait_row = 0
49
+ age_row = None
50
+ gender_row = None
51
+
52
+ def convert_trait(x):
53
+ # Map to binary: hepatitis (1) vs non-hepatitis/others (0)
54
+ if x is None:
55
+ return None
56
+ val = str(x)
57
+ if ':' in val:
58
+ val = val.split(':', 1)[1]
59
+ v = val.strip().lower()
60
+
61
+ if v in {'', 'na', 'n/a', 'unknown'}:
62
+ return None
63
+
64
+ # Explicit negatives
65
+ if 'steatohepatitis' in v: # e.g., non alcoholic steatohepatitis (NASH)
66
+ return 0
67
+ if any(k in v for k in [
68
+ 'primary sclerosing cholangitis', 'psc',
69
+ 'primary biliary cirrhosis', 'primary biliary cholangitis', 'pbc',
70
+ 'haemochromatosis',
71
+ 'alcohol related',
72
+ 'healthy', 'normal', 'control'
73
+ ]):
74
+ return 0
75
+
76
+ # Explicit hepatitis positives
77
+ if any(k in v for k in [
78
+ 'autoimmune hepatitis',
79
+ 'hepatitis b', 'hbv',
80
+ 'hepatitis c', 'hcv',
81
+ 'viral hepatitis',
82
+ 'hepatitis '
83
+ ]) or v == 'hepatitis':
84
+ return 1
85
+
86
+ # Default to non-hepatitis for other liver diseases
87
+ return 0
88
+
89
+ convert_age = None
90
+ convert_gender = None
91
+
92
+ # 3) Save metadata (initial filtering)
93
+ is_trait_available = trait_row is not None
94
+ _ = validate_and_save_cohort_info(
95
+ is_final=False,
96
+ cohort=cohort,
97
+ info_path=json_path,
98
+ is_gene_available=is_gene_available,
99
+ is_trait_available=is_trait_available
100
+ )
101
+
102
+ # 4) Clinical feature extraction (only if trait is available)
103
+ if trait_row is not None:
104
+ selected_clinical_df = geo_select_clinical_features(
105
+ clinical_df=clinical_data,
106
+ trait=trait,
107
+ trait_row=trait_row,
108
+ convert_trait=convert_trait,
109
+ age_row=age_row,
110
+ convert_age=convert_age,
111
+ gender_row=gender_row,
112
+ convert_gender=convert_gender
113
+ )
114
+ preview = preview_df(selected_clinical_df)
115
+ print(preview)
116
+
117
+ # Save clinical features
118
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
119
+ selected_clinical_df.to_csv(out_clinical_data_file)
120
+
121
+ # Step 3: Gene Data Extraction
122
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
123
+ gene_data = get_genetic_data(matrix_file)
124
+
125
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
126
+ print(gene_data.index[:20])
127
+
128
+ # Step 4: Gene Identifier Review
129
+ # The observed identifiers are numeric probe IDs, not standard human gene symbols.
130
+ print("requires_gene_mapping = True")
131
+
132
+ # Step 5: Gene Annotation
133
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
134
+ gene_annotation = get_gene_annotation(soft_file)
135
+
136
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
137
+ print("Gene annotation preview:")
138
+ print(preview_df(gene_annotation))
139
+
140
+ # Step 6: Gene Identifier Mapping
141
+ # Map probe IDs to gene symbols using annotation, then aggregate probe-level data to gene-level.
142
+
143
+ # 1) Decide columns:
144
+ # - Expression uses numeric probe IDs matching the 'ID' column in annotation.
145
+ # - Gene symbols are embedded in the 'gene_assignment' column.
146
+ probe_col = 'ID'
147
+ gene_col = 'gene_assignment'
148
+
149
+ # 2) Build mapping dataframe (ID -> Gene text)
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
+ gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
154
+
155
+ # Step 7: Data Normalization and Linking
156
+ # Step 7: Data Normalization and Linking
157
+
158
+ import os
159
+
160
+ # 1. Normalize gene symbols and save
161
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
162
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
163
+ normalized_gene_data.to_csv(out_gene_data_file)
164
+
165
+ # 2. Link clinical and genetic data
166
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
167
+
168
+ # 3. Handle missing values
169
+ linked_data = handle_missing_values(linked_data, trait)
170
+
171
+ # 4. Bias assessment and removal of biased demographic features
172
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
173
+
174
+ # 5. Final validation and saving cohort info
175
+ try:
176
+ gene_avail = is_gene_available
177
+ except NameError:
178
+ gene_avail = True # Based on platform and previous steps
179
+
180
+ try:
181
+ trait_avail = is_trait_available
182
+ except NameError:
183
+ trait_avail = True # Trait row was identified earlier
184
+
185
+ is_usable = validate_and_save_cohort_info(
186
+ is_final=True,
187
+ cohort=cohort,
188
+ info_path=json_path,
189
+ is_gene_available=gene_avail,
190
+ is_trait_available=trait_avail,
191
+ is_biased=is_trait_biased,
192
+ df=unbiased_linked_data,
193
+ note=""
194
+ )
195
+
196
+ # 6. Save linked dataset if usable
197
+ if is_usable:
198
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
199
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Hepatitis/code/GSE168049.py ADDED
@@ -0,0 +1,219 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Hepatitis"
6
+ cohort = "GSE168049"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Hepatitis"
10
+ in_cohort_dir = "../DATA/GEO/Hepatitis/GSE168049"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z3/preprocess/Hepatitis/GSE168049.csv"
14
+ out_gene_data_file = "./output/z3/preprocess/Hepatitis/gene_data/GSE168049.csv"
15
+ out_clinical_data_file = "./output/z3/preprocess/Hepatitis/clinical_data/GSE168049.csv"
16
+ json_path = "./output/z3/preprocess/Hepatitis/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 math
41
+
42
+ # 1) Gene expression availability
43
+ is_gene_available = True # mRNA mentioned in the series title (microRNA present too, but mRNA indicates gene expression)
44
+
45
+ # 2) Variable availability (from Sample Characteristics Dictionary)
46
+ # trait (Hepatitis) is constant: all samples are HBV-ACLF -> not useful for association within this dataset
47
+ trait_row = None
48
+ age_row = 3
49
+ gender_row = 2
50
+
51
+ # 2.2) Conversion functions
52
+ def _extract_value(cell):
53
+ if cell is None:
54
+ return None
55
+ if isinstance(cell, float) and math.isnan(cell):
56
+ return None
57
+ s = str(cell)
58
+ parts = s.split(":", 1)
59
+ val = parts[1].strip() if len(parts) > 1 else s.strip()
60
+ return val if val != "" else None
61
+
62
+ def convert_trait(x):
63
+ # Binary: 1 = hepatitis-related case, 0 = control
64
+ val = _extract_value(x)
65
+ if val is None:
66
+ return None
67
+ v = val.lower()
68
+ # Heuristic mappings
69
+ if any(k in v for k in ["hbv", "hepatitis", "aclf", "liver failure"]):
70
+ return 1
71
+ if any(k in v for k in ["healthy", "control", "normal", "non-hepatitis"]):
72
+ return 0
73
+ return None
74
+
75
+ def convert_age(x):
76
+ # Continuous age in years
77
+ val = _extract_value(x)
78
+ if val is None:
79
+ return None
80
+ m = re.search(r"(\d+(\.\d+)?)", val)
81
+ if not m:
82
+ return None
83
+ age = float(m.group(1))
84
+ if age < 0 or age > 120:
85
+ return None
86
+ return age
87
+
88
+ def convert_gender(x):
89
+ # Binary: female=0, male=1
90
+ val = _extract_value(x)
91
+ if val is None:
92
+ return None
93
+ v = val.strip().lower()
94
+ if v in {"male", "m", "man"}:
95
+ return 1
96
+ if v in {"female", "f", "woman"}:
97
+ return 0
98
+ return None
99
+
100
+ # 3) Save metadata (initial filtering)
101
+ is_trait_available = trait_row is not None
102
+ _ = validate_and_save_cohort_info(
103
+ is_final=False,
104
+ cohort=cohort,
105
+ info_path=json_path,
106
+ is_gene_available=is_gene_available,
107
+ is_trait_available=is_trait_available
108
+ )
109
+
110
+ # 4) Clinical feature extraction (skip if trait_row is None)
111
+ if trait_row is not None:
112
+ selected_clinical = geo_select_clinical_features(
113
+ clinical_df=clinical_data,
114
+ trait=trait,
115
+ trait_row=trait_row,
116
+ convert_trait=convert_trait,
117
+ age_row=age_row,
118
+ convert_age=convert_age,
119
+ gender_row=gender_row,
120
+ convert_gender=convert_gender
121
+ )
122
+ preview = preview_df(selected_clinical, n=5)
123
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
124
+ selected_clinical.to_csv(out_clinical_data_file, index=True)
125
+
126
+ # Step 3: Gene Data Extraction
127
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
128
+ gene_data = get_genetic_data(matrix_file)
129
+
130
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
131
+ print(gene_data.index[:20])
132
+
133
+ # Step 4: Gene Identifier Review
134
+ requires_gene_mapping = True
135
+ print(f"requires_gene_mapping = {requires_gene_mapping}")
136
+
137
+ # Step 5: Gene Annotation
138
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
139
+ gene_annotation = get_gene_annotation(soft_file)
140
+
141
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
142
+ print("Gene annotation preview:")
143
+ print(preview_df(gene_annotation))
144
+
145
+ # Step 6: Gene Identifier Mapping
146
+ # Decide the identifier and gene symbol columns based on the annotation preview:
147
+ # Probe ID column: 'ID'; Gene symbol column: 'GENE_SYMBOL'
148
+ prob_col = 'ID'
149
+ gene_col = 'GENE_SYMBOL'
150
+
151
+ # Build mapping dataframe
152
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=prob_col, gene_col=gene_col)
153
+
154
+ # Convert probe-level data to gene-level expression
155
+ probe_data = gene_data
156
+ gene_data = apply_gene_mapping(expression_df=probe_data, mapping_df=mapping_df)
157
+
158
+ # Step 7: Data Normalization and Linking
159
+ import os
160
+
161
+ # 1. Normalize gene symbols and save gene expression data
162
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
163
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
164
+ normalized_gene_data.to_csv(out_gene_data_file)
165
+
166
+ # Determine trait availability from previous steps
167
+ is_trait_available = ('trait_row' in globals()) and (trait_row is not None)
168
+
169
+ # If trait is not available, record metadata and stop before linking
170
+ if not is_trait_available:
171
+ # Record that gene data exists but trait data is unavailable; skip linking
172
+ _ = validate_and_save_cohort_info(
173
+ is_final=False,
174
+ cohort=cohort,
175
+ info_path=json_path,
176
+ is_gene_available=True,
177
+ is_trait_available=False
178
+ )
179
+ linked_data = None
180
+ is_usable = False
181
+ else:
182
+ # 2. Extract clinical features (recompute here to ensure availability)
183
+ selected_clinical = geo_select_clinical_features(
184
+ clinical_df=clinical_data,
185
+ trait=trait,
186
+ trait_row=trait_row,
187
+ convert_trait=convert_trait,
188
+ age_row=age_row if 'age_row' in globals() else None,
189
+ convert_age=convert_age if 'convert_age' in globals() else None,
190
+ gender_row=gender_row if 'gender_row' in globals() else None,
191
+ convert_gender=convert_gender if 'convert_gender' in globals() else None
192
+ )
193
+
194
+ # 2. Link clinical and genetic data
195
+ linked_data = geo_link_clinical_genetic_data(selected_clinical, normalized_gene_data)
196
+
197
+ # 3. Handle missing values
198
+ linked_data = handle_missing_values(linked_data, trait)
199
+
200
+ # 4. Bias assessment and removal of biased demographic features
201
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
202
+
203
+ # 5. Final validation and save cohort info
204
+ note = "INFO: Clinical features extracted and linked with normalized gene expression."
205
+ is_usable = validate_and_save_cohort_info(
206
+ is_final=True,
207
+ cohort=cohort,
208
+ info_path=json_path,
209
+ is_gene_available=True,
210
+ is_trait_available=True,
211
+ is_biased=is_trait_biased,
212
+ df=unbiased_linked_data,
213
+ note=note
214
+ )
215
+
216
+ # 6. Save linked data if usable
217
+ if is_usable:
218
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
219
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Hepatitis/code/GSE45032.py ADDED
@@ -0,0 +1,198 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Hepatitis"
6
+ cohort = "GSE45032"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Hepatitis"
10
+ in_cohort_dir = "../DATA/GEO/Hepatitis/GSE45032"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z3/preprocess/Hepatitis/GSE45032.csv"
14
+ out_gene_data_file = "./output/z3/preprocess/Hepatitis/gene_data/GSE45032.csv"
15
+ out_clinical_data_file = "./output/z3/preprocess/Hepatitis/clinical_data/GSE45032.csv"
16
+ json_path = "./output/z3/preprocess/Hepatitis/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 availability based on series description
40
+ is_gene_available = True # Microarray gene expression per summary/title
41
+
42
+ # 2) Variable availability and data type conversion
43
+ # Keys identified from Sample Characteristics Dictionary:
44
+ # 0: cell type (hepatocellular carcinoma vs chronic hepatitis type C) -> trait
45
+ # 2: gender
46
+ # 3: age(yrs)
47
+ trait_row = 0
48
+ age_row = 3
49
+ gender_row = 2
50
+
51
+ # 2.2 Define conversion functions
52
+ def _after_colon(val):
53
+ if val is None:
54
+ return None
55
+ s = str(val)
56
+ parts = s.split(":", 1)
57
+ v = parts[1] if len(parts) > 1 else parts[0]
58
+ return v.strip()
59
+
60
+ def convert_trait(x):
61
+ v = _after_colon(x)
62
+ if v is None or v == "":
63
+ return None
64
+ v_low = v.lower()
65
+
66
+ # Normalize common variations/misspellings
67
+ v_low = v_low.replace("hepatocallular", "hepatocellular") # handle misspelling in dict
68
+
69
+ # Map to hepatitis (1) vs non-hepatitis (0)
70
+ # "chronic hepatitis type c" (CHC) -> 1
71
+ # "hepatocellular carcinoma" (HCC) -> 0
72
+ if "hepatitis" in v_low:
73
+ return 1
74
+ if "hepatocellular carcinoma" in v_low or v_low == "hcc":
75
+ return 0
76
+ if v_low in {"chc", "chronic hepatitis", "chronic hepatitis c", "chronic hepatitis type c"}:
77
+ return 1
78
+
79
+ # Unknown label
80
+ return None
81
+
82
+ def convert_age(x):
83
+ v = _after_colon(x)
84
+ if v is None or v == "":
85
+ return None
86
+ # Strip potential units and convert to float
87
+ try:
88
+ # Keep digits and dot only from the value
89
+ import re
90
+ m = re.search(r"[-+]?\d*\.?\d+", v)
91
+ return float(m.group()) if m else None
92
+ except Exception:
93
+ return None
94
+
95
+ def convert_gender(x):
96
+ v = _after_colon(x)
97
+ if v is None or v == "":
98
+ return None
99
+ v_low = v.lower()
100
+ if v_low in {"male", "m", "man"}:
101
+ return 1
102
+ if v_low in {"female", "f", "woman"}:
103
+ return 0
104
+ return None
105
+
106
+ # Determine trait availability
107
+ is_trait_available = trait_row is not None
108
+
109
+ # 3) Initial filtering and save metadata
110
+ _ = validate_and_save_cohort_info(
111
+ is_final=False,
112
+ cohort=cohort,
113
+ info_path=json_path,
114
+ is_gene_available=is_gene_available,
115
+ is_trait_available=is_trait_available
116
+ )
117
+
118
+ # 4) Clinical feature extraction, preview, and save
119
+ if trait_row is not None:
120
+ selected_clinical_df = geo_select_clinical_features(
121
+ clinical_df=clinical_data,
122
+ trait=trait,
123
+ trait_row=trait_row,
124
+ convert_trait=convert_trait,
125
+ age_row=age_row,
126
+ convert_age=convert_age,
127
+ gender_row=gender_row,
128
+ convert_gender=convert_gender
129
+ )
130
+ clinical_preview = preview_df(selected_clinical_df)
131
+ print("Clinical features preview:", clinical_preview)
132
+
133
+ import os
134
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
135
+ selected_clinical_df.to_csv(out_clinical_data_file)
136
+
137
+ # Step 3: Gene Data Extraction
138
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
139
+ gene_data = get_genetic_data(matrix_file)
140
+
141
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
142
+ print(gene_data.index[:20])
143
+
144
+ # Step 4: Gene Identifier Review
145
+ requires_gene_mapping = True
146
+ print(f"requires_gene_mapping = {requires_gene_mapping}")
147
+
148
+ # Step 5: Gene Annotation
149
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
150
+ gene_annotation = get_gene_annotation(soft_file)
151
+
152
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
153
+ print("Gene annotation preview:")
154
+ print(preview_df(gene_annotation))
155
+
156
+ # Step 6: Gene Identifier Mapping
157
+ # Decide columns for mapping: probe identifiers are in 'ID', gene symbols are in 'GeneName'
158
+ # 1) Build mapping dataframe
159
+ mapping_df = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='GeneName')
160
+
161
+ # 2) Apply mapping to convert probe-level data to gene-level expression
162
+ probe_data = gene_data # preserve original probe-level data
163
+ gene_data = apply_gene_mapping(probe_data, mapping_df)
164
+
165
+ # Step 7: Data Normalization and Linking
166
+ import os
167
+
168
+ # 1. Normalize gene symbols and save gene data
169
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
170
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
171
+ normalized_gene_data.to_csv(out_gene_data_file)
172
+
173
+ # 2. Link clinical and genetic data
174
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
175
+
176
+ # 3. Handle missing values
177
+ linked_data = handle_missing_values(linked_data, trait)
178
+
179
+ # 4. Assess bias and remove biased demographic features
180
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
181
+
182
+ # 5. Final validation and save cohort info
183
+ note = "INFO: Trait encoding for Hepatitis: CHC=1 (chronic hepatitis C), HCC=0 (hepatocellular carcinoma)."
184
+ is_usable = validate_and_save_cohort_info(
185
+ is_final=True,
186
+ cohort=cohort,
187
+ info_path=json_path,
188
+ is_gene_available=True,
189
+ is_trait_available=True,
190
+ is_biased=is_trait_biased,
191
+ df=unbiased_linked_data,
192
+ note=note
193
+ )
194
+
195
+ # 6. Save linked data if usable
196
+ if is_usable:
197
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
198
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Hepatitis/code/GSE66843.py ADDED
@@ -0,0 +1,193 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Hepatitis"
6
+ cohort = "GSE66843"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Hepatitis"
10
+ in_cohort_dir = "../DATA/GEO/Hepatitis/GSE66843"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z3/preprocess/Hepatitis/GSE66843.csv"
14
+ out_gene_data_file = "./output/z3/preprocess/Hepatitis/gene_data/GSE66843.csv"
15
+ out_clinical_data_file = "./output/z3/preprocess/Hepatitis/clinical_data/GSE66843.csv"
16
+ json_path = "./output/z3/preprocess/Hepatitis/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ import os
40
+ import re
41
+
42
+ # 1) Gene expression data availability
43
+ is_gene_available = True # Likely mRNA expression in this series (cell-based model), not miRNA-only or methylation-only.
44
+
45
+ # 2) Variable availability and conversion functions
46
+ # Use infection status as the trait (key 1). Age and gender are not applicable in a cell line model.
47
+ trait_row = 1
48
+ age_row = None
49
+ gender_row = None
50
+
51
+ def _extract_after_colon(x):
52
+ if x is None:
53
+ return None
54
+ if isinstance(x, str):
55
+ parts = x.split(":", 1)
56
+ val = parts[1] if len(parts) > 1 else parts[0]
57
+ return val.strip()
58
+ return x
59
+
60
+ def convert_trait(x):
61
+ # Binary: 1 = HCV infection, 0 = control/mock/uninfected
62
+ val = _extract_after_colon(x)
63
+ if val is None:
64
+ return None
65
+ s = str(val).strip().lower()
66
+ if any(t in s for t in ["na", "not available", "unknown", "n/a", "none"]):
67
+ return None
68
+ if "mock" in s or "control" in s or "uninfected" in s:
69
+ return 0
70
+ if "hcv" in s or "infect" in s:
71
+ return 1
72
+ return None
73
+
74
+ def convert_age(x):
75
+ # Continuous: extract number in years (not applicable here; defined for interface completeness)
76
+ val = _extract_after_colon(x)
77
+ if val is None:
78
+ return None
79
+ s = str(val).strip().lower()
80
+ if any(t in s for t in ["na", "not available", "unknown", "n/a", "none"]):
81
+ return None
82
+ m = re.search(r"[-+]?\d*\.?\d+", s)
83
+ if m:
84
+ try:
85
+ return float(m.group())
86
+ except:
87
+ return None
88
+ return None
89
+
90
+ def convert_gender(x):
91
+ # Binary: female=0, male=1 (not applicable here; defined for interface completeness)
92
+ val = _extract_after_colon(x)
93
+ if val is None:
94
+ return None
95
+ s = str(val).strip().lower()
96
+ if any(t in s for t in ["na", "not available", "unknown", "n/a", "none"]):
97
+ return None
98
+ if s.startswith("f"):
99
+ return 0
100
+ if s.startswith("m"):
101
+ return 1
102
+ return None
103
+
104
+ # 3) Save metadata (initial filtering)
105
+ is_trait_available = trait_row is not None
106
+ _ = validate_and_save_cohort_info(
107
+ is_final=False,
108
+ cohort=cohort,
109
+ info_path=json_path,
110
+ is_gene_available=is_gene_available,
111
+ is_trait_available=is_trait_available
112
+ )
113
+
114
+ # 4) Clinical Feature Extraction
115
+ if trait_row is not None:
116
+ selected_clinical_df = geo_select_clinical_features(
117
+ clinical_df=clinical_data,
118
+ trait=trait,
119
+ trait_row=trait_row,
120
+ convert_trait=convert_trait,
121
+ age_row=age_row,
122
+ convert_age=convert_age if age_row is not None else None,
123
+ gender_row=gender_row,
124
+ convert_gender=convert_gender if gender_row is not None else None
125
+ )
126
+ clinical_preview = preview_df(selected_clinical_df)
127
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
128
+ selected_clinical_df.to_csv(out_clinical_data_file, index=False)
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 mapping based on previous previews:
150
+ # Probe identifiers: 'ID' (e.g., ILMN_1343***)
151
+ # Gene symbols: 'Symbol'
152
+ gene_mapping = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='Symbol')
153
+
154
+ # Apply mapping to convert probe-level data to gene-level expression
155
+ gene_data = apply_gene_mapping(gene_data, gene_mapping)
156
+
157
+ # Step 7: Data Normalization and Linking
158
+ import os
159
+
160
+ # 1. Normalize the obtained gene data and save
161
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
162
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
163
+ normalized_gene_data.to_csv(out_gene_data_file)
164
+
165
+ # 2. Link the clinical and genetic data
166
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
167
+
168
+ # 3. Handle missing values in the linked data
169
+ linked_data = handle_missing_values(linked_data, trait)
170
+
171
+ # 4. Determine whether the trait and demographic features are severely biased
172
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
173
+
174
+ # Derive availability flags based on processed data
175
+ is_gene_available_final = (normalized_gene_data.shape[0] > 0 and normalized_gene_data.shape[1] > 0)
176
+ is_trait_available_final = (trait in unbiased_linked_data.columns) and (len(unbiased_linked_data) > 0)
177
+
178
+ # 5. Final quality validation and save cohort information
179
+ note = ("INFO: Cell-line HCV infection model (Huh7.5.1). Trait derived from infection status; "
180
+ "no Age/Gender available. ILMN probes mapped via 'Symbol' and gene symbols normalized.")
181
+ is_usable = validate_and_save_cohort_info(
182
+ True, cohort, json_path,
183
+ is_gene_available=is_gene_available_final,
184
+ is_trait_available=is_trait_available_final,
185
+ is_biased=is_trait_biased,
186
+ df=unbiased_linked_data,
187
+ note=note
188
+ )
189
+
190
+ # 6. Save linked data if usable
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/Hepatitis/code/GSE85550.py ADDED
@@ -0,0 +1,196 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Hepatitis"
6
+ cohort = "GSE85550"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Hepatitis"
10
+ in_cohort_dir = "../DATA/GEO/Hepatitis/GSE85550"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z3/preprocess/Hepatitis/GSE85550.csv"
14
+ out_gene_data_file = "./output/z3/preprocess/Hepatitis/gene_data/GSE85550.csv"
15
+ out_clinical_data_file = "./output/z3/preprocess/Hepatitis/clinical_data/GSE85550.csv"
16
+ json_path = "./output/z3/preprocess/Hepatitis/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 availability
40
+ is_gene_available = True # Liver biopsy transcriptomic profiling; not miRNA/methylation-only by description.
41
+
42
+ # 2) Variable availability and converters
43
+ # Based on the sample characteristics dictionary, only patient IDs, tissue, and time_point are present.
44
+ trait_row = None # No hepatitis status provided; likely all have liver disease and no variation recorded.
45
+ age_row = None # No age field available.
46
+ gender_row = None # No gender field available.
47
+
48
+ def _after_colon(x: str) -> str:
49
+ if x is None:
50
+ return ""
51
+ parts = str(x).split(":", 1)
52
+ return parts[1].strip() if len(parts) == 2 else str(x).strip()
53
+
54
+ def convert_trait(x):
55
+ # Binary mapping for hepatitis status if ever present:
56
+ # 1 = hepatitis (HBV/HCV/other viral hepatitis/chronic hepatitis), 0 = non-hepatitis/healthy/control.
57
+ v = _after_colon(x).lower()
58
+ if v in ("", "na", "n/a", "none", "unknown"):
59
+ return None
60
+ # Positive cases
61
+ pos_keywords = ["hepatitis", "hbv", "hcv", "hbc", "hepatitis b", "hepatitis c", "chronic hepatitis", "acute hepatitis"]
62
+ if any(k in v for k in pos_keywords) or v in ("yes", "case", "disease", "patient"):
63
+ return 1
64
+ # Negative cases
65
+ neg_keywords = ["healthy", "control", "non-hepatitis", "no hepatitis", "normal"]
66
+ if any(k in v for k in neg_keywords) or v in ("no", "ctrl"):
67
+ return 0
68
+ # Ambiguous tokens
69
+ return None
70
+
71
+ def convert_age(x):
72
+ v = _after_colon(x).lower()
73
+ if v in ("", "na", "n/a", "none", "unknown"):
74
+ return None
75
+ # Extract first numeric token; handle units like years/yrs/y/o
76
+ import re
77
+ m = re.search(r"[-+]?\d*\.?\d+", v)
78
+ if not m:
79
+ return None
80
+ try:
81
+ return float(m.group())
82
+ except Exception:
83
+ return None
84
+
85
+ def convert_gender(x):
86
+ v = _after_colon(x).lower()
87
+ if v in ("", "na", "n/a", "none", "unknown"):
88
+ return None
89
+ if v in ("female", "f", "woman", "girl", "famale"):
90
+ return 0
91
+ if v in ("male", "m", "man", "boy"):
92
+ return 1
93
+ return None
94
+
95
+ # 3) Save metadata (initial filtering)
96
+ is_trait_available = trait_row is not None
97
+ _ = validate_and_save_cohort_info(
98
+ is_final=False,
99
+ cohort=cohort,
100
+ info_path=json_path,
101
+ is_gene_available=is_gene_available,
102
+ is_trait_available=is_trait_available
103
+ )
104
+
105
+ # 4) Clinical feature extraction (skip because trait_row is None)
106
+ if trait_row is not None:
107
+ selected_clinical_df = geo_select_clinical_features(
108
+ clinical_df=clinical_data,
109
+ trait=trait,
110
+ trait_row=trait_row,
111
+ convert_trait=convert_trait,
112
+ age_row=age_row,
113
+ convert_age=convert_age if age_row is not None else None,
114
+ gender_row=gender_row,
115
+ convert_gender=convert_gender if gender_row is not None else None
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)
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 = False")
130
+
131
+ # Step 5: Data Normalization and Linking
132
+ import os
133
+
134
+ # 1. Normalize gene symbols and save
135
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
136
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
137
+ normalized_gene_data.to_csv(out_gene_data_file)
138
+
139
+ # Initialize linked_data for completeness
140
+ linked_data = None
141
+
142
+ # 2-6. Proceed only if trait/clinical data are available; otherwise, skip linking and record unusable
143
+ if 'trait_row' in globals() and (trait_row is not None):
144
+ # Ensure selected_clinical_data exists; if not, recreate it
145
+ if 'selected_clinical_data' in globals():
146
+ selected_clinical_df = selected_clinical_data
147
+ else:
148
+ selected_clinical_df = geo_select_clinical_features(
149
+ clinical_df=clinical_data,
150
+ trait=trait,
151
+ trait_row=trait_row,
152
+ convert_trait=convert_trait,
153
+ age_row=age_row,
154
+ convert_age=convert_age if 'age_row' in globals() and age_row is not None else None,
155
+ gender_row=gender_row,
156
+ convert_gender=convert_gender if 'gender_row' in globals() and gender_row is not None else None
157
+ )
158
+
159
+ # Link clinical and genetic data
160
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
161
+
162
+ # Handle missing values
163
+ linked_data = handle_missing_values(linked_data, trait)
164
+
165
+ # Bias check and remove biased demographic features
166
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
167
+
168
+ # Final validation and cohort info saving
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=True,
175
+ is_biased=is_trait_biased,
176
+ df=unbiased_linked_data,
177
+ note="INFO: Proceeded with linking and preprocessing."
178
+ )
179
+
180
+ # Save linked dataset only if usable
181
+ if is_usable:
182
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
183
+ unbiased_linked_data.to_csv(out_data_file)
184
+
185
+ else:
186
+ # No trait data available: skip linking and mark dataset as unavailable for association analysis
187
+ is_usable = validate_and_save_cohort_info(
188
+ is_final=True,
189
+ cohort=cohort,
190
+ info_path=json_path,
191
+ is_gene_available=True,
192
+ is_trait_available=False,
193
+ is_biased=False,
194
+ df=normalized_gene_data,
195
+ note="INFO: Trait not available in clinical annotations; skipped linking and downstream processing."
196
+ )
output/preprocess/Hepatitis/code/GSE97475.py ADDED
@@ -0,0 +1,323 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Hepatitis"
6
+ cohort = "GSE97475"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Hepatitis"
10
+ in_cohort_dir = "../DATA/GEO/Hepatitis/GSE97475"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z3/preprocess/Hepatitis/GSE97475.csv"
14
+ out_gene_data_file = "./output/z3/preprocess/Hepatitis/gene_data/GSE97475.csv"
15
+ out_clinical_data_file = "./output/z3/preprocess/Hepatitis/clinical_data/GSE97475.csv"
16
+ json_path = "./output/z3/preprocess/Hepatitis/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ import os
40
+ import re
41
+ import pandas as pd
42
+
43
+ # 1) Gene expression availability (microarray mentioned in series design)
44
+ is_gene_available = True
45
+
46
+ # 2) Variable availability and converters
47
+
48
+ def _extract_header(value: str) -> str:
49
+ if pd.isna(value):
50
+ return ''
51
+ s = str(value)
52
+ if ':' in s:
53
+ return s.split(':', 1)[0].strip().lower()
54
+ return s.strip().lower()
55
+
56
+ def _extract_value(value: str):
57
+ if pd.isna(value):
58
+ return None
59
+ s = str(value).strip()
60
+ if s == '' or s.lower() in {'na', 'n/a', 'nan', 'none', 'null', 'unknown', 'not available'}:
61
+ return None
62
+ if ':' in s:
63
+ s = s.split(':', 1)[1].strip()
64
+ if s.lower() in {'na', 'n/a', 'nan', 'none', 'null', 'unknown', 'not available'}:
65
+ return None
66
+ return s
67
+
68
+ def _unique_non_null_values(series_like) -> set:
69
+ vals = []
70
+ for v in series_like:
71
+ vv = _extract_value(v)
72
+ if vv is not None:
73
+ vals.append(vv)
74
+ return set(vals)
75
+
76
+ # Default to None; we will try to detect from clinical_data if possible
77
+ trait_row = None
78
+ age_row = None
79
+ gender_row = None
80
+
81
+ # Try to detect variable rows from the provided clinical_data DataFrame
82
+ try:
83
+ # clinical_data is assumed to be present in the environment
84
+ row_headers = {}
85
+ unique_values_map = {}
86
+ for rid in clinical_data.index:
87
+ row_vals = clinical_data.loc[rid].tolist()
88
+ header = ''
89
+ # find the first non-empty header
90
+ for v in row_vals:
91
+ h = _extract_header(v)
92
+ if h:
93
+ header = h
94
+ break
95
+ row_headers[rid] = header
96
+ unique_values_map[rid] = _unique_non_null_values(row_vals)
97
+
98
+ # Detect age row: prioritize demographics age with more than one unique numeric value
99
+ age_candidates = []
100
+ for rid, header in row_headers.items():
101
+ if 'age' in header and 'demographics' in header:
102
+ uniq = unique_values_map[rid]
103
+ # count numeric-like values
104
+ numeric_count = 0
105
+ for u in uniq:
106
+ try:
107
+ float(str(u).strip().replace('years', '').replace('year', '').replace('yrs', '').replace('yr', ''))
108
+ numeric_count += 1
109
+ except Exception:
110
+ pass
111
+ if len(uniq) > 1 and numeric_count >= 2:
112
+ age_candidates.append((rid, len(uniq), numeric_count))
113
+ if age_candidates:
114
+ # choose the row with the largest number of unique numeric values
115
+ age_candidates.sort(key=lambda x: (x[2], x[1]), reverse=True)
116
+ age_row = age_candidates[0][0]
117
+ else:
118
+ # Fallback: any header containing 'age' with >1 unique numeric values
119
+ fallback_age = []
120
+ for rid, header in row_headers.items():
121
+ if 'age' in header:
122
+ uniq = unique_values_map[rid]
123
+ numeric_count = 0
124
+ for u in uniq:
125
+ try:
126
+ float(str(u).strip().replace('years', '').replace('year', '').replace('yrs', '').replace('yr', ''))
127
+ numeric_count += 1
128
+ except Exception:
129
+ pass
130
+ if len(uniq) > 1 and numeric_count >= 2:
131
+ fallback_age.append((rid, len(uniq), numeric_count))
132
+ if fallback_age:
133
+ fallback_age.sort(key=lambda x: (x[2], x[1]), reverse=True)
134
+ age_row = fallback_age[0][0]
135
+
136
+ # Detect gender row: headers containing 'gender' or 'sex' with at least two unique values
137
+ gender_candidates = []
138
+ for rid, header in row_headers.items():
139
+ if ('gender' in header) or (re.search(r'\bsex\b', header) is not None):
140
+ uniq = {str(u).strip().lower() for u in unique_values_map[rid]}
141
+ # typical values include male/female; ensure >1 unique categorical values
142
+ if len(uniq) > 1:
143
+ gender_candidates.append((rid, len(uniq)))
144
+ if gender_candidates:
145
+ gender_candidates.sort(key=lambda x: x[1], reverse=True)
146
+ gender_row = gender_candidates[0][0]
147
+
148
+ # Detect trait row for Hepatitis: look for hepatitis/hbv/vaccine terms with >1 unique values
149
+ trait_candidates = []
150
+ hep_terms = ['hepatitis', 'hbv', 'hep b', 'hep-b', 'hepb', 'b vaccine', 'vaccin']
151
+ for rid, header in row_headers.items():
152
+ if any(t in header for t in hep_terms):
153
+ uniq = {str(u).strip().lower() for u in unique_values_map[rid]}
154
+ # if all values are same or empty, skip
155
+ if len(uniq) > 1:
156
+ trait_candidates.append((rid, len(uniq)))
157
+ # In this dataset (healthy HBV vaccine recipients), trait likely constant; only select if >1 unique
158
+ if trait_candidates:
159
+ trait_candidates.sort(key=lambda x: x[1], reverse=True)
160
+ trait_row = trait_candidates[0][0]
161
+ else:
162
+ trait_row = None
163
+
164
+ except NameError:
165
+ # clinical_data not available in scope; fall back to known keys from the sample dictionary
166
+ # From provided snippet, age is at key 81; trait and gender likely unavailable/constant in this cohort
167
+ age_row = 81
168
+ trait_row = None
169
+ gender_row = None
170
+
171
+ # Converters
172
+
173
+ def convert_age(x):
174
+ v = _extract_value(x)
175
+ if v is None:
176
+ return None
177
+ s = str(v).lower().replace('years', '').replace('year', '').replace('yrs', '').replace('yr', '').strip()
178
+ # remove any trailing '+' or other non-numeric chars
179
+ s = re.sub(r'[^\d\.]+', '', s)
180
+ if s == '':
181
+ return None
182
+ try:
183
+ val = float(s)
184
+ # return integer if it is an integer value
185
+ return int(val) if abs(val - int(val)) < 1e-9 else val
186
+ except Exception:
187
+ return None
188
+
189
+ def convert_gender(x):
190
+ v = _extract_value(x)
191
+ if v is None:
192
+ return None
193
+ s = str(v).strip().lower()
194
+ # common mappings
195
+ if s in {'female', 'f', 'woman', 'women', 'girl'}:
196
+ return 0
197
+ if s in {'male', 'm', 'man', 'men', 'boy'}:
198
+ return 1
199
+ # sometimes encoded as 0/1 or 1/2
200
+ if s in {'0'}:
201
+ # ambiguous; assume 0=female in our convention only if explicitly stated; otherwise None
202
+ return None
203
+ if s in {'1'}:
204
+ return None
205
+ if s in {'2'}:
206
+ # some datasets: 1=male,2=female
207
+ return 0
208
+ return None
209
+
210
+ def convert_trait(x):
211
+ v = _extract_value(x)
212
+ if v is None:
213
+ return None
214
+ s = str(v).strip().lower()
215
+ # Map presence of Hepatitis (disease) to 1; controls (including vaccinated healthy) to 0
216
+ positive_terms = {'hepatitis', 'hepatitis b', 'hbv', 'hbv-infected', 'chb', 'chronic hepatitis b', 'acute hepatitis b'}
217
+ negative_terms = {'healthy', 'control', 'non-hepatitis', 'vaccinated', 'vaccine recipient', 'hbv-negative', 'uninfected'}
218
+ if s in positive_terms:
219
+ return 1
220
+ if s in negative_terms:
221
+ return 0
222
+ # heuristics
223
+ if 'hepatitis' in s or re.search(r'\bhbv\b', s):
224
+ # If mentions infection/positive
225
+ if any(t in s for t in ['infect', 'positive', 'pos', 'carrier', 'hbsag+']):
226
+ return 1
227
+ if any(t in s for t in ['negative', 'neg', 'uninfect', 'vaccine', 'vaccinated', 'recipient']):
228
+ return 0
229
+ return None
230
+
231
+ # 3) Save metadata (initial filtering)
232
+ is_trait_available = trait_row is not None
233
+ _ = validate_and_save_cohort_info(is_final=False,
234
+ cohort=cohort,
235
+ info_path=json_path,
236
+ is_gene_available=is_gene_available,
237
+ is_trait_available=is_trait_available)
238
+
239
+ # 4) Clinical feature extraction (only if trait is available)
240
+ if is_trait_available:
241
+ # Use detected age_row and gender_row if available; otherwise pass None
242
+ selected_clinical_df = geo_select_clinical_features(
243
+ clinical_df=clinical_data,
244
+ trait=trait,
245
+ trait_row=trait_row,
246
+ convert_trait=convert_trait,
247
+ age_row=age_row,
248
+ convert_age=convert_age,
249
+ gender_row=gender_row,
250
+ convert_gender=convert_gender
251
+ )
252
+ _ = preview_df(selected_clinical_df)
253
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
254
+ selected_clinical_df.to_csv(out_clinical_data_file)
255
+
256
+ # Step 3: Gene Data Extraction
257
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
258
+ gene_data = get_genetic_data(matrix_file)
259
+
260
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
261
+ print(gene_data.index[:20])
262
+
263
+ # Step 4: Gene Identifier Review
264
+ print("requires_gene_mapping = False")
265
+
266
+ # Step 5: Data Normalization and Linking
267
+ import os
268
+ import pandas as pd
269
+
270
+ # 1. Normalize gene symbols and save
271
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
272
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
273
+ normalized_gene_data.to_csv(out_gene_data_file)
274
+
275
+ # Determine if clinical features were extracted previously
276
+ has_selected_clinical = (
277
+ 'selected_clinical_data' in globals()
278
+ and isinstance(selected_clinical_data, pd.DataFrame)
279
+ and not selected_clinical_data.empty
280
+ )
281
+
282
+ if has_selected_clinical:
283
+ # 2. Link clinical and genetic data
284
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_data, normalized_gene_data)
285
+
286
+ # 3. Handle missing values
287
+ linked_data = handle_missing_values(linked_data, trait)
288
+
289
+ # 4. Bias assessment
290
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
291
+
292
+ # 5. Final validation and save cohort info
293
+ note = "INFO: Clinical trait available; proceeding with standard preprocessing."
294
+ is_usable = validate_and_save_cohort_info(
295
+ is_final=True,
296
+ cohort=cohort,
297
+ info_path=json_path,
298
+ is_gene_available=True,
299
+ is_trait_available=True,
300
+ is_biased=is_trait_biased,
301
+ df=unbiased_linked_data,
302
+ note=note
303
+ )
304
+
305
+ # 6. Save linked data only if usable
306
+ if is_usable:
307
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
308
+ unbiased_linked_data.to_csv(out_data_file)
309
+ else:
310
+ # Trait not available; perform final validation without linking and do not save linked data
311
+ note = ("INFO: Trait not available; cohort consists of healthy HBV vaccine recipients with no "
312
+ "case-control variation for Hepatitis. Skipping linking and downstream steps.")
313
+ is_usable = validate_and_save_cohort_info(
314
+ is_final=True,
315
+ cohort=cohort,
316
+ info_path=json_path,
317
+ is_gene_available=True,
318
+ is_trait_available=False,
319
+ is_biased=False,
320
+ df=normalized_gene_data,
321
+ note=note
322
+ )
323
+ # Do not save out_data_file when trait is unavailable
output/preprocess/Hepatitis/code/TCGA.py ADDED
@@ -0,0 +1,289 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Hepatitis"
6
+
7
+ # Input paths
8
+ tcga_root_dir = "../DATA/TCGA"
9
+
10
+ # Output paths
11
+ out_data_file = "./output/z3/preprocess/Hepatitis/TCGA.csv"
12
+ out_gene_data_file = "./output/z3/preprocess/Hepatitis/gene_data/TCGA.csv"
13
+ out_clinical_data_file = "./output/z3/preprocess/Hepatitis/clinical_data/TCGA.csv"
14
+ json_path = "./output/z3/preprocess/Hepatitis/cohort_info.json"
15
+
16
+
17
+ # Step 1: Initial Data Loading
18
+ import os
19
+ import pandas as pd
20
+
21
+ # Step 1: Select the most relevant TCGA cohort directory for the trait "Hepatitis"
22
+ subdirs = [d for d in os.listdir(tcga_root_dir) if os.path.isdir(os.path.join(tcga_root_dir, d))]
23
+
24
+ # Keyword-based scoring to find best match
25
+ keywords_priority = {
26
+ "hepatitis": 3,
27
+ "hepatocellular": 2,
28
+ "liver": 1
29
+ }
30
+
31
+ best_dir = None
32
+ best_score = -1
33
+ for d in subdirs:
34
+ name_lower = d.lower()
35
+ score = sum(w for k, w in keywords_priority.items() if k in name_lower)
36
+ if score > best_score:
37
+ best_score = score
38
+ best_dir = d
39
+
40
+ # If no suitable directory is found, mark as unavailable and exit early
41
+ if best_dir is None or best_score <= 0:
42
+ _ = validate_and_save_cohort_info(
43
+ is_final=False,
44
+ cohort="TCGA",
45
+ info_path=json_path,
46
+ is_gene_available=False,
47
+ is_trait_available=False
48
+ )
49
+ print("No suitable TCGA cohort directory found for the trait. Skipping.")
50
+ else:
51
+ selected_cohort_dir = os.path.join(tcga_root_dir, best_dir)
52
+ print(f"Selected cohort directory: {selected_cohort_dir}")
53
+
54
+ # Step 2: Identify clinical and genetic file paths
55
+ clinical_file_path, genetic_file_path = tcga_get_relevant_filepaths(selected_cohort_dir)
56
+ print(f"Clinical file: {clinical_file_path}")
57
+ print(f"Genetic file: {genetic_file_path}")
58
+
59
+ # Step 3: Load both files as DataFrames
60
+ def _read_tcga_file(fp: str) -> pd.DataFrame:
61
+ compression = 'gzip' if fp.lower().endswith('.gz') else 'infer'
62
+ return pd.read_csv(fp, sep='\t', index_col=0, low_memory=False, compression=compression)
63
+
64
+ clinical_df = _read_tcga_file(clinical_file_path)
65
+ genetic_df = _read_tcga_file(genetic_file_path)
66
+
67
+ # Step 4: Print the column names of the clinical data
68
+ print(list(clinical_df.columns))
69
+
70
+ # Step 2: Find Candidate Demographic Features
71
+ import os
72
+ import re
73
+ import pandas as pd
74
+
75
+ # Determine cohort directory and clinical file path
76
+ cohort_dir = os.path.join(tcga_root_dir, "TCGA_Liver_Cancer_(LIHC)")
77
+ clinical_file_path, _ = tcga_get_relevant_filepaths(cohort_dir)
78
+
79
+ # Load clinical data
80
+ clinical_df = pd.read_csv(clinical_file_path, sep="\t", index_col=0, dtype=str)
81
+
82
+ # Refined regex patterns to avoid substring false positives (e.g., 'stage')
83
+ pattern_age = re.compile(r'(^|[^a-zA-Z])age([^a-zA-Z]|$)|birth', re.I)
84
+ pattern_gender = re.compile(r'(^|[^a-zA-Z])gender([^a-zA-Z]|$)|(^|[^a-zA-Z])sex([^a-zA-Z]|$)', re.I)
85
+
86
+ # Exclude known confounders
87
+ exclude_age = {"pathologic_stage"}
88
+
89
+ # Identify candidate columns in original order
90
+ candidate_age_cols = [c for c in clinical_df.columns if pattern_age.search(c) and c not in exclude_age]
91
+ candidate_gender_cols = [c for c in clinical_df.columns if pattern_gender.search(c)]
92
+
93
+ # Print required lists
94
+ print(f"candidate_age_cols = {candidate_age_cols}")
95
+ print(f"candidate_gender_cols = {candidate_gender_cols}")
96
+
97
+ # Preview extracted data
98
+ if candidate_age_cols:
99
+ age_preview = preview_df(clinical_df[candidate_age_cols], n=5)
100
+ print(age_preview)
101
+ if candidate_gender_cols:
102
+ gender_preview = preview_df(clinical_df[candidate_gender_cols], n=5)
103
+ print(gender_preview)
104
+
105
+ # Step 3: Select Demographic Features
106
+ # Select demographic feature columns based on data validity and completeness
107
+
108
+ age_col = None
109
+ gender_col = None
110
+
111
+ def _age_valid_rate(series):
112
+ # Convert to numeric ages and assess plausibility (0-120 years)
113
+ ages = series.apply(tcga_convert_age)
114
+ if ages is None or len(ages) == 0:
115
+ return 0.0, 0.0
116
+ valid_mask = ages.apply(lambda x: (x is not None) and (0 <= x <= 120))
117
+ valid_rate = valid_mask.mean()
118
+ nonnull_rate = series.notna().mean()
119
+ return float(valid_rate), float(nonnull_rate)
120
+
121
+ def _gender_valid_rate(series):
122
+ genders = series.apply(tcga_convert_gender)
123
+ if genders is None or len(genders) == 0:
124
+ return 0.0
125
+ return float(genders.notna().mean())
126
+
127
+ # Try data-driven selection if clinical_df is available
128
+ if 'clinical_df' in globals():
129
+ # Age: select column with highest valid rate (0-120) and then highest non-null rate
130
+ best_age = None
131
+ best_age_score = (-1.0, -1.0) # (valid_rate, nonnull_rate)
132
+ for c in candidate_age_cols:
133
+ if c in clinical_df.columns:
134
+ vr, nr = _age_valid_rate(clinical_df[c])
135
+ # Prefer columns with "age" in name if scores tie
136
+ prefer = 1 if ("age" in c.lower()) else 0
137
+ score = (vr, nr, prefer)
138
+ if (score > (best_age_score[0], best_age_score[1], 0)):
139
+ best_age = c
140
+ best_age_score = (vr, nr)
141
+ # Ensure reasonable validity threshold
142
+ if best_age is not None and best_age_score[0] >= 0.5:
143
+ age_col = best_age
144
+ else:
145
+ age_col = None
146
+
147
+ # Gender: select column with highest valid rate (recognized by tcga_convert_gender)
148
+ best_gender = None
149
+ best_gender_rate = -1.0
150
+ for c in candidate_gender_cols:
151
+ if c in clinical_df.columns:
152
+ vr = _gender_valid_rate(clinical_df[c])
153
+ if vr > best_gender_rate:
154
+ best_gender = c
155
+ best_gender_rate = vr
156
+ if best_gender is not None and best_gender_rate >= 0.5:
157
+ gender_col = best_gender
158
+ else:
159
+ gender_col = None
160
+ else:
161
+ # Fallback: heuristic based on column names if clinical_df is not available
162
+ for c in candidate_age_cols:
163
+ if "age" in c.lower():
164
+ age_col = c
165
+ break
166
+ if age_col is None and len(candidate_age_cols) > 0:
167
+ age_col = candidate_age_cols[0]
168
+
169
+ for c in candidate_gender_cols:
170
+ if "gender" in c.lower() or "sex" in c.lower():
171
+ gender_col = c
172
+ break
173
+ if gender_col is None and len(candidate_gender_cols) > 0:
174
+ gender_col = candidate_gender_cols[0]
175
+
176
+ # Explicitly print out the information for the chosen columns
177
+ print(f"Selected age_col: {age_col}")
178
+ if age_col is not None and 'clinical_df' in globals() and age_col in clinical_df.columns:
179
+ print("age_col preview (first 5):", clinical_df[age_col].head(5).tolist())
180
+ vr, nr = _age_valid_rate(clinical_df[age_col])
181
+ print(f"age_col valid_rate (0-120 years): {vr:.3f}, nonnull_rate: {nr:.3f}")
182
+
183
+ print(f"Selected gender_col: {gender_col}")
184
+ if gender_col is not None and 'clinical_df' in globals() and gender_col in clinical_df.columns:
185
+ print("gender_col preview (first 5):", clinical_df[gender_col].head(5).tolist())
186
+ gr = _gender_valid_rate(clinical_df[gender_col])
187
+ nnr = clinical_df[gender_col].notna().mean() if 'clinical_df' in globals() else None
188
+ print(f"gender_col valid_rate (recognized male/female): {gr:.3f}, nonnull_rate: {nnr:.3f}" if nnr is not None else f"gender_col valid_rate: {gr:.3f}")
189
+
190
+ # Step 4: Feature Engineering and Validation
191
+ import os
192
+ import re
193
+ import pandas as pd
194
+
195
+ # Ensure cohort data is loaded (reuse from previous steps if available; otherwise reload)
196
+ if 'clinical_df' not in globals() or 'genetic_df' not in globals():
197
+ cohort_dir = os.path.join(tcga_root_dir, "TCGA_Liver_Cancer_(LIHC)")
198
+ clinical_file_path, genetic_file_path = tcga_get_relevant_filepaths(cohort_dir)
199
+
200
+ def _read_tcga_file(fp: str) -> pd.DataFrame:
201
+ compression = 'gzip' if fp.lower().endswith('.gz') else 'infer'
202
+ return pd.read_csv(fp, sep='\t', index_col=0, low_memory=False, compression=compression)
203
+
204
+ clinical_df = _read_tcga_file(clinical_file_path)
205
+ genetic_df = _read_tcga_file(genetic_file_path)
206
+
207
+ # 1) Extract and standardize clinical features (Age, Gender) and construct Hepatitis trait from viral_hepatitis_serology
208
+ age_arg = age_col if ('age_col' in globals() and age_col in clinical_df.columns) else None
209
+ gender_arg = gender_col if ('gender_col' in globals() and gender_col in clinical_df.columns) else None
210
+ selected_clinical_df = tcga_select_clinical_features(clinical_df, trait=trait, age_col=age_arg, gender_col=gender_arg)
211
+
212
+ def _convert_hepatitis(x):
213
+ s = str(x).strip().lower()
214
+ if s in ("", "nan", "none", "not available", "na", "n/a", "unknown", "not reported", "null", "missing"):
215
+ return None
216
+ # Normalize spaces
217
+ s = re.sub(r"\s+", " ", s)
218
+ # Common synonyms
219
+ if any(tok in s for tok in ["positive", "pos", "yes", "y", "reactive", "detected", "presence"]):
220
+ # Avoid false positive from "non-reactive"/"not detected"
221
+ if any(tok in s for tok in ["nonreactive", "non-reactive", "not detected", "negative", "neg", "no", "n"]):
222
+ # conflicting signals; set None
223
+ return None
224
+ return 1
225
+ if any(tok in s for tok in ["negative", "neg", "no", "n", "nonreactive", "non-reactive", "not detected", "absence"]):
226
+ return 0
227
+ if s in {"1", "true"}:
228
+ return 1
229
+ if s in {"0", "false"}:
230
+ return 0
231
+ return None
232
+
233
+ if "viral_hepatitis_serology" in clinical_df.columns:
234
+ selected_clinical_df[trait] = clinical_df["viral_hepatitis_serology"].apply(_convert_hepatitis)
235
+ else:
236
+ # Trait not available; record and stop after saving gene data
237
+ trait_available = False
238
+
239
+ # Determine trait availability (at least one non-missing label)
240
+ trait_available = bool(selected_clinical_df[trait].notna().sum() > 0) if "viral_hepatitis_serology" in clinical_df.columns else False
241
+
242
+ # 2) Normalize gene symbols and save
243
+ gene_df = genetic_df.copy()
244
+ gene_df_norm = normalize_gene_symbols_in_index(gene_df)
245
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
246
+ gene_df_norm.to_csv(out_gene_data_file)
247
+
248
+ # If the trait is unavailable, record and stop early (do not link or save cohort data)
249
+ if not trait_available:
250
+ _ = validate_and_save_cohort_info(
251
+ is_final=False,
252
+ cohort="TCGA",
253
+ info_path=json_path,
254
+ is_gene_available=True,
255
+ is_trait_available=False
256
+ )
257
+ else:
258
+ # 3) Link clinical and genetic data on sample IDs
259
+ gene_df_norm_T = gene_df_norm.T # samples x genes
260
+ linked_data = selected_clinical_df.join(gene_df_norm_T, how='inner')
261
+
262
+ # 4) Handle missing values
263
+ linked_data = handle_missing_values(linked_data, trait_col=trait)
264
+
265
+ # 5) Judge and remove biased features; record trait bias for final validation
266
+ trait_biased, linked_data = judge_and_remove_biased_features(linked_data, trait=trait)
267
+
268
+ # 6) Final validation and save cohort info
269
+ note = (
270
+ "INFO: Cohort LIHC; Trait 'Hepatitis' derived from clinical column 'viral_hepatitis_serology': "
271
+ "positive/reactive/detected/yes -> 1; negative/nonreactive/not detected/no -> 0; others -> NaN. "
272
+ f"Age from '{age_arg}' and Gender from '{gender_arg}'. "
273
+ "Gene symbols normalized using NCBI synonym mapping; samples inner-joined across clinical and expression data."
274
+ )
275
+ is_usable = validate_and_save_cohort_info(
276
+ is_final=True,
277
+ cohort="TCGA",
278
+ info_path=json_path,
279
+ is_gene_available=True,
280
+ is_trait_available=trait_available,
281
+ is_biased=trait_biased,
282
+ df=linked_data,
283
+ note=note
284
+ )
285
+
286
+ # 7) Save linked data only if usable
287
+ if is_usable:
288
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
289
+ linked_data.to_csv(out_data_file)
output/preprocess/Hepatitis/cohort_info.json CHANGED
@@ -1,112 +1 @@
1
- {
2
- "GSE97475": {
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": true,
10
- "sample_size": 158
11
- },
12
- "GSE85550": {
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
- "GSE66843": {
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": 17
31
- },
32
- "GSE45032": {
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": 48
41
- },
42
- "GSE168049": {
43
- "is_usable": true,
44
- "is_gene_available": true,
45
- "is_trait_available": true,
46
- "is_available": true,
47
- "is_biased": false,
48
- "has_age": true,
49
- "has_gender": true,
50
- "sample_size": 16
51
- },
52
- "GSE159676": {
53
- "is_usable": true,
54
- "is_gene_available": true,
55
- "is_trait_available": true,
56
- "is_available": true,
57
- "is_biased": false,
58
- "has_age": false,
59
- "has_gender": false,
60
- "sample_size": 33
61
- },
62
- "GSE152738": {
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
- "GSE125860": {
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
- "GSE124719": {
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
- "GSE114783": {
93
- "is_usable": false,
94
- "is_gene_available": false,
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": true,
110
- "sample_size": 423
111
- }
112
- }
 
1
+ {"GSE97475": {"is_usable": false, "is_gene_available": true, "is_trait_available": false, "is_available": false, "is_biased": null, "has_age": null, "has_gender": null, "sample_size": null, "note": "INFO: Trait not available; cohort consists of healthy HBV vaccine recipients with no case-control variation for Hepatitis. Skipping linking and downstream steps."}, "GSE85550": {"is_usable": false, "is_gene_available": true, "is_trait_available": false, "is_available": false, "is_biased": null, "has_age": null, "has_gender": null, "sample_size": null, "note": "INFO: Trait not available in clinical annotations; skipped linking and downstream processing."}, "GSE66843": {"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": 17, "note": "INFO: Cell-line HCV infection model (Huh7.5.1). Trait derived from infection status; no Age/Gender available. ILMN probes mapped via 'Symbol' and gene symbols normalized."}, "GSE45032": {"is_usable": true, "is_gene_available": true, "is_trait_available": true, "is_available": true, "is_biased": false, "has_age": true, "has_gender": true, "sample_size": 48, "note": "INFO: Trait encoding for Hepatitis: CHC=1 (chronic hepatitis C), HCC=0 (hepatocellular carcinoma)."}, "GSE168049": {"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}, "GSE159676": {"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": 33, "note": ""}, "GSE152738": {"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}, "GSE125860": {"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": 172, "note": "INFO: Probe-to-gene mapping applied and gene symbols normalized in Step 6; age and gender not available in this series; trait is continuous HBV post-vaccination antibody concentration (mIU/mL) with left-censored values (e.g., '<5') mapped to the threshold."}, "GSE124719": {"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": 179, "note": "INFO: All participants are male; Gender not available. Trait defined as HepB vaccine (FENDRIX/FENDRIXE) vs others."}, "GSE114783": {"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: Gene symbol normalization yielded low retention (ratio=0.0000); retained original identifiers (likely Entrez IDs)."}, "TCGA": {"is_usable": false, "is_gene_available": true, "is_trait_available": true, "is_available": true, "is_biased": true, "has_age": true, "has_gender": true, "sample_size": 22, "note": "INFO: Cohort LIHC; Trait 'Hepatitis' derived from clinical column 'viral_hepatitis_serology': positive/reactive/detected/yes -> 1; negative/nonreactive/not detected/no -> 0; others -> NaN. Age from 'age_at_initial_pathologic_diagnosis' and Gender from 'gender'. Gene symbols normalized using NCBI synonym mapping; samples inner-joined across clinical and expression data."}}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
output/preprocess/Hepatitis/gene_data/GSE114783.csv CHANGED
The diff for this file is too large to render. See raw diff
 
output/preprocess/High-Density_Lipoprotein_Deficiency/code/GSE34945.py ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "High-Density_Lipoprotein_Deficiency"
6
+ cohort = "GSE34945"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/High-Density_Lipoprotein_Deficiency"
10
+ in_cohort_dir = "../DATA/GEO/High-Density_Lipoprotein_Deficiency/GSE34945"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z3/preprocess/High-Density_Lipoprotein_Deficiency/GSE34945.csv"
14
+ out_gene_data_file = "./output/z3/preprocess/High-Density_Lipoprotein_Deficiency/gene_data/GSE34945.csv"
15
+ out_clinical_data_file = "./output/z3/preprocess/High-Density_Lipoprotein_Deficiency/clinical_data/GSE34945.csv"
16
+ json_path = "./output/z3/preprocess/High-Density_Lipoprotein_Deficiency/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
+ # Decide data availability based on provided background/sample characteristics
40
+ is_gene_available = False # SNP genotyping only; no gene expression matrix suitable for analysis here.
41
+
42
+ # No explicit or inferable human-level trait (HDL deficiency), age, or gender fields in the sample characteristics.
43
+ trait_row = None
44
+ age_row = None
45
+ gender_row = None
46
+
47
+ # Converters
48
+ def _extract_value(x):
49
+ if x is None:
50
+ return None
51
+ s = str(x)
52
+ parts = s.split(":", 1)
53
+ val = parts[1] if len(parts) > 1 else parts[0]
54
+ val = val.strip()
55
+ return val if val != "" else None
56
+
57
+ def convert_trait(x):
58
+ # Binary: 1 = High-Density Lipoprotein Deficiency present; 0 = absent
59
+ val = _extract_value(x)
60
+ if val is None:
61
+ return None
62
+ v = val.lower()
63
+ # Map common indicators of HDL deficiency
64
+ keywords_pos = [
65
+ "hdl deficiency", "high-density lipoprotein deficiency", "hypoalphalipoproteinemia",
66
+ "low hdl", "reduced hdl", "decreased hdl"
67
+ ]
68
+ keywords_neg = ["normal hdl", "control"]
69
+ if any(k in v for k in keywords_pos):
70
+ return 1
71
+ if any(k in v for k in keywords_neg):
72
+ return 0
73
+ # For this dataset, entries like "mixed dyslipidemia", "treatment group", or "percent change in apoc3" are not trait labels
74
+ return None
75
+
76
+ def convert_age(x):
77
+ # Continuous age in years
78
+ val = _extract_value(x)
79
+ if val is None:
80
+ return None
81
+ import re
82
+ # Extract first integer/float number
83
+ m = re.search(r"(-?\d+\.?\d*)", val)
84
+ if m:
85
+ try:
86
+ return float(m.group(1))
87
+ except Exception:
88
+ return None
89
+ return None
90
+
91
+ def convert_gender(x):
92
+ # Binary: female=0, male=1
93
+ val = _extract_value(x)
94
+ if val is None:
95
+ return None
96
+ v = val.strip().lower()
97
+ if v in {"female", "f", "woman", "women"}:
98
+ return 0
99
+ if v in {"male", "m", "man", "men"}:
100
+ return 1
101
+ # Handle numeric encodings if present
102
+ if v in {"0", "1"}:
103
+ return int(v)
104
+ return None
105
+
106
+ # Initial filtering and save metadata
107
+ is_trait_available = trait_row is not None
108
+ _ = validate_and_save_cohort_info(
109
+ is_final=False,
110
+ cohort=cohort,
111
+ info_path=json_path,
112
+ is_gene_available=is_gene_available,
113
+ is_trait_available=is_trait_available
114
+ )
115
+
116
+ # Clinical feature extraction: skip because trait_row is None (no usable clinical trait data here)
117
+ # If in another scenario trait_row is not None, the following would be used:
118
+ # selected_clinical_df = geo_select_clinical_features(
119
+ # clinical_df=clinical_data,
120
+ # trait=trait,
121
+ # trait_row=trait_row,
122
+ # convert_trait=convert_trait,
123
+ # age_row=age_row,
124
+ # convert_age=convert_age,
125
+ # gender_row=gender_row,
126
+ # convert_gender=convert_gender
127
+ # )
128
+ # preview = preview_df(selected_clinical_df, n=5)
129
+ # os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
130
+ # selected_clinical_df.to_csv(out_clinical_data_file)
output/preprocess/High-Density_Lipoprotein_Deficiency/code/TCGA.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "High-Density_Lipoprotein_Deficiency"
6
+
7
+ # Input paths
8
+ tcga_root_dir = "../DATA/TCGA"
9
+
10
+ # Output paths
11
+ out_data_file = "./output/z3/preprocess/High-Density_Lipoprotein_Deficiency/TCGA.csv"
12
+ out_gene_data_file = "./output/z3/preprocess/High-Density_Lipoprotein_Deficiency/gene_data/TCGA.csv"
13
+ out_clinical_data_file = "./output/z3/preprocess/High-Density_Lipoprotein_Deficiency/clinical_data/TCGA.csv"
14
+ json_path = "./output/z3/preprocess/High-Density_Lipoprotein_Deficiency/cohort_info.json"
15
+
16
+
17
+ # Step 1: Initial Data Loading
18
+ import os
19
+ import re
20
+ import pandas as pd
21
+
22
+ # Helper to normalize names for matching
23
+ def _normalize(text: str) -> str:
24
+ return re.sub(r'[^a-z0-9]+', ' ', text.lower()).strip()
25
+
26
+ # Keywords related to High-Density Lipoprotein Deficiency
27
+ trait_keywords = [
28
+ 'hdl', 'high density lipoprotein', 'high density', 'high-density',
29
+ 'lipoprotein', 'cholesterol', 'hdl c', 'hdl-c',
30
+ 'apoa1', 'apolipoprotein a1', 'abca1', 'tangier', 'hypoalphalipoproteinemia'
31
+ ]
32
+ trait_keywords_norm = [_normalize(k) for k in trait_keywords]
33
+
34
+ # List subdirectories and attempt to find best-matching cohort
35
+ subdirs = [d for d in os.listdir(tcga_root_dir) if os.path.isdir(os.path.join(tcga_root_dir, d))]
36
+ scored = []
37
+ for d in subdirs:
38
+ d_norm = _normalize(d)
39
+ hits = sum(1 for k in trait_keywords_norm if k and k in d_norm)
40
+ if hits > 0:
41
+ scored.append((hits, len(d_norm), d))
42
+
43
+ selected_tcga_dir = None
44
+ if scored:
45
+ # Most specific = most hits; tie-breaker = shorter name length
46
+ scored.sort(key=lambda x: (-x[0], x[1]))
47
+ selected_tcga_dir = scored[0][2]
48
+
49
+ clinical_df = None
50
+ genetic_df = None
51
+
52
+ if selected_tcga_dir is None:
53
+ # No suitable cohort; record and exit this step gracefully
54
+ validate_and_save_cohort_info(
55
+ is_final=False,
56
+ cohort="TCGA_no_matching_cohort",
57
+ info_path=json_path,
58
+ is_gene_available=False,
59
+ is_trait_available=False
60
+ )
61
+ else:
62
+ cohort_dir = os.path.join(tcga_root_dir, selected_tcga_dir)
63
+
64
+ # Identify clinical and genetic file paths
65
+ clinical_file_path, genetic_file_path = tcga_get_relevant_filepaths(cohort_dir)
66
+
67
+ # Load dataframes (handle possible gzip with compression='infer')
68
+ clinical_df = pd.read_csv(clinical_file_path, sep='\t', index_col=0, low_memory=False, compression='infer')
69
+ genetic_df = pd.read_csv(genetic_file_path, sep='\t', index_col=0, low_memory=False, compression='infer')
70
+
71
+ # Print clinical columns for further analysis
72
+ print(clinical_df.columns.tolist())
output/preprocess/High-Density_Lipoprotein_Deficiency/cohort_info.json CHANGED
@@ -1,22 +1 @@
1
- {
2
- "GSE34945": {
3
- "is_usable": false,
4
- "is_gene_available": false,
5
- "is_trait_available": true,
6
- "is_available": false,
7
- "is_biased": null,
8
- "has_age": null,
9
- "has_gender": null,
10
- "sample_size": null
11
- },
12
- "TCGA": {
13
- "is_usable": false,
14
- "is_gene_available": false,
15
- "is_trait_available": false,
16
- "is_available": false,
17
- "is_biased": null,
18
- "has_age": null,
19
- "has_gender": null,
20
- "sample_size": null
21
- }
22
- }
 
1
+ {"GSE34945": {"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}, "TCGA_no_matching_cohort": {"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/Huntingtons_Disease/clinical_data/GSE26927.csv CHANGED
@@ -1,4 +1,4 @@
1
- ,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29
2
- Huntingtons_Disease,0.0,0.0,1.0,0.0,0.0,0.0,,,,,,,,,,,,,,,,,,,,,,,,
3
- Age,70.0,73.0,59.0,40.0,47.0,82.0,86.0,93.0,72.0,85.0,80.0,79.0,76.0,77.0,55.0,43.0,39.0,67.0,84.0,54.0,74.0,69.0,64.0,60.0,68.0,18.0,57.0,46.0,50.0,53.0
4
- Gender,1.0,0.0,,,,,,,,,,,,,,,,,,,,,,,,,,,,
 
1
+ ,GSM663008,GSM663009,GSM663010,GSM663011,GSM663012,GSM663013,GSM663014,GSM663015,GSM663016,GSM663017,GSM663018,GSM663019,GSM663020,GSM663021,GSM663022,GSM663023,GSM663024,GSM663025,GSM663026,GSM663027,GSM663028,GSM663029,GSM663030,GSM663031,GSM663032,GSM663033,GSM663034,GSM663035,GSM663036,GSM663037,GSM663038,GSM663039,GSM663040,GSM663041,GSM663042,GSM663043,GSM663044,GSM663045,GSM663046,GSM663047,GSM663048,GSM663049,GSM663050,GSM663051,GSM663052,GSM663053,GSM663054,GSM663055,GSM663056,GSM663057,GSM663058,GSM663059,GSM663060,GSM663061,GSM663062,GSM663063,GSM663064,GSM663065,GSM663066,GSM663067,GSM663068,GSM663069,GSM663070,GSM663071,GSM663072,GSM663073,GSM663074,GSM663075,GSM663076,GSM663077,GSM663078,GSM663079,GSM663080,GSM663081,GSM663082,GSM663083,GSM663084,GSM663085,GSM663086,GSM663087,GSM663088,GSM663089,GSM663090,GSM663091,GSM663092,GSM663093,GSM663094,GSM663095,GSM663096,GSM663097,GSM663098,GSM663099,GSM663100,GSM663101,GSM663102,GSM663103,GSM663104,GSM663105,GSM663106,GSM663107,GSM663108,GSM663109,GSM663110,GSM663111,GSM663112,GSM663113,GSM663114,GSM663115,GSM663116,GSM663117,GSM663118,GSM663119,GSM663120,GSM663121,GSM663122,GSM663123,GSM663124,GSM663125
2
+ Huntingtons_Disease,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,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,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,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,70.0,73.0,73.0,59.0,40.0,47.0,47.0,82.0,86.0,82.0,93.0,82.0,72.0,85.0,80.0,79.0,76.0,77.0,55.0,55.0,43.0,39.0,77.0,67.0,84.0,84.0,82.0,82.0,54.0,72.0,82.0,74.0,69.0,69.0,74.0,64.0,60.0,64.0,64.0,60.0,68.0,18.0,57.0,46.0,50.0,46.0,53.0,75.0,51.0,38.0,74.0,57.0,54.0,72.0,57.0,60.0,,69.0,59.0,47.0,56.0,53.0,55.0,57.0,46.0,50.0,53.0,55.0,51.0,53.0,53.0,42.0,53.0,45.0,53.0,45.0,45.0,54.0,66.0,54.0,64.0,55.0,55.0,60.0,58.0,104.0,86.0,78.0,85.0,76.0,77.0,80.0,80.0,80.0,86.0,87.0,81.0,82.0,41.0,91.0,57.0,53.0,63.0,66.0,79.0,57.0,50.0,55.0,51.0,64.0,64.0,73.0,43.0,77.0,76.0,63.0,81.0,71.0
4
+ Gender,1.0,0.0,0.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,1.0,0.0,1.0,1.0,1.0,1.0,1.0,0.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,0.0,0.0,1.0,1.0,1.0,1.0,1.0,0.0,1.0,1.0,0.0,1.0,1.0,1.0,0.0,1.0,1.0,1.0,1.0,0.0,1.0,1.0,1.0,0.0,1.0,1.0,1.0,1.0,0.0,1.0,0.0,0.0,1.0,1.0,1.0,0.0,1.0,1.0,0.0,0.0,0.0,1.0,0.0,1.0,1.0,0.0,1.0,1.0,0.0,1.0,1.0,1.0,1.0,1.0,0.0,1.0,0.0,0.0,1.0,0.0,0.0,1.0,1.0,1.0,0.0,1.0,0.0,0.0,1.0,1.0,0.0,1.0,1.0,1.0,0.0,1.0,1.0,1.0,0.0,1.0,0.0,0.0,1.0,1.0,0.0,0.0,0.0,1.0,1.0
output/preprocess/Huntingtons_Disease/clinical_data/GSE34721.csv CHANGED
@@ -1,3 +1,3 @@
1
- GSM853700,GSM853701,GSM853702,GSM853703,GSM853704,GSM853705,GSM853706,GSM853707,GSM853708,GSM853709,GSM853710,GSM853711,GSM853712,GSM853713,GSM853714,GSM853715,GSM853716,GSM853717,GSM853718,GSM853719,GSM853720,GSM853721,GSM853722,GSM853723,GSM853724,GSM853725,GSM853726,GSM853727,GSM853728,GSM853729,GSM853730,GSM853731,GSM853732,GSM853733,GSM853734,GSM853735,GSM853736,GSM853737,GSM853738,GSM853739,GSM853740,GSM853741,GSM853742,GSM853743,GSM853744,GSM853745,GSM853746,GSM853747,GSM853748,GSM853749,GSM853750,GSM853751,GSM853752,GSM853753,GSM853754,GSM853755,GSM853756,GSM853757,GSM853758,GSM853759,GSM853760,GSM853761,GSM853762,GSM853763,GSM853764,GSM853765,GSM853766,GSM853767,GSM853768,GSM853769,GSM853770,GSM853771,GSM853772,GSM853773,GSM853774,GSM853775,GSM853776,GSM853777,GSM853778,GSM853779,GSM853780,GSM853781,GSM853782,GSM853783,GSM853784,GSM853785,GSM853786,GSM853787,GSM853788,GSM853789,GSM853790,GSM853791,GSM853792,GSM853793,GSM853794,GSM853795,GSM853796,GSM853797,GSM853798,GSM853799,GSM853800,GSM853801,GSM853802,GSM853803,GSM853804,GSM853805,GSM853806,GSM853807,GSM853808,GSM853809,GSM853810,GSM853811,GSM853812,GSM853813,GSM853814,GSM853815,GSM853816,GSM853817,GSM853818,GSM853819,GSM853820,GSM853821,GSM853822,GSM853823,GSM853824,GSM853825,GSM853826,GSM853827,GSM853828,GSM853829,GSM853830,GSM853831,GSM853832,GSM853833,GSM853834,GSM853835,GSM853836,GSM853837,GSM853838,GSM853839,GSM853840,GSM853841,GSM853842,GSM853843,GSM853844,GSM853845,GSM853846,GSM853847,GSM853848,GSM853849,GSM853850,GSM853851,GSM853852,GSM853853,GSM853854,GSM853855,GSM853856,GSM853857,GSM853858,GSM853859,GSM853860,GSM853861,GSM853862,GSM853863,GSM853864,GSM853865,GSM853866,GSM853867,GSM853868,GSM853869,GSM853870,GSM853871,GSM853872,GSM853873,GSM853874,GSM853875,GSM853876,GSM853877,GSM853878,GSM853879,GSM853880,GSM853881,GSM853882,GSM853883,GSM853884,GSM853885,GSM853886,GSM853887,GSM853888,GSM853889,GSM853890,GSM853891,GSM853892,GSM853893,GSM853894,GSM853895,GSM853896,GSM853897,GSM853898,GSM853899,GSM853900,GSM853901,GSM853902,GSM853903,GSM853904,GSM853905,GSM853906,GSM853907,GSM853908,GSM853909,GSM853910,GSM853911,GSM853912,GSM853913,GSM853914,GSM853915,GSM853916,GSM853917,GSM853918,GSM853919,GSM853920,GSM853921,GSM853922,GSM853923,GSM853924,GSM853925,GSM853926
2
- 1.0,0.0,0.0,1.0,1.0,1.0,0.0,1.0,1.0,0.0,0.0,1.0,1.0,0.0,1.0,1.0,0.0,0.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,1.0,0.0,1.0,1.0,1.0,0.0,1.0,1.0,0.0,1.0,1.0,0.0,0.0,1.0,0.0,0.0,0.0,1.0,1.0,0.0,0.0,1.0,1.0,0.0,1.0,1.0,0.0,1.0,1.0,1.0,0.0,1.0,1.0,0.0,0.0,0.0,1.0,1.0,1.0,0.0,0.0,1.0,1.0,1.0,1.0,0.0,0.0,1.0,0.0,0.0,0.0,1.0,0.0,1.0,0.0,0.0,1.0,0.0,0.0,1.0,0.0,1.0,1.0,1.0,1.0,0.0,1.0,1.0,1.0,0.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,0.0,1.0,0.0,1.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,0.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,0.0,1.0,0.0,1.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,0.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,0.0,1.0,0.0,1.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,0.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,0.0,1.0,0.0,1.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,0.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,0.0,1.0,0.0,1.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,0.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,0.0,1.0,0.0,1.0,0.0,0.0,0.0,1.0
3
- 1.0,0.0,1.0,0.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,0.0,1.0,0.0,1.0,1.0,0.0,1.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,0.0,0.0,1.0,0.0,1.0,0.0,0.0,1.0,0.0,0.0,1.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,0.0,0.0,1.0,0.0,1.0,0.0,0.0,1.0,1.0,0.0,0.0,1.0,0.0,0.0,0.0,1.0,1.0,0.0,1.0,0.0,1.0,1.0,1.0,1.0,0.0,0.0,1.0,1.0,1.0,0.0,1.0,0.0,1.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,0.0,1.0,1.0,1.0,0.0,1.0,0.0,0.0,1.0,0.0,0.0,1.0,0.0,0.0,1.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,1.0,0.0,0.0,1.0,0.0,0.0,1.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,0.0,1.0,1.0,0.0,1.0,1.0,1.0,0.0,0.0,1.0,0.0,0.0,1.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,0.0,1.0,1.0,0.0,1.0,1.0,1.0,0.0,0.0,1.0,0.0,0.0,1.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,0.0,1.0,1.0,0.0,1.0,1.0,1.0,0.0,0.0,1.0,0.0,0.0,1.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,0.0,1.0,1.0,0.0,1.0,1.0,1.0,0.0,0.0,1.0,0.0,0.0,1.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,0.0,1.0,1.0,0.0,1.0,1.0,1.0,0.0,0.0,1.0,0.0,0.0,1.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,0.0,1.0,1.0,0.0
 
1
+ ,GSM853700,GSM853701,GSM853702,GSM853703,GSM853704,GSM853705,GSM853706,GSM853707,GSM853708,GSM853709,GSM853710,GSM853711,GSM853712,GSM853713,GSM853714,GSM853715,GSM853716,GSM853717,GSM853718,GSM853719,GSM853720,GSM853721,GSM853722,GSM853723,GSM853724,GSM853725,GSM853726,GSM853727,GSM853728,GSM853729,GSM853730,GSM853731,GSM853732,GSM853733,GSM853734,GSM853735,GSM853736,GSM853737,GSM853738,GSM853739,GSM853740,GSM853741,GSM853742,GSM853743,GSM853744,GSM853745,GSM853746,GSM853747,GSM853748,GSM853749,GSM853750,GSM853751,GSM853752,GSM853753,GSM853754,GSM853755,GSM853756,GSM853757,GSM853758,GSM853759,GSM853760,GSM853761,GSM853762,GSM853763,GSM853764,GSM853765,GSM853766,GSM853767,GSM853768,GSM853769,GSM853770,GSM853771,GSM853772,GSM853773,GSM853774,GSM853775,GSM853776,GSM853777,GSM853778,GSM853779,GSM853780,GSM853781,GSM853782,GSM853783,GSM853784,GSM853785,GSM853786,GSM853787,GSM853788,GSM853789,GSM853790,GSM853791,GSM853792,GSM853793,GSM853794,GSM853795,GSM853796,GSM853797,GSM853798,GSM853799,GSM853800,GSM853801,GSM853802,GSM853803,GSM853804,GSM853805,GSM853806,GSM853807,GSM853808,GSM853809,GSM853810,GSM853811,GSM853812,GSM853813,GSM853814,GSM853815,GSM853816,GSM853817,GSM853818,GSM853819,GSM853820,GSM853821,GSM853822,GSM853823,GSM853824,GSM853825,GSM853826,GSM853827,GSM853828,GSM853829,GSM853830,GSM853831,GSM853832,GSM853833,GSM853834,GSM853835,GSM853836,GSM853837,GSM853838,GSM853839,GSM853840,GSM853841,GSM853842,GSM853843,GSM853844,GSM853845,GSM853846,GSM853847,GSM853848,GSM853849,GSM853850,GSM853851,GSM853852,GSM853853,GSM853854,GSM853855,GSM853856,GSM853857,GSM853858,GSM853859,GSM853860,GSM853861,GSM853862,GSM853863,GSM853864,GSM853865,GSM853866,GSM853867,GSM853868,GSM853869,GSM853870,GSM853871,GSM853872,GSM853873,GSM853874,GSM853875,GSM853876,GSM853877,GSM853878,GSM853879,GSM853880,GSM853881,GSM853882,GSM853883,GSM853884,GSM853885,GSM853886,GSM853887,GSM853888,GSM853889,GSM853890,GSM853891,GSM853892,GSM853893,GSM853894,GSM853895,GSM853896,GSM853897,GSM853898,GSM853899,GSM853900,GSM853901,GSM853902,GSM853903,GSM853904,GSM853905,GSM853906,GSM853907,GSM853908,GSM853909,GSM853910,GSM853911,GSM853912,GSM853913,GSM853914,GSM853915,GSM853916,GSM853917,GSM853918,GSM853919,GSM853920,GSM853921,GSM853922,GSM853923,GSM853924,GSM853925,GSM853926
2
+ Huntingtons_Disease,1.0,0.0,0.0,1.0,1.0,1.0,0.0,1.0,1.0,0.0,0.0,1.0,1.0,0.0,1.0,1.0,0.0,0.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,1.0,0.0,1.0,1.0,1.0,0.0,1.0,1.0,0.0,1.0,1.0,0.0,0.0,1.0,0.0,0.0,0.0,1.0,1.0,0.0,0.0,1.0,1.0,0.0,1.0,1.0,0.0,1.0,1.0,1.0,0.0,1.0,1.0,0.0,0.0,0.0,1.0,1.0,1.0,0.0,0.0,1.0,1.0,1.0,1.0,0.0,0.0,1.0,0.0,0.0,0.0,1.0,0.0,1.0,0.0,0.0,1.0,0.0,0.0,1.0,0.0,1.0,1.0,1.0,1.0,0.0,1.0,1.0,1.0,0.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,0.0,1.0,0.0,1.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,0.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,0.0,1.0,0.0,1.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,0.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,0.0,1.0,0.0,1.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,0.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,0.0,1.0,0.0,1.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,0.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,0.0,1.0,0.0,1.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,0.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,0.0,1.0,0.0,1.0,0.0,0.0,0.0,1.0
3
+ Gender,1.0,0.0,1.0,0.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,0.0,1.0,0.0,1.0,1.0,0.0,1.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,0.0,0.0,1.0,0.0,1.0,0.0,0.0,1.0,0.0,0.0,1.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,0.0,0.0,1.0,0.0,1.0,0.0,0.0,1.0,1.0,0.0,0.0,1.0,0.0,0.0,0.0,1.0,1.0,0.0,1.0,0.0,1.0,1.0,1.0,1.0,0.0,0.0,1.0,1.0,1.0,0.0,1.0,0.0,1.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,0.0,1.0,1.0,1.0,0.0,1.0,0.0,0.0,1.0,0.0,0.0,1.0,0.0,0.0,1.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,1.0,0.0,0.0,1.0,0.0,0.0,1.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,0.0,1.0,1.0,0.0,1.0,1.0,1.0,0.0,0.0,1.0,0.0,0.0,1.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,0.0,1.0,1.0,0.0,1.0,1.0,1.0,0.0,0.0,1.0,0.0,0.0,1.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,0.0,1.0,1.0,0.0,1.0,1.0,1.0,0.0,0.0,1.0,0.0,0.0,1.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,0.0,1.0,1.0,0.0,1.0,1.0,1.0,0.0,0.0,1.0,0.0,0.0,1.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,0.0,1.0,1.0,0.0,1.0,1.0,1.0,0.0,0.0,1.0,0.0,0.0,1.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,0.0,1.0,1.0,0.0
output/preprocess/Huntingtons_Disease/code/GSE135589.py ADDED
@@ -0,0 +1,190 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Huntingtons_Disease"
6
+ cohort = "GSE135589"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Huntingtons_Disease"
10
+ in_cohort_dir = "../DATA/GEO/Huntingtons_Disease/GSE135589"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z3/preprocess/Huntingtons_Disease/GSE135589.csv"
14
+ out_gene_data_file = "./output/z3/preprocess/Huntingtons_Disease/gene_data/GSE135589.csv"
15
+ out_clinical_data_file = "./output/z3/preprocess/Huntingtons_Disease/clinical_data/GSE135589.csv"
16
+ json_path = "./output/z3/preprocess/Huntingtons_Disease/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ import os
40
+ import re
41
+ import pandas as pd
42
+ import numpy as np
43
+
44
+ # 1) Gene expression data availability (based on background info: peripheral blood RNA gene expression)
45
+ is_gene_available = True
46
+
47
+ # 2) Variable availability (identify rows from the provided Sample Characteristics Dictionary)
48
+ trait_row = 4 # 'disease stage: Control / preHD A/B / zHD stage1/2'
49
+ age_row = 2 # 'age at year 1: <number>'
50
+ gender_row = 1 # 'Sex: Male/Female'
51
+
52
+ # 2.2) Conversion functions
53
+ def _after_colon(x: str) -> str:
54
+ if x is None or (isinstance(x, float) and np.isnan(x)):
55
+ return ''
56
+ parts = str(x).split(':', 1)
57
+ return parts[1].strip() if len(parts) > 1 else str(x).strip()
58
+
59
+ def convert_trait(x):
60
+ v = _after_colon(x).lower()
61
+ if v == '' or v in {'na', 'n/a', 'none', 'unknown'}:
62
+ return None
63
+ # Map to Huntington's disease status: control=0, preHD/zHD=1
64
+ if 'control' in v:
65
+ return 0
66
+ if 'prehd' in v or 'zhd' in v or 'stage' in v:
67
+ return 1
68
+ return None
69
+
70
+ def convert_age(x):
71
+ v = _after_colon(x).lower()
72
+ if v == '' or v in {'na', 'n/a', 'none', 'unknown'}:
73
+ return None
74
+ m = re.search(r'[-+]?\d+(\.\d+)?', v)
75
+ if not m:
76
+ return None
77
+ try:
78
+ return float(m.group(0))
79
+ except Exception:
80
+ return None
81
+
82
+ def convert_gender(x):
83
+ v = _after_colon(x).lower()
84
+ if 'female' in v:
85
+ return 0
86
+ if 'male' in v:
87
+ return 1
88
+ return None
89
+
90
+ # 3) Save metadata (initial filtering)
91
+ is_trait_available = trait_row is not None
92
+ _ = validate_and_save_cohort_info(
93
+ is_final=False,
94
+ cohort=cohort,
95
+ info_path=json_path,
96
+ is_gene_available=is_gene_available,
97
+ is_trait_available=is_trait_available
98
+ )
99
+
100
+ # 4) Clinical Feature Extraction (only if clinical 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, n=5)
113
+ print(preview)
114
+
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
+ print("requires_gene_mapping = True")
127
+
128
+ # Step 5: Gene Annotation
129
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
130
+ gene_annotation = get_gene_annotation(soft_file)
131
+
132
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
133
+ print("Gene annotation preview:")
134
+ print(preview_df(gene_annotation))
135
+
136
+ # Step 6: Gene Identifier Mapping
137
+ # 1. Decide the identifier and gene symbol columns from the gene annotation preview
138
+ probe_col = 'ID'
139
+ gene_symbol_col = 'Gene Symbol'
140
+
141
+ # 2. Build mapping dataframe
142
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=probe_col, gene_col=gene_symbol_col)
143
+
144
+ # 3. Apply mapping to convert probe-level data to gene-level expression
145
+ gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
146
+
147
+ # Step 7: Data Normalization and Linking
148
+ import os
149
+ import pandas as pd
150
+
151
+ # 1. Normalize gene symbols and save gene data
152
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
153
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
154
+ normalized_gene_data.to_csv(out_gene_data_file)
155
+
156
+ # 2. Link clinical and genetic data
157
+ try:
158
+ selected_clinical_df
159
+ except NameError:
160
+ # Fallback: load clinical data from file if not in scope
161
+ selected_clinical_df = pd.read_csv(out_clinical_data_file, index_col=0)
162
+
163
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
164
+
165
+ # 3. Handle missing values
166
+ linked_data = handle_missing_values(linked_data, trait)
167
+
168
+ # 4. Bias assessment and removal of biased demographic features
169
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
170
+
171
+ # 5. Final validation and save cohort info
172
+ is_gene_available_final = (normalized_gene_data.shape[0] > 0) and (normalized_gene_data.shape[1] > 0)
173
+ is_trait_available_final = (trait in unbiased_linked_data.columns)
174
+
175
+ note = "INFO: Trait coded as Control=0 and preHD/zHD=1. Age corresponds to 'age at year 1'."
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=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/Huntingtons_Disease/code/GSE154141.py ADDED
@@ -0,0 +1,507 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Huntingtons_Disease"
6
+ cohort = "GSE154141"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Huntingtons_Disease"
10
+ in_cohort_dir = "../DATA/GEO/Huntingtons_Disease/GSE154141"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z3/preprocess/Huntingtons_Disease/GSE154141.csv"
14
+ out_gene_data_file = "./output/z3/preprocess/Huntingtons_Disease/gene_data/GSE154141.csv"
15
+ out_clinical_data_file = "./output/z3/preprocess/Huntingtons_Disease/clinical_data/GSE154141.csv"
16
+ json_path = "./output/z3/preprocess/Huntingtons_Disease/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ import os
40
+ import re
41
+ import pandas as pd
42
+
43
+ # 1) Gene expression availability
44
+ is_gene_available = True # Lentiviral manipulation with Q-lengths strongly suggests gene expression profiling.
45
+
46
+ # 2) Variable availability and converters
47
+ # From the sample characteristics dictionary:
48
+ # 0: sort: Gpos_Pneg / Gpos_Ppos -> sorting status, not the trait
49
+ # 1: lentivirus: pTANK / Q23 / Q73 -> disease modeling; use as trait
50
+ # 2: sampleID: A/B/C -> IDs
51
+ trait_row = 1
52
+ age_row = None # No age field in the characteristics; unavailable.
53
+ gender_row = None # No gender field in the characteristics; unavailable.
54
+
55
+ def _value_after_colon(x):
56
+ if x is None:
57
+ return None
58
+ try:
59
+ parts = str(x).split(":", 1)
60
+ val = parts[1] if len(parts) > 1 else parts[0]
61
+ val = val.strip()
62
+ return val if val != "" else None
63
+ except Exception:
64
+ return None
65
+
66
+ def convert_trait(x):
67
+ v = _value_after_colon(x)
68
+ if v is None:
69
+ return None
70
+ s = re.sub(r"\s+", "", str(v)).lower()
71
+ # Map common controls
72
+ if s in {"ptank", "control", "ctrl", "vehicle", "empty", "mock"}:
73
+ return 0
74
+ # Map Q-lengths by threshold for HD
75
+ m = re.search(r"q(\d+)", s)
76
+ if m:
77
+ try:
78
+ q = int(m.group(1))
79
+ return 1 if q >= 36 else 0
80
+ except Exception:
81
+ pass
82
+ # Heuristics
83
+ if any(t in s for t in ["mut", "expanded", "hd", "mhtt", "htt-exp"]):
84
+ return 1
85
+ if any(t in s for t in ["wt", "nonhd", "normal", "unchanged"]):
86
+ return 0
87
+ return None
88
+
89
+ def convert_age(x):
90
+ v = _value_after_colon(x)
91
+ if v is None:
92
+ return None
93
+ s = str(v).strip().lower()
94
+ m = re.search(r"(\d+(\.\d+)?)", s)
95
+ if not m:
96
+ return None
97
+ try:
98
+ num = float(m.group(1))
99
+ except Exception:
100
+ return None
101
+ if "month" in s:
102
+ return num / 12.0
103
+ if "day" in s or "d " in s:
104
+ return num / 365.0
105
+ if "week" in s:
106
+ return num / 52.0
107
+ return num
108
+
109
+ def convert_gender(x):
110
+ v = _value_after_colon(x)
111
+ if v is None:
112
+ return None
113
+ s = str(v).strip().lower()
114
+ if s in {"female", "f", "woman", "girl"}:
115
+ return 0
116
+ if s in {"male", "m", "man", "boy"}:
117
+ return 1
118
+ return None
119
+
120
+ # 3) Save metadata (initial filtering)
121
+ is_trait_available = trait_row is not None
122
+ _ = validate_and_save_cohort_info(
123
+ is_final=False,
124
+ cohort=cohort,
125
+ info_path=json_path,
126
+ is_gene_available=is_gene_available,
127
+ is_trait_available=is_trait_available
128
+ )
129
+
130
+ # 4) Clinical feature extraction (only if trait_row is available)
131
+ if trait_row is not None:
132
+ selected_clinical = geo_select_clinical_features(
133
+ clinical_df=clinical_data,
134
+ trait=trait,
135
+ trait_row=trait_row,
136
+ convert_trait=convert_trait,
137
+ age_row=age_row,
138
+ convert_age=convert_age,
139
+ gender_row=gender_row,
140
+ convert_gender=convert_gender
141
+ )
142
+ preview = preview_df(selected_clinical)
143
+ print(preview)
144
+ # Save
145
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
146
+ selected_clinical.to_csv(out_clinical_data_file, index=True)
147
+
148
+ # Step 3: Gene Data Extraction
149
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
150
+ gene_data = get_genetic_data(matrix_file)
151
+
152
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
153
+ print(gene_data.index[:20])
154
+
155
+ # Step 4: Gene Identifier Review
156
+ requires_gene_mapping = True
157
+ print(f"requires_gene_mapping = {requires_gene_mapping}")
158
+
159
+ # Step 5: Gene Annotation
160
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
161
+ gene_annotation = get_gene_annotation(soft_file)
162
+
163
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
164
+ print("Gene annotation preview:")
165
+ print(preview_df(gene_annotation))
166
+
167
+ # Step 6: Gene Identifier Mapping
168
+ import os
169
+ import re
170
+ import pandas as pd
171
+
172
+ # Prepare expression probe ID set
173
+ expr_ids = set(gene_data.index.astype(str).str.strip())
174
+
175
+ # Collect all SOFT files from cohort dir and trait dir (to capture GPL files if present)
176
+ soft_files = []
177
+ for base in [in_cohort_dir, in_trait_dir]:
178
+ for root, _, files in os.walk(base):
179
+ for f in files:
180
+ if 'soft' in f.lower():
181
+ soft_files.append(os.path.join(root, f))
182
+ soft_files = list(dict.fromkeys(soft_files)) # de-duplicate while preserving order
183
+
184
+ def pick_best_annotation(soft_paths, expr_ids_set):
185
+ best = {"soft_path": None, "id_col": None, "overlap": -1, "annotation": None}
186
+ diagnostics = []
187
+ for sp in soft_paths:
188
+ try:
189
+ ann = get_gene_annotation(sp)
190
+ except Exception as e:
191
+ diagnostics.append((os.path.basename(sp), "READ_FAIL", 0, str(e)))
192
+ continue
193
+
194
+ # Evaluate overlap for each column
195
+ top_col = None
196
+ top_overlap = -1
197
+ for col in ann.columns:
198
+ try:
199
+ series = ann[col].astype(str).str.strip()
200
+ except Exception:
201
+ continue
202
+ # Drop obvious non-ID columns by limiting value length (heuristic)
203
+ vals = series.dropna().unique()
204
+ if len(vals) == 0:
205
+ continue
206
+ # Compute overlap
207
+ overlap = len(expr_ids_set.intersection(set(vals)))
208
+ if overlap > top_overlap:
209
+ top_overlap = overlap
210
+ top_col = col
211
+
212
+ diagnostics.append((os.path.basename(sp), top_col, top_overlap, None))
213
+ if top_overlap > best["overlap"]:
214
+ best.update({"soft_path": sp, "id_col": top_col, "overlap": top_overlap, "annotation": ann})
215
+
216
+ print("Annotation matching diagnostics (file, chosen_id_col, overlap):")
217
+ for d in diagnostics:
218
+ print(" ", d)
219
+ return best
220
+
221
+ best_match = pick_best_annotation(soft_files, expr_ids)
222
+
223
+ # Require a minimal meaningful overlap
224
+ min_required_overlap = 100
225
+ if best_match["overlap"] < min_required_overlap or best_match["annotation"] is None or best_match["id_col"] is None:
226
+ raise RuntimeError(
227
+ f"No suitable annotation found for expression IDs. Best overlap={best_match['overlap']} "
228
+ f"with file={os.path.basename(best_match['soft_path']) if best_match['soft_path'] else None} "
229
+ f"and column={best_match['id_col']}. Please verify platform files in {in_cohort_dir}."
230
+ )
231
+
232
+ gene_annotation_all = best_match["annotation"]
233
+ probe_col = best_match["id_col"]
234
+
235
+ # Subset annotation to rows matching our expression probes
236
+ ann_ids_series = gene_annotation_all[probe_col].astype(str).str.strip()
237
+ ann_subset = gene_annotation_all.loc[ann_ids_series.isin(expr_ids)].copy()
238
+
239
+ # Identify the best gene symbol column within the subset
240
+ def find_gene_symbol_col_in_subset(df_subset: pd.DataFrame) -> str | None:
241
+ preferred = [
242
+ "Gene Symbol", "GENE_SYMBOL", "Gene symbol", "Symbol", "SYMBOL", "GeneSymbol",
243
+ "Approved Symbol", "Associated Gene Name", "Associated.Symbol", "gene_assignment"
244
+ ]
245
+ # Exact preferred matches first (case-insensitive), prioritizing non-null count
246
+ candidates = []
247
+ for p in preferred:
248
+ for c in df_subset.columns:
249
+ if c.lower() == p.lower():
250
+ nonnull = df_subset[c].notna().sum()
251
+ if nonnull > 0:
252
+ candidates.append((c, nonnull))
253
+ if candidates:
254
+ candidates.sort(key=lambda x: x[1], reverse=True)
255
+ return candidates[0][0]
256
+ # Heuristic: any column name containing 'symbol' with non-null values
257
+ symbol_like = []
258
+ for c in df_subset.columns:
259
+ if "symbol" in c.lower():
260
+ nonnull = df_subset[c].notna().sum()
261
+ if nonnull > 0:
262
+ symbol_like.append((c, nonnull))
263
+ if symbol_like:
264
+ symbol_like.sort(key=lambda x: x[1], reverse=True)
265
+ return symbol_like[0][0]
266
+ return None
267
+
268
+ gene_symbol_col = find_gene_symbol_col_in_subset(ann_subset)
269
+
270
+ # Fallback: parse gene symbol from 'Target Description' if symbol column unavailable or mostly empty
271
+ def parse_symbol_from_target_desc(s: str) -> str | None:
272
+ if not isinstance(s, str):
273
+ return None
274
+ # Try /UG_GENE= or /GEN= tags
275
+ m = re.search(r"/UG_GENE=([A-Za-z0-9\-]+)", s)
276
+ if not m:
277
+ m = re.search(r"/GEN=([A-Za-z0-9\-]+)", s)
278
+ if m:
279
+ return m.group(1)
280
+ return None
281
+
282
+ if gene_symbol_col is None or ann_subset[gene_symbol_col].notna().sum() == 0:
283
+ if "Target Description" in ann_subset.columns:
284
+ ann_subset["__ParsedSymbol__"] = ann_subset["Target Description"].apply(parse_symbol_from_target_desc)
285
+ if ann_subset["__ParsedSymbol__"].notna().sum() == 0:
286
+ # As a last heuristic, try to extract any all-caps token up to 10 chars as a putative symbol
287
+ def loose_parse(s: str) -> str | None:
288
+ if not isinstance(s, str):
289
+ return None
290
+ toks = re.findall(r"\b[A-Z][A-Z0-9\-]{1,9}\b", s)
291
+ if len(toks) > 0:
292
+ return toks[0]
293
+ return None
294
+ ann_subset["__ParsedSymbol__"] = ann_subset["Target Description"].apply(loose_parse)
295
+ gene_symbol_col = "__ParsedSymbol__"
296
+ else:
297
+ raise RuntimeError("No gene symbol column found and 'Target Description' absent for fallback parsing.")
298
+
299
+ # Build mapping dataframe from subset
300
+ mapping_df = ann_subset[[probe_col, gene_symbol_col]].rename(columns={probe_col: "ID", gene_symbol_col: "Gene"})
301
+ mapping_df = mapping_df.dropna(subset=["ID", "Gene"]).copy()
302
+
303
+ # Ensure mapping IDs align with expression probes
304
+ mapping_df["ID"] = mapping_df["ID"].astype(str).str.strip()
305
+ mapping_df = mapping_df[mapping_df["ID"].isin(gene_data.index)]
306
+
307
+ # Normalize gene symbols to uppercase to survive human-gene extractor
308
+ mapping_df["Gene"] = mapping_df["Gene"].astype(str).str.strip().str.upper()
309
+
310
+ # Drop empty gene symbols after cleanup
311
+ mapping_df = mapping_df[mapping_df["Gene"] != ""]
312
+
313
+ # Apply mapping to convert probe-level data to gene-level expression
314
+ mapped_gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
315
+
316
+ # Diagnostics
317
+ n_probes = len(expr_ids)
318
+ n_mapping_ids = mapping_df['ID'].nunique()
319
+ n_genes = mapped_gene_data.shape[0]
320
+ print(f"Mapping diagnostics: n_probes_in_expr={n_probes}, n_probes_mapped={n_mapping_ids}, n_genes_result={n_genes}")
321
+
322
+ if n_genes == 0:
323
+ raise RuntimeError("Gene mapping resulted in zero genes after refined selection. Likely platform mismatch or unusable annotation.")
324
+
325
+ # Overwrite gene_data with the mapped gene-level dataframe
326
+ gene_data = mapped_gene_data
327
+
328
+ # Step 7: Gene Annotation
329
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
330
+ gene_annotation = get_gene_annotation(soft_file)
331
+
332
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
333
+ print("Gene annotation preview:")
334
+ print(preview_df(gene_annotation))
335
+
336
+ # Step 8: Gene Identifier Mapping
337
+ import gzip
338
+ import io
339
+ import re
340
+ import pandas as pd
341
+
342
+ # Use existing gene_data (probe-level expression) and soft_file from previous steps
343
+
344
+ # 1) Parse all platform tables from the family SOFT and evaluate ID overlap with expression probes
345
+ expr_ids = set(gene_data.index.astype(str).str.strip())
346
+
347
+ def iter_platform_tables(soft_fp: str):
348
+ """Yield (platform_id, table_df) for each !platform_table block in the family SOFT."""
349
+ with gzip.open(soft_fp, 'rt') as f:
350
+ in_table = False
351
+ buf = []
352
+ platform_id = None
353
+ last_platform_id = None
354
+ for line in f:
355
+ line = line.rstrip('\n')
356
+ if line.startswith('!Platform_geo_accession') or line.startswith('!platform_geo_accession'):
357
+ parts = line.split('=', 1)
358
+ if len(parts) == 2:
359
+ last_platform_id = parts[1].strip()
360
+ if line.startswith('^PLATFORM'):
361
+ parts = line.split('=', 1)
362
+ if len(parts) == 2:
363
+ last_platform_id = parts[1].strip()
364
+ if line.startswith('!platform_table_begin') or line.startswith('!Platform_table_begin'):
365
+ in_table = True
366
+ buf = []
367
+ platform_id = last_platform_id
368
+ continue
369
+ if line.startswith('!platform_table_end') or line.startswith('!Platform_table_end'):
370
+ in_table = False
371
+ table_txt = '\n'.join(buf)
372
+ try:
373
+ df = pd.read_csv(io.StringIO(table_txt), sep='\t', dtype=str, low_memory=False, on_bad_lines='skip')
374
+ df.columns = [c.strip() for c in df.columns]
375
+ yield (platform_id, df)
376
+ except Exception:
377
+ pass
378
+ buf = []
379
+ platform_id = None
380
+ continue
381
+ if in_table:
382
+ buf.append(line)
383
+
384
+ def best_id_match(df: pd.DataFrame, expr_ids: set):
385
+ candidates = [
386
+ "ID", "ID_REF",
387
+ "Array Address ID", "Array_Address_ID", "ArrayAddressID", "Array_Address_Id", "Array Address Id",
388
+ "Reporter Identifier", "Reporter_Name", "Reporter Name",
389
+ "ProbeID", "Probe Id", "PROBE_ID", "TargetID", "TARGETID",
390
+ "Representative Public ID", "GB_ACC", "ACCESSION"
391
+ ]
392
+ present = [c for c in candidates if c in df.columns]
393
+ if not present:
394
+ present = list(df.columns)
395
+ expr_ids_digits = set(re.sub(r"\D", "", x) for x in expr_ids if re.sub(r"\D", "", x) != "")
396
+ best = {"col": None, "norm": None, "overlap": -1}
397
+ for col in present:
398
+ series = df[col].astype(str).str.strip()
399
+ vals = set(series.dropna().unique())
400
+ ovA = len(expr_ids.intersection(vals))
401
+ vals_no_ilmn = set(re.sub(r"^ILMN_", "", v) for v in vals)
402
+ ovB = len(expr_ids.intersection(vals_no_ilmn))
403
+ vals_digits = set(re.sub(r"\D", "", v) for v in vals if re.sub(r"\D", "", v) != "")
404
+ ovC = len(expr_ids_digits.intersection(vals_digits))
405
+ for norm, ov in [("direct", ovA), ("drop_ilmn_prefix", ovB), ("digits_only", ovC)]:
406
+ if ov > best["overlap"]:
407
+ best.update({"col": col, "norm": norm, "overlap": ov})
408
+ return best
409
+
410
+ # Scan all platform tables and pick the one with maximal overlap
411
+ diagnostics = []
412
+ best_block = {"platform": None, "df": None, "id_col": None, "norm": None, "overlap": -1}
413
+ for plat_id, plat_df in iter_platform_tables(soft_file):
414
+ match = best_id_match(plat_df, expr_ids)
415
+ diagnostics.append((plat_id, match["col"], match["norm"], match["overlap"]))
416
+ if match["overlap"] > best_block["overlap"]:
417
+ best_block = {"platform": plat_id, "df": plat_df, "id_col": match["col"], "norm": match["norm"], "overlap": match["overlap"]}
418
+
419
+ print("Platform matching diagnostics (platform, id_col, norm, overlap):")
420
+ for d in diagnostics:
421
+ print(" ", d)
422
+
423
+ if best_block["df"] is None or best_block["id_col"] is None or best_block["overlap"] < 100:
424
+ raise RuntimeError(f"No suitable platform table found to match expression probe IDs. Best overlap={best_block['overlap']} for platform={best_block['platform']} and id_col={best_block['id_col']}.")
425
+
426
+ plat_df = best_block["df"]
427
+ probe_col = best_block["id_col"]
428
+ norm_strategy = best_block["norm"]
429
+
430
+ # 2) Robust gene symbol/text column selection driven by extraction
431
+ def pick_gene_text_col(df: pd.DataFrame, id_col: str) -> tuple[str, int]:
432
+ # Prefer common symbol/name columns if present
433
+ preferred = [
434
+ "Gene Symbol", "GENE_SYMBOL", "Gene symbol", "Symbol", "SYMBOL", "GeneSymbol",
435
+ "Gene", "GENE", "ILMN_Gene", "Associated Gene Name", "Associated.Symbol",
436
+ "gene_assignment", "Gene Title", "Target Description", "Description", "DEFINITION", "Definition", "DESCRIPTION"
437
+ ]
438
+ candidates = [c for c in preferred if c in df.columns and c != id_col]
439
+ if not candidates:
440
+ candidates = [c for c in df.columns if c != id_col]
441
+
442
+ best_col = None
443
+ best_score = -1
444
+
445
+ # Evaluate by how many rows yield at least one plausible human-like gene symbol after uppercasing
446
+ # Use a sample for efficiency if very large
447
+ eval_df = df
448
+ if len(df) > 10000:
449
+ eval_df = df.iloc[:10000].copy()
450
+
451
+ for c in candidates:
452
+ series = eval_df[c].dropna().astype(str).str.strip()
453
+ if series.empty:
454
+ continue
455
+ # Uppercase to make symbol extraction robust
456
+ series_upper = series.str.upper()
457
+ count = 0
458
+ for val in series_upper:
459
+ if len(extract_human_gene_symbols(val)) > 0:
460
+ count += 1
461
+ if count > best_score:
462
+ best_score = count
463
+ best_col = c
464
+ # Early exit if a clear symbol column found
465
+ if count > 1000:
466
+ break
467
+ return best_col, best_score
468
+
469
+ gene_symbol_col, score = pick_gene_text_col(plat_df, probe_col)
470
+ if gene_symbol_col is None or score <= 0:
471
+ raise RuntimeError("Unable to locate a gene symbol/text column that yields extractable symbols in the selected platform table.")
472
+
473
+ # 3) Build mapping dataframe and apply mapping
474
+ ann = plat_df[[probe_col, gene_symbol_col]].dropna(subset=[probe_col, gene_symbol_col]).copy()
475
+ ann[probe_col] = ann[probe_col].astype(str).str.strip()
476
+
477
+ if norm_strategy == "direct":
478
+ ann["ID"] = ann[probe_col]
479
+ elif norm_strategy == "drop_ilmn_prefix":
480
+ ann["ID"] = ann[probe_col].str.replace(r"^ILMN_", "", regex=True)
481
+ elif norm_strategy == "digits_only":
482
+ ann["ID"] = ann[probe_col].str.replace(r"\D", "", regex=True)
483
+ else:
484
+ ann["ID"] = ann[probe_col]
485
+
486
+ # Keep only IDs present in expression
487
+ ann["ID"] = ann["ID"].astype(str).str.strip()
488
+ ann = ann[ann["ID"].isin(expr_ids)]
489
+
490
+ mapping_df = ann[["ID", gene_symbol_col]].rename(columns={gene_symbol_col: "Gene"}).copy()
491
+ # Uppercase to aid extraction of symbols from descriptive text as needed
492
+ mapping_df["Gene"] = mapping_df["Gene"].astype(str).str.strip().str.upper()
493
+ mapping_df = mapping_df[(mapping_df["ID"] != "") & (mapping_df["Gene"] != "")]
494
+
495
+ # Apply mapping using helper (extracts human-like symbols from text and aggregates)
496
+ mapped_gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
497
+
498
+ n_probes = len(gene_data.index)
499
+ n_mapped = mapping_df["ID"].nunique()
500
+ n_genes = mapped_gene_data.shape[0]
501
+ print(f"Mapping diagnostics: probes_in_expr={n_probes}, probes_mapped={n_mapped}, genes_after_mapping={n_genes}, platform={best_block['platform']}, id_col={probe_col}, symbol_col={gene_symbol_col}, symbol_hits_in_sample={score}")
502
+
503
+ if n_mapped == 0 or n_genes == 0:
504
+ raise RuntimeError("Gene mapping resulted in zero genes after selecting the best platform table. Please verify platform/ID matching.")
505
+
506
+ # Overwrite gene_data with gene-level expression
507
+ gene_data = mapped_gene_data
output/preprocess/Huntingtons_Disease/code/GSE26927.py ADDED
@@ -0,0 +1,193 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Huntingtons_Disease"
6
+ cohort = "GSE26927"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Huntingtons_Disease"
10
+ in_cohort_dir = "../DATA/GEO/Huntingtons_Disease/GSE26927"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z3/preprocess/Huntingtons_Disease/GSE26927.csv"
14
+ out_gene_data_file = "./output/z3/preprocess/Huntingtons_Disease/gene_data/GSE26927.csv"
15
+ out_clinical_data_file = "./output/z3/preprocess/Huntingtons_Disease/clinical_data/GSE26927.csv"
16
+ json_path = "./output/z3/preprocess/Huntingtons_Disease/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ # Determine gene expression availability based on platform description (Illumina HumanRef8 v2 BeadChip: mRNA expression)
40
+ is_gene_available = True
41
+
42
+ # Identify rows for variables from the provided Sample Characteristics Dictionary
43
+ trait_row = 0 # disease field
44
+ age_row = 2 # age at death (in years)
45
+ gender_row = 1 # gender
46
+
47
+ # Conversion helpers
48
+ def _after_colon(value):
49
+ if value is None:
50
+ return None
51
+ if not isinstance(value, str):
52
+ return value
53
+ parts = value.split(":", 1)
54
+ v = parts[1].strip() if len(parts) > 1 else value.strip()
55
+ # Normalize common unknown markers
56
+ if v in {"?", "NA", "N/A", "", "nan", "NaN", "None"}:
57
+ return None
58
+ return v
59
+
60
+ def convert_trait(x):
61
+ v = _after_colon(x)
62
+ if v is None:
63
+ return None
64
+ vl = v.lower()
65
+ # Map Huntington's disease to 1; all other diseases to 0
66
+ if "huntington" in vl:
67
+ return 1
68
+ # For any other disease label, map to 0
69
+ return 0
70
+
71
+ def convert_age(x):
72
+ v = _after_colon(x)
73
+ if v is None:
74
+ return None
75
+ # Extract numeric age; tolerate strings like "82"
76
+ try:
77
+ return float(v)
78
+ except Exception:
79
+ # Try to extract the first number from the string
80
+ import re
81
+ m = re.search(r"[-+]?\d*\.?\d+", v)
82
+ if m:
83
+ try:
84
+ return float(m.group(0))
85
+ except Exception:
86
+ return None
87
+ return None
88
+
89
+ def convert_gender(x):
90
+ v = _after_colon(x)
91
+ if v is None:
92
+ return None
93
+ vl = v.strip().lower()
94
+ if vl in {"f", "female"}:
95
+ return 0
96
+ if vl in {"m", "male"}:
97
+ return 1
98
+ return None
99
+
100
+ # Trait availability: determined by whether trait_row is not None
101
+ is_trait_available = trait_row is not None
102
+
103
+ # Save initial metadata (initial filtering)
104
+ _ = validate_and_save_cohort_info(
105
+ is_final=False,
106
+ cohort=cohort,
107
+ info_path=json_path,
108
+ is_gene_available=is_gene_available,
109
+ is_trait_available=is_trait_available
110
+ )
111
+
112
+ # Clinical feature extraction if clinical data (trait) is available
113
+ if trait_row is not None:
114
+ selected_clinical_df = geo_select_clinical_features(
115
+ clinical_df=clinical_data,
116
+ trait=trait,
117
+ trait_row=trait_row,
118
+ convert_trait=convert_trait,
119
+ age_row=age_row,
120
+ convert_age=convert_age,
121
+ gender_row=gender_row,
122
+ convert_gender=convert_gender
123
+ )
124
+ preview = preview_df(selected_clinical_df)
125
+ print(preview)
126
+ # Save clinical features
127
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
128
+ selected_clinical_df.to_csv(out_clinical_data_file)
129
+
130
+ # Step 3: Gene Data Extraction
131
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
132
+ gene_data = get_genetic_data(matrix_file)
133
+
134
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
135
+ print(gene_data.index[:20])
136
+
137
+ # Step 4: Gene Identifier Review
138
+ requires_gene_mapping = True
139
+ print(f"requires_gene_mapping = {requires_gene_mapping}")
140
+
141
+ # Step 5: Gene Annotation
142
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
143
+ gene_annotation = get_gene_annotation(soft_file)
144
+
145
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
146
+ print("Gene annotation preview:")
147
+ print(preview_df(gene_annotation))
148
+
149
+ # Step 6: Gene Identifier Mapping
150
+ # Identify appropriate columns for mapping: probe IDs and gene symbols
151
+ prob_col = 'ID' # Matches probe identifiers like ILMN_10000 in gene expression data
152
+ gene_col = 'SYMBOL' # Contains human gene symbols
153
+
154
+ # Build mapping dataframe from annotation
155
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=prob_col, gene_col=gene_col)
156
+
157
+ # Apply mapping to convert probe-level data to gene-level expression
158
+ gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
159
+
160
+ # Step 7: Data Normalization and Linking
161
+ import os
162
+
163
+ # 1. Normalize gene symbols and save gene expression data
164
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
165
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
166
+ normalized_gene_data.to_csv(out_gene_data_file)
167
+
168
+ # 2. Link clinical and genetic data
169
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
170
+
171
+ # 3. Handle missing values
172
+ linked_data = handle_missing_values(linked_data, trait)
173
+
174
+ # 4. Bias check and removal of biased demographic features
175
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
176
+
177
+ # 5. Final validation and save cohort info
178
+ note = "INFO: Trait defined as Huntington's disease vs other neurodegenerative diseases; post-mortem brain tissue; Illumina HumanRef8 v2 platform."
179
+ is_usable = validate_and_save_cohort_info(
180
+ is_final=True,
181
+ cohort=cohort,
182
+ info_path=json_path,
183
+ is_gene_available=True,
184
+ is_trait_available=True,
185
+ is_biased=is_trait_biased,
186
+ df=unbiased_linked_data,
187
+ note=note
188
+ )
189
+
190
+ # 6. Save linked data if usable
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/Huntingtons_Disease/code/GSE34201.py ADDED
@@ -0,0 +1,190 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Huntingtons_Disease"
6
+ cohort = "GSE34201"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Huntingtons_Disease"
10
+ in_cohort_dir = "../DATA/GEO/Huntingtons_Disease/GSE34201"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z3/preprocess/Huntingtons_Disease/GSE34201.csv"
14
+ out_gene_data_file = "./output/z3/preprocess/Huntingtons_Disease/gene_data/GSE34201.csv"
15
+ out_clinical_data_file = "./output/z3/preprocess/Huntingtons_Disease/clinical_data/GSE34201.csv"
16
+ json_path = "./output/z3/preprocess/Huntingtons_Disease/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ import os
40
+ import re
41
+ import pandas as pd
42
+
43
+ # 1) Gene expression data availability
44
+ is_gene_available = True # Expression profiling was performed on ES cells and NSC progeny
45
+
46
+ # 2) Variable availability and converters
47
+ # From the provided Sample Characteristics Dictionary:
48
+ # 1: 'hd genotype: HD' / 'hd genotype: wild type' -> trait
49
+ # 3: 'gender: male' / 'gender: female' -> gender
50
+ trait_row = 1
51
+ age_row = None
52
+ gender_row = 3
53
+
54
+ def _get_value_after_colon(x):
55
+ if x is None:
56
+ return None
57
+ if isinstance(x, (int, float)):
58
+ return x
59
+ x = str(x)
60
+ parts = x.split(":", 1)
61
+ val = parts[1] if len(parts) > 1 else parts[0]
62
+ return val.strip() if isinstance(val, str) else val
63
+
64
+ def convert_trait(x):
65
+ val = _get_value_after_colon(x)
66
+ if val is None:
67
+ return None
68
+ v = str(val).strip().lower()
69
+ # Map HD vs WT
70
+ if v in {"hd", "huntington", "huntington's", "huntingtons", "case", "mutant", "mutation", "affected"}:
71
+ return 1
72
+ if v in {"wild type", "wild-type", "wildtype", "wt", "control", "normal", "unaffected"}:
73
+ return 0
74
+ return None
75
+
76
+ def convert_age(x):
77
+ # Not available in this dataset; function provided for API completeness
78
+ val = _get_value_after_colon(x)
79
+ if val is None:
80
+ return None
81
+ # Try to parse a number if present
82
+ m = re.search(r"([-+]?\d*\.?\d+)", str(val))
83
+ return float(m.group(1)) if m else None
84
+
85
+ def convert_gender(x):
86
+ val = _get_value_after_colon(x)
87
+ if val is None:
88
+ return None
89
+ v = str(val).strip().lower()
90
+ if v in {"male", "m"}:
91
+ return 1
92
+ if v in {"female", "f"}:
93
+ return 0
94
+ return None
95
+
96
+ # 3) Save metadata with initial filtering
97
+ is_trait_available = trait_row is not None
98
+ _ = validate_and_save_cohort_info(
99
+ is_final=False,
100
+ cohort=cohort,
101
+ info_path=json_path,
102
+ is_gene_available=is_gene_available,
103
+ is_trait_available=is_trait_available
104
+ )
105
+
106
+ # 4) Clinical feature extraction (only if trait is available)
107
+ if trait_row is not None:
108
+ selected_clinical_df = geo_select_clinical_features(
109
+ clinical_df=clinical_data,
110
+ trait=trait,
111
+ trait_row=trait_row,
112
+ convert_trait=convert_trait,
113
+ age_row=age_row,
114
+ convert_age=None,
115
+ gender_row=gender_row,
116
+ convert_gender=convert_gender
117
+ )
118
+ preview = preview_df(selected_clinical_df, n=5)
119
+ print(preview)
120
+
121
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
122
+ selected_clinical_df.to_csv(out_clinical_data_file)
123
+
124
+ # Step 3: Gene Data Extraction
125
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
126
+ gene_data = get_genetic_data(matrix_file)
127
+
128
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
129
+ print(gene_data.index[:20])
130
+
131
+ # Step 4: Gene Identifier Review
132
+ requires_gene_mapping = True
133
+ print(f"requires_gene_mapping = {requires_gene_mapping}")
134
+
135
+ # Step 5: Gene Annotation
136
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
137
+ gene_annotation = get_gene_annotation(soft_file)
138
+
139
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
140
+ print("Gene annotation preview:")
141
+ print(preview_df(gene_annotation))
142
+
143
+ # Step 6: Gene Identifier Mapping
144
+ # Determine the appropriate columns for probe IDs and gene symbols from the annotation preview:
145
+ # Probe identifier column: 'ID' (e.g., ILMN_#######)
146
+ # Gene symbol column: 'Symbol'
147
+
148
+ # 1-2) Build mapping dataframe from annotation
149
+ mapping_df = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='Symbol')
150
+
151
+ # 3) Apply mapping to convert probe-level data to gene-level expression
152
+ gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
153
+
154
+ # Optionally save the processed gene expression data
155
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
156
+ gene_data.to_csv(out_gene_data_file)
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 (fix variable name to selected_clinical_df)
167
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
168
+
169
+ # Optional quick preview to verify alignment
170
+ print(preview_df(linked_data, n=3))
171
+
172
+ # 3. Handle missing values
173
+ linked_data = handle_missing_values(linked_data, trait)
174
+
175
+ # 4. Bias assessment and removal of biased covariates
176
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
177
+
178
+ # 5. Final validation and save cohort info
179
+ is_gene_available_final = normalized_gene_data.shape[0] > 0
180
+ is_trait_available_final = trait in selected_clinical_df.index
181
+ note_msg = "INFO: Age not provided; used Gender as covariate only."
182
+ is_usable = validate_and_save_cohort_info(
183
+ True, cohort, json_path, is_gene_available_final, is_trait_available_final,
184
+ is_trait_biased, unbiased_linked_data, note=note_msg
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/Huntingtons_Disease/code/GSE34721.py ADDED
@@ -0,0 +1,203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Huntingtons_Disease"
6
+ cohort = "GSE34721"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Huntingtons_Disease"
10
+ in_cohort_dir = "../DATA/GEO/Huntingtons_Disease/GSE34721"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z3/preprocess/Huntingtons_Disease/GSE34721.csv"
14
+ out_gene_data_file = "./output/z3/preprocess/Huntingtons_Disease/gene_data/GSE34721.csv"
15
+ out_clinical_data_file = "./output/z3/preprocess/Huntingtons_Disease/clinical_data/GSE34721.csv"
16
+ json_path = "./output/z3/preprocess/Huntingtons_Disease/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ import os
40
+
41
+ # Determine data availability based on provided background and characteristics
42
+ is_gene_available = True # Gene expression dataset (mRNA) per background info
43
+
44
+ # Identify rows in the sample characteristics dictionary
45
+ trait_row = 1 # 'htt cag repeat length (longer allele)'
46
+ age_row = None # No age information available
47
+ gender_row = 0 # 'gender'
48
+
49
+ # Converters
50
+ def _after_colon(value):
51
+ if value is None:
52
+ return None
53
+ try:
54
+ s = str(value)
55
+ except Exception:
56
+ return None
57
+ parts = s.split(":", 1)
58
+ val = parts[1] if len(parts) > 1 else parts[0]
59
+ return val.strip()
60
+
61
+ def convert_trait(x):
62
+ # Map status from HTT CAG repeat length on the longer allele:
63
+ # Commonly, >=36 repeats indicates an expanded allele consistent with HD mutation carrier (1),
64
+ # while <36 is non-expanded (0). Borderline 36–39 can be reduced penetrance but treated as 1 here.
65
+ v = _after_colon(x)
66
+ if v is None or v == '':
67
+ return None
68
+ try:
69
+ n = int(str(v).strip())
70
+ except Exception:
71
+ import re
72
+ m = re.search(r'-?\d+', str(v))
73
+ if not m:
74
+ return None
75
+ try:
76
+ n = int(m.group(0))
77
+ except Exception:
78
+ return None
79
+ return 1 if n >= 36 else 0
80
+
81
+ def convert_age(x):
82
+ # Age not available in this dataset
83
+ return None
84
+
85
+ def convert_gender(x):
86
+ v = _after_colon(x)
87
+ if v is None:
88
+ return None
89
+ v_low = str(v).strip().lower()
90
+ if v_low in {'female', 'f'}:
91
+ return 0
92
+ if v_low in {'male', 'm'}:
93
+ return 1
94
+ return None
95
+
96
+ # Initial filtering and save metadata
97
+ is_trait_available = trait_row is not None
98
+ _ = validate_and_save_cohort_info(
99
+ is_final=False,
100
+ cohort=cohort,
101
+ info_path=json_path,
102
+ is_gene_available=is_gene_available,
103
+ is_trait_available=is_trait_available
104
+ )
105
+
106
+ # Clinical feature extraction if available
107
+ if is_trait_available:
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
+ gender_row=gender_row,
114
+ convert_gender=convert_gender
115
+ )
116
+ preview = preview_df(selected_clinical_df, n=5)
117
+ print(preview)
118
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
119
+ selected_clinical_df.to_csv(out_clinical_data_file)
120
+
121
+ # Step 3: Gene Data Extraction
122
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
123
+ gene_data = get_genetic_data(matrix_file)
124
+
125
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
126
+ print(gene_data.index[:20])
127
+
128
+ # Step 4: Gene Identifier Review
129
+ import re
130
+
131
+ # Given identifiers from the previous step
132
+ gene_ids = ['1007_s_at', '1053_at', '117_at', '121_at', '1255_g_at', '1294_at',
133
+ '1316_at', '1320_at', '1405_i_at', '1431_at', '1438_at', '1487_at',
134
+ '1494_f_at', '1552256_a_at', '1552257_a_at', '1552258_at', '1552261_at',
135
+ '1552263_at', '1552264_a_at', '1552266_at']
136
+
137
+ affy_pattern = re.compile(r'^\d+(_[a-z])?_at$')
138
+ affy_like = sum(bool(affy_pattern.match(x)) for x in gene_ids)
139
+ requires_gene_mapping = affy_like / len(gene_ids) > 0.5
140
+
141
+ print(f"requires_gene_mapping = {requires_gene_mapping}")
142
+
143
+ # Step 5: Gene Annotation
144
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
145
+ gene_annotation = get_gene_annotation(soft_file)
146
+
147
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
148
+ print("Gene annotation preview:")
149
+ print(preview_df(gene_annotation))
150
+
151
+ # Step 6: Gene Identifier Mapping
152
+ # Identify the appropriate columns in the annotation dataframe
153
+ probe_col = 'ID' # Matches probe identifiers in expression data (e.g., '1007_s_at')
154
+ gene_symbol_col = 'Gene Symbol' # Contains human gene symbols
155
+
156
+ # Build mapping dataframe
157
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=probe_col, gene_col=gene_symbol_col)
158
+
159
+ # Apply mapping to convert probe-level expression to gene-level expression
160
+ gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
161
+
162
+ # Step 7: Data Normalization and Linking
163
+ import os
164
+
165
+ # 1. Normalize gene symbols and save gene-level data
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 assessment 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
+ # Cast flags explicitly to native Python bool to avoid JSON serialization issues
181
+ is_gene_available_flag = bool((normalized_gene_data.shape[0] > 0) and (normalized_gene_data.shape[1] > 0))
182
+ is_trait_available_flag = bool((trait in selected_clinical_df.index) and bool(selected_clinical_df.loc[trait].notna().any()))
183
+ is_trait_biased = bool(is_trait_biased)
184
+
185
+ note = ("INFO: Affymetrix probe IDs mapped to gene symbols using SOFT annotation. "
186
+ "Trait (Huntingtons_Disease) derived from HTT CAG repeat length on longer allele (>=36 as 1, else 0). "
187
+ "Age not available; Gender included.")
188
+
189
+ is_usable = validate_and_save_cohort_info(
190
+ is_final=True,
191
+ cohort=cohort,
192
+ info_path=json_path,
193
+ is_gene_available=is_gene_available_flag,
194
+ is_trait_available=is_trait_available_flag,
195
+ is_biased=is_trait_biased,
196
+ df=unbiased_linked_data,
197
+ note=note
198
+ )
199
+
200
+ # 6. Save linked data if usable
201
+ if is_usable:
202
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
203
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Huntingtons_Disease/code/GSE71220.py ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Huntingtons_Disease"
6
+ cohort = "GSE71220"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Huntingtons_Disease"
10
+ in_cohort_dir = "../DATA/GEO/Huntingtons_Disease/GSE71220"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z3/preprocess/Huntingtons_Disease/GSE71220.csv"
14
+ out_gene_data_file = "./output/z3/preprocess/Huntingtons_Disease/gene_data/GSE71220.csv"
15
+ out_clinical_data_file = "./output/z3/preprocess/Huntingtons_Disease/clinical_data/GSE71220.csv"
16
+ json_path = "./output/z3/preprocess/Huntingtons_Disease/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ # 1. Gene Expression Data Availability
40
+ is_gene_available = True # Affymetrix Human Gene 1.1 ST microarray => gene expression data present
41
+
42
+ # 2. Variable Availability and Data Type Conversion
43
+
44
+ # Trait: Huntington's Disease (not present in this COPD/statin dataset)
45
+ trait_row = None # No field corresponds to Huntington's Disease in this dataset
46
+
47
+ # Age
48
+ age_row = 2 # 'age: <number>'
49
+
50
+ # Gender
51
+ gender_row = 3 # 'Sex: M' / 'Sex: F'
52
+
53
+ # Conversion functions
54
+ def _after_colon(x):
55
+ if x is None:
56
+ return None
57
+ if isinstance(x, (int, float)):
58
+ return x
59
+ s = str(x)
60
+ parts = s.split(":", 1)
61
+ return parts[1].strip() if len(parts) > 1 else s.strip()
62
+
63
+ def convert_trait(x):
64
+ # Binary: 1 = Huntington's Disease case, 0 = non-HD (control/other diseases)
65
+ v = _after_colon(x)
66
+ if v is None or v == "" or str(v).lower() in {"na", "nan", "none"}:
67
+ return None
68
+ s = str(v).strip().lower()
69
+ # Positive indicators for Huntington's Disease
70
+ hd_pos = ["huntington", "huntington's", "huntingtons", "hd (huntington", "hd patient"]
71
+ if any(tok in s for tok in hd_pos):
72
+ return 1
73
+ # Negative indicators (controls or other diseases)
74
+ neg_tokens = ["control", "healthy", "no", "normal", "copd", "parkinson", "aml", "statin user", "statin", "y", "n"]
75
+ if any(tok in s for tok in neg_tokens):
76
+ return 0
77
+ return None
78
+
79
+ def convert_age(x):
80
+ v = _after_colon(x)
81
+ if v is None:
82
+ return None
83
+ s = str(v).strip()
84
+ if s.lower() in {"na", "nan", ""}:
85
+ return None
86
+ # Extract numeric part
87
+ try:
88
+ return float(s)
89
+ except Exception:
90
+ # Attempt to extract numbers from strings like "63 years"
91
+ import re
92
+ m = re.search(r"[-+]?\d*\.?\d+", s)
93
+ if m:
94
+ try:
95
+ return float(m.group())
96
+ except Exception:
97
+ return None
98
+ return None
99
+
100
+ def convert_gender(x):
101
+ # Binary: female=0, male=1
102
+ v = _after_colon(x)
103
+ if v is None:
104
+ return None
105
+ s = str(v).strip().lower()
106
+ if s in {"m", "male", "1"}:
107
+ return 1
108
+ if s in {"f", "female", "0"}:
109
+ return 0
110
+ return None
111
+
112
+ # 3. Save Metadata (initial filtering)
113
+ is_trait_available = trait_row is not None
114
+ is_usable = validate_and_save_cohort_info(
115
+ is_final=False,
116
+ cohort=cohort,
117
+ info_path=json_path,
118
+ is_gene_available=is_gene_available,
119
+ is_trait_available=is_trait_available
120
+ )
121
+
122
+ # 4. Clinical Feature Extraction (skip if trait_row is None)
123
+ if trait_row is not None:
124
+ selected_clinical_df = geo_select_clinical_features(
125
+ clinical_df=clinical_data,
126
+ trait=trait,
127
+ trait_row=trait_row,
128
+ convert_trait=convert_trait,
129
+ age_row=age_row,
130
+ convert_age=convert_age,
131
+ gender_row=gender_row,
132
+ convert_gender=convert_gender
133
+ )
134
+ _preview = preview_df(selected_clinical_df, n=5)
135
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
136
+ selected_clinical_df.to_csv(out_clinical_data_file, index=True)
output/preprocess/Huntingtons_Disease/code/GSE95843.py ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Huntingtons_Disease"
6
+ cohort = "GSE95843"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Huntingtons_Disease"
10
+ in_cohort_dir = "../DATA/GEO/Huntingtons_Disease/GSE95843"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z3/preprocess/Huntingtons_Disease/GSE95843.csv"
14
+ out_gene_data_file = "./output/z3/preprocess/Huntingtons_Disease/gene_data/GSE95843.csv"
15
+ out_clinical_data_file = "./output/z3/preprocess/Huntingtons_Disease/clinical_data/GSE95843.csv"
16
+ json_path = "./output/z3/preprocess/Huntingtons_Disease/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ # Determine data availability and define conversion functions
40
+
41
+ # Try to use existing sample_char_dict if available; otherwise, define from provided output
42
+ try:
43
+ sample_char_dict
44
+ except NameError:
45
+ sample_char_dict = {
46
+ 0: [
47
+ 'plasma donor amyloid beta 42 level (pg/ml): 114.56',
48
+ 'plasma donor amyloid beta 42 level (pg/ml): 77.86',
49
+ 'plasma donor amyloid beta 42 level (pg/ml): 126.36',
50
+ 'plasma donor amyloid beta 42 level (pg/ml): 68.18',
51
+ 'plasma donor amyloid beta 42 level (pg/ml): 183.68',
52
+ 'plasma donor amyloid beta 42 level (pg/ml): 122.5',
53
+ 'plasma donor amyloid beta 42 level (pg/ml): 91.48',
54
+ 'plasma donor amyloid beta 42 level (pg/ml): 138.2',
55
+ 'plasma donor amyloid beta 42 level (pg/ml): 189.32',
56
+ 'plasma donor amyloid beta 42 level (pg/ml): 187.22',
57
+ 'plasma donor amyloid beta 42 level (pg/ml): 187.89',
58
+ 'plasma donor amyloid beta 42 level (pg/ml): 157.07',
59
+ 'plasma donor amyloid beta 42 level (pg/ml): 165.57',
60
+ 'plasma donor amyloid beta 42 level (pg/ml): 162.6',
61
+ 'plasma donor amyloid beta 42 level (pg/ml): 44.72',
62
+ 'plasma donor amyloid beta 42 level (pg/ml): 154.49',
63
+ 'plasma donor amyloid beta 42 level (pg/ml): 152.31',
64
+ 'plasma donor amyloid beta 42 level (pg/ml): 184.5',
65
+ 'plasma donor amyloid beta 42 level (pg/ml): 106.86',
66
+ 'plasma donor amyloid beta 42 level (pg/ml): 102.43',
67
+ 'plasma donor amyloid beta 42 level (pg/ml): 69.45',
68
+ 'plasma donor amyloid beta 42 level (pg/ml): 155.02',
69
+ 'plasma donor amyloid beta 42 level (pg/ml): 114.46',
70
+ 'plasma donor amyloid beta 42 level (pg/ml): 146.74',
71
+ 'plasma donor amyloid beta 42 level (pg/ml): 158.9',
72
+ 'plasma donor amyloid beta 42 level (pg/ml): 89.9',
73
+ 'plasma donor amyloid beta 42 level (pg/ml): 130.07',
74
+ 'plasma donor amyloid beta 42 level (pg/ml): 113.48',
75
+ 'plasma donor amyloid beta 42 level (pg/ml): 72.38',
76
+ 'plasma donor amyloid beta 42 level (pg/ml): 146.32'
77
+ ]
78
+ }
79
+
80
+ # 1) Gene expression availability (based on series title/content; not miRNA/methylation)
81
+ is_gene_available = True
82
+
83
+ # 2) Variable availability:
84
+ # Only amyloid-beta levels are present; no HD trait, age, or gender fields.
85
+ trait_row = None
86
+ age_row = None
87
+ gender_row = None
88
+
89
+ # 2.2) Conversion functions
90
+ import re
91
+ from typing import Optional
92
+
93
+ def _after_colon(x):
94
+ if x is None:
95
+ return None
96
+ s = str(x)
97
+ parts = s.split(":", 1)
98
+ return parts[1].strip() if len(parts) > 1 else s.strip()
99
+
100
+ def convert_trait(x) -> Optional[int]:
101
+ v = _after_colon(x)
102
+ if v is None:
103
+ return None
104
+ val = v.lower().strip()
105
+ # Map common case/control or HD annotations to binary
106
+ positives = ['hd', "huntington", "huntington's", 'case', 'patient', 'affected', 'disease', 'yes', 'y', 'positive', 'pos']
107
+ negatives = ['control', 'healthy', 'normal', 'unaffected', 'no', 'n', 'negative', 'neg', 'non-hd', 'non hd', 'wildtype', 'wt']
108
+ if any(p in val for p in positives):
109
+ return 1
110
+ if any(n in val for n in negatives):
111
+ return 0
112
+ return None
113
+
114
+ def convert_age(x) -> Optional[float]:
115
+ v = _after_colon(x)
116
+ if v is None:
117
+ return None
118
+ m = re.search(r'(\d+(\.\d+)?)', v)
119
+ if not m:
120
+ return None
121
+ age = float(m.group(1))
122
+ if 0 < age < 120:
123
+ return age
124
+ return None
125
+
126
+ def convert_gender(x) -> Optional[int]:
127
+ v = _after_colon(x)
128
+ if v is None:
129
+ return None
130
+ val = v.lower().strip()
131
+ if val in ['female', 'f', 'woman', 'girl', 'xx']:
132
+ return 0
133
+ if val in ['male', 'm', 'man', 'boy', 'xy']:
134
+ return 1
135
+ return None
136
+
137
+ # 3) Save metadata (initial filtering)
138
+ is_trait_available = trait_row is not None
139
+ _ = validate_and_save_cohort_info(
140
+ is_final=False,
141
+ cohort=cohort,
142
+ info_path=json_path,
143
+ is_gene_available=is_gene_available,
144
+ is_trait_available=is_trait_available
145
+ )
146
+
147
+ # 4) Clinical Feature Extraction: skipped because trait_row is None
output/preprocess/Huntingtons_Disease/code/TCGA.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Huntingtons_Disease"
6
+
7
+ # Input paths
8
+ tcga_root_dir = "../DATA/TCGA"
9
+
10
+ # Output paths
11
+ out_data_file = "./output/z3/preprocess/Huntingtons_Disease/TCGA.csv"
12
+ out_gene_data_file = "./output/z3/preprocess/Huntingtons_Disease/gene_data/TCGA.csv"
13
+ out_clinical_data_file = "./output/z3/preprocess/Huntingtons_Disease/clinical_data/TCGA.csv"
14
+ json_path = "./output/z3/preprocess/Huntingtons_Disease/cohort_info.json"
15
+
16
+
17
+ # Step 1: Initial Data Loading
18
+ import os
19
+ import pandas as pd
20
+
21
+ # Given subdirectories from instruction
22
+ listed_subdirs = [
23
+ 'TCGA_lower_grade_glioma_and_glioblastoma_(GBMLGG)', 'TCGA_Uterine_Carcinosarcoma_(UCS)',
24
+ 'TCGA_Thyroid_Cancer_(THCA)', 'TCGA_Thymoma_(THYM)', 'TCGA_Testicular_Cancer_(TGCT)',
25
+ 'TCGA_Stomach_Cancer_(STAD)', 'TCGA_Sarcoma_(SARC)', 'TCGA_Rectal_Cancer_(READ)',
26
+ 'TCGA_Prostate_Cancer_(PRAD)', 'TCGA_Pheochromocytoma_Paraganglioma_(PCPG)',
27
+ 'TCGA_Pancreatic_Cancer_(PAAD)', 'TCGA_Ovarian_Cancer_(OV)', 'TCGA_Ocular_melanomas_(UVM)',
28
+ 'TCGA_Mesothelioma_(MESO)', 'TCGA_Melanoma_(SKCM)', 'TCGA_Lung_Squamous_Cell_Carcinoma_(LUSC)',
29
+ 'TCGA_Lung_Cancer_(LUNG)', 'TCGA_Lung_Adenocarcinoma_(LUAD)', 'TCGA_Lower_Grade_Glioma_(LGG)',
30
+ 'TCGA_Liver_Cancer_(LIHC)', 'TCGA_Large_Bcell_Lymphoma_(DLBC)', 'TCGA_Kidney_Papillary_Cell_Carcinoma_(KIRP)',
31
+ 'TCGA_Kidney_Clear_Cell_Carcinoma_(KIRC)', 'TCGA_Kidney_Chromophobe_(KICH)',
32
+ 'TCGA_Head_and_Neck_Cancer_(HNSC)', 'TCGA_Glioblastoma_(GBM)', 'TCGA_Esophageal_Cancer_(ESCA)',
33
+ 'TCGA_Endometrioid_Cancer_(UCEC)', 'TCGA_Colon_and_Rectal_Cancer_(COADREAD)', 'TCGA_Colon_Cancer_(COAD)',
34
+ 'TCGA_Cervical_Cancer_(CESC)', 'TCGA_Breast_Cancer_(BRCA)', 'TCGA_Bladder_Cancer_(BLCA)',
35
+ 'TCGA_Bile_Duct_Cancer_(CHOL)', 'TCGA_Adrenocortical_Cancer_(ACC)', 'TCGA_Acute_Myeloid_Leukemia_(LAML)'
36
+ ]
37
+
38
+ # Try to use actual filesystem listing when possible; otherwise fallback to provided list
39
+ if os.path.isdir(tcga_root_dir):
40
+ fs_subdirs = [d for d in os.listdir(tcga_root_dir) if os.path.isdir(os.path.join(tcga_root_dir, d))]
41
+ else:
42
+ fs_subdirs = listed_subdirs
43
+
44
+ # Attempt to find a TCGA cohort relevant to Huntington's Disease (not a cancer -> likely none)
45
+ trait_synonyms = ["huntington", "huntington's", "huntingtons", "huntington_disease", "hd", "chorea"]
46
+ def normalize_name(s: str) -> str:
47
+ return ''.join(ch.lower() if ch.isalnum() or ch == '_' else ' ' for ch in s)
48
+
49
+ selected_dir = None
50
+ for d in fs_subdirs:
51
+ nd = normalize_name(d)
52
+ if any(sym in nd for sym in trait_synonyms):
53
+ selected_dir = d
54
+ break
55
+
56
+ if selected_dir is None:
57
+ # No appropriate TCGA cohort for Huntington's Disease; mark as unavailable and exit gracefully
58
+ validate_and_save_cohort_info(
59
+ is_final=False,
60
+ cohort="TCGA",
61
+ info_path=json_path,
62
+ is_gene_available=False,
63
+ is_trait_available=False
64
+ )
65
+ print("No suitable TCGA cohort found for Huntington's Disease. Skipping TCGA for this trait.")
66
+ else:
67
+ cohort_dir = os.path.join(tcga_root_dir, selected_dir)
68
+ clinical_path, genetic_path = tcga_get_relevant_filepaths(cohort_dir)
69
+
70
+ # Load dataframes
71
+ clinical_df = pd.read_csv(clinical_path, sep='\t', index_col=0, low_memory=False, compression='infer')
72
+ genetic_df = pd.read_csv(genetic_path, sep='\t', index_col=0, low_memory=False, compression='infer')
73
+
74
+ # Print clinical columns
75
+ print(clinical_df.columns.tolist())
output/preprocess/Huntingtons_Disease/cohort_info.json CHANGED
@@ -1,82 +1 @@
1
- {
2
- "GSE95843": {
3
- "is_usable": false,
4
- "is_gene_available": true,
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
- "GSE71220": {
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
- "GSE34721": {
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": true,
30
- "sample_size": 227
31
- },
32
- "GSE34201": {
33
- "is_usable": true,
34
- "is_gene_available": true,
35
- "is_trait_available": true,
36
- "is_available": true,
37
- "is_biased": false,
38
- "has_age": false,
39
- "has_gender": true,
40
- "sample_size": 72
41
- },
42
- "GSE26927": {
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
- "GSE154141": {
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": 18
61
- },
62
- "GSE135589": {
63
- "is_usable": true,
64
- "is_gene_available": true,
65
- "is_trait_available": true,
66
- "is_available": true,
67
- "is_biased": false,
68
- "has_age": true,
69
- "has_gender": true,
70
- "sample_size": 178
71
- },
72
- "TCGA": {
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": true,
80
- "sample_size": 702
81
- }
82
- }
 
1
+ {"GSE95843": {"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}, "GSE71220": {"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}, "GSE34721": {"is_usable": true, "is_gene_available": true, "is_trait_available": true, "is_available": true, "is_biased": false, "has_age": false, "has_gender": true, "sample_size": 227, "note": "INFO: Affymetrix probe IDs mapped to gene symbols using SOFT annotation. Trait (Huntingtons_Disease) derived from HTT CAG repeat length on longer allele (>=36 as 1, else 0). Age not available; Gender included."}, "GSE34201": {"is_usable": true, "is_gene_available": true, "is_trait_available": true, "is_available": true, "is_biased": false, "has_age": false, "has_gender": true, "sample_size": 72, "note": "INFO: Age not provided; used Gender as covariate only."}, "GSE26927": {"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": 118, "note": "INFO: Trait defined as Huntington's disease vs other neurodegenerative diseases; post-mortem brain tissue; Illumina HumanRef8 v2 platform."}, "GSE135589": {"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": 178, "note": "INFO: Trait coded as Control=0 and preHD/zHD=1. Age corresponds to 'age at year 1'."}, "TCGA": {"is_usable": false, "is_gene_available": false, "is_trait_available": false, "is_available": false, "is_biased": null, "has_age": null, "has_gender": null, "sample_size": null, "note": null}}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
output/preprocess/Hutchinson-Gilford_Progeria_Syndrome/clinical_data/GSE84351.csv CHANGED
@@ -1,3 +1,3 @@
1
- ,Sample_1,Sample_2,Sample_3,Sample_4,Sample_5,Sample_6,Sample_7
2
- Hutchinson-Gilford_Progeria_Syndrome,1.0,0.0,,,,,
3
- Gender,1.0,0.0,,,,,
 
1
+ ,GSM2232606,GSM2232607,GSM2232608,GSM2232609,GSM2232610,GSM2232611,GSM2232612,GSM2232613,GSM2232614,GSM2232615,GSM2232616,GSM2232617,GSM2232618,GSM2232619,GSM2232620,GSM2232621,GSM2232622,GSM2232623,GSM2232624,GSM2232625,GSM2232626,GSM2232627,GSM2232628,GSM2232629,GSM2232630,GSM2232631,GSM2232632,GSM2232633,GSM2232634,GSM2232635,GSM2232636,GSM2232637,GSM2232638,GSM2232639,GSM2232640,GSM2232641,GSM2232642,GSM2232643,GSM2232644,GSM2232645,GSM2232646,GSM2232647,GSM2232648,GSM2232649,GSM2232650,GSM2232651,GSM2232652,GSM2232653,GSM2232654,GSM2232655,GSM2232656,GSM2232657,GSM2232658,GSM2232659
2
+ Hutchinson-Gilford_Progeria_Syndrome,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,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0
3
+ Gender,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,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,,
output/preprocess/Hutchinson-Gilford_Progeria_Syndrome/code/GSE84351.py ADDED
@@ -0,0 +1,348 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Hutchinson-Gilford_Progeria_Syndrome"
6
+ cohort = "GSE84351"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Hutchinson-Gilford_Progeria_Syndrome"
10
+ in_cohort_dir = "../DATA/GEO/Hutchinson-Gilford_Progeria_Syndrome/GSE84351"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z3/preprocess/Hutchinson-Gilford_Progeria_Syndrome/GSE84351.csv"
14
+ out_gene_data_file = "./output/z3/preprocess/Hutchinson-Gilford_Progeria_Syndrome/gene_data/GSE84351.csv"
15
+ out_clinical_data_file = "./output/z3/preprocess/Hutchinson-Gilford_Progeria_Syndrome/clinical_data/GSE84351.csv"
16
+ json_path = "./output/z3/preprocess/Hutchinson-Gilford_Progeria_Syndrome/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ import os
40
+
41
+ # 1. Gene Expression Data Availability
42
+ is_gene_available = True # Affymetrix microarray platform implies gene expression data
43
+
44
+ # 2. Variable Availability and Data Type Conversion
45
+
46
+ # 2.1 Data Availability
47
+ trait_row = 2 # 'condition: Normal' vs 'condition: HGPS'
48
+ age_row = None # No age information in the sample characteristics
49
+ gender_row = 0 # 'Sex: Male', 'Sex: Female', 'Sex: ?'
50
+
51
+ # 2.2 Data Type Conversion
52
+ def _extract_after_colon(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_after_colon(x)
62
+ if v is None:
63
+ return None
64
+ v_low = v.lower()
65
+ # Map HGPS/Progeria/Case/Patient to 1; Normal/Control to 0
66
+ if v_low in {'hgps', 'hutchinson-gilford progeria syndrome', 'progeria', 'affected', 'case', 'patient', 'disease'}:
67
+ return 1
68
+ if v_low in {'normal', 'control', 'wildtype', 'wt', 'unaffected', 'healthy', 'non-hgps'}:
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
+ # Not used since age_row is None; keep for compatibility
77
+ try:
78
+ # Remove common units if present
79
+ v_clean = v.replace('years', '').replace('year', '').replace('yrs', '').replace('yr', '').strip()
80
+ return float(v_clean)
81
+ except Exception:
82
+ return None
83
+
84
+ def convert_gender(x):
85
+ v = _extract_after_colon(x)
86
+ if v is None:
87
+ return None
88
+ v_low = v.lower()
89
+ if v_low in {'female', 'f'}:
90
+ return 0
91
+ if v_low in {'male', 'm'}:
92
+ return 1
93
+ if v_low in {'?', 'unknown', 'na', 'n/a'}:
94
+ return None
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 (only if clinical data is available)
108
+ if trait_row is not None:
109
+ selected_clinical_df = geo_select_clinical_features(
110
+ clinical_df=clinical_data,
111
+ trait=trait,
112
+ trait_row=trait_row,
113
+ convert_trait=convert_trait,
114
+ age_row=age_row,
115
+ convert_age=None,
116
+ gender_row=gender_row,
117
+ convert_gender=convert_gender
118
+ )
119
+ preview = preview_df(selected_clinical_df)
120
+ print(preview)
121
+
122
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
123
+ selected_clinical_df.to_csv(out_clinical_data_file)
124
+
125
+ # Step 3: Gene Data Extraction
126
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
127
+ gene_data = get_genetic_data(matrix_file)
128
+
129
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
130
+ print(gene_data.index[:20])
131
+
132
+ # Step 4: Gene Identifier Review
133
+ requires_gene_mapping = True
134
+ print(f"requires_gene_mapping = {requires_gene_mapping}")
135
+
136
+ # Step 5: Gene Annotation
137
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
138
+ gene_annotation = get_gene_annotation(soft_file)
139
+
140
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
141
+ print("Gene annotation preview:")
142
+ print(preview_df(gene_annotation))
143
+
144
+ # Step 6: Gene Identifier Mapping
145
+ import os
146
+ import re
147
+ import pandas as pd
148
+
149
+ # Preserve the original probe-level data from prior step
150
+ probe_expression_df = gene_data
151
+
152
+ # Try to load a platform (GPL) SOFT annotation if available; fall back to previously loaded gene_annotation
153
+ try:
154
+ soft_files = [f for f in os.listdir(in_cohort_dir) if 'soft' in f.lower()]
155
+ gpl_softs = [os.path.join(in_cohort_dir, f) for f in soft_files if 'gpl' in f.lower()]
156
+ chosen_annot = None
157
+ if gpl_softs:
158
+ try:
159
+ gpl_annotation = get_gene_annotation(gpl_softs[0])
160
+ # Prefer the annotation with more informative columns
161
+ if 'gene_annotation' in locals():
162
+ chosen_annot = gpl_annotation if gpl_annotation.shape[1] >= gene_annotation.shape[1] else gene_annotation
163
+ else:
164
+ chosen_annot = gpl_annotation
165
+ except Exception:
166
+ chosen_annot = gene_annotation if 'gene_annotation' in locals() else None
167
+ else:
168
+ chosen_annot = gene_annotation if 'gene_annotation' in locals() else None
169
+ except Exception:
170
+ chosen_annot = gene_annotation if 'gene_annotation' in locals() else None
171
+
172
+ if chosen_annot is None or not isinstance(chosen_annot, pd.DataFrame) or chosen_annot.empty:
173
+ # As an extreme fallback, proceed without mapping
174
+ print("WARNING: No usable platform annotation found. Proceeding with probe-level data (no mapping).")
175
+ gene_data = probe_expression_df.copy()
176
+ else:
177
+ gene_annotation = chosen_annot
178
+
179
+ # 1) Identify the probe ID column
180
+ if 'ID' in gene_annotation.columns:
181
+ id_col = 'ID'
182
+ else:
183
+ common_id_cols = ['ID_REF', 'PROBE_ID', 'PROBE SET ID', 'PROBE_SET_ID', 'PROBE SET NAME',
184
+ 'PROBESET_ID', 'PROBESETNAME', 'REPORTER_ID']
185
+ id_col = next((c for c in gene_annotation.columns if c in common_id_cols or 'ID' in c.upper()), None)
186
+ if id_col is None:
187
+ # fallback: take the first column as ID if it looks like the probe IDs in expression
188
+ id_col = gene_annotation.columns[0]
189
+
190
+ # 2) Try to find a gene symbol column
191
+ def _norm_col(c: str) -> str:
192
+ return re.sub(r'[^A-Z0-9]+', '', str(c).upper())
193
+
194
+ normalized_map = {_norm_col(c): c for c in gene_annotation.columns}
195
+ preferred_norm_names = [
196
+ 'GENESYMBOL', 'SYMBOL', 'GENE_SYMBOL', 'GENESYMBOLS', 'GENE_SYMBOLS',
197
+ 'GENEASSIGNMENT', 'GENEASSIGNMENTS', 'GENE', 'GENENAME', 'GENE_NAME'
198
+ ]
199
+ gene_col = None
200
+ for norm_name in preferred_norm_names:
201
+ if norm_name in normalized_map:
202
+ gene_col = normalized_map[norm_name]
203
+ break
204
+
205
+ # Heuristic scoring if name-based search failed
206
+ def _score_gene_col(series: pd.Series) -> float:
207
+ s = series.dropna().astype(str)
208
+ if s.empty:
209
+ return 0.0
210
+ sample = s.sample(min(len(s), 5000), random_state=0)
211
+ extracted = sample.map(extract_human_gene_symbols)
212
+ return (extracted.map(lambda lst: len(lst) > 0)).mean()
213
+
214
+ used_symbol_column = False
215
+ used_refseq_fallback = False
216
+
217
+ if gene_col is None:
218
+ candidates = [c for c in gene_annotation.columns if c != id_col]
219
+ if candidates:
220
+ scores = {c: _score_gene_col(gene_annotation[c]) for c in candidates}
221
+ viable = {c: s for c, s in scores.items() if s >= 0.10}
222
+ if len(viable) > 0:
223
+ gene_col = max(viable, key=viable.get)
224
+ used_symbol_column = True
225
+
226
+ # 3) If still no gene symbol column, fall back to RefSeq-like identifiers
227
+ if gene_col is None:
228
+ # Prefer GB_ACC or any column that looks like RefSeq
229
+ refseq_like = [c for c in gene_annotation.columns if _norm_col(c) in {'GBACC', 'REFSEQ', 'REFSEQID', 'REFSEQTRANSCRIPTID'} or 'REFSEQ' in _norm_col(c)]
230
+ if 'GB_ACC' in gene_annotation.columns:
231
+ gene_col = 'GB_ACC'
232
+ elif refseq_like:
233
+ gene_col = refseq_like[0]
234
+ else:
235
+ # As a last resort, use SPOT_ID (genomic range), acknowledging it's not a true gene ID
236
+ gene_col = 'SPOT_ID' if 'SPOT_ID' in gene_annotation.columns else candidates[0] if candidates else gene_annotation.columns[0]
237
+ used_refseq_fallback = True
238
+
239
+ # Build mapping dataframe using the chosen columns
240
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=id_col, gene_col=gene_col)
241
+
242
+ # Remove obviously empty/placeholder entries
243
+ if not mapping_df.empty:
244
+ mapping_df['Gene'] = mapping_df['Gene'].astype(str)
245
+ mapping_df = mapping_df[~mapping_df['Gene'].isin(['', 'nan', 'NaN', 'None'])]
246
+
247
+ # Define a generic mapping function that does not strip non-symbol IDs
248
+ def apply_probe_mapping_generic(expression_df: pd.DataFrame, mapping_df: pd.DataFrame) -> pd.DataFrame:
249
+ mapping_df = mapping_df[mapping_df['ID'].isin(expression_df.index)].copy()
250
+ if mapping_df.empty:
251
+ return pd.DataFrame()
252
+ # Split multi-mapped entries on common delimiters (avoid splitting on underscore)
253
+ delim = r'\s*(?:///|/|;|,|\|)\s*'
254
+ mapping_df['Gene'] = mapping_df['Gene'].astype(str).str.strip()
255
+ mapping_df = mapping_df[mapping_df['Gene'] != '']
256
+ mapping_df['Gene'] = mapping_df['Gene'].str.split(delim)
257
+ mapping_df['num_genes'] = mapping_df['Gene'].apply(lambda lst: len([g for g in lst if g]))
258
+ mapping_df = mapping_df.explode('Gene')
259
+ mapping_df = mapping_df.dropna(subset=['Gene'])
260
+ mapping_df['Gene'] = mapping_df['Gene'].astype(str).str.strip()
261
+ mapping_df = mapping_df[mapping_df['Gene'] != '']
262
+ if mapping_df.empty:
263
+ return pd.DataFrame()
264
+ mapping_df.set_index('ID', inplace=True)
265
+
266
+ merged_df = mapping_df.join(expression_df)
267
+ expr_cols = [col for col in merged_df.columns if col not in ['Gene', 'num_genes']]
268
+ if len(expr_cols) == 0:
269
+ return pd.DataFrame()
270
+ merged_df[expr_cols] = merged_df[expr_cols].div(merged_df['num_genes'].replace(0, 1), axis=0)
271
+ gene_expression_df = merged_df.groupby('Gene')[expr_cols].sum()
272
+ return gene_expression_df
273
+
274
+ # 4) Apply mapping according to the chosen strategy
275
+ if not used_refseq_fallback:
276
+ # Use symbol-extracting helper when we believe we have symbols/gene assignments
277
+ print(f"Using annotation columns -> ID: '{id_col}', Gene symbols: '{gene_col}' (symbol-based mapping)")
278
+ try:
279
+ gene_data_mapped = apply_gene_mapping(expression_df=probe_expression_df, mapping_df=mapping_df)
280
+ except Exception:
281
+ gene_data_mapped = pd.DataFrame()
282
+ else:
283
+ # Use generic mapping with RefSeq or coordinate-based IDs
284
+ print(f"WARNING: No clear gene symbol column found. Falling back to '{gene_col}' as gene identifier.")
285
+ print(f"Using annotation columns -> ID: '{id_col}', Gene IDs: '{gene_col}' (generic mapping)")
286
+ gene_data_mapped = apply_probe_mapping_generic(expression_df=probe_expression_df, mapping_df=mapping_df)
287
+
288
+ # 5) Final fallback if mapping fails
289
+ if gene_data_mapped is None or gene_data_mapped.empty:
290
+ print("WARNING: Mapping produced no gene-level data. Falling back to probe-level measurements.")
291
+ gene_data = probe_expression_df.copy()
292
+ else:
293
+ gene_data = gene_data_mapped
294
+
295
+ # Step 7: Data Normalization and Linking
296
+ import os
297
+
298
+ # 1. Normalize the obtained gene data and save
299
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
300
+
301
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
302
+ normalized_gene_data.to_csv(out_gene_data_file)
303
+
304
+ # 2. Link the clinical and genetic data (fix variable name)
305
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
306
+
307
+ # 3. Handle missing values in the linked data
308
+ linked_data = handle_missing_values(linked_data, trait)
309
+
310
+ # 4. Determine whether the trait and some demographic features are severely biased, and remove biased features.
311
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
312
+
313
+ # Compute availability flags for final validation
314
+ is_gene_available_final = (normalized_gene_data.shape[0] > 0 and normalized_gene_data.shape[1] > 0)
315
+ is_trait_available_final = (trait in selected_clinical_df.index) and (selected_clinical_df.loc[trait].notna().any())
316
+
317
+ # Prepare an informative note
318
+ retained_pct = None
319
+ try:
320
+ retained_pct = (normalized_gene_data.shape[0] / gene_data.shape[0]) if gene_data.shape[0] > 0 else None
321
+ except Exception:
322
+ retained_pct = None
323
+
324
+ if retained_pct is None:
325
+ note = "INFO: Normalization completed; unable to compute retained gene proportion."
326
+ else:
327
+ note = f"INFO: Normalization retained {retained_pct:.2%} of rows after mapping to standardized symbols."
328
+ if retained_pct < 0.05:
329
+ note = ("WARNING: Normalization retained fewer than 5% of rows after symbol mapping; "
330
+ "platform annotation likely used RefSeq/coordinate IDs causing most rows to be dropped. "
331
+ + note)
332
+
333
+ # 5. Conduct quality check and save the cohort information.
334
+ is_usable = validate_and_save_cohort_info(
335
+ is_final=True,
336
+ cohort=cohort,
337
+ info_path=json_path,
338
+ is_gene_available=is_gene_available_final,
339
+ is_trait_available=is_trait_available_final,
340
+ is_biased=is_trait_biased,
341
+ df=unbiased_linked_data,
342
+ note=note
343
+ )
344
+
345
+ # 6. If the linked data is usable, save it as a CSV file to 'out_data_file'.
346
+ if is_usable:
347
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
348
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Hutchinson-Gilford_Progeria_Syndrome/code/GSE84360.py ADDED
@@ -0,0 +1,222 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Hutchinson-Gilford_Progeria_Syndrome"
6
+ cohort = "GSE84360"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Hutchinson-Gilford_Progeria_Syndrome"
10
+ in_cohort_dir = "../DATA/GEO/Hutchinson-Gilford_Progeria_Syndrome/GSE84360"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z3/preprocess/Hutchinson-Gilford_Progeria_Syndrome/GSE84360.csv"
14
+ out_gene_data_file = "./output/z3/preprocess/Hutchinson-Gilford_Progeria_Syndrome/gene_data/GSE84360.csv"
15
+ out_clinical_data_file = "./output/z3/preprocess/Hutchinson-Gilford_Progeria_Syndrome/clinical_data/GSE84360.csv"
16
+ json_path = "./output/z3/preprocess/Hutchinson-Gilford_Progeria_Syndrome/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ # 1) Gene expression data availability
40
+ is_gene_available = True # The series involves patient-derived cells; likely includes gene expression rather than pure miRNA/methylation only.
41
+
42
+ # 2) Variable availability based on the provided Sample Characteristics Dictionary
43
+ # Keys observed:
44
+ # 0: Sex: Male/Female/?
45
+ # 1: cell line: ...
46
+ # 2: condition: Normal/HGPS
47
+ # 3: cell type: ...
48
+ trait_row = 2
49
+ age_row = None
50
+ gender_row = 0
51
+
52
+ # 2.2) Conversion functions
53
+ def _after_colon(val):
54
+ if val is None:
55
+ return None
56
+ s = str(val).strip().strip('"').strip("'")
57
+ if ":" in s:
58
+ s = s.split(":", 1)[1]
59
+ return s.strip()
60
+
61
+ def convert_trait(val):
62
+ v = _after_colon(val)
63
+ if v is None:
64
+ return None
65
+ vl = v.lower()
66
+ # Positive for HGPS cases
67
+ if any(k in vl for k in ["hgps", "hutchinson", "progeria"]):
68
+ return 1
69
+ # Negative for controls
70
+ if vl in ["normal", "control", "wildtype", "wt", "healthy", "unaffected", "non-hgps"]:
71
+ return 0
72
+ return None
73
+
74
+ def convert_age(val):
75
+ v = _after_colon(val)
76
+ if v is None:
77
+ return None
78
+ # Extract numeric component if present
79
+ import re
80
+ m = re.search(r"[-+]?\d*\.?\d+", v)
81
+ if m:
82
+ try:
83
+ return float(m.group())
84
+ except Exception:
85
+ return None
86
+ return None
87
+
88
+ def convert_gender(val):
89
+ v = _after_colon(val)
90
+ if v is None:
91
+ return None
92
+ vl = v.lower()
93
+ if vl in ["male", "m", "man", "boy"]:
94
+ return 1
95
+ if vl in ["female", "f", "woman", "girl"]:
96
+ return 0
97
+ if vl in ["?", "unknown", "na", "n/a", "not available", "undetermined", "u"]:
98
+ return None
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 and save
124
+ preview = preview_df(selected_clinical_df)
125
+ print(preview)
126
+
127
+ import os
128
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
129
+ selected_clinical_df.to_csv(out_clinical_data_file)
130
+
131
+ # Step 3: Gene Data Extraction
132
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
133
+ gene_data = get_genetic_data(matrix_file)
134
+
135
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
136
+ print(gene_data.index[:20])
137
+
138
+ # Step 4: Gene Identifier Review
139
+ requires_gene_mapping = True
140
+ print(f"requires_gene_mapping = {requires_gene_mapping}")
141
+
142
+ # Step 5: Gene Annotation
143
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
144
+ gene_annotation = get_gene_annotation(soft_file)
145
+
146
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
147
+ print("Gene annotation preview:")
148
+ print(preview_df(gene_annotation))
149
+
150
+ # Step 6: Gene Identifier Mapping
151
+ import re
152
+
153
+ # Determine the probe identifier column in the annotation (must match expression row index)
154
+ id_col = 'ID' if 'ID' in gene_annotation.columns else gene_annotation.columns[0]
155
+
156
+ # Identify a column that likely contains human gene symbols using heuristic hits
157
+ def symbol_hit_score(series, sample_n=1000):
158
+ sample = series.dropna().astype(str).head(sample_n)
159
+ hits = sample.map(lambda x: len(extract_human_gene_symbols(x)))
160
+ return int(hits.sum())
161
+
162
+ text_cols = [c for c in gene_annotation.columns if getattr(gene_annotation[c], 'dtype', None) == object]
163
+ best_col = None
164
+ best_score = -1
165
+ for c in text_cols:
166
+ try:
167
+ score = symbol_hit_score(gene_annotation[c])
168
+ except Exception:
169
+ score = -1
170
+ if score > best_score:
171
+ best_score = score
172
+ best_col = c
173
+
174
+ # Prefer explicit symbol-like columns if they exist, otherwise rely on best_col by score
175
+ preferred_order = [c for c in gene_annotation.columns if re.search(r'(symbol|gene.*name|gene)', c, flags=re.I)]
176
+ gene_col = None
177
+ for c in preferred_order:
178
+ if c in text_cols and symbol_hit_score(gene_annotation[c]) > 0:
179
+ gene_col = c
180
+ break
181
+ if gene_col is None and best_score > 0:
182
+ gene_col = best_col
183
+
184
+ print(f"Chosen identifier column (probe/feature IDs): {id_col}")
185
+ print(f"Detected gene symbol column: {gene_col if gene_col is not None else 'None'}")
186
+
187
+ mapped_successfully = False
188
+
189
+ # Attempt 1: map using detected gene symbol column
190
+ if gene_col is not None:
191
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=id_col, gene_col=gene_col)
192
+ mapped_gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
193
+ if mapped_gene_data.shape[0] > 0 and mapped_gene_data.shape[1] == gene_data.shape[1]:
194
+ gene_data = mapped_gene_data
195
+ mapped_successfully = True
196
+ print(f"Mapping succeeded using gene symbol column: {gene_col} "
197
+ f"-> gene-level rows: {gene_data.shape[0]}, samples: {gene_data.shape[1]}")
198
+ else:
199
+ print("WARNING: Mapping via detected gene symbol column produced empty/invalid result.")
200
+
201
+ # Attempt 2 (fallback): try RefSeq accession column (GB_ACC) if present, then extract human symbols
202
+ # Note: Many tiling/region arrays only have accessions or genomic coordinates; this may still fail to yield symbols.
203
+ if not mapped_successfully and 'GB_ACC' in gene_annotation.columns:
204
+ print("Attempting fallback mapping via GB_ACC (RefSeq accessions) -> human symbol extraction.")
205
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=id_col, gene_col='GB_ACC')
206
+ mapped_gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
207
+ if mapped_gene_data.shape[0] > 0 and mapped_gene_data.shape[1] == gene_data.shape[1]:
208
+ gene_data = mapped_gene_data
209
+ mapped_successfully = True
210
+ print(f"Mapping succeeded using GB_ACC fallback -> gene-level rows: {gene_data.shape[0]}, "
211
+ f"samples: {gene_data.shape[1]}")
212
+ else:
213
+ print("WARNING: GB_ACC-based mapping did not yield valid human gene symbols.")
214
+
215
+ # If mapping still failed, raise an error instead of silently keeping probe-level data
216
+ if not mapped_successfully:
217
+ raise RuntimeError(
218
+ "Gene symbol mapping failed: No suitable gene symbol column found in the platform annotation, "
219
+ "and fallback via GB_ACC (RefSeq) did not yield valid symbols. "
220
+ "This platform likely lacks direct gene symbol annotations (e.g., tiling/genome-region array). "
221
+ "Cannot proceed with gene-level analysis."
222
+ )
output/preprocess/Hutchinson-Gilford_Progeria_Syndrome/code/TCGA.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Hutchinson-Gilford_Progeria_Syndrome"
6
+
7
+ # Input paths
8
+ tcga_root_dir = "../DATA/TCGA"
9
+
10
+ # Output paths
11
+ out_data_file = "./output/z3/preprocess/Hutchinson-Gilford_Progeria_Syndrome/TCGA.csv"
12
+ out_gene_data_file = "./output/z3/preprocess/Hutchinson-Gilford_Progeria_Syndrome/gene_data/TCGA.csv"
13
+ out_clinical_data_file = "./output/z3/preprocess/Hutchinson-Gilford_Progeria_Syndrome/clinical_data/TCGA.csv"
14
+ json_path = "./output/z3/preprocess/Hutchinson-Gilford_Progeria_Syndrome/cohort_info.json"
15
+
16
+
17
+ # Step 1: Initial Data Loading
18
+ import os
19
+ import pandas as pd
20
+
21
+ # Identify the most relevant TCGA cohort directory for Hutchinson-Gilford Progeria Syndrome (unlikely in TCGA)
22
+ search_terms = {
23
+ "hutchinson", "gilford", "progeria", "hgps", "progeroid", "lamin a", "lamina", "lmna"
24
+ }
25
+
26
+ selected_dir = None
27
+ try:
28
+ subdirs = [d for d in os.listdir(tcga_root_dir) if os.path.isdir(os.path.join(tcga_root_dir, d))]
29
+ # Score directories by number of matched keywords; choose the highest scoring one
30
+ scored = []
31
+ for d in subdirs:
32
+ dl = d.lower()
33
+ score = sum(1 for t in search_terms if t in dl)
34
+ if score > 0:
35
+ scored.append((score, d))
36
+ if scored:
37
+ scored.sort(key=lambda x: (-x[0], len(x[1])))
38
+ selected_dir = scored[0][1]
39
+ except Exception:
40
+ selected_dir = None
41
+
42
+ if not selected_dir:
43
+ # No suitable TCGA cohort for this trait; record and skip
44
+ _ = validate_and_save_cohort_info(
45
+ is_final=False,
46
+ cohort="TCGA_NoMatchingCohort",
47
+ info_path=json_path,
48
+ is_gene_available=False,
49
+ is_trait_available=False
50
+ )
51
+ else:
52
+ cohort_dir = os.path.join(tcga_root_dir, selected_dir)
53
+ try:
54
+ clinical_file_path, genetic_file_path = tcga_get_relevant_filepaths(cohort_dir)
55
+
56
+ clinical_df = pd.read_csv(clinical_file_path, sep='\t', index_col=0, low_memory=False)
57
+ genetic_df = pd.read_csv(genetic_file_path, sep='\t', index_col=0, low_memory=False)
58
+
59
+ print(list(clinical_df.columns))
60
+ except Exception:
61
+ # If file discovery or loading fails, record and skip
62
+ _ = validate_and_save_cohort_info(
63
+ is_final=False,
64
+ cohort=selected_dir,
65
+ info_path=json_path,
66
+ is_gene_available=False,
67
+ is_trait_available=False
68
+ )
output/preprocess/Hutchinson-Gilford_Progeria_Syndrome/cohort_info.json CHANGED
@@ -1,32 +1 @@
1
- {
2
- "GSE84360": {
3
- "is_usable": false,
4
- "is_gene_available": false,
5
- "is_trait_available": true,
6
- "is_available": false,
7
- "is_biased": null,
8
- "has_age": null,
9
- "has_gender": null,
10
- "sample_size": null
11
- },
12
- "GSE84351": {
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
- "TCGA": {
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
- }
 
1
+ {"GSE84351": {"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: Normalization retained fewer than 5% of rows after symbol mapping; platform annotation likely used RefSeq/coordinate IDs causing most rows to be dropped. INFO: Normalization retained 0.00% of rows after mapping to standardized symbols."}, "TCGA_NoMatchingCohort": {"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}}