Liu-Hy commited on
Commit
fcf7aea
·
verified ·
1 Parent(s): c78bff9

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/Alopecia/code/GSE18876.py +242 -0
  2. output/preprocess/Alopecia/code/GSE66664.py +242 -0
  3. output/preprocess/Alopecia/code/GSE80342.py +200 -0
  4. output/preprocess/Alopecia/code/GSE81071.py +454 -0
  5. output/preprocess/Alopecia/code/TCGA.py +54 -0
  6. output/preprocess/Alzheimers_Disease/GSE117589.csv +0 -0
  7. output/preprocess/Alzheimers_Disease/GSE139384.csv +0 -0
  8. output/preprocess/Alzheimers_Disease/clinical_data/GSE117589.csv +4 -4
  9. output/preprocess/Alzheimers_Disease/clinical_data/GSE122063.csv +1 -1
  10. output/preprocess/Alzheimers_Disease/clinical_data/GSE139384.csv +1 -1
  11. output/preprocess/Alzheimers_Disease/code/GSE109887.py +206 -0
  12. output/preprocess/Alzheimers_Disease/code/GSE117589.py +185 -0
  13. output/preprocess/Alzheimers_Disease/code/GSE122063.py +193 -0
  14. output/preprocess/Alzheimers_Disease/code/GSE132903.py +229 -0
  15. output/preprocess/Alzheimers_Disease/code/GSE137202.py +194 -0
  16. output/preprocess/Alzheimers_Disease/code/GSE139384.py +229 -0
  17. output/preprocess/Alzheimers_Disease/code/GSE167559.py +122 -0
  18. output/preprocess/Alzheimers_Disease/code/GSE185909.py +218 -0
  19. output/preprocess/Alzheimers_Disease/code/GSE214417.py +96 -0
  20. output/preprocess/Alzheimers_Disease/code/GSE243243.py +133 -0
  21. output/preprocess/Alzheimers_Disease/code/TCGA.py +53 -0
  22. output/preprocess/Alzheimers_Disease/cohort_info.json +1 -112
  23. output/preprocess/Alzheimers_Disease/gene_data/GSE117589.csv +0 -0
  24. output/preprocess/Amyotrophic_Lateral_Sclerosis/GSE139384.csv +0 -0
  25. output/preprocess/Amyotrophic_Lateral_Sclerosis/GSE68608.csv +0 -0
  26. output/preprocess/Amyotrophic_Lateral_Sclerosis/clinical_data/GSE118336.csv +2 -2
  27. output/preprocess/Amyotrophic_Lateral_Sclerosis/clinical_data/GSE139384.csv +4 -4
  28. output/preprocess/Amyotrophic_Lateral_Sclerosis/clinical_data/GSE26927.csv +4 -4
  29. output/preprocess/Amyotrophic_Lateral_Sclerosis/clinical_data/GSE68608.csv +2 -2
  30. output/preprocess/Amyotrophic_Lateral_Sclerosis/code/GSE118336.py +254 -0
  31. output/preprocess/Amyotrophic_Lateral_Sclerosis/code/GSE139384.py +213 -0
  32. output/preprocess/Amyotrophic_Lateral_Sclerosis/code/GSE212131.py +221 -0
  33. output/preprocess/Amyotrophic_Lateral_Sclerosis/code/GSE212134.py +139 -0
  34. output/preprocess/Amyotrophic_Lateral_Sclerosis/code/GSE26927.py +214 -0
  35. output/preprocess/Amyotrophic_Lateral_Sclerosis/code/GSE52937.py +112 -0
  36. output/preprocess/Amyotrophic_Lateral_Sclerosis/code/GSE61322.py +145 -0
  37. output/preprocess/Amyotrophic_Lateral_Sclerosis/code/GSE68607.py +209 -0
  38. output/preprocess/Amyotrophic_Lateral_Sclerosis/code/GSE68608.py +195 -0
  39. output/preprocess/Amyotrophic_Lateral_Sclerosis/code/GSE95810.py +143 -0
  40. output/preprocess/Amyotrophic_Lateral_Sclerosis/code/TCGA.py +65 -0
  41. output/preprocess/Amyotrophic_Lateral_Sclerosis/cohort_info.json +1 -112
  42. output/preprocess/Angelman_Syndrome/code/GSE43900.py +79 -0
  43. output/preprocess/Angelman_Syndrome/code/TCGA.py +51 -0
  44. output/preprocess/Angelman_Syndrome/cohort_info.json +1 -22
  45. output/preprocess/Aniridia/clinical_data/GSE137997.csv +4 -4
  46. output/preprocess/Aniridia/code/GSE137996.py +195 -0
  47. output/preprocess/Aniridia/code/GSE137997.py +152 -0
  48. output/preprocess/Aniridia/code/GSE204791.py +198 -0
  49. output/preprocess/Aniridia/code/TCGA.py +73 -0
  50. output/preprocess/Aniridia/cohort_info.json +1 -42
output/preprocess/Alopecia/code/GSE18876.py ADDED
@@ -0,0 +1,242 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Alopecia"
6
+ cohort = "GSE18876"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Alopecia"
10
+ in_cohort_dir = "../DATA/GEO/Alopecia/GSE18876"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z1/preprocess/Alopecia/GSE18876.csv"
14
+ out_gene_data_file = "./output/z1/preprocess/Alopecia/gene_data/GSE18876.csv"
15
+ out_clinical_data_file = "./output/z1/preprocess/Alopecia/clinical_data/GSE18876.csv"
16
+ json_path = "./output/z1/preprocess/Alopecia/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ # Step 1: Determine gene expression availability
40
+ is_gene_available = True # Affymetrix Exon 1.0 ST array indicates mRNA gene expression
41
+
42
+ # Step 2: Variable availability and conversion functions
43
+
44
+ # Availability based on provided sample characteristics
45
+ trait_row = None # Alopecia status not provided per sample
46
+ age_row = 0 # 'age: <value>' is present at row 0
47
+ gender_row = None # All healthy males per background => constant, thus not useful
48
+
49
+ # Conversion functions
50
+ def _extract_value_after_colon(x):
51
+ if x is None:
52
+ return None
53
+ if isinstance(x, str):
54
+ parts = x.split(":", 1)
55
+ val = parts[1].strip() if len(parts) > 1 else x.strip()
56
+ return val
57
+ return x
58
+
59
+ def convert_trait(x):
60
+ # Binary: 1 = alopecia present/AGA/AA; 0 = control/healthy/no alopecia
61
+ val = _extract_value_after_colon(x)
62
+ if val is None:
63
+ return None
64
+ s = str(val).strip().lower()
65
+ if s in {"na", "n/a", "nan", "", "unknown", "not available"}:
66
+ return None
67
+ # Positive indicators
68
+ positive_terms = [
69
+ "alopecia", "androgenetic alopecia", "aga", "aa",
70
+ "pattern hair loss", "male pattern baldness", "baldness",
71
+ "case", "patient", "disease", "affected", "yes", "present"
72
+ ]
73
+ # Negative indicators
74
+ negative_terms = [
75
+ "control", "healthy", "normal", "no alopecia", "none",
76
+ "unaffected", "absent", "no", "non-diseased"
77
+ ]
78
+ for t in positive_terms:
79
+ if t in s:
80
+ return 1
81
+ for t in negative_terms:
82
+ if t in s:
83
+ return 0
84
+ # Heuristic: severity implies presence
85
+ if any(t in s for t in ["mild", "moderate", "severe", "grade", "stage"]):
86
+ return 1
87
+ return None
88
+
89
+ def convert_age(x):
90
+ val = _extract_value_after_colon(x)
91
+ if val is None:
92
+ return None
93
+ s = str(val).strip().lower()
94
+ if s in {"na", "n/a", "nan", "", "unknown", "not available"}:
95
+ return None
96
+ # Extract first integer/float in the string
97
+ num = ""
98
+ dot_seen = False
99
+ for ch in s:
100
+ if ch.isdigit():
101
+ num += ch
102
+ elif ch == "." and not dot_seen:
103
+ num += ch
104
+ dot_seen = True
105
+ elif num:
106
+ break
107
+ if num == "" or num == ".":
108
+ return None
109
+ try:
110
+ v = float(num)
111
+ return int(v) if abs(v - int(v)) < 1e-6 else v
112
+ except Exception:
113
+ return None
114
+
115
+ def convert_gender(x):
116
+ # Binary: female=0, male=1
117
+ val = _extract_value_after_colon(x)
118
+ if val is None:
119
+ return None
120
+ s = str(val).strip().lower()
121
+ if s in {"na", "n/a", "nan", "", "unknown", "not available"}:
122
+ return None
123
+ if s in {"male", "m", "man", "men"}:
124
+ return 1
125
+ if s in {"female", "f", "woman", "women"}:
126
+ return 0
127
+ return None
128
+
129
+ # Step 3: Initial filtering and save metadata
130
+ is_trait_available = trait_row is not None
131
+ _ = validate_and_save_cohort_info(
132
+ is_final=False,
133
+ cohort=cohort,
134
+ info_path=json_path,
135
+ is_gene_available=is_gene_available,
136
+ is_trait_available=is_trait_available
137
+ )
138
+
139
+ # Step 4: Clinical feature extraction (skip if trait_row is None)
140
+ if trait_row is not None and 'clinical_data' in globals():
141
+ selected_clinical_df = geo_select_clinical_features(
142
+ clinical_df=clinical_data,
143
+ trait=trait,
144
+ trait_row=trait_row,
145
+ convert_trait=convert_trait,
146
+ age_row=age_row,
147
+ convert_age=convert_age,
148
+ gender_row=gender_row,
149
+ convert_gender=convert_gender
150
+ )
151
+ _ = preview_df(selected_clinical_df)
152
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
153
+ selected_clinical_df.to_csv(out_clinical_data_file, index=True)
154
+
155
+ # Step 3: Gene Data Extraction
156
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
157
+ gene_data = get_genetic_data(matrix_file)
158
+
159
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
160
+ print(gene_data.index[:20])
161
+
162
+ # Step 4: Gene Identifier Review
163
+ print("requires_gene_mapping = True")
164
+
165
+ # Step 5: Gene Annotation
166
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
167
+ gene_annotation = get_gene_annotation(soft_file)
168
+
169
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
170
+ print("Gene annotation preview:")
171
+ print(preview_df(gene_annotation))
172
+
173
+ # Step 6: Gene Identifier Mapping
174
+ # Decide which columns to use for mapping based on observed identifiers
175
+ probe_col = 'ID' # Probe IDs match the 'ID' column in annotation
176
+
177
+ # Prefer 'gene_assignment' for gene symbols; fallback to 'mrna_assignment' or any column containing 'gene'
178
+ if 'gene_assignment' in gene_annotation.columns:
179
+ gene_col = 'gene_assignment'
180
+ elif 'mrna_assignment' in gene_annotation.columns:
181
+ gene_col = 'mrna_assignment'
182
+ else:
183
+ gene_col = next((c for c in gene_annotation.columns if 'gene' in c.lower()), None)
184
+ if gene_col is None:
185
+ raise ValueError("No suitable gene symbol column found in the annotation.")
186
+
187
+ # Build mapping dataframe (ID -> Gene text)
188
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=probe_col, gene_col=gene_col)
189
+
190
+ # Apply mapping to convert probe-level data to gene-level expression
191
+ gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
192
+
193
+ # Step 7: Data Normalization and Linking
194
+ import os
195
+ import pandas as pd
196
+
197
+ # 1. Normalize gene symbols and save
198
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
199
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
200
+ normalized_gene_data.to_csv(out_gene_data_file)
201
+
202
+ # 2–6. Proceed only if clinical features were extracted earlier; otherwise, skip linking and record metadata accordingly.
203
+ selected_clinical_data_obj = globals().get('selected_clinical_data', None)
204
+ has_clinical = isinstance(selected_clinical_data_obj, pd.DataFrame) and (trait in selected_clinical_data_obj.index)
205
+
206
+ linked_data = None # ensure variable exists as required by the step
207
+
208
+ if has_clinical:
209
+ # 2. Link clinical and genetic data
210
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_data_obj, normalized_gene_data)
211
+
212
+ # 3. Handle missing values
213
+ linked_data = handle_missing_values(linked_data, trait)
214
+
215
+ # 4. Bias checks and removal of biased demographic covariates
216
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
217
+
218
+ # 5. Final quality validation and save cohort info
219
+ is_usable = validate_and_save_cohort_info(
220
+ is_final=True,
221
+ cohort=cohort,
222
+ info_path=json_path,
223
+ is_gene_available=True,
224
+ is_trait_available=True,
225
+ is_biased=is_trait_biased,
226
+ df=unbiased_linked_data,
227
+ note="INFO: Clinical features available and linked; demographics pruned if biased."
228
+ )
229
+
230
+ # 6. Save linked data only if usable
231
+ if is_usable:
232
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
233
+ unbiased_linked_data.to_csv(out_data_file)
234
+ else:
235
+ # Trait is not available per sample; record metadata and do not attempt linking
236
+ _ = validate_and_save_cohort_info(
237
+ is_final=False,
238
+ cohort=cohort,
239
+ info_path=json_path,
240
+ is_gene_available=True,
241
+ is_trait_available=False
242
+ )
output/preprocess/Alopecia/code/GSE66664.py ADDED
@@ -0,0 +1,242 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Alopecia"
6
+ cohort = "GSE66664"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Alopecia"
10
+ in_cohort_dir = "../DATA/GEO/Alopecia/GSE66664"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z1/preprocess/Alopecia/GSE66664.csv"
14
+ out_gene_data_file = "./output/z1/preprocess/Alopecia/gene_data/GSE66664.csv"
15
+ out_clinical_data_file = "./output/z1/preprocess/Alopecia/clinical_data/GSE66664.csv"
16
+ json_path = "./output/z1/preprocess/Alopecia/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ import os
40
+ import re
41
+ import pandas as pd
42
+
43
+ # 1) Gene expression availability
44
+ is_gene_available = True # Transcriptome analysis of DP cells (not miRNA-only or methylation)
45
+
46
+ # 2) Variable availability and converters
47
+ # Based on sample characteristics:
48
+ # 0: ['cell line: BAB', 'cell line: BAN'] -> Use as Alopecia trait (BAB=balding, BAN=non-balding)
49
+ # 1: ['agent: DHT'] -> Constant, not useful
50
+ # 2: ['dose: 10nM', 'dose: 1nM']
51
+ # 3: time points -> Not trait, age, or gender
52
+ trait_row = 0
53
+ age_row = None
54
+ gender_row = None # All samples are male per background; constant feature, thus considered unavailable
55
+
56
+ def _extract_value(x):
57
+ if x is None:
58
+ return None
59
+ s = str(x).strip()
60
+ if ':' in s:
61
+ s = s.split(':', 1)[1].strip()
62
+ return s if s != '' else None
63
+
64
+ def convert_trait(x):
65
+ v = _extract_value(x)
66
+ if v is None:
67
+ return None
68
+ t = v.lower()
69
+ # Normalize to improve robustness when extra descriptors are present
70
+ t = re.sub(r'\b(cell line|dermal papilla|dp)\b', '', t)
71
+ t = t.replace('-', ' ')
72
+ t = re.sub(r'\s+', ' ', t).strip()
73
+ if re.search(r'\bbab\b', t) or 'balding' in t:
74
+ return 1
75
+ if re.search(r'\bban\b', t) or 'non balding' in t or 'nonbald' in t or 'non bald' in t:
76
+ return 0
77
+ return None
78
+
79
+ def convert_age(x):
80
+ v = _extract_value(x)
81
+ if v is None:
82
+ return None
83
+ m = re.search(r'(\d+(?:\.\d+)?)', v)
84
+ if m:
85
+ try:
86
+ return float(m.group(1))
87
+ except Exception:
88
+ return None
89
+ return None
90
+
91
+ def convert_gender(x):
92
+ v = _extract_value(x)
93
+ if v is None:
94
+ return None
95
+ v_low = v.lower()
96
+ if v_low in {'male', 'm', 'man', 'boy'}:
97
+ return 1
98
+ if v_low in {'female', 'f', 'woman', 'girl'}:
99
+ return 0
100
+ return None
101
+
102
+ # 3) Save metadata (initial filtering)
103
+ is_trait_available = trait_row is not None
104
+ _ = validate_and_save_cohort_info(
105
+ is_final=False,
106
+ cohort=cohort,
107
+ info_path=json_path,
108
+ is_gene_available=is_gene_available,
109
+ is_trait_available=is_trait_available
110
+ )
111
+
112
+ # 4) Clinical feature extraction (only if trait 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
+ # Decide mapping columns based on observation:
151
+ # - Probe identifiers in expression data: 'ILMN_...' (matches 'ID' column in annotation)
152
+ # - Gene symbols in annotation: 'Symbol'
153
+ prob_col = 'ID'
154
+ gene_col = 'Symbol'
155
+
156
+ # 2. Build probe-to-gene mapping dataframe
157
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=prob_col, gene_col=gene_col)
158
+
159
+ # 3. Apply mapping to convert probe-level data to gene-level expression
160
+ gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
161
+
162
+ # Step 7: Data Normalization and Linking
163
+ import os
164
+ import pandas as pd
165
+
166
+ # Ensure clinical features are available; load from file if not in scope
167
+ if 'selected_clinical_df' not in globals():
168
+ selected_clinical_df = pd.read_csv(out_clinical_data_file, index_col=0)
169
+
170
+ # 1) Normalize gene symbols; ensure output directory exists before saving
171
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
172
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
173
+ normalized_gene_data.to_csv(out_gene_data_file)
174
+
175
+ # 2) Link clinical and genetic data
176
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
177
+
178
+ # 3) Handle missing values
179
+ linked_data = handle_missing_values(linked_data, trait)
180
+
181
+ # 4) Assess bias; drop biased demographic covariates
182
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
183
+
184
+ # Derive availability flags for final validation (ensure native Python bool)
185
+ is_gene_available = bool((normalized_gene_data.shape[0] > 0) and (normalized_gene_data.shape[1] > 0))
186
+ is_trait_available = bool((trait in selected_clinical_df.index) and selected_clinical_df.loc[trait].notna().any())
187
+ is_trait_biased_py = bool(is_trait_biased)
188
+
189
+ # 5) Final validation and save cohort metadata
190
+ note = ("INFO: DP cell line dataset; trait derived from 'cell line: BAB'(1) vs 'BAN'(0). "
191
+ "Male-only; no age available. DHT dose/time present but not included as covariates.")
192
+
193
+ try:
194
+ is_usable = validate_and_save_cohort_info(
195
+ is_final=True,
196
+ cohort=cohort,
197
+ info_path=json_path,
198
+ is_gene_available=is_gene_available,
199
+ is_trait_available=is_trait_available,
200
+ is_biased=is_trait_biased_py,
201
+ df=unbiased_linked_data,
202
+ note=note
203
+ )
204
+ except TypeError as e:
205
+ # Fallback: manually write metadata if JSON serialization fails
206
+ is_available = bool(is_gene_available and is_trait_available)
207
+ record = {
208
+ "is_usable": bool(is_available and (is_trait_biased_py is False)),
209
+ "is_gene_available": bool(is_gene_available),
210
+ "is_trait_available": bool(is_trait_available),
211
+ "is_available": bool(is_available),
212
+ "is_biased": (bool(is_trait_biased_py) if is_available else None),
213
+ "has_age": (bool('Age' in unbiased_linked_data.columns) if is_available else None),
214
+ "has_gender": (bool('Gender' in unbiased_linked_data.columns) if is_available else None),
215
+ "sample_size": (int(len(unbiased_linked_data)) if is_available else None),
216
+ "note": str(note)
217
+ }
218
+
219
+ # Prepare directory and file
220
+ trait_directory = os.path.dirname(json_path)
221
+ os.makedirs(trait_directory, exist_ok=True)
222
+ if not os.path.exists(json_path):
223
+ with open(json_path, 'w') as file:
224
+ import json
225
+ json.dump({}, file)
226
+
227
+ # Read, update, and write atomically
228
+ import json
229
+ with open(json_path, "r") as file:
230
+ records = json.load(file)
231
+ records[cohort] = record
232
+ temp_path = json_path + ".tmp"
233
+ with open(temp_path, 'w') as file:
234
+ json.dump(records, file)
235
+ os.replace(temp_path, json_path)
236
+
237
+ is_usable = record["is_usable"]
238
+
239
+ # 6) Save linked data if usable
240
+ if is_usable:
241
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
242
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Alopecia/code/GSE80342.py ADDED
@@ -0,0 +1,200 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Alopecia"
6
+ cohort = "GSE80342"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Alopecia"
10
+ in_cohort_dir = "../DATA/GEO/Alopecia/GSE80342"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z1/preprocess/Alopecia/GSE80342.csv"
14
+ out_gene_data_file = "./output/z1/preprocess/Alopecia/gene_data/GSE80342.csv"
15
+ out_clinical_data_file = "./output/z1/preprocess/Alopecia/clinical_data/GSE80342.csv"
16
+ json_path = "./output/z1/preprocess/Alopecia/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 # Microarray gene expression profiling per background info
43
+
44
+ # 2) Variable availability and conversion functions
45
+ # From the sample characteristics dictionary:
46
+ # - trait (Alopecia) can be inferred from 'aatype' at row 7 (healthy_control vs AA subtypes)
47
+ # - age from 'agebaseline' at row 4
48
+ # - gender from 'gender' at row 3
49
+ trait_row = 7
50
+ age_row = 4
51
+ gender_row = 3
52
+
53
+ def convert_trait(x: str):
54
+ # Extract value after colon and map to binary: healthy_control -> 0, AA types -> 1
55
+ if not isinstance(x, str):
56
+ return None
57
+ val = x.split(":", 1)[1].strip().lower() if ":" in x else x.strip().lower()
58
+ if val in {"na", "n/a", "", "unknown"}:
59
+ return None
60
+ # Map AA subtypes to 1
61
+ aa_positive = {"persistent_patchy", "severe_patchy", "totalis", "universalis", "patchy", "alopecia_areata"}
62
+ if val in {"healthy_control", "control", "healthy"}:
63
+ return 0
64
+ if val in aa_positive:
65
+ return 1
66
+ # If it's not explicitly known, apply heuristic: any value containing 'control' -> 0, otherwise 1
67
+ if "control" in val:
68
+ return 0
69
+ # Conservatively assume non-control indicates AA involvement
70
+ return 1
71
+
72
+ def convert_age(x: str):
73
+ # Extract numeric age from 'agebaseline: <number>'
74
+ if not isinstance(x, str):
75
+ return None
76
+ val = x.split(":", 1)[1].strip() if ":" in x else x.strip()
77
+ if val.lower() in {"na", "n/a", "", "unknown"}:
78
+ return None
79
+ m = re.search(r"(\d+(\.\d+)?)", val)
80
+ if not m:
81
+ return None
82
+ try:
83
+ num = float(m.group(1))
84
+ # Return int if it's a whole number
85
+ return int(num) if num.is_integer() else num
86
+ except Exception:
87
+ return None
88
+
89
+ def convert_gender(x: str):
90
+ # Map gender: F->0, M->1
91
+ if not isinstance(x, str):
92
+ return None
93
+ val = x.split(":", 1)[1].strip().lower() if ":" in x else x.strip().lower()
94
+ if val in {"na", "n/a", "", "unknown"}:
95
+ return None
96
+ if val.startswith("f"):
97
+ return 0
98
+ if val.startswith("m"):
99
+ return 1
100
+ return None
101
+
102
+ # 3) Save metadata (initial filtering)
103
+ is_trait_available = trait_row is not None
104
+ _ = validate_and_save_cohort_info(
105
+ is_final=False,
106
+ cohort=cohort,
107
+ info_path=json_path,
108
+ is_gene_available=is_gene_available,
109
+ is_trait_available=is_trait_available
110
+ )
111
+
112
+ # 4) Clinical feature extraction (only if trait data 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 data
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
+ # Affymetrix probe set IDs detected (e.g., '1007_s_at', '1552256_a_at'), not human gene symbols
139
+ requires_gene_mapping = True
140
+ print(f"requires_gene_mapping = {requires_gene_mapping}")
141
+
142
+ # Step 5: Gene Annotation
143
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
144
+ gene_annotation = get_gene_annotation(soft_file)
145
+
146
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
147
+ print("Gene annotation preview:")
148
+ print(preview_df(gene_annotation))
149
+
150
+ # Step 6: Gene Identifier Mapping
151
+ # Identify the appropriate columns for probe IDs and gene symbols
152
+ probe_col = 'ID'
153
+ gene_symbol_col = 'Gene Symbol'
154
+
155
+ # Create the mapping DataFrame from the annotation
156
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=probe_col, gene_col=gene_symbol_col)
157
+
158
+ # Apply the mapping to convert probe-level data to gene-level data
159
+ probe_level_df = gene_data # preserve original probe-level data
160
+ gene_data = apply_gene_mapping(probe_level_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 check and remove 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
+ is_gene_available_final = bool((normalized_gene_data.shape[0] > 0) and (normalized_gene_data.shape[1] > 0))
181
+ is_trait_available_final = bool((trait in linked_data.columns) and bool(linked_data[trait].notna().any()))
182
+ is_trait_biased_bool = bool(is_trait_biased)
183
+
184
+ note = (
185
+ "INFO: "
186
+ f"Samples={int(len(unbiased_linked_data))}, "
187
+ f"Genes={int(sum(col not in [trait, 'Age', 'Gender'] for col in unbiased_linked_data.columns))}, "
188
+ f"Age_included={bool('Age' in unbiased_linked_data.columns)}, "
189
+ f"Gender_included={bool('Gender' in unbiased_linked_data.columns)}."
190
+ )
191
+
192
+ is_usable = validate_and_save_cohort_info(
193
+ True, cohort, json_path, is_gene_available_final, is_trait_available_final,
194
+ is_trait_biased_bool, unbiased_linked_data, note
195
+ )
196
+
197
+ # 6. Save linked data if usable
198
+ if is_usable:
199
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
200
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Alopecia/code/GSE81071.py ADDED
@@ -0,0 +1,454 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Alopecia"
6
+ cohort = "GSE81071"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Alopecia"
10
+ in_cohort_dir = "../DATA/GEO/Alopecia/GSE81071"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z1/preprocess/Alopecia/GSE81071.csv"
14
+ out_gene_data_file = "./output/z1/preprocess/Alopecia/gene_data/GSE81071.csv"
15
+ out_clinical_data_file = "./output/z1/preprocess/Alopecia/clinical_data/GSE81071.csv"
16
+ json_path = "./output/z1/preprocess/Alopecia/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ import re
40
+ import os
41
+ import pandas as pd
42
+
43
+ # 1) Gene expression availability
44
+ is_gene_available = True # Affymetrix mRNA microarrays from FFPE blocks
45
+
46
+ # 2) Variable availability from the provided sample characteristics
47
+ # Sample Characteristics Dictionary indicates only disease state and tissue, no explicit age or gender.
48
+ # Trait here is Alopecia, which is not explicitly recorded; inferring from DLE is unreliable (<90% certainty).
49
+ trait_row = None
50
+ age_row = None
51
+ gender_row = None
52
+
53
+ # 2.2) Converters
54
+ def _after_colon(x: str) -> str:
55
+ if x is None:
56
+ return ""
57
+ parts = str(x).split(":", 1)
58
+ return parts[1].strip() if len(parts) == 2 else str(x).strip()
59
+
60
+ def convert_trait(x):
61
+ # Conservatively only map explicit alopecia indications
62
+ val = _after_colon(x).lower()
63
+ if val in ["", "na", "n/a", "none", "unknown", "not available"]:
64
+ return None
65
+ # Positive indications
66
+ if "alopecia" in val and not ("no alopecia" in val or "without alopecia" in val):
67
+ return 1
68
+ # Explicit negatives
69
+ if "no alopecia" in val or "without alopecia" in val:
70
+ return 0
71
+ # Healthy/control without alopecia info is uncertain -> None
72
+ return None
73
+
74
+ def convert_age(x):
75
+ val = _after_colon(x)
76
+ if not val:
77
+ return None
78
+ m = re.search(r"(\d+(\.\d+)?)", val)
79
+ if m:
80
+ try:
81
+ return float(m.group(1))
82
+ except Exception:
83
+ return None
84
+ return None
85
+
86
+ def convert_gender(x):
87
+ val = _after_colon(x).lower()
88
+ if val in ["", "na", "n/a", "none", "unknown", "not available"]:
89
+ return None
90
+ if val in ["female", "f", "woman", "women"]:
91
+ return 0
92
+ if val in ["male", "m", "man", "men"]:
93
+ return 1
94
+ return None
95
+
96
+ # 3) Initial filtering metadata save
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 (skip if trait not available)
107
+ if trait_row is not None:
108
+ selected_clinical_df = geo_select_clinical_features(
109
+ clinical_df=clinical_data,
110
+ trait=trait,
111
+ trait_row=trait_row,
112
+ convert_trait=convert_trait,
113
+ age_row=age_row,
114
+ convert_age=convert_age,
115
+ gender_row=gender_row,
116
+ convert_gender=convert_gender
117
+ )
118
+ preview = preview_df(selected_clinical_df, n=5)
119
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
120
+ selected_clinical_df.to_csv(out_clinical_data_file, index=True)
121
+
122
+ # Step 3: Gene Data Extraction
123
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
124
+ gene_data = get_genetic_data(matrix_file)
125
+
126
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
127
+ print(gene_data.index[:20])
128
+
129
+ # Step 4: Gene Identifier Review
130
+ requires_gene_mapping = True
131
+ print(f"requires_gene_mapping = {requires_gene_mapping}")
132
+
133
+ # Step 5: Gene Annotation
134
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
135
+ gene_annotation = get_gene_annotation(soft_file)
136
+
137
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
138
+ print("Gene annotation preview:")
139
+ print(preview_df(gene_annotation))
140
+
141
+ # Step 6: Gene Identifier Mapping
142
+ import os
143
+ import re
144
+
145
+ # We will try to map probes to gene symbols using the best available annotation.
146
+ # 1) Try platform (GPL) annotation first for a SYMBOL-like column.
147
+ # 2) Fallback to series-level annotation for symbol columns.
148
+ # 3) If no symbol column works, map to Entrez IDs explicitly without using extract_human_gene_symbols.
149
+ # 4) If all fail, keep probe-level data and warn.
150
+
151
+ probe_col = 'ID' # Matches gene_data index name after get_genetic_data()
152
+
153
+ def find_symbol_column(df):
154
+ cols = list(df.columns)
155
+ # Direct symbol column candidates
156
+ direct_candidates = [
157
+ 'SYMBOL', 'Gene Symbol', 'GENE_SYMBOL', 'GENE SYMBOL', 'Symbol', 'gene_symbol',
158
+ 'Gene symbol', 'gene symbols', 'GENE_SYMBOLS', 'Gene Symbols'
159
+ ]
160
+ for cand in direct_candidates:
161
+ if cand in cols:
162
+ return cand
163
+ # Regex-based search for 'gene symbol' variants
164
+ regexes = [
165
+ r'^\s*gene\s*symbol\s*$',
166
+ r'^\s*symbol\s*$',
167
+ r'^\s*gene\s*symbols?\s*$',
168
+ r'associated\s*gene\s*symbol'
169
+ ]
170
+ for c in cols:
171
+ for pat in regexes:
172
+ if re.search(pat, c, flags=re.IGNORECASE):
173
+ return c
174
+ # Fallbacks that often contain symbol-like strings
175
+ fallbacks = [
176
+ 'GENE_ASSIGNMENT', 'Gene Assignment', 'Gene assignment',
177
+ 'GENE_TITLE', 'Gene Title', 'Gene title',
178
+ 'Representative Public ID', 'REPRESENTATIVE_PUBLIC_ID'
179
+ ]
180
+ for fb in fallbacks:
181
+ if fb in cols:
182
+ return fb
183
+ return None
184
+
185
+ def map_by_entrez(expression_df, anno_df, prob_col='ID', entrez_col='ENTREZ_GENE_ID'):
186
+ if (prob_col not in anno_df.columns) or (entrez_col not in anno_df.columns):
187
+ return None
188
+ m = anno_df.loc[:, [prob_col, entrez_col]].dropna()
189
+ if m.empty:
190
+ return None
191
+ m = m.rename(columns={prob_col: 'ID', entrez_col: 'Entrez'})
192
+ m['ID'] = m['ID'].astype(str).str.strip()
193
+ m = m[m['ID'] != '']
194
+ # Keep only probes present in expression data
195
+ m = m[m['ID'].isin(expression_df.index)]
196
+ if m.empty:
197
+ return None
198
+
199
+ def split_entrez(x):
200
+ if x is None:
201
+ return []
202
+ s = str(x)
203
+ s = s.replace('///', ';')
204
+ parts = re.split(r'[;,\s]+', s)
205
+ parts = [p for p in parts if re.fullmatch(r'\d+', p)]
206
+ return parts
207
+
208
+ m['Gene'] = m['Entrez'].map(split_entrez)
209
+ m['num_genes'] = m['Gene'].apply(len)
210
+ m = m.explode('Gene').dropna(subset=['Gene'])
211
+ if m.empty:
212
+ return None
213
+ m = m.set_index('ID')
214
+
215
+ merged = m.join(expression_df)
216
+ expr_cols = [c for c in merged.columns if c not in ['Gene', 'num_genes', 'Entrez']]
217
+ if not expr_cols:
218
+ return None
219
+ merged[expr_cols] = merged[expr_cols].div(merged['num_genes'].replace(0, 1), axis=0)
220
+ gene_expression = merged.groupby('Gene')[expr_cols].sum()
221
+ if gene_expression.empty:
222
+ return None
223
+ return gene_expression
224
+
225
+ # Build annotation sources: platform first (if available), then series-level annotation
226
+ annotation_sources = []
227
+
228
+ # Search recursively for GPL files (gzipped) in the cohort directory
229
+ try:
230
+ gpl_paths = []
231
+ for root, _, files in os.walk(in_cohort_dir):
232
+ for f in files:
233
+ fl = f.lower()
234
+ if ('gpl' in fl) and (f.endswith('.gz')): # prioritize gz which get_gene_annotation can read
235
+ gpl_paths.append(os.path.join(root, f))
236
+ # Add platform annotations first
237
+ for p in sorted(gpl_paths):
238
+ try:
239
+ gpl_anno = get_gene_annotation(p)
240
+ annotation_sources.append(('platform_soft', gpl_anno))
241
+ except Exception:
242
+ continue
243
+ except Exception:
244
+ pass
245
+
246
+ # Add the series-level annotation as fallback
247
+ annotation_sources.append(('series_soft', gene_annotation))
248
+
249
+ mapped = False
250
+
251
+ # Try symbol-based mapping first
252
+ for src_name, anno_df in annotation_sources:
253
+ try:
254
+ gene_col = find_symbol_column(anno_df)
255
+ if gene_col is None:
256
+ continue
257
+ mapping_df = get_gene_mapping(anno_df, prob_col=probe_col, gene_col=gene_col)
258
+ if mapping_df.empty:
259
+ continue
260
+ # Map probes to symbols
261
+ candidate_gene_data = apply_gene_mapping(gene_data, mapping_df)
262
+ if candidate_gene_data is not None and candidate_gene_data.shape[0] > 0:
263
+ gene_data = candidate_gene_data
264
+ print(f"Gene mapping to SYMBOLs successful using source='{src_name}', "
265
+ f"probe_col='{probe_col}', gene_col='{gene_col}'. "
266
+ f"Mapped genes: {gene_data.shape[0]}")
267
+ mapped = True
268
+ break
269
+ except Exception:
270
+ continue
271
+
272
+ # If symbol mapping failed, try Entrez-based mapping explicitly
273
+ if not mapped:
274
+ for src_name, anno_df in annotation_sources:
275
+ try:
276
+ if 'ENTREZ_GENE_ID' not in anno_df.columns:
277
+ continue
278
+ candidate_gene_data = map_by_entrez(gene_data, anno_df, prob_col=probe_col, entrez_col='ENTREZ_GENE_ID')
279
+ if candidate_gene_data is not None and candidate_gene_data.shape[0] > 0:
280
+ gene_data = candidate_gene_data
281
+ print(f"Gene mapping to Entrez IDs successful using source='{src_name}', "
282
+ f"probe_col='{probe_col}', gene_col='ENTREZ_GENE_ID'. "
283
+ f"Mapped genes: {gene_data.shape[0]}")
284
+ mapped = True
285
+ break
286
+ except Exception:
287
+ continue
288
+
289
+ # If both strategies fail, retain probe-level expression
290
+ if not mapped:
291
+ print("WARNING: Failed to map probes to gene symbols or Entrez IDs. "
292
+ "Proceeding with probe-level expression data.")
293
+
294
+ # Step 7: Data Normalization and Linking
295
+ import os
296
+ import re
297
+ import pandas as pd
298
+
299
+ # Helper to find a plausible SYMBOL column
300
+ def _find_symbol_col(cols):
301
+ priority = [
302
+ 'SYMBOL', 'Gene Symbol', 'GENE_SYMBOL', 'GENE SYMBOL', 'Symbol',
303
+ 'gene_symbol', 'Gene symbol', 'GENE_SYMBOLS', 'Gene Symbols'
304
+ ]
305
+ for c in priority:
306
+ if c in cols:
307
+ return c
308
+ # Regex fallback
309
+ for c in cols:
310
+ if re.search(r'\bsymbols?\b', c, flags=re.IGNORECASE):
311
+ return c
312
+ return None
313
+
314
+ # Build Entrez->Symbol mapping from any available annotation (GPL preferred, then series-level)
315
+ entrez_to_symbol = {}
316
+ annotation_sources = []
317
+
318
+ # Try to load GPL annotations
319
+ try:
320
+ gpl_paths = []
321
+ for root, _, files in os.walk(in_cohort_dir):
322
+ for f in files:
323
+ fl = f.lower()
324
+ if ('gpl' in fl) and f.endswith('.gz'):
325
+ gpl_paths.append(os.path.join(root, f))
326
+ for p in sorted(gpl_paths):
327
+ try:
328
+ gpl_anno = get_gene_annotation(p)
329
+ annotation_sources.append(('platform_soft', gpl_anno))
330
+ except Exception:
331
+ continue
332
+ except Exception:
333
+ pass
334
+
335
+ # Add previously loaded series-level annotation as fallback (from Step 5)
336
+ if 'gene_annotation' in locals():
337
+ annotation_sources.append(('series_soft', gene_annotation))
338
+
339
+ def _split_list_field(x):
340
+ if x is None:
341
+ return []
342
+ s = str(x)
343
+ # Common delimiters in GEO/GPL annotations
344
+ s = s.replace('///', ';')
345
+ parts = re.split(r'[;,/|\s]+', s)
346
+ parts = [p for p in parts if p] # non-empty
347
+ return parts
348
+
349
+ # Construct mapping
350
+ for src_name, anno_df in annotation_sources:
351
+ try:
352
+ if 'ENTREZ_GENE_ID' not in anno_df.columns:
353
+ continue
354
+ sym_col = _find_symbol_col(anno_df.columns)
355
+ if sym_col is None:
356
+ continue
357
+ sub = anno_df[['ENTREZ_GENE_ID', sym_col]].dropna()
358
+ if sub.empty:
359
+ continue
360
+ for _, row in sub.iterrows():
361
+ entrez_list = [p for p in _split_list_field(row['ENTREZ_GENE_ID']) if re.fullmatch(r'\d+', p)]
362
+ sym_list = _split_list_field(row[sym_col])
363
+ # Choose the first plausible gene symbol token
364
+ sym = None
365
+ for token in sym_list:
366
+ tok = token.strip()
367
+ # Basic sanity: uppercase letters/digits/dash or C#orf#
368
+ if re.fullmatch(r"(?:[A-Z][A-Z0-9-]{0,9}|C\d+orf\d+)", tok):
369
+ sym = tok
370
+ break
371
+ if sym is None and sym_list:
372
+ sym = sym_list[0].strip() # fallback to first token
373
+ if sym:
374
+ for e in entrez_list:
375
+ if e not in entrez_to_symbol:
376
+ entrez_to_symbol[e] = sym
377
+ # If we built a decent mapping, we can stop early
378
+ if len(entrez_to_symbol) > 0:
379
+ break
380
+ except Exception:
381
+ continue
382
+
383
+ # 1) Normalize to gene symbols if possible, then apply synonym normalization; otherwise keep Entrez IDs
384
+ normalized_gene_data = None
385
+ note_parts = []
386
+ try:
387
+ if len(entrez_to_symbol) > 0:
388
+ # Map current Entrez-indexed expression to SYMBOLs
389
+ mapped_index = gene_data.index.to_series().map(lambda x: entrez_to_symbol.get(str(x)))
390
+ symbol_gene_data = gene_data.copy()
391
+ symbol_gene_data.index = mapped_index
392
+ symbol_gene_data = symbol_gene_data[symbol_gene_data.index.notnull()]
393
+ if len(symbol_gene_data) > 0:
394
+ # Aggregate duplicates and normalize using synonym dictionary
395
+ symbol_gene_data = symbol_gene_data.groupby(symbol_gene_data.index).sum()
396
+ candidate = normalize_gene_symbols_in_index(symbol_gene_data)
397
+ if candidate is not None and len(candidate) > 0:
398
+ normalized_gene_data = candidate
399
+ note_parts.append("Mapped Entrez->SYMBOL using available annotation and normalized symbols via NCBI synonym dictionary.")
400
+ else:
401
+ note_parts.append("SYMBOL normalization produced empty matrix; falling back to Entrez-indexed matrix.")
402
+ else:
403
+ note_parts.append("No SYMBOLs obtained from Entrez mapping; falling back to Entrez-indexed matrix.")
404
+ else:
405
+ note_parts.append("No SYMBOL column available in annotation; kept Entrez-indexed matrix.")
406
+ except Exception as e:
407
+ note_parts.append(f"Symbol normalization failed with error: {e}; kept Entrez-indexed matrix.")
408
+
409
+ # Choose the gene matrix to save
410
+ gene_matrix_to_save = normalized_gene_data if normalized_gene_data is not None else gene_data
411
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
412
+ gene_matrix_to_save.to_csv(out_gene_data_file)
413
+
414
+ # 2-6) Linking and downstream steps should proceed only if trait data is available
415
+ if 'selected_clinical_data' in locals():
416
+ # 2. Link clinical and genetic data
417
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_data, gene_matrix_to_save)
418
+
419
+ # 3. Handle missing values
420
+ linked_data = handle_missing_values(linked_data, trait)
421
+
422
+ # 4. Check bias and remove biased demographics
423
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
424
+
425
+ # 5. Final validation and metadata save
426
+ note = "INFO: " + " ".join(note_parts) if note_parts else "INFO: Standard preprocessing completed."
427
+ is_usable = validate_and_save_cohort_info(
428
+ is_final=True,
429
+ cohort=cohort,
430
+ info_path=json_path,
431
+ is_gene_available=True,
432
+ is_trait_available=True,
433
+ is_biased=is_trait_biased,
434
+ df=unbiased_linked_data,
435
+ note=note
436
+ )
437
+
438
+ # 6. Save linked data if usable
439
+ if is_usable:
440
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
441
+ unbiased_linked_data.to_csv(out_data_file)
442
+ else:
443
+ # Trait not available; record final metadata with a note, no linking performed
444
+ note = "INFO: Trait not available; skipped linking and QC. " + (" ".join(note_parts) if note_parts else "")
445
+ _ = validate_and_save_cohort_info(
446
+ is_final=True,
447
+ cohort=cohort,
448
+ info_path=json_path,
449
+ is_gene_available=True,
450
+ is_trait_available=False,
451
+ is_biased=False, # placeholder; will be recorded as None since data is not available
452
+ df=gene_matrix_to_save,
453
+ note=note
454
+ )
output/preprocess/Alopecia/code/TCGA.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Alopecia"
6
+
7
+ # Input paths
8
+ tcga_root_dir = "../DATA/TCGA"
9
+
10
+ # Output paths
11
+ out_data_file = "./output/z1/preprocess/Alopecia/TCGA.csv"
12
+ out_gene_data_file = "./output/z1/preprocess/Alopecia/gene_data/TCGA.csv"
13
+ out_clinical_data_file = "./output/z1/preprocess/Alopecia/clinical_data/TCGA.csv"
14
+ json_path = "./output/z1/preprocess/Alopecia/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 the trait "Alopecia"
22
+ subdirs = [d for d in os.listdir(tcga_root_dir) if os.path.isdir(os.path.join(tcga_root_dir, d))]
23
+ trait_terms = ['alopecia', 'hair', 'hairloss', 'hair_loss', 'hypotrich', 'atrich', 'trichotillomania']
24
+ selected_subdir = None
25
+ for d in subdirs:
26
+ name_l = d.lower()
27
+ if any(term in name_l for term in trait_terms):
28
+ selected_subdir = d
29
+ break
30
+
31
+ clinical_df = None
32
+ genetic_df = None
33
+
34
+ if selected_subdir is None:
35
+ # No suitable cohort found for Alopecia in TCGA; record and skip further processing.
36
+ validate_and_save_cohort_info(
37
+ is_final=False,
38
+ cohort="TCGA",
39
+ info_path=json_path,
40
+ is_gene_available=False,
41
+ is_trait_available=False
42
+ )
43
+ print("No suitable TCGA cohort found for the trait; skipping.")
44
+ else:
45
+ # Step 2: Locate clinicalMatrix and PANCAN files within the selected cohort directory
46
+ cohort_dir = os.path.join(tcga_root_dir, selected_subdir)
47
+ clinical_path, genetic_path = tcga_get_relevant_filepaths(cohort_dir)
48
+
49
+ # Step 3: Load both files into DataFrames
50
+ clinical_df = pd.read_csv(clinical_path, sep='\t', index_col=0, low_memory=False)
51
+ genetic_df = pd.read_csv(genetic_path, sep='\t', index_col=0, low_memory=False)
52
+
53
+ # Step 4: Print clinical column names
54
+ print(clinical_df.columns.tolist())
output/preprocess/Alzheimers_Disease/GSE117589.csv ADDED
The diff for this file is too large to render. See raw diff
 
output/preprocess/Alzheimers_Disease/GSE139384.csv CHANGED
The diff for this file is too large to render. See raw diff
 
output/preprocess/Alzheimers_Disease/clinical_data/GSE117589.csv CHANGED
@@ -1,4 +1,4 @@
1
- GSM3304268,GSM3304269,GSM3304270,GSM3304271,GSM3304272,GSM3304273,GSM3304274,GSM3304275,GSM3304276,GSM3304277,GSM3304278,GSM3304279,GSM3304280,GSM3304281,GSM3304282,GSM3304283,GSM3304284,GSM3304285,GSM3304286,GSM3304287,GSM3304288,GSM3304289,GSM3304290,GSM3304291,GSM3304292,GSM3304293,GSM3304294,GSM3304295,GSM3304296,GSM3304297,GSM3304298
2
- 0.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,1.0
3
- 60.0,64.0,72.0,73.0,75.0,92.0,60.0,69.0,72.0,87.0,60.0,64.0,72.0,73.0,75.0,92.0,60.0,60.0,69.0,72.0,87.0,60.0,64.0,72.0,73.0,92.0,60.0,60.0,69.0,72.0,87.0
4
- 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,1.0,0.0,0.0,0.0,1.0,0.0,1.0,0.0,0.0,1.0,1.0,1.0,0.0,0.0,1.0,0.0,1.0,0.0
 
1
+ ,GSM3304268,GSM3304269,GSM3304270,GSM3304271,GSM3304272,GSM3304273,GSM3304274,GSM3304275,GSM3304276,GSM3304277,GSM3304278,GSM3304279,GSM3304280,GSM3304281,GSM3304282,GSM3304283,GSM3304284,GSM3304285,GSM3304286,GSM3304287,GSM3304288,GSM3304289,GSM3304290,GSM3304291,GSM3304292,GSM3304293,GSM3304294,GSM3304295,GSM3304296,GSM3304297,GSM3304298
2
+ Alzheimers_Disease,0.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,1.0
3
+ Age,60.0,64.0,72.0,73.0,75.0,92.0,60.0,69.0,72.0,87.0,60.0,64.0,72.0,73.0,75.0,92.0,60.0,60.0,69.0,72.0,87.0,60.0,64.0,72.0,73.0,92.0,60.0,60.0,69.0,72.0,87.0
4
+ Gender,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,1.0,0.0,0.0,0.0,1.0,0.0,1.0,0.0,0.0,1.0,1.0,1.0,0.0,0.0,1.0,0.0,1.0,0.0
output/preprocess/Alzheimers_Disease/clinical_data/GSE122063.csv CHANGED
@@ -1,4 +1,4 @@
1
  ,GSM3454053,GSM3454054,GSM3454055,GSM3454056,GSM3454057,GSM3454058,GSM3454059,GSM3454060,GSM3454061,GSM3454062,GSM3454063,GSM3454064,GSM3454065,GSM3454066,GSM3454067,GSM3454068,GSM3454069,GSM3454070,GSM3454071,GSM3454072,GSM3454073,GSM3454074,GSM3454075,GSM3454076,GSM3454077,GSM3454078,GSM3454079,GSM3454080,GSM3454081,GSM3454082,GSM3454083,GSM3454084,GSM3454085,GSM3454086,GSM3454087,GSM3454088,GSM3454089,GSM3454090,GSM3454091,GSM3454092,GSM3454093,GSM3454094,GSM3454095,GSM3454096,GSM3454097,GSM3454098,GSM3454099,GSM3454100,GSM3454101,GSM3454102,GSM3454103,GSM3454104,GSM3454105,GSM3454106,GSM3454107,GSM3454108,GSM3454109,GSM3454110,GSM3454111,GSM3454112,GSM3454113,GSM3454114,GSM3454115,GSM3454116,GSM3454117,GSM3454118,GSM3454119,GSM3454120,GSM3454121,GSM3454122,GSM3454123,GSM3454124,GSM3454125,GSM3454126,GSM3454127,GSM3454128,GSM3454129,GSM3454130,GSM3454131,GSM3454132,GSM3454133,GSM3454134,GSM3454135,GSM3454136,GSM3454137,GSM3454138,GSM3454139,GSM3454140,GSM3454141,GSM3454142,GSM3454143,GSM3454144,GSM3454145,GSM3454146,GSM3454147,GSM3454148,GSM3454149,GSM3454150,GSM3454151,GSM3454152,GSM3454153,GSM3454154,GSM3454155,GSM3454156,GSM3454157,GSM3454158,GSM3454159,GSM3454160,GSM3454161,GSM3454162,GSM3454163,GSM3454164,GSM3454165,GSM3454166,GSM3454167,GSM3454168,GSM3454169,GSM3454170,GSM3454171,GSM3454172,GSM3454173,GSM3454174,GSM3454175,GSM3454176,GSM3454177,GSM3454178,GSM3454179,GSM3454180,GSM3454181,GSM3454182,GSM3454183,GSM3454184,GSM3454185,GSM3454186,GSM3454187,GSM3454188
2
- Alzheimers_Disease,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,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
3
  Age,75.0,75.0,75.0,75.0,75.0,75.0,75.0,75.0,90.0,90.0,90.0,90.0,78.0,78.0,78.0,78.0,82.0,82.0,82.0,82.0,96.0,96.0,96.0,96.0,77.0,77.0,77.0,77.0,93.0,93.0,93.0,93.0,62.0,62.0,62.0,62.0,82.0,82.0,82.0,82.0,82.0,82.0,82.0,82.0,89.0,89.0,89.0,89.0,82.0,82.0,82.0,82.0,77.0,77.0,77.0,77.0,79.0,79.0,79.0,79.0,81.0,81.0,81.0,81.0,81.0,81.0,81.0,81.0,75.0,75.0,75.0,75.0,81.0,81.0,81.0,81.0,91.0,91.0,91.0,91.0,83.0,83.0,83.0,83.0,63.0,63.0,63.0,63.0,88.0,88.0,88.0,88.0,74.0,74.0,74.0,74.0,73.0,73.0,73.0,73.0,87.0,87.0,87.0,87.0,73.0,73.0,73.0,73.0,81.0,81.0,81.0,81.0,81.0,81.0,81.0,81.0,60.0,60.0,60.0,60.0,91.0,91.0,91.0,91.0,81.0,81.0,81.0,81.0,77.0,77.0,77.0,77.0,89.0,89.0,89.0,89.0
4
  Gender,1.0,1.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,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,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,0.0,0.0,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,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0
 
1
  ,GSM3454053,GSM3454054,GSM3454055,GSM3454056,GSM3454057,GSM3454058,GSM3454059,GSM3454060,GSM3454061,GSM3454062,GSM3454063,GSM3454064,GSM3454065,GSM3454066,GSM3454067,GSM3454068,GSM3454069,GSM3454070,GSM3454071,GSM3454072,GSM3454073,GSM3454074,GSM3454075,GSM3454076,GSM3454077,GSM3454078,GSM3454079,GSM3454080,GSM3454081,GSM3454082,GSM3454083,GSM3454084,GSM3454085,GSM3454086,GSM3454087,GSM3454088,GSM3454089,GSM3454090,GSM3454091,GSM3454092,GSM3454093,GSM3454094,GSM3454095,GSM3454096,GSM3454097,GSM3454098,GSM3454099,GSM3454100,GSM3454101,GSM3454102,GSM3454103,GSM3454104,GSM3454105,GSM3454106,GSM3454107,GSM3454108,GSM3454109,GSM3454110,GSM3454111,GSM3454112,GSM3454113,GSM3454114,GSM3454115,GSM3454116,GSM3454117,GSM3454118,GSM3454119,GSM3454120,GSM3454121,GSM3454122,GSM3454123,GSM3454124,GSM3454125,GSM3454126,GSM3454127,GSM3454128,GSM3454129,GSM3454130,GSM3454131,GSM3454132,GSM3454133,GSM3454134,GSM3454135,GSM3454136,GSM3454137,GSM3454138,GSM3454139,GSM3454140,GSM3454141,GSM3454142,GSM3454143,GSM3454144,GSM3454145,GSM3454146,GSM3454147,GSM3454148,GSM3454149,GSM3454150,GSM3454151,GSM3454152,GSM3454153,GSM3454154,GSM3454155,GSM3454156,GSM3454157,GSM3454158,GSM3454159,GSM3454160,GSM3454161,GSM3454162,GSM3454163,GSM3454164,GSM3454165,GSM3454166,GSM3454167,GSM3454168,GSM3454169,GSM3454170,GSM3454171,GSM3454172,GSM3454173,GSM3454174,GSM3454175,GSM3454176,GSM3454177,GSM3454178,GSM3454179,GSM3454180,GSM3454181,GSM3454182,GSM3454183,GSM3454184,GSM3454185,GSM3454186,GSM3454187,GSM3454188
2
+ Alzheimers_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,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,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
3
  Age,75.0,75.0,75.0,75.0,75.0,75.0,75.0,75.0,90.0,90.0,90.0,90.0,78.0,78.0,78.0,78.0,82.0,82.0,82.0,82.0,96.0,96.0,96.0,96.0,77.0,77.0,77.0,77.0,93.0,93.0,93.0,93.0,62.0,62.0,62.0,62.0,82.0,82.0,82.0,82.0,82.0,82.0,82.0,82.0,89.0,89.0,89.0,89.0,82.0,82.0,82.0,82.0,77.0,77.0,77.0,77.0,79.0,79.0,79.0,79.0,81.0,81.0,81.0,81.0,81.0,81.0,81.0,81.0,75.0,75.0,75.0,75.0,81.0,81.0,81.0,81.0,91.0,91.0,91.0,91.0,83.0,83.0,83.0,83.0,63.0,63.0,63.0,63.0,88.0,88.0,88.0,88.0,74.0,74.0,74.0,74.0,73.0,73.0,73.0,73.0,87.0,87.0,87.0,87.0,73.0,73.0,73.0,73.0,81.0,81.0,81.0,81.0,81.0,81.0,81.0,81.0,60.0,60.0,60.0,60.0,91.0,91.0,91.0,91.0,81.0,81.0,81.0,81.0,77.0,77.0,77.0,77.0,89.0,89.0,89.0,89.0
4
  Gender,1.0,1.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,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,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,0.0,0.0,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,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0
output/preprocess/Alzheimers_Disease/clinical_data/GSE139384.csv CHANGED
@@ -1,4 +1,4 @@
1
  ,GSM4140293,GSM4140294,GSM4140295,GSM4140296,GSM4140297,GSM4140298,GSM4140299,GSM4140300,GSM4140301,GSM4140302,GSM4140303,GSM4140304,GSM4140305,GSM4140306,GSM4140307,GSM4140308,GSM4140309,GSM4140310,GSM4140311,GSM4140312,GSM4140313,GSM4140314,GSM4140315,GSM4140316,GSM4140317,GSM4140318,GSM4140319,GSM4140320,GSM4140321,GSM4140322,GSM4140323,GSM4140324,GSM4140325
2
- Alzheimers_Disease,0.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,1.0,1.0,,,,,,,,,,,,,,,,,,,,,
3
  Age,,,,,,,,,,,,,66.0,77.0,70.0,74.0,76.0,60.0,79.0,71.0,63.0,65.0,70.0,81.0,70.0,74.0,73.0,72.0,72.0,75.0,85.0,76.0,74.0
4
  Gender,,,,,,,,,,,,,0.0,1.0,0.0,0.0,0.0,0.0,1.0,0.0,0.0,1.0,0.0,0.0,0.0,1.0,0.0,1.0,0.0,1.0,1.0,0.0,0.0
 
1
  ,GSM4140293,GSM4140294,GSM4140295,GSM4140296,GSM4140297,GSM4140298,GSM4140299,GSM4140300,GSM4140301,GSM4140302,GSM4140303,GSM4140304,GSM4140305,GSM4140306,GSM4140307,GSM4140308,GSM4140309,GSM4140310,GSM4140311,GSM4140312,GSM4140313,GSM4140314,GSM4140315,GSM4140316,GSM4140317,GSM4140318,GSM4140319,GSM4140320,GSM4140321,GSM4140322,GSM4140323,GSM4140324,GSM4140325
2
+ Alzheimers_Disease,0.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0
3
  Age,,,,,,,,,,,,,66.0,77.0,70.0,74.0,76.0,60.0,79.0,71.0,63.0,65.0,70.0,81.0,70.0,74.0,73.0,72.0,72.0,75.0,85.0,76.0,74.0
4
  Gender,,,,,,,,,,,,,0.0,1.0,0.0,0.0,0.0,0.0,1.0,0.0,0.0,1.0,0.0,0.0,0.0,1.0,0.0,1.0,0.0,1.0,1.0,0.0,0.0
output/preprocess/Alzheimers_Disease/code/GSE109887.py ADDED
@@ -0,0 +1,206 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Alzheimers_Disease"
6
+ cohort = "GSE109887"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Alzheimers_Disease"
10
+ in_cohort_dir = "../DATA/GEO/Alzheimers_Disease/GSE109887"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z1/preprocess/Alzheimers_Disease/GSE109887.csv"
14
+ out_gene_data_file = "./output/z1/preprocess/Alzheimers_Disease/gene_data/GSE109887.csv"
15
+ out_clinical_data_file = "./output/z1/preprocess/Alzheimers_Disease/clinical_data/GSE109887.csv"
16
+ json_path = "./output/z1/preprocess/Alzheimers_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 numpy as np
42
+ import pandas as pd
43
+
44
+ # 1) Gene expression data availability
45
+ is_gene_available = True # Illumina HumanHT-12 v4 expression data
46
+
47
+ # 2) Variable availability
48
+ trait_row = 3 # 'disease state: AD' vs 'Control'
49
+ age_row = 1 # 'age: <number>'
50
+ gender_row = 0 # 'gender: Female'/'Male'
51
+
52
+ # 2.2) Converters
53
+ def _extract_value(cell):
54
+ if cell is None or (isinstance(cell, float) and np.isnan(cell)):
55
+ return None
56
+ s = str(cell).strip()
57
+ if ":" in s:
58
+ s = s.split(":", 1)[1].strip()
59
+ return s if s != "" else None
60
+
61
+ def convert_trait(cell):
62
+ v = _extract_value(cell)
63
+ if v is None:
64
+ return None
65
+ v_low = v.lower()
66
+ if v_low in {"ad", "alzheimer", "alzheimer's disease", "alzheimers disease", "alzheimer disease"}:
67
+ return 1
68
+ if v_low in {"control", "ctrl", "healthy control", "non-demented", "nd", "cn"}:
69
+ return 0
70
+ if "alzheimer" in v_low or v_low == "ad":
71
+ return 1
72
+ if "control" in v_low:
73
+ return 0
74
+ return None
75
+
76
+ def convert_age(cell):
77
+ v = _extract_value(cell)
78
+ if v is None:
79
+ return None
80
+ match = re.search(r"[-+]?\d*\.?\d+", v)
81
+ if match:
82
+ try:
83
+ age_val = float(match.group())
84
+ if 0 < age_val < 120:
85
+ return age_val
86
+ except Exception:
87
+ return None
88
+ return None
89
+
90
+ def convert_gender(cell):
91
+ v = _extract_value(cell)
92
+ if v is None:
93
+ return None
94
+ v_low = v.lower()
95
+ if v_low in {"female", "f"}:
96
+ return 0
97
+ if v_low in {"male", "m"}:
98
+ return 1
99
+ return None
100
+
101
+ # 3) Save metadata (initial filtering)
102
+ is_trait_available = trait_row is not None
103
+ _ = validate_and_save_cohort_info(
104
+ is_final=False,
105
+ cohort=cohort,
106
+ info_path=json_path,
107
+ is_gene_available=is_gene_available,
108
+ is_trait_available=is_trait_available
109
+ )
110
+
111
+ # 4) Clinical feature extraction (only if trait available)
112
+ if trait_row is not None:
113
+ assert 'clinical_data' in globals(), "clinical_data is not available from the previous step."
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
+ clinical_preview = preview_df(selected_clinical_df, n=5)
125
+ print(clinical_preview)
126
+ # Save clinical data (keep index to preserve feature labels)
127
+ out_dir = os.path.dirname(out_clinical_data_file)
128
+ os.makedirs(out_dir, 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
+ print("requires_gene_mapping = True")
140
+
141
+ # Step 5: Gene Identifier Review
142
+ # Based on the previous step's observation for GSE109887
143
+ requires_gene_mapping = True
144
+ print(f"requires_gene_mapping = {requires_gene_mapping}")
145
+
146
+ # Step 6: Gene Annotation
147
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
148
+ gene_annotation = get_gene_annotation(soft_file)
149
+
150
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
151
+ print("Gene annotation preview:")
152
+ print(preview_df(gene_annotation))
153
+
154
+ # Step 7: Gene Identifier Mapping
155
+ # Decide the identifier and gene symbol columns based on annotation preview:
156
+ # - Expression data index matches the 'ID' column in annotation
157
+ # - Gene symbols appear to be in the 'ORF' column
158
+
159
+ # 1-2. Build mapping dataframe from annotation
160
+ mapping_df = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='ORF')
161
+
162
+ # 3. Apply mapping to convert probe/identifier-level data to gene-level expression
163
+ gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
164
+
165
+ # Step 8: 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. Bias check and removal of 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
+ # Ensure pure Python bools for JSON serialization
184
+ is_gene_available_final = bool((normalized_gene_data.shape[0] > 0) and (normalized_gene_data.shape[1] > 0))
185
+ is_trait_available_final = bool((trait in linked_data.columns) and bool(linked_data[trait].notna().any()))
186
+ is_trait_biased = bool(is_trait_biased)
187
+
188
+ note = ("INFO: Illumina HumanHT-12 v4 expression data; identifiers mapped using annotation "
189
+ "('ID'->'ORF'); gene symbols normalized via NCBI synonyms. Clinical features include "
190
+ "Alzheimers_Disease trait, Age, Gender.")
191
+
192
+ is_usable = validate_and_save_cohort_info(
193
+ is_final=True,
194
+ cohort=cohort,
195
+ info_path=json_path,
196
+ is_gene_available=is_gene_available_final,
197
+ is_trait_available=is_trait_available_final,
198
+ is_biased=is_trait_biased,
199
+ df=unbiased_linked_data,
200
+ note=note
201
+ )
202
+
203
+ # 6. Save linked data if usable
204
+ if is_usable:
205
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
206
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Alzheimers_Disease/code/GSE117589.py ADDED
@@ -0,0 +1,185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Alzheimers_Disease"
6
+ cohort = "GSE117589"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Alzheimers_Disease"
10
+ in_cohort_dir = "../DATA/GEO/Alzheimers_Disease/GSE117589"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z1/preprocess/Alzheimers_Disease/GSE117589.csv"
14
+ out_gene_data_file = "./output/z1/preprocess/Alzheimers_Disease/gene_data/GSE117589.csv"
15
+ out_clinical_data_file = "./output/z1/preprocess/Alzheimers_Disease/clinical_data/GSE117589.csv"
16
+ json_path = "./output/z1/preprocess/Alzheimers_Disease/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ import os
40
+ import re
41
+
42
+ # 1) Gene expression data availability
43
+ is_gene_available = True # iPSC/neuronal models SuperSeries with diagnosis groups strongly suggests mRNA expression data.
44
+
45
+ # 2) Variable availability and converters
46
+
47
+ # Keys inferred from the Sample Characteristics Dictionary provided
48
+ trait_row = 2 # diagnosis: normal vs sporadic Alzheimer's disease
49
+ age_row = 1 # subject: e.g., '72M' (age+sex together)
50
+ gender_row = 1 # subject: e.g., '72M' (age+sex together)
51
+
52
+ def _after_colon(x):
53
+ if x is None:
54
+ return None
55
+ parts = str(x).split(":", 1)
56
+ return parts[1].strip() if len(parts) > 1 else str(x).strip()
57
+
58
+ def convert_trait(x):
59
+ val = _after_colon(x)
60
+ if val is None:
61
+ return None
62
+ v = val.strip().lower()
63
+ if "alzheimer" in v:
64
+ return 1
65
+ if v == "normal":
66
+ return 0
67
+ return None
68
+
69
+ def convert_age(x):
70
+ val = _after_colon(x)
71
+ if val is None:
72
+ return None
73
+ m = re.search(r'(\d+(?:\.\d+)?)', val)
74
+ if not m:
75
+ return None
76
+ try:
77
+ num = float(m.group(1))
78
+ return int(num) if num.is_integer() else num
79
+ except Exception:
80
+ return None
81
+
82
+ def convert_gender(x):
83
+ val = _after_colon(x)
84
+ if val is None:
85
+ return None
86
+ v = val.strip().lower()
87
+
88
+ # Prefer pattern like "72M" / "72 F"
89
+ m = re.match(r'^\s*\d+(?:\.\d+)?\s*([mf])\s*$', v)
90
+ if m:
91
+ return 1 if m.group(1) == 'm' else 0
92
+
93
+ if re.search(r'\bfemale\b', v):
94
+ return 0
95
+ if re.search(r'\bmale\b', v):
96
+ return 1
97
+
98
+ if v == 'f':
99
+ return 0
100
+ if v == '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 if available
115
+ if trait_row is not None:
116
+ selected_clinical_df = geo_select_clinical_features(
117
+ clinical_df=clinical_data,
118
+ trait=trait,
119
+ trait_row=trait_row,
120
+ convert_trait=convert_trait,
121
+ age_row=age_row,
122
+ convert_age=convert_age,
123
+ gender_row=gender_row,
124
+ convert_gender=convert_gender
125
+ )
126
+ clinical_preview = preview_df(selected_clinical_df, n=5)
127
+ print(clinical_preview)
128
+ # Save clinical data
129
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
130
+ selected_clinical_df.to_csv(out_clinical_data_file)
131
+
132
+ # Step 3: Gene Data Extraction
133
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
134
+ gene_data = get_genetic_data(matrix_file)
135
+
136
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
137
+ print(gene_data.index[:20])
138
+
139
+ # Step 4: Gene Identifier Review
140
+ 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
+ # Map probe IDs ('ID') to human gene symbols parsed from the 'Description' column
153
+ mapping_df = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='Description')
154
+
155
+ # Convert probe-level data to gene-level expression using provided utility
156
+ probe_data = gene_data # from previous step
157
+ gene_data = apply_gene_mapping(expression_df=probe_data, mapping_df=mapping_df)
158
+
159
+ # Step 7: Data Normalization and Linking
160
+ import os
161
+
162
+ # 1. Normalize gene symbols and save gene expression data
163
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
164
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
165
+ normalized_gene_data.to_csv(out_gene_data_file)
166
+
167
+ # 2. Link clinical and genetic data
168
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
169
+
170
+ # 3. Handle missing values systematically
171
+ linked_data = handle_missing_values(linked_data, trait)
172
+
173
+ # 4. Assess bias and remove biased demographic features if necessary
174
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
175
+
176
+ # 5. Final validation and save cohort info
177
+ note = "INFO: Age and Gender parsed from combined 'subject' field (e.g., '72M'); trait from 'diagnosis' row."
178
+ is_usable = validate_and_save_cohort_info(
179
+ True, cohort, json_path, True, True, is_trait_biased, unbiased_linked_data, note
180
+ )
181
+
182
+ # 6. Save linked data if usable
183
+ if is_usable:
184
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
185
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Alzheimers_Disease/code/GSE122063.py ADDED
@@ -0,0 +1,193 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Alzheimers_Disease"
6
+ cohort = "GSE122063"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Alzheimers_Disease"
10
+ in_cohort_dir = "../DATA/GEO/Alzheimers_Disease/GSE122063"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z1/preprocess/Alzheimers_Disease/GSE122063.csv"
14
+ out_gene_data_file = "./output/z1/preprocess/Alzheimers_Disease/gene_data/GSE122063.csv"
15
+ out_clinical_data_file = "./output/z1/preprocess/Alzheimers_Disease/clinical_data/GSE122063.csv"
16
+ json_path = "./output/z1/preprocess/Alzheimers_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 pandas as pd
41
+
42
+ # 1) Gene expression data availability (Agilent Human 8x60k gene expression arrays)
43
+ is_gene_available = True
44
+
45
+ # 2) Variable availability (from Sample Characteristics Dictionary)
46
+ trait_row = 0 # patient diagnosis: AD / Control / Vascular dementia
47
+ age_row = 6 # age: numeric
48
+ gender_row = 5 # Sex: Male/Female
49
+
50
+ # 2.2) Converters
51
+ def _after_colon(value):
52
+ if value is None:
53
+ return None
54
+ if not isinstance(value, str):
55
+ return value
56
+ parts = value.split(":", 1)
57
+ s = parts[1] if len(parts) > 1 else parts[0]
58
+ return s.strip().strip('"').strip("'")
59
+
60
+ def convert_trait(value):
61
+ s = _after_colon(value)
62
+ if s is None:
63
+ return None
64
+ s_low = s.lower()
65
+ # Map Alzheimer's disease to 1; Control and Vascular dementia to 0 (non-AD)
66
+ if "alzheimer" in s_low: # covers "alzheimer's disease" and variants
67
+ return 1
68
+ if any(k in s_low for k in ["control", "non-demented", "non demented", "healthy", "normal"]):
69
+ return 0
70
+ if any(k in s_low for k in ["vascular", "vad"]):
71
+ return 0
72
+ return None
73
+
74
+ def convert_age(value):
75
+ s = _after_colon(value)
76
+ if s is None:
77
+ return None
78
+ s = s.replace(",", "").strip()
79
+ try:
80
+ return float(s)
81
+ except Exception:
82
+ return None
83
+
84
+ def convert_gender(value):
85
+ s = _after_colon(value)
86
+ if s is None:
87
+ return None
88
+ s_low = s.lower()
89
+ if s_low in ["female", "f", "woman", "women"]:
90
+ return 0
91
+ if s_low in ["male", "m", "man", "men"]:
92
+ return 1
93
+ return None
94
+
95
+ # 3) Save metadata with initial filtering
96
+ is_trait_available = trait_row is not None
97
+ _ = validate_and_save_cohort_info(
98
+ is_final=False,
99
+ cohort=cohort,
100
+ info_path=json_path,
101
+ is_gene_available=is_gene_available,
102
+ is_trait_available=is_trait_available
103
+ )
104
+
105
+ # 4) Clinical feature extraction (only if clinical data available)
106
+ if trait_row is not None:
107
+ selected_clinical_df = geo_select_clinical_features(
108
+ clinical_df=clinical_data,
109
+ trait=trait,
110
+ trait_row=trait_row,
111
+ convert_trait=convert_trait,
112
+ age_row=age_row,
113
+ convert_age=convert_age,
114
+ gender_row=gender_row,
115
+ convert_gender=convert_gender
116
+ )
117
+ preview = preview_df(selected_clinical_df, n=5)
118
+ print(preview)
119
+
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("\nrequires_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
+ # Identify the appropriate columns in the annotation for probe IDs and gene symbols
143
+ probe_col = 'ID' # Matches the numeric probe IDs in gene_data index (e.g., '4', '5', ...)
144
+ gene_symbol_col = 'GENE_SYMBOL' # Contains gene symbols like 'HEBP1', 'KCNE4'
145
+
146
+ # 2) Build 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
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 info
170
+ # Cast to native Python bool to avoid JSON serialization issues
171
+ is_gene_available_final = bool((normalized_gene_data.shape[0] > 0) and (normalized_gene_data.shape[1] > 0))
172
+ is_trait_available_final = bool((trait in unbiased_linked_data.columns) and (unbiased_linked_data[trait].notna().any()))
173
+ is_trait_biased = bool(is_trait_biased)
174
+
175
+ note = ("INFO: Trait encoded as AD=1, Control/VaD=0. "
176
+ "Agilent Human 8x60k v2; dual channel processed as single channel. "
177
+ "Brain regions: frontal and temporal cortex.")
178
+
179
+ is_usable = validate_and_save_cohort_info(
180
+ is_final=True,
181
+ cohort=cohort,
182
+ info_path=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/Alzheimers_Disease/code/GSE132903.py ADDED
@@ -0,0 +1,229 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Alzheimers_Disease"
6
+ cohort = "GSE132903"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Alzheimers_Disease"
10
+ in_cohort_dir = "../DATA/GEO/Alzheimers_Disease/GSE132903"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z1/preprocess/Alzheimers_Disease/GSE132903.csv"
14
+ out_gene_data_file = "./output/z1/preprocess/Alzheimers_Disease/gene_data/GSE132903.csv"
15
+ out_clinical_data_file = "./output/z1/preprocess/Alzheimers_Disease/clinical_data/GSE132903.csv"
16
+ json_path = "./output/z1/preprocess/Alzheimers_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 # Illumina Human HT-12 v4 mRNA arrays indicate gene expression data
45
+
46
+ # 2. Variable availability from the provided Sample Characteristics Dictionary
47
+ trait_row = 3 # diagnosis: ND/AD
48
+ age_row = 2 # expired_age (years): values including numbers and "90+"
49
+ gender_row = 1 # Sex: male/female
50
+
51
+ # 2.2 Conversion functions
52
+ def _after_colon(x):
53
+ if x is None:
54
+ return None
55
+ parts = str(x).split(':', 1)
56
+ return parts[1].strip() if len(parts) > 1 else str(x).strip()
57
+
58
+ def convert_trait(x):
59
+ v = _after_colon(x)
60
+ if v is None:
61
+ return None
62
+ v_low = v.strip().lower()
63
+ # Cases vs Controls mapping
64
+ if v_low in {'ad', "alzheimer's disease", 'alzheimers disease', 'alzheimers', 'alzheimer disease'}:
65
+ return 1
66
+ if v_low in {'nd', 'control', 'non-demented', 'non demented', 'non-demented control', 'normal'}:
67
+ return 0
68
+ return None
69
+
70
+ def convert_age(x):
71
+ v = _after_colon(x)
72
+ if v is None:
73
+ return None
74
+ v = v.strip()
75
+ # Handle formats like "90+"
76
+ v = v.replace('+', '')
77
+ # Extract leading number
78
+ m = re.search(r'[-+]?\d*\.?\d+', v)
79
+ if not m:
80
+ return None
81
+ try:
82
+ age_val = float(m.group())
83
+ # Ages are in years; cast to float to keep continuous type
84
+ return age_val
85
+ except Exception:
86
+ return None
87
+
88
+ def convert_gender(x):
89
+ v = _after_colon(x)
90
+ if v is None:
91
+ return None
92
+ v_low = v.strip().lower()
93
+ if v_low in {'male', 'm'}:
94
+ return 1
95
+ if v_low in {'female', 'f'}:
96
+ return 0
97
+ return None
98
+
99
+ # 3. Save initial filtering metadata
100
+ is_trait_available = trait_row is not None
101
+ _ = validate_and_save_cohort_info(
102
+ is_final=False,
103
+ cohort=cohort,
104
+ info_path=json_path,
105
+ is_gene_available=is_gene_available,
106
+ is_trait_available=is_trait_available
107
+ )
108
+
109
+ # 4. Clinical feature extraction (only if trait data is available)
110
+ if trait_row is not None:
111
+ selected_clinical_df = geo_select_clinical_features(
112
+ clinical_df=clinical_data,
113
+ trait=trait,
114
+ trait_row=trait_row,
115
+ convert_trait=convert_trait,
116
+ age_row=age_row,
117
+ convert_age=convert_age,
118
+ gender_row=gender_row,
119
+ convert_gender=convert_gender
120
+ )
121
+
122
+ # Preview and save
123
+ preview = preview_df(selected_clinical_df)
124
+ print("Preview of selected clinical features:", preview)
125
+
126
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
127
+ selected_clinical_df.to_csv(out_clinical_data_file)
128
+ else:
129
+ print("Trait data not available; skipping clinical feature extraction.")
130
+
131
+ # For transparency in this step
132
+ print({
133
+ "is_gene_available": is_gene_available,
134
+ "trait_row": trait_row,
135
+ "age_row": age_row,
136
+ "gender_row": gender_row
137
+ })
138
+
139
+ # Step 3: Gene Data Extraction
140
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
141
+ gene_data = get_genetic_data(matrix_file)
142
+
143
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
144
+ print(gene_data.index[:20])
145
+
146
+ # Step 4: Gene Identifier Review
147
+ # ILMN_ prefixes indicate Illumina probe IDs, not human gene symbols.
148
+ requires_gene_mapping = True
149
+ print(f"requires_gene_mapping = {requires_gene_mapping}")
150
+
151
+ # Step 5: Gene Annotation
152
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
153
+ gene_annotation = get_gene_annotation(soft_file)
154
+
155
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
156
+ print("Gene annotation preview:")
157
+ print(preview_df(gene_annotation))
158
+
159
+ # Step 6: Gene Identifier Mapping
160
+ # Determine the columns for probe IDs and gene symbols based on the annotation preview:
161
+ # Probe identifier column: 'ID' (e.g., ILMN_1343***)
162
+ # Gene symbol column: 'Symbol'
163
+
164
+ # 1-2. Build mapping dataframe from annotation
165
+ mapping_df = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='Symbol')
166
+
167
+ # 3. Apply mapping to convert probe-level data to gene-level data
168
+ gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
169
+
170
+ # Step 7: Data Normalization and Linking
171
+ import os
172
+ import json
173
+
174
+ # 1. Normalize gene symbols and save
175
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
176
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
177
+ normalized_gene_data.to_csv(out_gene_data_file)
178
+
179
+ # 2. Link clinical and genetic data
180
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
181
+
182
+ # 3. Handle missing values
183
+ linked_data = handle_missing_values(linked_data, trait)
184
+
185
+ # 4. Assess bias and remove biased demographic features
186
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
187
+
188
+ # 5. Final quality validation and save cohort info
189
+ covariate_cols = [trait, 'Age', 'Gender']
190
+ gene_cols_count = len([c for c in unbiased_linked_data.columns if c not in covariate_cols])
191
+
192
+ # Ensure pure Python bools for JSON serialization
193
+ is_gene_available_final = bool(gene_cols_count > 0)
194
+ is_trait_available_final = bool((trait in unbiased_linked_data.columns) and (unbiased_linked_data[trait].notna().sum() > 0))
195
+ is_trait_biased = bool(is_trait_biased)
196
+
197
+ note = "INFO: Illumina HT-12 V4 probes mapped to gene symbols; split multi-gene probes; ages like '90+' parsed as 90."
198
+
199
+ try:
200
+ is_usable = validate_and_save_cohort_info(
201
+ is_final=True,
202
+ cohort=cohort,
203
+ info_path=json_path,
204
+ is_gene_available=is_gene_available_final,
205
+ is_trait_available=is_trait_available_final,
206
+ is_biased=is_trait_biased,
207
+ df=unbiased_linked_data,
208
+ note=note
209
+ )
210
+ except TypeError:
211
+ # If JSON serialization fails (e.g., due to numpy.bool_), reset the JSON file and retry once
212
+ os.makedirs(os.path.dirname(json_path), exist_ok=True)
213
+ with open(json_path, 'w') as f:
214
+ json.dump({}, f)
215
+ is_usable = validate_and_save_cohort_info(
216
+ is_final=True,
217
+ cohort=cohort,
218
+ info_path=json_path,
219
+ is_gene_available=is_gene_available_final,
220
+ is_trait_available=is_trait_available_final,
221
+ is_biased=is_trait_biased,
222
+ df=unbiased_linked_data,
223
+ note=note
224
+ )
225
+
226
+ # 6. Save usable linked data
227
+ if is_usable:
228
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
229
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Alzheimers_Disease/code/GSE137202.py ADDED
@@ -0,0 +1,194 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Alzheimers_Disease"
6
+ cohort = "GSE137202"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Alzheimers_Disease"
10
+ in_cohort_dir = "../DATA/GEO/Alzheimers_Disease/GSE137202"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z1/preprocess/Alzheimers_Disease/GSE137202.csv"
14
+ out_gene_data_file = "./output/z1/preprocess/Alzheimers_Disease/gene_data/GSE137202.csv"
15
+ out_clinical_data_file = "./output/z1/preprocess/Alzheimers_Disease/clinical_data/GSE137202.csv"
16
+ json_path = "./output/z1/preprocess/Alzheimers_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
40
+ is_gene_available = True # Affymetrix PrimeView whole-genome expression profiling (mRNA) -> gene expression available
41
+
42
+ # Map trait to genotype status (mutated AD models vs WT). No age/gender in cell lines.
43
+ trait_row = 1
44
+ age_row = None
45
+ gender_row = None
46
+
47
+ def _after_colon(val):
48
+ if val is None:
49
+ return None
50
+ s = str(val)
51
+ parts = s.split(":", 1)
52
+ s = parts[1] if len(parts) == 2 else parts[0]
53
+ return s.strip().lower()
54
+
55
+ def convert_trait(x):
56
+ v = _after_colon(x)
57
+ if v is None or v == "":
58
+ return None
59
+ # WT vs AD model (mutated)
60
+ if "wild" in v:
61
+ return 0
62
+ if "mut" in v or "app" in v or "psen" in v:
63
+ return 1
64
+ return None
65
+
66
+ def convert_age(x):
67
+ # Not available in this dataset; safe general parser if ever present
68
+ v = _after_colon(x)
69
+ if v is None or v == "":
70
+ return None
71
+ # Extract first numeric token
72
+ import re
73
+ m = re.search(r"[-+]?\d*\.?\d+", v)
74
+ return float(m.group()) if m else None
75
+
76
+ def convert_gender(x):
77
+ v = _after_colon(x)
78
+ if v is None or v == "":
79
+ return None
80
+ if v in {"female", "f", "woman", "women"}:
81
+ return 0
82
+ if v in {"male", "m", "man", "men"}:
83
+ return 1
84
+ return None
85
+
86
+ # Save initial metadata
87
+ is_trait_available = trait_row is not None
88
+ _ = validate_and_save_cohort_info(
89
+ is_final=False,
90
+ cohort=cohort,
91
+ info_path=json_path,
92
+ is_gene_available=is_gene_available,
93
+ is_trait_available=is_trait_available
94
+ )
95
+
96
+ # Clinical feature extraction if available
97
+ if trait_row is not None:
98
+ selected_clinical_df = geo_select_clinical_features(
99
+ clinical_df=clinical_data,
100
+ trait=trait,
101
+ trait_row=trait_row,
102
+ convert_trait=convert_trait,
103
+ age_row=age_row,
104
+ convert_age=convert_age,
105
+ gender_row=gender_row,
106
+ convert_gender=convert_gender
107
+ )
108
+ preview = preview_df(selected_clinical_df, n=5)
109
+ print(preview)
110
+
111
+ import os
112
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
113
+ selected_clinical_df.to_csv(out_clinical_data_file)
114
+
115
+ # Step 3: Gene Data Extraction
116
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
117
+ gene_data = get_genetic_data(matrix_file)
118
+
119
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
120
+ print(gene_data.index[:20])
121
+
122
+ # Step 4: Gene Identifier Review
123
+ print("requires_gene_mapping = True")
124
+
125
+ # Step 5: Gene Annotation
126
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
127
+ gene_annotation = get_gene_annotation(soft_file)
128
+
129
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
130
+ print("Gene annotation preview:")
131
+ print(preview_df(gene_annotation))
132
+
133
+ # Step 6: Gene Identifier Mapping
134
+ # Select appropriate columns for mapping: probe IDs ('ID') and gene symbols ('Gene Symbol')
135
+ mapping_df = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='Gene Symbol')
136
+
137
+ # Apply mapping to convert probe-level data to gene-level expression
138
+ gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
139
+
140
+ # Step 7: Data Normalization and Linking
141
+ import os
142
+ import json
143
+
144
+ # 1. Normalize gene symbols and save gene-level data
145
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
146
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
147
+ normalized_gene_data.to_csv(out_gene_data_file)
148
+
149
+ # 2. Link clinical and genetic data
150
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
151
+
152
+ # Compute availability flags based on actual data and coerce to native Python bool
153
+ is_gene_available = bool((normalized_gene_data.shape[0] > 0) and (normalized_gene_data.shape[1] > 0))
154
+ is_trait_available = bool((trait in linked_data.columns) and (linked_data[trait].notna().sum() > 0))
155
+
156
+ # 3. Handle missing values
157
+ linked_data = handle_missing_values(linked_data, trait)
158
+
159
+ # 4. Bias assessment and removal of biased demographic features
160
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
161
+ is_trait_biased = bool(is_trait_biased) # ensure native bool
162
+
163
+ # 5. Final validation and save cohort info
164
+ note = "INFO: Cell line AD model (WT vs mutated); no Age/Gender covariates available."
165
+ try:
166
+ is_usable = validate_and_save_cohort_info(
167
+ is_final=True,
168
+ cohort=cohort,
169
+ info_path=json_path,
170
+ is_gene_available=is_gene_available,
171
+ is_trait_available=is_trait_available,
172
+ is_biased=is_trait_biased,
173
+ df=unbiased_linked_data,
174
+ note=note
175
+ )
176
+ except TypeError:
177
+ # If JSON serialization fails (e.g., corrupted existing file), recreate a clean metadata file and retry
178
+ if os.path.exists(json_path):
179
+ os.remove(json_path)
180
+ is_usable = validate_and_save_cohort_info(
181
+ is_final=True,
182
+ cohort=cohort,
183
+ info_path=json_path,
184
+ is_gene_available=bool(is_gene_available),
185
+ is_trait_available=bool(is_trait_available),
186
+ is_biased=bool(is_trait_biased),
187
+ df=unbiased_linked_data,
188
+ note=note
189
+ )
190
+
191
+ # 6. Save linked dataset if usable
192
+ if is_usable:
193
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
194
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Alzheimers_Disease/code/GSE139384.py ADDED
@@ -0,0 +1,229 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Alzheimers_Disease"
6
+ cohort = "GSE139384"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Alzheimers_Disease"
10
+ in_cohort_dir = "../DATA/GEO/Alzheimers_Disease/GSE139384"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z1/preprocess/Alzheimers_Disease/GSE139384.csv"
14
+ out_gene_data_file = "./output/z1/preprocess/Alzheimers_Disease/gene_data/GSE139384.csv"
15
+ out_clinical_data_file = "./output/z1/preprocess/Alzheimers_Disease/clinical_data/GSE139384.csv"
16
+ json_path = "./output/z1/preprocess/Alzheimers_Disease/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ import os
40
+ import re
41
+
42
+ # 1) Gene expression data availability
43
+ is_gene_available = True # Illumina HumanHT-12 v4 Expression BeadChip indicates mRNA expression data
44
+
45
+ # 2) Variable availability and conversion functions
46
+
47
+ # From the sample characteristics dictionary in the prompt, we infer:
48
+ # - trait_row: 0 (contains clinical phenotypes for ALS/PDC and subject ids like AD/CT to infer AD status)
49
+ # - age_row: 2 (mostly contains 'age: NN', with occasional gender entries we will ignore)
50
+ # - gender_row: 1 (contains 'gender: Male/Female'; will ignore entries with clinical phenotypes)
51
+
52
+ trait_row = 0
53
+ age_row = 2
54
+ gender_row = 1
55
+
56
+ def _after_colon(value: str) -> str:
57
+ if value is None:
58
+ return ""
59
+ s = str(value)
60
+ parts = s.split(":", 1)
61
+ return parts[1].strip() if len(parts) == 2 else s.strip()
62
+
63
+ def convert_trait(value):
64
+ """
65
+ Map Alzheimer's Disease status to binary:
66
+ - 1: Alzheimer's Disease
67
+ Heuristics:
68
+ * subject id contains 'AD' (e.g., 'subject id: AD3')
69
+ * 'clinical phenotypes' contains 'Alzheimer'
70
+ - 0: Non-AD (Healthy control or other diseases like ALS/PDC)
71
+ Heuristics:
72
+ * subject id contains 'CT'
73
+ * 'clinical phenotypes' contains 'healthy control', 'als', 'pdc'
74
+ - None: unknown/irrelevant entries
75
+ """
76
+ if value is None:
77
+ return None
78
+ s = str(value).lower()
79
+ v = _after_colon(value).lower()
80
+
81
+ # Direct Alzheimer detection
82
+ if "alzheimer" in s or "alzheimer" in v:
83
+ return 1
84
+
85
+ # Subject ID heuristics
86
+ if "subject id" in s:
87
+ # AD subjects
88
+ if re.search(r"\bad\d*\b", v):
89
+ return 1
90
+ # Controls
91
+ if re.search(r"\bct\d*\b", v) or "control" in v:
92
+ return 0
93
+
94
+ # Clinical phenotype heuristics for non-AD
95
+ if "clinical phenotypes" in s:
96
+ if "healthy control" in v or "control" in v:
97
+ return 0
98
+ if "als" in v or "pdc" in v:
99
+ return 0
100
+
101
+ return None
102
+
103
+ def convert_age(value):
104
+ """
105
+ Extract age as continuous numeric value if present; else None.
106
+ """
107
+ if value is None:
108
+ return None
109
+ v = _after_colon(value)
110
+ m = re.search(r"\d+", v)
111
+ return int(m.group()) if m else None
112
+
113
+ def convert_gender(value):
114
+ """
115
+ Map gender to binary: female -> 0, male -> 1. Unknown/other -> None.
116
+ Ignore entries that are not gender fields.
117
+ """
118
+ if value is None:
119
+ return None
120
+ s = str(value).lower()
121
+ v = _after_colon(value).lower()
122
+ if "gender" not in s:
123
+ return None
124
+ if "female" in v:
125
+ return 0
126
+ if "male" in v:
127
+ return 1
128
+ return None
129
+
130
+ # 3) Save metadata using initial filtering
131
+ is_trait_available = trait_row is not None
132
+ _ = validate_and_save_cohort_info(
133
+ is_final=False,
134
+ cohort=cohort,
135
+ info_path=json_path,
136
+ is_gene_available=is_gene_available,
137
+ is_trait_available=is_trait_available
138
+ )
139
+
140
+ # 4) Clinical feature extraction (only if trait_row is available)
141
+ if trait_row is not None:
142
+ selected_clinical_df = geo_select_clinical_features(
143
+ clinical_df=clinical_data,
144
+ trait=trait,
145
+ trait_row=trait_row,
146
+ convert_trait=convert_trait,
147
+ age_row=age_row,
148
+ convert_age=convert_age,
149
+ gender_row=gender_row,
150
+ convert_gender=convert_gender
151
+ )
152
+ preview_result = preview_df(selected_clinical_df)
153
+ print(preview_result)
154
+
155
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
156
+ selected_clinical_df.to_csv(out_clinical_data_file)
157
+
158
+ # Step 3: Gene Data Extraction
159
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
160
+ gene_data = get_genetic_data(matrix_file)
161
+
162
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
163
+ print(gene_data.index[:20])
164
+
165
+ # Step 4: Gene Identifier Review
166
+ # Illumina probe IDs (ILMN_*) are not human gene symbols and require mapping
167
+ requires_gene_mapping = True
168
+ print(f"requires_gene_mapping = {requires_gene_mapping}")
169
+
170
+ # Step 5: Gene Annotation
171
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
172
+ gene_annotation = get_gene_annotation(soft_file)
173
+
174
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
175
+ print("Gene annotation preview:")
176
+ print(preview_df(gene_annotation))
177
+
178
+ # Step 6: Gene Identifier Mapping
179
+ # Decide the appropriate columns for probe IDs and gene symbols based on the preview:
180
+ # - Probe identifiers match the 'ID' column (e.g., ILMN_1343***).
181
+ # - Gene symbols are in the 'Symbol' column.
182
+
183
+ # 1-2. Build the mapping dataframe from annotation
184
+ mapping_df = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='Symbol')
185
+
186
+ # 3. Apply mapping to convert probe-level data to gene-level expression
187
+ gene_data = apply_gene_mapping(gene_data, mapping_df)
188
+
189
+ # Step 7: Data Normalization and Linking
190
+ import os
191
+ import pandas as pd
192
+
193
+ # 1. Normalize gene symbols and save
194
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
195
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
196
+ normalized_gene_data.to_csv(out_gene_data_file)
197
+
198
+ # Ensure clinical data is available in memory; if not, load from disk
199
+ try:
200
+ selected_clinical_df
201
+ except NameError:
202
+ selected_clinical_df = pd.read_csv(out_clinical_data_file, index_col=0)
203
+
204
+ # 2. Link clinical and genetic data
205
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
206
+
207
+ # 3. Handle missing values
208
+ linked_data = handle_missing_values(linked_data, trait)
209
+
210
+ # 4. Evaluate bias and drop biased demographic features
211
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
212
+
213
+ # 5. Final validation and save cohort info
214
+ note = "INFO: Normalized gene symbols using NCBI synonyms; linked clinical data; applied systematic missing value handling and bias checks."
215
+ is_usable = validate_and_save_cohort_info(
216
+ is_final=True,
217
+ cohort=cohort,
218
+ info_path=json_path,
219
+ is_gene_available=True,
220
+ is_trait_available=True,
221
+ is_biased=is_trait_biased,
222
+ df=unbiased_linked_data,
223
+ note=note
224
+ )
225
+
226
+ # 6. Save linked data if usable
227
+ if is_usable:
228
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
229
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Alzheimers_Disease/code/GSE167559.py ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Alzheimers_Disease"
6
+ cohort = "GSE167559"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Alzheimers_Disease"
10
+ in_cohort_dir = "../DATA/GEO/Alzheimers_Disease/GSE167559"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z1/preprocess/Alzheimers_Disease/GSE167559.csv"
14
+ out_gene_data_file = "./output/z1/preprocess/Alzheimers_Disease/gene_data/GSE167559.csv"
15
+ out_clinical_data_file = "./output/z1/preprocess/Alzheimers_Disease/clinical_data/GSE167559.csv"
16
+ json_path = "./output/z1/preprocess/Alzheimers_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) Determine gene expression availability (miRNA-only dataset => not suitable)
40
+ is_gene_available = False
41
+
42
+ # 2) Variable availability and converters based on provided Sample Characteristics Dictionary
43
+ # Keys identified from the dictionary:
44
+ # 0: tissue: serum
45
+ # 1: diagnosis: NPH
46
+ # 2: age: ...
47
+ # 3: Sex: male/female
48
+ # 4: apoe4: 0/1/2
49
+ # For the AD trait, diagnosis is constant (all NPH). Therefore, trait is not available for association analysis.
50
+ trait_row = None
51
+ age_row = 2
52
+ gender_row = 3
53
+
54
+ def _after_colon(value):
55
+ if value is None:
56
+ return None
57
+ s = str(value)
58
+ if ':' in s:
59
+ s = s.split(':', 1)[1]
60
+ return s.strip()
61
+
62
+ def convert_trait(v):
63
+ # Binary: 1 = Alzheimer's disease, 0 = non-AD; unknown -> None
64
+ # This function won't be used since trait_row is None, but defined for completeness.
65
+ s = _after_colon(v)
66
+ if s is None or s == '':
67
+ return None
68
+ s_low = s.lower()
69
+ if 'alzheimer' in s_low or 'alzheimer’s' in s_low or 'alzheim' in s_low:
70
+ return 1
71
+ # Map other dementia/control labels to 0 when reasonably confident
72
+ negatives = ['control', 'healthy', 'normal', 'nph', 'dlb', 'lewy', 'vascular', 'vad', 'vci', 'mci', 'non-ad', 'non alzheimer']
73
+ if any(tok in s_low for tok in negatives):
74
+ return 0
75
+ return None
76
+
77
+ def convert_age(v):
78
+ s = _after_colon(v)
79
+ if s is None or s == '':
80
+ return None
81
+ try:
82
+ return float(s)
83
+ except Exception:
84
+ return None
85
+
86
+ def convert_gender(v):
87
+ # Binary: female -> 0, male -> 1; unknown -> None
88
+ s = _after_colon(v)
89
+ if s is None or s == '':
90
+ return None
91
+ s_low = s.lower()
92
+ if s_low in ['male', 'm']:
93
+ return 1
94
+ if s_low in ['female', 'f']:
95
+ return 0
96
+ return None
97
+
98
+ # 3) Save initial metadata
99
+ is_trait_available = trait_row is not None
100
+ _ = validate_and_save_cohort_info(
101
+ is_final=False,
102
+ cohort=cohort,
103
+ info_path=json_path,
104
+ is_gene_available=is_gene_available,
105
+ is_trait_available=is_trait_available
106
+ )
107
+
108
+ # 4) Clinical Feature Extraction (skip since trait_row is None)
109
+ if (trait_row is not None) and ('clinical_data' in globals()):
110
+ selected_clinical_df = geo_select_clinical_features(
111
+ clinical_df=clinical_data,
112
+ trait=trait,
113
+ trait_row=trait_row,
114
+ convert_trait=convert_trait,
115
+ age_row=age_row,
116
+ convert_age=convert_age,
117
+ gender_row=gender_row,
118
+ convert_gender=convert_gender
119
+ )
120
+ _ = preview_df(selected_clinical_df)
121
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
122
+ selected_clinical_df.to_csv(out_clinical_data_file, index=True)
output/preprocess/Alzheimers_Disease/code/GSE185909.py ADDED
@@ -0,0 +1,218 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Alzheimers_Disease"
6
+ cohort = "GSE185909"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Alzheimers_Disease"
10
+ in_cohort_dir = "../DATA/GEO/Alzheimers_Disease/GSE185909"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z1/preprocess/Alzheimers_Disease/GSE185909.csv"
14
+ out_gene_data_file = "./output/z1/preprocess/Alzheimers_Disease/gene_data/GSE185909.csv"
15
+ out_clinical_data_file = "./output/z1/preprocess/Alzheimers_Disease/clinical_data/GSE185909.csv"
16
+ json_path = "./output/z1/preprocess/Alzheimers_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 # Nimblegen human expression array with RMA preprocessing
43
+ trait_row = 0 # diagnosis: AD/MCI/NCI
44
+ age_row = 2 # age_death: numeric
45
+ gender_row = 1 # Sex: Male/Female
46
+
47
+ def _after_colon(x):
48
+ if x is None:
49
+ return None
50
+ s = str(x)
51
+ if ':' in s:
52
+ s = s.split(':', 1)[1]
53
+ return s.strip().strip('"').strip()
54
+
55
+ def convert_trait(x):
56
+ v = _after_colon(x)
57
+ if v is None or v == '' or v.lower() in {'na', 'n/a', 'nan', 'none', 'unknown'}:
58
+ return None
59
+ vl = v.lower().replace('’', "'").replace('_', ' ').strip()
60
+ # Map AD vs non-AD (NCI and MCI considered non-AD)
61
+ if vl in {'ad', "alzheimer's disease", 'alzheimers disease', 'alzheimer disease'}:
62
+ return 1
63
+ if vl in {'nci', 'mci', 'control', 'cn', 'ctl', 'non-ad', 'no cognitive impairment', 'mild cognitive impairment'}:
64
+ return 0
65
+ return None
66
+
67
+ def convert_age(x):
68
+ v = _after_colon(x)
69
+ if v is None or v == '' or v.lower() in {'na', 'n/a', 'nan', 'none', 'unknown'}:
70
+ return None
71
+ try:
72
+ return float(v)
73
+ except Exception:
74
+ vv = ''.join(ch for ch in v if (ch.isdigit() or ch == '.' or ch == '-'))
75
+ try:
76
+ return float(vv) if vv not in {'', '-', '.'} else None
77
+ except Exception:
78
+ return None
79
+
80
+ def convert_gender(x):
81
+ v = _after_colon(x)
82
+ if v is None or v == '':
83
+ return None
84
+ vl = v.lower().strip()
85
+ if vl in {'male', 'm'}:
86
+ return 1
87
+ if vl in {'female', 'f'}:
88
+ return 0
89
+ return None
90
+
91
+ # Initial filtering and save metadata
92
+ is_trait_available = trait_row is not None
93
+ _ = validate_and_save_cohort_info(
94
+ is_final=False,
95
+ cohort=cohort,
96
+ info_path=json_path,
97
+ is_gene_available=is_gene_available,
98
+ is_trait_available=is_trait_available
99
+ )
100
+
101
+ # Clinical feature extraction
102
+ if trait_row is not None:
103
+ selected_clinical_df = geo_select_clinical_features(
104
+ clinical_df=clinical_data,
105
+ trait=trait,
106
+ trait_row=trait_row,
107
+ convert_trait=convert_trait,
108
+ age_row=age_row,
109
+ convert_age=convert_age,
110
+ gender_row=gender_row,
111
+ convert_gender=convert_gender
112
+ )
113
+ preview = preview_df(selected_clinical_df)
114
+ print("Clinical features preview:", preview)
115
+
116
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
117
+ # Preserve feature names (rows) when saving
118
+ selected_clinical_df.to_csv(out_clinical_data_file, index=True)
119
+
120
+ # Step 3: Gene Data Extraction
121
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
122
+ gene_data = get_genetic_data(matrix_file)
123
+
124
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
125
+ print(gene_data.index[:20])
126
+
127
+ # Step 4: Gene Identifier Review
128
+ requires_gene_mapping = True
129
+ print(f"requires_gene_mapping = {requires_gene_mapping}")
130
+
131
+ # Step 5: Gene Annotation
132
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
133
+ gene_annotation = get_gene_annotation(soft_file)
134
+
135
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
136
+ print("Gene annotation preview:")
137
+ print(preview_df(gene_annotation))
138
+
139
+ # Step 6: Gene Identifier Mapping
140
+ # Determine the identifier column in annotation that matches expression IDs
141
+ expr_ids = set(gene_data.index.astype(str))
142
+
143
+ # Candidate columns for probe/identifier and gene symbol
144
+ candidate_id_cols = ['ID', 'ID_REF', 'GB_ACC', 'ProbeID', 'PROBE_ID', 'Accession', 'ACCESSION']
145
+ candidate_gene_cols = [
146
+ 'Gene Symbol', 'GENE_SYMBOL', 'SYMBOL', 'Symbol', 'Gene symbol',
147
+ 'gene_assignment', 'GENE', 'GeneName', 'Gene', 'GENE_NAME',
148
+ 'Entrez_Gene', 'GENE_SYMBOLS', 'GeneSymbol', 'Description', 'DESCRIPTION'
149
+ ]
150
+
151
+ # Choose id column by maximum overlap with expression IDs
152
+ best_id_col = None
153
+ best_overlap = -1
154
+ for col in candidate_id_cols:
155
+ if col in gene_annotation.columns:
156
+ overlap = len(expr_ids.intersection(set(gene_annotation[col].astype(str))))
157
+ if overlap > best_overlap:
158
+ best_overlap = overlap
159
+ best_id_col = col
160
+
161
+ # Fallback to 'ID' if nothing else found
162
+ if best_id_col is None and 'ID' in gene_annotation.columns:
163
+ best_id_col = 'ID'
164
+
165
+ # Choose gene symbol column by availability with a preferred order
166
+ best_gene_col = None
167
+ for col in candidate_gene_cols:
168
+ if col in gene_annotation.columns:
169
+ best_gene_col = col
170
+ break
171
+
172
+ # As a final fallback, use DESCRIPTION if nothing else is found
173
+ if best_gene_col is None and 'DESCRIPTION' in gene_annotation.columns:
174
+ best_gene_col = 'DESCRIPTION'
175
+
176
+ # Build mapping dataframe
177
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=best_id_col, gene_col=best_gene_col)
178
+
179
+ # Apply mapping to convert probe-level to gene-level data
180
+ gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
181
+
182
+ # Step 7: Data Normalization and Linking
183
+ import os
184
+
185
+ # 1. Normalize gene symbols and save normalized gene data
186
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
187
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
188
+ normalized_gene_data.to_csv(out_gene_data_file)
189
+
190
+ # 2. Link clinical and genetic data
191
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
192
+
193
+ # 3. Handle missing values in the linked data
194
+ linked_data = handle_missing_values(linked_data, trait)
195
+
196
+ # 4. Determine bias and remove biased demographic features
197
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
198
+
199
+ # 5. Final validation and save cohort info (ensure native Python bools)
200
+ is_gene_available_final = bool((normalized_gene_data.shape[0] > 0) and (normalized_gene_data.shape[1] > 0))
201
+ is_trait_available_final = bool((trait in selected_clinical_df.index) and bool(selected_clinical_df.loc[trait].notna().any()))
202
+
203
+ note = "INFO: Gene IDs mapped via annotation DESCRIPTION using heuristic symbol extraction; symbols normalized using NCBI synonym mapping."
204
+ is_usable = validate_and_save_cohort_info(
205
+ is_final=True,
206
+ cohort=cohort,
207
+ info_path=json_path,
208
+ is_gene_available=is_gene_available_final,
209
+ is_trait_available=is_trait_available_final,
210
+ is_biased=bool(is_trait_biased),
211
+ df=unbiased_linked_data,
212
+ note=note
213
+ )
214
+
215
+ # 6. Save linked data if usable
216
+ if is_usable:
217
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
218
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Alzheimers_Disease/code/GSE214417.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Alzheimers_Disease"
6
+ cohort = "GSE214417"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Alzheimers_Disease"
10
+ in_cohort_dir = "../DATA/GEO/Alzheimers_Disease/GSE214417"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z1/preprocess/Alzheimers_Disease/GSE214417.csv"
14
+ out_gene_data_file = "./output/z1/preprocess/Alzheimers_Disease/gene_data/GSE214417.csv"
15
+ out_clinical_data_file = "./output/z1/preprocess/Alzheimers_Disease/clinical_data/GSE214417.csv"
16
+ json_path = "./output/z1/preprocess/Alzheimers_Disease/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ import re
40
+ import pandas as pd
41
+
42
+ # 1) Gene expression availability
43
+ # This GEO SuperSeries likely contains gene expression (non-miRNA, non-methylation) data.
44
+ is_gene_available = True
45
+
46
+ # 2) Variable availability and converters
47
+ # Human trait data is not available in this mouse model dataset; gender is constant (Male only); age is murine.
48
+ trait_row = None
49
+ age_row = None
50
+ gender_row = None
51
+
52
+ def _extract_value(x):
53
+ if x is None or (isinstance(x, float) and pd.isna(x)):
54
+ return None
55
+ s = str(x).strip()
56
+ # Extract substring after the first colon if present
57
+ parts = s.split(":", 1)
58
+ return parts[1].strip() if len(parts) == 2 else s
59
+
60
+ def convert_trait(x):
61
+ # Not available for human AD status in this mouse dataset
62
+ return None
63
+
64
+ def convert_age(x):
65
+ # Not available (murine age not used for human analysis in this context)
66
+ return None
67
+
68
+ def convert_gender(x):
69
+ # Not available (murine data and constant Male)
70
+ return None
71
+
72
+ # 3) Initial filtering and save metadata
73
+ is_trait_available = trait_row is not None
74
+ _ = validate_and_save_cohort_info(
75
+ is_final=False,
76
+ cohort=cohort,
77
+ info_path=json_path,
78
+ is_gene_available=is_gene_available,
79
+ is_trait_available=is_trait_available
80
+ )
81
+
82
+ # 4) Clinical Feature Extraction (skip since trait_row is None)
83
+ # If trait_row were available:
84
+ # if trait_row is not None:
85
+ # selected_clinical_df = geo_select_clinical_features(
86
+ # clinical_df=clinical_data,
87
+ # trait=trait,
88
+ # trait_row=trait_row,
89
+ # convert_trait=convert_trait,
90
+ # age_row=age_row,
91
+ # convert_age=convert_age,
92
+ # gender_row=gender_row,
93
+ # convert_gender=convert_gender
94
+ # )
95
+ # preview = preview_df(selected_clinical_df, n=5)
96
+ # selected_clinical_df.to_csv(out_clinical_data_file, index=True)
output/preprocess/Alzheimers_Disease/code/GSE243243.py ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Alzheimers_Disease"
6
+ cohort = "GSE243243"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Alzheimers_Disease"
10
+ in_cohort_dir = "../DATA/GEO/Alzheimers_Disease/GSE243243"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z1/preprocess/Alzheimers_Disease/GSE243243.csv"
14
+ out_gene_data_file = "./output/z1/preprocess/Alzheimers_Disease/gene_data/GSE243243.csv"
15
+ out_clinical_data_file = "./output/z1/preprocess/Alzheimers_Disease/clinical_data/GSE243243.csv"
16
+ json_path = "./output/z1/preprocess/Alzheimers_Disease/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ # Step 1: Determine gene expression data availability based on background information
40
+ # Affymetrix microarrays for RNA expression indicate gene expression data is available.
41
+ is_gene_available = True
42
+
43
+ # Step 2: Variable availability and conversion functions
44
+
45
+ # Based on the sample characteristics, none of the keys map to Alzheimer's Disease status, age, or gender.
46
+ # Keys present: 0 -> ASO treatments, 1 -> treatment time (h), 2 -> dose (microm)
47
+ trait_row = None # No AD case/control or diagnosis info
48
+ age_row = None # No age info
49
+ gender_row = None # No gender info
50
+
51
+ def _get_value_after_colon(x):
52
+ if x is None:
53
+ return None
54
+ try:
55
+ s = str(x)
56
+ except Exception:
57
+ return None
58
+ if ':' in s:
59
+ return s.split(':', 1)[1].strip()
60
+ return s.strip()
61
+
62
+ def convert_trait(x):
63
+ # Generic AD/control mapper (not used here since trait_row is None)
64
+ val = _get_value_after_colon(x)
65
+ if val is None or val == '':
66
+ return None
67
+ v = val.strip().lower()
68
+ # Map common AD labels
69
+ ad_pos = {'ad', 'alzheimer', 'alzheimer’s disease', 'alzheimer disease', 'alzheimers', 'case', 'patient'}
70
+ ad_neg = {'control', 'healthy', 'normal', 'non-ad', 'non ad', 'non_alzheimer'}
71
+ if v in ad_pos:
72
+ return 1
73
+ if v in ad_neg:
74
+ return 0
75
+ # Heuristic keywords
76
+ if 'alzheimer' in v or v == 'ad':
77
+ return 1
78
+ if 'control' in v or 'healthy' in v or 'normal' in v:
79
+ return 0
80
+ return None
81
+
82
+ def convert_age(x):
83
+ # Parse age to continuous numeric (years) if provided; not used here (age_row is None)
84
+ val = _get_value_after_colon(x)
85
+ if val is None or val == '':
86
+ return None
87
+ s = val.strip().lower()
88
+ # Remove common units or text
89
+ for tok in ['years', 'year', 'yrs', 'yr', 'y', 'yo', 'age', 'ages']:
90
+ s = s.replace(tok, '')
91
+ s = s.replace('~', '').replace('+', '').replace('>', '').replace('<', '')
92
+ try:
93
+ return float(s.strip())
94
+ except Exception:
95
+ return None
96
+
97
+ def convert_gender(x):
98
+ # Map female->0, male->1
99
+ val = _get_value_after_colon(x)
100
+ if val is None or val == '':
101
+ return None
102
+ v = val.strip().lower()
103
+ if v in {'female', 'f', 'woman', 'women', 'girl'}:
104
+ return 0
105
+ if v in {'male', 'm', 'man', 'men', 'boy'}:
106
+ return 1
107
+ return None
108
+
109
+ # Step 3: Initial filtering metadata save
110
+ is_trait_available = trait_row is not None
111
+ _ = validate_and_save_cohort_info(
112
+ is_final=False,
113
+ cohort=cohort,
114
+ info_path=json_path,
115
+ is_gene_available=is_gene_available,
116
+ is_trait_available=is_trait_available
117
+ )
118
+
119
+ # Step 4: Clinical feature extraction (skip since trait_row is None)
120
+ # If trait_row was available, we would extract and save clinical data as follows:
121
+ # selected_clinical_df = geo_select_clinical_features(
122
+ # clinical_df=clinical_data,
123
+ # trait=trait,
124
+ # trait_row=trait_row,
125
+ # convert_trait=convert_trait,
126
+ # age_row=age_row,
127
+ # convert_age=convert_age,
128
+ # gender_row=gender_row,
129
+ # convert_gender=convert_gender
130
+ # )
131
+ # preview = preview_df(selected_clinical_df)
132
+ # os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
133
+ # selected_clinical_df.to_csv(out_clinical_data_file, index=True)
output/preprocess/Alzheimers_Disease/code/TCGA.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Alzheimers_Disease"
6
+
7
+ # Input paths
8
+ tcga_root_dir = "../DATA/TCGA"
9
+
10
+ # Output paths
11
+ out_data_file = "./output/z1/preprocess/Alzheimers_Disease/TCGA.csv"
12
+ out_gene_data_file = "./output/z1/preprocess/Alzheimers_Disease/gene_data/TCGA.csv"
13
+ out_clinical_data_file = "./output/z1/preprocess/Alzheimers_Disease/clinical_data/TCGA.csv"
14
+ json_path = "./output/z1/preprocess/Alzheimers_Disease/cohort_info.json"
15
+
16
+
17
+ # Step 1: Initial Data Loading
18
+ import os
19
+ import pandas as pd
20
+
21
+ # Discover available TCGA subdirectories
22
+ all_subdirs = [d for d in os.listdir(tcga_root_dir) if os.path.isdir(os.path.join(tcga_root_dir, d))]
23
+
24
+ # Select cohort directory matching Alzheimer's Disease (none of TCGA cohorts should match; be conservative)
25
+ keywords = {"alzheimer", "alzheimers", "alzheimer's", "dementia", "neurodegenerative"}
26
+ candidates = [d for d in all_subdirs if any(k in d.lower() for k in keywords)]
27
+
28
+ selected_dir = None
29
+ if candidates:
30
+ # If any unexpected match appears, choose the one with the longest matching keyword (most specific)
31
+ def match_score(name):
32
+ lname = name.lower()
33
+ return max((len(k) for k in keywords if k in lname), default=0)
34
+ candidates.sort(key=lambda x: match_score(x), reverse=True)
35
+ selected_dir = candidates[0]
36
+
37
+ if selected_dir is None:
38
+ # No relevant TCGA cohort for Alzheimer's Disease; record and stop 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
+ cohort_path = os.path.join(tcga_root_dir, selected_dir)
48
+ clinical_file_path, genetic_file_path = tcga_get_relevant_filepaths(cohort_path)
49
+
50
+ clinical_df = pd.read_csv(clinical_file_path, sep='\t', index_col=0, low_memory=False)
51
+ genetic_df = pd.read_csv(genetic_file_path, sep='\t', index_col=0, low_memory=False)
52
+
53
+ print(clinical_df.columns.tolist())
output/preprocess/Alzheimers_Disease/cohort_info.json CHANGED
@@ -1,112 +1 @@
1
- {
2
- "GSE243243": {
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": 93
11
- },
12
- "GSE214417": {
13
- "is_usable": true,
14
- "is_gene_available": true,
15
- "is_trait_available": true,
16
- "is_available": true,
17
- "is_biased": false,
18
- "has_age": true,
19
- "has_gender": false,
20
- "sample_size": 24
21
- },
22
- "GSE185909": {
23
- "is_usable": true,
24
- "is_gene_available": true,
25
- "is_trait_available": true,
26
- "is_available": true,
27
- "is_biased": false,
28
- "has_age": true,
29
- "has_gender": true,
30
- "sample_size": 35
31
- },
32
- "GSE167559": {
33
- "is_usable": false,
34
- "is_gene_available": false,
35
- "is_trait_available": false,
36
- "is_available": false,
37
- "is_biased": null,
38
- "has_age": null,
39
- "has_gender": null,
40
- "sample_size": null
41
- },
42
- "GSE139384": {
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": false,
50
- "sample_size": 12
51
- },
52
- "GSE137202": {
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": 30
61
- },
62
- "GSE132903": {
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": 195
71
- },
72
- "GSE122063": {
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": 100
81
- },
82
- "GSE117589": {
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
- "GSE109887": {
93
- "is_usable": true,
94
- "is_gene_available": true,
95
- "is_trait_available": true,
96
- "is_available": true,
97
- "is_biased": false,
98
- "has_age": true,
99
- "has_gender": true,
100
- "sample_size": 78
101
- },
102
- "TCGA": {
103
- "is_usable": false,
104
- "is_gene_available": false,
105
- "is_trait_available": false,
106
- "is_available": false,
107
- "is_biased": null,
108
- "has_age": null,
109
- "has_gender": null,
110
- "sample_size": null
111
- }
112
- }
 
1
+ {"GSE243243": {"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}, "GSE214417": {"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}, "GSE185909": {"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": 35, "note": "INFO: Gene IDs mapped via annotation DESCRIPTION using heuristic symbol extraction; symbols normalized using NCBI synonym mapping."}, "GSE167559": {"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}, "GSE139384": {"is_usable": true, "is_gene_available": true, "is_trait_available": true, "is_available": true, "is_biased": false, "has_age": true, "has_gender": true, "sample_size": 33, "note": "INFO: Normalized gene symbols using NCBI synonyms; linked clinical data; applied systematic missing value handling and bias checks."}, "GSE137202": {"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": 30, "note": "INFO: Cell line AD model (WT vs mutated); no Age/Gender covariates available."}, "GSE132903": {"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": 195, "note": "INFO: Illumina HT-12 V4 probes mapped to gene symbols; split multi-gene probes; ages like '90+' parsed as 90."}, "GSE122063": {"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": 136, "note": "INFO: Trait encoded as AD=1, Control/VaD=0. Agilent Human 8x60k v2; dual channel processed as single channel. Brain regions: frontal and temporal cortex."}, "GSE117589": {"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": 31, "note": "INFO: Age and Gender parsed from combined 'subject' field (e.g., '72M'); trait from 'diagnosis' row."}, "GSE109887": {"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": 78, "note": "INFO: Illumina HumanHT-12 v4 expression data; identifiers mapped using annotation ('ID'->'ORF'); gene symbols normalized via NCBI synonyms. Clinical features include Alzheimers_Disease trait, Age, Gender."}, "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/Alzheimers_Disease/gene_data/GSE117589.csv CHANGED
The diff for this file is too large to render. See raw diff
 
output/preprocess/Amyotrophic_Lateral_Sclerosis/GSE139384.csv ADDED
The diff for this file is too large to render. See raw diff
 
output/preprocess/Amyotrophic_Lateral_Sclerosis/GSE68608.csv ADDED
The diff for this file is too large to render. See raw diff
 
output/preprocess/Amyotrophic_Lateral_Sclerosis/clinical_data/GSE118336.csv CHANGED
@@ -1,2 +1,2 @@
1
- ,0,1,2
2
- Amyotrophic_Lateral_Sclerosis,0.0,1.0,1.0
 
1
+ ,GSM3325490,GSM3325491,GSM3325492,GSM3325493,GSM3325494,GSM3325495,GSM3325496,GSM3325497,GSM3325498,GSM3325499,GSM3325500,GSM3325501,GSM3325502,GSM3325503,GSM3325504,GSM3325505,GSM3325506,GSM3325507,GSM3325508,GSM3325509,GSM3325510,GSM3325511,GSM3325512,GSM3325513,GSM3325514,GSM3325515,GSM3325516,GSM3325517,GSM3325518,GSM3325519,GSM3325520,GSM3325521,GSM3325522,GSM3325523,GSM3325524,GSM3325525,GSM3325526,GSM3325527,GSM3325528,GSM3325529,GSM3325530,GSM3325531,GSM3325532,GSM3325533,GSM3325534,GSM3325535,GSM3325536,GSM3325537,GSM3325538,GSM3325539,GSM3325540,GSM3325541,GSM3325542,GSM3325543,GSM3325544,GSM3325545,GSM3325546,GSM3325547,GSM3325548,GSM3325549
2
+ Amyotrophic_Lateral_Sclerosis,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,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
output/preprocess/Amyotrophic_Lateral_Sclerosis/clinical_data/GSE139384.csv CHANGED
@@ -1,4 +1,4 @@
1
- Sample_0,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
2
- 0.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,,,,,,
3
- ,66.0,77.0,70.0,74.0,76.0,60.0,79.0,71.0,63.0,65.0,81.0,73.0,72.0,75.0,85.0
4
- ,,0.0,1.0,,,,,,,,,,,,
 
1
+ ,GSM4140293,GSM4140294,GSM4140295,GSM4140296,GSM4140297,GSM4140298,GSM4140299,GSM4140300,GSM4140301,GSM4140302,GSM4140303,GSM4140304,GSM4140305,GSM4140306,GSM4140307,GSM4140308,GSM4140309,GSM4140310,GSM4140311,GSM4140312,GSM4140313,GSM4140314,GSM4140315,GSM4140316,GSM4140317,GSM4140318,GSM4140319,GSM4140320,GSM4140321,GSM4140322,GSM4140323,GSM4140324,GSM4140325
2
+ Amyotrophic_Lateral_Sclerosis,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,0.0,0.0,0.0,1.0,1.0,1.0,1.0,0.0,0.0,1.0,1.0,0.0,0.0,0.0,1.0,0.0
3
+ Age,,,,,,,,,,,,,66.0,77.0,70.0,74.0,76.0,60.0,79.0,71.0,63.0,65.0,70.0,81.0,70.0,74.0,73.0,72.0,72.0,75.0,85.0,76.0,74.0
4
+ Gender,,,,,,,,,,,,,0.0,1.0,0.0,0.0,0.0,0.0,1.0,0.0,0.0,1.0,0.0,0.0,0.0,1.0,0.0,1.0,0.0,1.0,1.0,0.0,0.0
output/preprocess/Amyotrophic_Lateral_Sclerosis/clinical_data/GSE26927.csv CHANGED
@@ -1,4 +1,4 @@
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
- Amyotrophic_Lateral_Sclerosis,0.0,0.0,0.0,0.0,0.0,0.0,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,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,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
 
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
+ 0.0,0.0,0.0,0.0,0.0,0.0,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,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,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
+ 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
+ 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/Amyotrophic_Lateral_Sclerosis/clinical_data/GSE68608.csv CHANGED
@@ -1,2 +1,2 @@
1
- ID_REF,1
2
- ,1.0
 
1
+ ,GSM1676853,GSM1676854,GSM1676855,GSM1676856,GSM1676857,GSM1676858,GSM1676859,GSM1676860,GSM1676861,GSM1676862,GSM1676863
2
+ Amyotrophic_Lateral_Sclerosis,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0
output/preprocess/Amyotrophic_Lateral_Sclerosis/code/GSE118336.py ADDED
@@ -0,0 +1,254 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Amyotrophic_Lateral_Sclerosis"
6
+ cohort = "GSE118336"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Amyotrophic_Lateral_Sclerosis"
10
+ in_cohort_dir = "../DATA/GEO/Amyotrophic_Lateral_Sclerosis/GSE118336"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z1/preprocess/Amyotrophic_Lateral_Sclerosis/GSE118336.csv"
14
+ out_gene_data_file = "./output/z1/preprocess/Amyotrophic_Lateral_Sclerosis/gene_data/GSE118336.csv"
15
+ out_clinical_data_file = "./output/z1/preprocess/Amyotrophic_Lateral_Sclerosis/clinical_data/GSE118336.csv"
16
+ json_path = "./output/z1/preprocess/Amyotrophic_Lateral_Sclerosis/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 # HTA2.0 human transcriptome array indicates mRNA expression profiling.
44
+
45
+ # 2. Variable Availability and Data Type Conversion
46
+
47
+ # 2.1 Identify rows in the sample characteristics
48
+ trait_row = 1 # 'genotype' with values including WT/WT and H517D variants; map to ALS status (case/control)
49
+ age_row = None # No human age available; 'time (differentiation ...)' is not human age
50
+ gender_row = None # No gender information available
51
+
52
+ # 2.2 Converters
53
+ def _extract_value(x):
54
+ if x is None:
55
+ return None
56
+ if not isinstance(x, str):
57
+ return None
58
+ # Take value after the last colon to be robust to extra colons
59
+ parts = x.split(':')
60
+ val = parts[-1].strip() if parts else None
61
+ return val if val != '' else None
62
+
63
+ def convert_trait(x):
64
+ """
65
+ Binary mapping for ALS status proxied by FUS H517D mutation status in genotype:
66
+ - 1 if genotype contains H517D (mutant; disease model)
67
+ - 0 if genotype is WT/WT (control)
68
+ - None otherwise
69
+ """
70
+ v = _extract_value(x)
71
+ if v is None:
72
+ return None
73
+ v_low = v.lower().replace(' ', '')
74
+ # Any presence of H517D indicates mutant (case)
75
+ if 'h517d' in v_low:
76
+ return 1
77
+ # Explicit wildtype control
78
+ if 'wt/wt' in v_low:
79
+ return 0
80
+ return None
81
+
82
+ def convert_age(x):
83
+ # Not applicable; return None
84
+ return None
85
+
86
+ def convert_gender(x):
87
+ # Not applicable; return None
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=None,
109
+ gender_row=gender_row,
110
+ convert_gender=None
111
+ )
112
+ print(preview_df(selected_clinical_df))
113
+
114
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
115
+ selected_clinical_df.to_csv(out_clinical_data_file)
116
+
117
+ # Step 3: Gene Data Extraction
118
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
119
+ gene_data = get_genetic_data(matrix_file)
120
+
121
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
122
+ print(gene_data.index[:20])
123
+
124
+ # Step 4: Gene Identifier Review
125
+ requires_gene_mapping = True
126
+ print(f"requires_gene_mapping = {requires_gene_mapping}")
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
+ import re
138
+
139
+ # Determine which annotation column best matches the probe IDs in gene_data.index
140
+ gene_ids = set(gene_data.index.astype(str))
141
+
142
+ best_col = None
143
+ best_mode = None # 'direct' or 'suffixed'
144
+ best_overlap = -1
145
+
146
+ # Try to match annotation columns to expression IDs
147
+ for col in gene_annotation.columns:
148
+ col_values = gene_annotation[col].astype(str).str.strip()
149
+ col_values_norm = col_values.str.replace(r'\.0$', '', regex=True)
150
+
151
+ direct_set = set(col_values_norm)
152
+ # Common Affymetrix suffix used in this dataset is "_st"
153
+ suffixed_set = set(v + '_st' for v in col_values_norm)
154
+
155
+ # Compute overlaps
156
+ direct_overlap = len(direct_set & gene_ids)
157
+ suffixed_overlap = len(suffixed_set & gene_ids)
158
+
159
+ # Choose the best mode for this column
160
+ if direct_overlap > best_overlap:
161
+ best_overlap = direct_overlap
162
+ best_col = col
163
+ best_mode = 'direct'
164
+ if suffixed_overlap > best_overlap:
165
+ best_overlap = suffixed_overlap
166
+ best_col = col
167
+ best_mode = 'suffixed'
168
+
169
+ print(f"[DEBUG] Best matching annotation column: {best_col} (mode={best_mode}), overlap={best_overlap}")
170
+
171
+ # Fail fast if no overlap found
172
+ if best_overlap == 0 or best_col is None:
173
+ raise ValueError(
174
+ "No overlap between annotation identifiers and expression IDs was found.\n"
175
+ "The annotation preview shows IDs like 'TC01000001.hg.1' while the expression IDs look like '2824546_st'.\n"
176
+ "This suggests the SOFT annotation corresponds to transcript-cluster IDs (TC...), whereas the matrix uses "
177
+ "probeset IDs with '_st' suffix. Please provide the correct platform (GPL) annotation for probeset-level IDs."
178
+ )
179
+
180
+ # Prepare a mapping ID column in the annotation that aligns with gene_data.index
181
+ mapping_id_col = "__probe_id_for_mapping__"
182
+ ann_values = gene_annotation[best_col].astype(str).str.strip().str.replace(r'\.0$', '', regex=True)
183
+ if best_mode == 'direct':
184
+ gene_annotation[mapping_id_col] = ann_values
185
+ else:
186
+ gene_annotation[mapping_id_col] = ann_values + "_st"
187
+
188
+ # Choose a gene-symbol containing column
189
+ if 'gene_assignment' in gene_annotation.columns:
190
+ gene_col = 'gene_assignment'
191
+ elif 'mrna_assignment' in gene_annotation.columns:
192
+ gene_col = 'mrna_assignment'
193
+ else:
194
+ candidates = [c for c in gene_annotation.columns if re.search(r'symbol|gene', c, re.IGNORECASE)]
195
+ gene_col = candidates[0] if candidates else gene_annotation.columns[0]
196
+
197
+ print(f"[DEBUG] Selected gene symbol column: {gene_col}")
198
+
199
+ # Build mapping dataframe
200
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=mapping_id_col, gene_col=gene_col)
201
+
202
+ # Validate that mapping_df actually intersects with expression IDs
203
+ id_intersection = set(mapping_df['ID']) & gene_ids
204
+ print(f"[DEBUG] Mapping rows intersecting expression IDs: {len(id_intersection)}")
205
+ if len(id_intersection) == 0:
206
+ raise ValueError(
207
+ "Mapping failed: No overlap between mapping_df IDs and expression_df index after preprocessing. "
208
+ "Likely due to mismatched identifier systems (TC... vs probeset '_st')."
209
+ )
210
+
211
+ # Apply mapping to convert probe-level data to gene-level expression
212
+ gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
213
+ print(f"[DEBUG] Gene-level data shape after mapping: {gene_data.shape}")
214
+
215
+ # Step 7: Data Normalization and Linking
216
+ import os
217
+ import builtins
218
+
219
+ # 1. Normalize gene symbols and save
220
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
221
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
222
+ normalized_gene_data.to_csv(out_gene_data_file)
223
+
224
+ # 2. Link clinical and genetic data
225
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
226
+
227
+ # 3. Handle missing values
228
+ linked_data = handle_missing_values(linked_data, trait)
229
+
230
+ # 4. Assess bias and remove biased demographic features
231
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
232
+
233
+ # 5. Final validation and save cohort info
234
+ # Ensure native Python bools for JSON serialization
235
+ is_gene_available_flag = builtins.bool((normalized_gene_data.shape[0] > 0) and (normalized_gene_data.shape[1] > 0))
236
+ is_trait_available_flag = builtins.bool((trait in unbiased_linked_data.columns) and builtins.bool(unbiased_linked_data[trait].notna().any()))
237
+ is_trait_biased_flag = builtins.bool(is_trait_biased)
238
+
239
+ note = "INFO: Trait derived from genotype (FUS H517D) in iPSC-derived MNs; HTA2.0 array."
240
+ is_usable = validate_and_save_cohort_info(
241
+ is_final=True,
242
+ cohort=cohort,
243
+ info_path=json_path,
244
+ is_gene_available=is_gene_available_flag,
245
+ is_trait_available=is_trait_available_flag,
246
+ is_biased=is_trait_biased_flag,
247
+ df=unbiased_linked_data,
248
+ note=note
249
+ )
250
+
251
+ # 6. Save linked data if usable
252
+ if is_usable:
253
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
254
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Amyotrophic_Lateral_Sclerosis/code/GSE139384.py ADDED
@@ -0,0 +1,213 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Amyotrophic_Lateral_Sclerosis"
6
+ cohort = "GSE139384"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Amyotrophic_Lateral_Sclerosis"
10
+ in_cohort_dir = "../DATA/GEO/Amyotrophic_Lateral_Sclerosis/GSE139384"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z1/preprocess/Amyotrophic_Lateral_Sclerosis/GSE139384.csv"
14
+ out_gene_data_file = "./output/z1/preprocess/Amyotrophic_Lateral_Sclerosis/gene_data/GSE139384.csv"
15
+ out_clinical_data_file = "./output/z1/preprocess/Amyotrophic_Lateral_Sclerosis/clinical_data/GSE139384.csv"
16
+ json_path = "./output/z1/preprocess/Amyotrophic_Lateral_Sclerosis/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ # Determine data availability based on background info
40
+ is_gene_available = True # Illumina HumanHT-12 v4 Expression BeadChip (mRNA expression)
41
+
42
+ # Identify rows in the sample characteristics dictionary
43
+ trait_row = 0 # Contains clinical phenotypes (ALS, PDC, ALS+D, PDC+A) and subject IDs (CT#, AD#)
44
+ age_row = 2 # Contains most age values
45
+ gender_row = 1 # Contains gender values
46
+
47
+ # Conversion utilities
48
+ def _after_colon(value):
49
+ if value is None:
50
+ return None
51
+ if not isinstance(value, str):
52
+ try:
53
+ value = str(value)
54
+ except Exception:
55
+ return None
56
+ parts = value.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
+ vl = v.lower().replace('`', "'").strip()
66
+ # Direct phenotype mappings
67
+ if vl in {"als", "als+d"}:
68
+ return 1
69
+ if vl in {"pdc", "pdc+a", "alzheimer's disease", "alzheimer’s disease", "healthy control", "control"}:
70
+ return 0
71
+ # Heuristic: subject IDs indicating controls
72
+ # CT# -> Healthy Control; AD# -> Alzheimer's Disease
73
+ if vl.startswith("ct"):
74
+ return 0
75
+ if vl.startswith("ad"):
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
+ # Filter out non-age entries inadvertently present in this row
84
+ if v.lower().startswith("gender") or v.lower().startswith("tissue"):
85
+ return None
86
+ # Extract numeric age
87
+ try:
88
+ vnum = ''.join(ch for ch in v if (ch.isdigit() or ch == '.' or ch == '-'))
89
+ if vnum == "" or vnum == "-":
90
+ return None
91
+ return float(vnum)
92
+ except Exception:
93
+ return None
94
+
95
+ def convert_gender(x):
96
+ v = _after_colon(x)
97
+ if v is None:
98
+ return None
99
+ vl = v.lower()
100
+ if vl.startswith("female"):
101
+ return 0
102
+ if vl.startswith("male"):
103
+ return 1
104
+ return None
105
+
106
+ # Initial filtering metadata save
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, preview, and save
117
+ if trait_row is not None:
118
+ selected_clinical_df = geo_select_clinical_features(
119
+ clinical_df=clinical_data,
120
+ trait=trait,
121
+ trait_row=trait_row,
122
+ convert_trait=convert_trait,
123
+ age_row=age_row,
124
+ convert_age=convert_age,
125
+ gender_row=gender_row,
126
+ convert_gender=convert_gender
127
+ )
128
+ clinical_preview = preview_df(selected_clinical_df, n=5)
129
+ print(clinical_preview)
130
+
131
+ import os
132
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
133
+ selected_clinical_df.to_csv(out_clinical_data_file)
134
+
135
+ # Step 3: Gene Data Extraction
136
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
137
+ gene_data = get_genetic_data(matrix_file)
138
+
139
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
140
+ print(gene_data.index[:20])
141
+
142
+ # Step 4: Gene Identifier Review
143
+ requires_gene_mapping = True
144
+ print(f"requires_gene_mapping = {requires_gene_mapping}")
145
+
146
+ # Step 5: Gene Annotation
147
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
148
+ gene_annotation = get_gene_annotation(soft_file)
149
+
150
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
151
+ print("Gene annotation preview:")
152
+ print(preview_df(gene_annotation))
153
+
154
+ # Step 6: Gene Identifier Mapping
155
+ # Decide the appropriate columns in the annotation for probe IDs and gene symbols
156
+ probe_col = 'ID'
157
+ gene_symbol_col = 'Symbol' if 'Symbol' in gene_annotation.columns else 'ILMN_Gene'
158
+
159
+ # Build mapping dataframe
160
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=probe_col, gene_col=gene_symbol_col)
161
+
162
+ # Apply mapping to convert probe-level data to gene-level data
163
+ gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
164
+
165
+ # Step 7: Data Normalization and Linking
166
+ import os
167
+ import pandas as pd
168
+
169
+ # 1. Normalize gene symbols and save
170
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
171
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
172
+ normalized_gene_data.to_csv(out_gene_data_file)
173
+
174
+ # 2. Link clinical and genetic data
175
+ try:
176
+ selected_clinical_df
177
+ except NameError:
178
+ # Fallback: load previously saved clinical features
179
+ selected_clinical_df = pd.read_csv(out_clinical_data_file, index_col=0)
180
+
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. Bias assessment (remove biased covariates if needed)
187
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
188
+
189
+ # Derive availability flags from actual data status, coerce to native Python bool
190
+ is_gene_available = bool((normalized_gene_data.shape[0] > 0) and (normalized_gene_data.shape[1] > 0))
191
+ has_trait_row = bool(isinstance(selected_clinical_df, pd.DataFrame) and (trait in selected_clinical_df.index))
192
+ trait_non_na_any = bool(selected_clinical_df.loc[trait].notna().any()) if has_trait_row else False
193
+ is_trait_available = bool(has_trait_row and trait_non_na_any)
194
+
195
+ # 5. Final validation and save cohort metadata
196
+ note = ("INFO: Illumina HumanHT-12 v4 platform; probe->gene mapping applied using SOFT annotation; "
197
+ "multi-mapped probes split equally and summed per gene; gene symbols normalized via NCBI synonyms; "
198
+ "trait mapped as ALS=1, non-ALS (PDC/AD/Control)=0.")
199
+ is_usable = validate_and_save_cohort_info(
200
+ is_final=True,
201
+ cohort=cohort,
202
+ info_path=json_path,
203
+ is_gene_available=bool(is_gene_available),
204
+ is_trait_available=bool(is_trait_available),
205
+ is_biased=bool(is_trait_biased),
206
+ df=unbiased_linked_data,
207
+ note=note
208
+ )
209
+
210
+ # 6. Save linked data if usable
211
+ if bool(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/Amyotrophic_Lateral_Sclerosis/code/GSE212131.py ADDED
@@ -0,0 +1,221 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Amyotrophic_Lateral_Sclerosis"
6
+ cohort = "GSE212131"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Amyotrophic_Lateral_Sclerosis"
10
+ in_cohort_dir = "../DATA/GEO/Amyotrophic_Lateral_Sclerosis/GSE212131"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z1/preprocess/Amyotrophic_Lateral_Sclerosis/GSE212131.csv"
14
+ out_gene_data_file = "./output/z1/preprocess/Amyotrophic_Lateral_Sclerosis/gene_data/GSE212131.csv"
15
+ out_clinical_data_file = "./output/z1/preprocess/Amyotrophic_Lateral_Sclerosis/clinical_data/GSE212131.csv"
16
+ json_path = "./output/z1/preprocess/Amyotrophic_Lateral_Sclerosis/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 Exon 1.0ST microarray for mRNA indicates gene expression data is present.
41
+
42
+ # 2. Variable Availability and Data Type Conversion
43
+
44
+ # Based on the sample characteristics dictionary: {0: ['gender: Male', 'gender: Female']}
45
+ trait_row = None # All samples are ALS patients; no case-control variability provided.
46
+ age_row = None # No age information found.
47
+ gender_row = 0 # Gender information is available.
48
+
49
+ # Conversion functions
50
+ def _extract_after_colon(x):
51
+ if x is None:
52
+ return None
53
+ s = str(x)
54
+ if ':' in s:
55
+ s = s.split(':', 1)[1]
56
+ return s.strip()
57
+
58
+ def convert_trait(x):
59
+ # Binary: ALS = 1, Control/Healthy = 0
60
+ v = _extract_after_colon(x)
61
+ if v is None or v == '':
62
+ return None
63
+ vl = v.lower()
64
+ # Heuristics for ALS vs control
65
+ if 'als' in vl or 'amyotrophic lateral sclerosis' in vl:
66
+ return 1
67
+ if 'control' in vl or 'healthy' in vl or 'normal' in vl:
68
+ return 0
69
+ return None
70
+
71
+ def convert_age(x):
72
+ # Continuous: extract numeric age in years if present
73
+ v = _extract_after_colon(x)
74
+ if v is None or v == '':
75
+ return None
76
+ vl = v.lower()
77
+ # Remove common units/words
78
+ for token in ['years', 'year', 'yrs', 'yr', 'y/o', 'yo', 'age']:
79
+ vl = vl.replace(token, '')
80
+ vl = vl.replace('~', ' ').replace('+', ' ').replace('approximately', ' ')
81
+ vl = ''.join(ch if ch.isdigit() or ch == '.' else ' ' for ch in vl)
82
+ try:
83
+ nums = [float(t) for t in vl.split() if t.replace('.', '', 1).isdigit()]
84
+ if len(nums) == 0:
85
+ return None
86
+ return nums[0]
87
+ except Exception:
88
+ return None
89
+
90
+ def convert_gender(x):
91
+ # Binary: Female = 0, Male = 1
92
+ v = _extract_after_colon(x)
93
+ if v is None or v == '':
94
+ return None
95
+ vl = v.lower().strip()
96
+ if vl in ['male', 'm', 'man', 'boy']:
97
+ return 1
98
+ if vl in ['female', 'f', 'woman', 'girl']:
99
+ return 0
100
+ return None
101
+
102
+ # 3. Save Metadata with initial filtering
103
+ is_trait_available = trait_row is not None
104
+ _ = validate_and_save_cohort_info(
105
+ is_final=False,
106
+ cohort=cohort,
107
+ info_path=json_path,
108
+ is_gene_available=is_gene_available,
109
+ is_trait_available=is_trait_available
110
+ )
111
+
112
+ # 4. Clinical Feature Extraction (skip because trait_row is None)
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_df(selected_clinical_df)
125
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
126
+ selected_clinical_df.to_csv(out_clinical_data_file, index=False)
127
+
128
+ # Step 3: Gene Data Extraction
129
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
130
+ gene_data = get_genetic_data(matrix_file)
131
+
132
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
133
+ print(gene_data.index[:20])
134
+
135
+ # Step 4: Gene Identifier Review
136
+ print("requires_gene_mapping = True")
137
+
138
+ # Step 5: Gene Annotation
139
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
140
+ gene_annotation = get_gene_annotation(soft_file)
141
+
142
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
143
+ print("Gene annotation preview:")
144
+ print(preview_df(gene_annotation))
145
+
146
+ # Step 6: Gene Identifier Mapping
147
+ # Map probe IDs to gene symbols using the annotation, then aggregate to gene-level expression.
148
+
149
+ # 1-2. Identify identifier and gene symbol columns and build mapping dataframe
150
+ # Probe/ID column: 'ID' (matches expression data index)
151
+ # Gene symbol info column: 'gene_assignment'
152
+ mapping_df = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='gene_assignment')
153
+
154
+ # 3. Apply mapping to convert probe-level data to gene-level expression
155
+ probe_data = gene_data # keep original probe-level data
156
+ gene_data = apply_gene_mapping(probe_data, 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 step context
167
+ trait_available = ('trait_row' in locals()) and (trait_row is not None)
168
+
169
+ # 2-6. Link data and downstream processing only if trait data is available
170
+ linked_data = None
171
+ if trait_available:
172
+ # Ensure clinical features are available; create if missing
173
+ if 'selected_clinical_df' not in locals():
174
+ selected_clinical_df = geo_select_clinical_features(
175
+ clinical_df=clinical_data,
176
+ trait=trait,
177
+ trait_row=trait_row,
178
+ convert_trait=convert_trait,
179
+ age_row=age_row,
180
+ convert_age=convert_age,
181
+ gender_row=gender_row,
182
+ convert_gender=convert_gender
183
+ )
184
+
185
+ # Link clinical and genetic data
186
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
187
+
188
+ # Handle missing values
189
+ linked_data = handle_missing_values(linked_data, trait)
190
+
191
+ # Bias assessment and removal of biased demographics
192
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
193
+
194
+ # Final validation and save cohort info
195
+ is_usable = validate_and_save_cohort_info(
196
+ is_final=True,
197
+ cohort=cohort,
198
+ info_path=json_path,
199
+ is_gene_available=True,
200
+ is_trait_available=True,
201
+ is_biased=is_trait_biased,
202
+ df=unbiased_linked_data,
203
+ note="INFO: Linked clinical and gene data; performed missing value handling and bias checks."
204
+ )
205
+
206
+ # Save linked data only if usable
207
+ if is_usable:
208
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
209
+ unbiased_linked_data.to_csv(out_data_file)
210
+ else:
211
+ # Trait unavailable; skip linking and mark as not usable
212
+ is_usable = validate_and_save_cohort_info(
213
+ is_final=True,
214
+ cohort=cohort,
215
+ info_path=json_path,
216
+ is_gene_available=True,
217
+ is_trait_available=False,
218
+ is_biased=False,
219
+ df=normalized_gene_data.T,
220
+ note="INFO: Trait unavailable in this series; only gender present. Skipping linkage and marking cohort as not usable for association analysis."
221
+ )
output/preprocess/Amyotrophic_Lateral_Sclerosis/code/GSE212134.py ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Amyotrophic_Lateral_Sclerosis"
6
+ cohort = "GSE212134"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Amyotrophic_Lateral_Sclerosis"
10
+ in_cohort_dir = "../DATA/GEO/Amyotrophic_Lateral_Sclerosis/GSE212134"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z1/preprocess/Amyotrophic_Lateral_Sclerosis/GSE212134.csv"
14
+ out_gene_data_file = "./output/z1/preprocess/Amyotrophic_Lateral_Sclerosis/gene_data/GSE212134.csv"
15
+ out_clinical_data_file = "./output/z1/preprocess/Amyotrophic_Lateral_Sclerosis/clinical_data/GSE212134.csv"
16
+ json_path = "./output/z1/preprocess/Amyotrophic_Lateral_Sclerosis/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
+ # Based on the SuperSeries title mentioning mRNA (gene expression) and microRNA, consider gene expression available.
44
+ is_gene_available = True
45
+
46
+ # 2. Variable Availability and Data Type Conversion
47
+
48
+ # 2.1 Data Availability
49
+ # From the sample characteristics dictionary: only gender information is available at key 0.
50
+ # Trait (ALS) is constant or not explicitly available => not usable for association analysis.
51
+ trait_row = None
52
+ age_row = None
53
+ gender_row = 0
54
+
55
+ # 2.2 Data Type Conversion
56
+
57
+ def _after_colon(x):
58
+ if x is None:
59
+ return None
60
+ s = str(x)
61
+ parts = s.split(":", 1)
62
+ val = parts[1] if len(parts) > 1 else parts[0]
63
+ return val.strip()
64
+
65
+ def convert_trait(x):
66
+ # Generic mapper for case/control if present; returns 1 for ALS/case, 0 for control; else None.
67
+ val = _after_colon(x)
68
+ if val is None:
69
+ return None
70
+ v = val.strip().lower()
71
+ # Positive mappings
72
+ pos_terms = [
73
+ "als", "amyotrophic lateral sclerosis", "patient", "case",
74
+ "als patient", "als_case", "disease: als"
75
+ ]
76
+ neg_terms = ["control", "healthy", "normal", "non-als", "non als", "hc"]
77
+ if any(t == v or t in v for t in pos_terms):
78
+ return 1
79
+ if any(t == v or t in v for t in neg_terms):
80
+ return 0
81
+ return None
82
+
83
+ def convert_age(x):
84
+ # Return age in years as float if parsable; else None.
85
+ val = _after_colon(x)
86
+ if val is None:
87
+ return None
88
+ v = val.lower()
89
+ # Extract first number (int/float)
90
+ m = re.search(r"(\d+(\.\d+)?)", v)
91
+ if not m:
92
+ return None
93
+ num = float(m.group(1))
94
+ # Unit inference
95
+ if "month" in v or "mo" in v:
96
+ return num / 12.0
97
+ if "week" in v or "wk" in v or "wks" in v:
98
+ return num / 52.0
99
+ if "day" in v or "d " in v or v.endswith("d"):
100
+ return num / 365.25
101
+ # default assume years
102
+ return num
103
+
104
+ def convert_gender(x):
105
+ val = _after_colon(x)
106
+ if val is None:
107
+ return None
108
+ v = val.strip().lower()
109
+ if v in ["female", "f", "woman", "women"]:
110
+ return 0
111
+ if v in ["male", "m", "man", "men"]:
112
+ return 1
113
+ return None
114
+
115
+ # 3. Save Metadata (initial filtering)
116
+ is_trait_available = trait_row is not None
117
+ _ = validate_and_save_cohort_info(
118
+ is_final=False,
119
+ cohort=cohort,
120
+ info_path=json_path,
121
+ is_gene_available=is_gene_available,
122
+ is_trait_available=is_trait_available
123
+ )
124
+
125
+ # 4. Clinical Feature Extraction (skip if trait_row is None)
126
+ if trait_row is not None and 'clinical_data' in globals():
127
+ selected_clinical_df = geo_select_clinical_features(
128
+ clinical_df=clinical_data,
129
+ trait=trait,
130
+ trait_row=trait_row,
131
+ convert_trait=convert_trait,
132
+ age_row=age_row,
133
+ convert_age=convert_age if age_row is not None else None,
134
+ gender_row=gender_row,
135
+ convert_gender=convert_gender if gender_row is not None else None
136
+ )
137
+ preview = preview_df(selected_clinical_df, n=5)
138
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
139
+ selected_clinical_df.to_csv(out_clinical_data_file)
output/preprocess/Amyotrophic_Lateral_Sclerosis/code/GSE26927.py ADDED
@@ -0,0 +1,214 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Amyotrophic_Lateral_Sclerosis"
6
+ cohort = "GSE26927"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Amyotrophic_Lateral_Sclerosis"
10
+ in_cohort_dir = "../DATA/GEO/Amyotrophic_Lateral_Sclerosis/GSE26927"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z1/preprocess/Amyotrophic_Lateral_Sclerosis/GSE26927.csv"
14
+ out_gene_data_file = "./output/z1/preprocess/Amyotrophic_Lateral_Sclerosis/gene_data/GSE26927.csv"
15
+ out_clinical_data_file = "./output/z1/preprocess/Amyotrophic_Lateral_Sclerosis/clinical_data/GSE26927.csv"
16
+ json_path = "./output/z1/preprocess/Amyotrophic_Lateral_Sclerosis/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
+ # Illumina HumanRef-8 v2 BeadChip is a whole-genome expression array -> gene data available
45
+ is_gene_available = True
46
+
47
+ # 2) Variable Availability
48
+ # From the provided Sample Characteristics Dictionary:
49
+ # 0 -> disease: ...
50
+ # 1 -> gender: M/F
51
+ # 2 -> age at death (in years): ...
52
+ trait_row = 0
53
+ age_row = 2
54
+ gender_row = 1
55
+
56
+ # 2.2) Data Type Conversion Functions
57
+ def _after_colon(x):
58
+ if x is None:
59
+ return None
60
+ if isinstance(x, (int, float)):
61
+ return x
62
+ s = str(x)
63
+ if ':' in s:
64
+ s = s.split(':', 1)[1]
65
+ return s.strip()
66
+
67
+ def convert_trait(x):
68
+ v = _after_colon(x)
69
+ if v is None or v == '' or v == '?':
70
+ return None
71
+ v_low = v.lower()
72
+ # Map ALS to 1, other diseases to 0
73
+ if 'amyotrophic' in v_low and 'lateral' in v_low and 'sclerosis' in v_low:
74
+ return 1
75
+ # Common abbreviations or synonyms (safety)
76
+ if v_low in {'als', 'amyotrophic lateral sclerosis'}:
77
+ return 1
78
+ # For other disease labels in this dataset, map to 0
79
+ known_non_als = [
80
+ "huntington", "parkinson", "multiple sclerosis", "schizophrenia", "alzheimer"
81
+ ]
82
+ if any(k in v_low for k in known_non_als):
83
+ return 0
84
+ # If unknown label appears, default to None to avoid mislabeling
85
+ return None
86
+
87
+ def convert_age(x):
88
+ v = _after_colon(x)
89
+ if v is None:
90
+ return None
91
+ v = str(v).strip()
92
+ if v in {'', '?', 'na', 'n/a', 'none'}:
93
+ return None
94
+ # Extract first numeric (int or float)
95
+ m = re.search(r'[-+]?\d*\.?\d+', v)
96
+ if not m:
97
+ return None
98
+ try:
99
+ return float(m.group())
100
+ except Exception:
101
+ return None
102
+
103
+ def convert_gender(x):
104
+ v = _after_colon(x)
105
+ if v is None:
106
+ return None
107
+ v_low = str(v).strip().lower()
108
+ if v_low in {'f', 'female'}:
109
+ return 0
110
+ if v_low in {'m', 'male'}:
111
+ return 1
112
+ return None
113
+
114
+ # 3) Save Metadata (initial filtering)
115
+ is_trait_available = trait_row is not None
116
+ _ = validate_and_save_cohort_info(
117
+ is_final=False,
118
+ cohort=cohort,
119
+ info_path=json_path,
120
+ is_gene_available=is_gene_available,
121
+ is_trait_available=is_trait_available
122
+ )
123
+
124
+ # 4) Clinical Feature Extraction (only if trait is available)
125
+ if trait_row is not None:
126
+ selected = geo_select_clinical_features(
127
+ clinical_df=clinical_data,
128
+ trait=trait,
129
+ trait_row=trait_row,
130
+ convert_trait=convert_trait,
131
+ age_row=age_row,
132
+ convert_age=convert_age,
133
+ gender_row=gender_row,
134
+ convert_gender=convert_gender
135
+ )
136
+ # Preview
137
+ preview = preview_df(selected)
138
+ print(preview)
139
+
140
+ # Ensure output directory exists and save
141
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
142
+ selected.to_csv(out_clinical_data_file, index=False)
143
+
144
+ # Step 3: Gene Data Extraction
145
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
146
+ gene_data = get_genetic_data(matrix_file)
147
+
148
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
149
+ print(gene_data.index[:20])
150
+
151
+ # Step 4: Gene Identifier Review
152
+ requires_gene_mapping = True
153
+ print(f"requires_gene_mapping = {requires_gene_mapping}")
154
+
155
+ # Step 5: Gene Annotation
156
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
157
+ gene_annotation = get_gene_annotation(soft_file)
158
+
159
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
160
+ print("Gene annotation preview:")
161
+ print(preview_df(gene_annotation))
162
+
163
+ # Step 6: Gene Identifier Mapping
164
+ # Identify the appropriate columns for mapping based on the annotation preview:
165
+ # Probe IDs: 'ID' (e.g., 'ILMN_10000'), Gene Symbols: 'SYMBOL' (e.g., 'THBS3')
166
+
167
+ # 1-2) Build mapping dataframe from annotation
168
+ mapping_df = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='SYMBOL')
169
+
170
+ # 3) Apply mapping to convert probe-level data to gene-level expression
171
+ gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
172
+
173
+ # Step 7: Data Normalization and Linking
174
+ import os
175
+ import pandas as pd
176
+
177
+ # 1. Normalize gene symbols and save normalized gene data
178
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
179
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
180
+ normalized_gene_data.to_csv(out_gene_data_file)
181
+
182
+ # 2. Reload clinical data (created in Step 2) and reconstruct feature index
183
+ selected_clinical_data = pd.read_csv(out_clinical_data_file)
184
+ selected_clinical_data.index = [trait, 'Age', 'Gender']
185
+
186
+ # Link clinical and genetic data
187
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_data, normalized_gene_data)
188
+
189
+ # 3. Handle missing values
190
+ linked_data = handle_missing_values(linked_data, trait)
191
+
192
+ # 4. Check bias and remove biased demographic features
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 = (
197
+ "INFO: Platform Illumina HumanRef-8 v2; multiple CNS diseases present; "
198
+ "trait encoded as ALS=1, others=0; gene symbols normalized via NCBI synonyms."
199
+ )
200
+ is_usable = validate_and_save_cohort_info(
201
+ is_final=True,
202
+ cohort=cohort,
203
+ info_path=json_path,
204
+ is_gene_available=True,
205
+ is_trait_available=True,
206
+ is_biased=is_trait_biased,
207
+ df=unbiased_linked_data,
208
+ note=note
209
+ )
210
+
211
+ # 6. Save linked data if usable
212
+ if is_usable:
213
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
214
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Amyotrophic_Lateral_Sclerosis/code/GSE52937.py ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Amyotrophic_Lateral_Sclerosis"
6
+ cohort = "GSE52937"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Amyotrophic_Lateral_Sclerosis"
10
+ in_cohort_dir = "../DATA/GEO/Amyotrophic_Lateral_Sclerosis/GSE52937"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z1/preprocess/Amyotrophic_Lateral_Sclerosis/GSE52937.csv"
14
+ out_gene_data_file = "./output/z1/preprocess/Amyotrophic_Lateral_Sclerosis/gene_data/GSE52937.csv"
15
+ out_clinical_data_file = "./output/z1/preprocess/Amyotrophic_Lateral_Sclerosis/clinical_data/GSE52937.csv"
16
+ json_path = "./output/z1/preprocess/Amyotrophic_Lateral_Sclerosis/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 gene expression availability based on background info
40
+ is_gene_available = True # Expression profiling on A549 cell line with siRNA/infection perturbations
41
+
42
+ # 2) Variable availability and conversion functions
43
+ # From the sample characteristics, there is no ALS trait labeling, nor age or gender for human subjects.
44
+ trait_row = None
45
+ age_row = None
46
+ gender_row = None
47
+
48
+ def _after_colon(value):
49
+ if value is None:
50
+ return None
51
+ if isinstance(value, str) and ':' in value:
52
+ return value.split(':', 1)[1].strip()
53
+ return value
54
+
55
+ def convert_trait(x):
56
+ # No ALS case/control or diagnosis labeling available in this cell-line dataset
57
+ return None
58
+
59
+ def convert_age(x):
60
+ # Generic age parser; not used here since no age is available
61
+ v = _after_colon(x)
62
+ if v is None:
63
+ return None
64
+ # Extract first number that looks like age
65
+ import re
66
+ m = re.search(r'(\d+(\.\d+)?)', str(v))
67
+ if not m:
68
+ return None
69
+ age = float(m.group(1))
70
+ if 0 < age < 120:
71
+ return age
72
+ return None
73
+
74
+ def convert_gender(x):
75
+ # Generic gender parser; not used here since no gender is available
76
+ v = _after_colon(x)
77
+ if v is None:
78
+ return None
79
+ s = str(v).strip().lower()
80
+ if s in {'female', 'f', 'woman', 'women', 'girl'}:
81
+ return 0
82
+ if s in {'male', 'm', 'man', 'men', 'boy'}:
83
+ return 1
84
+ # Heuristics for encoded values
85
+ if s in {'0', '1'}:
86
+ return int(s)
87
+ return None
88
+
89
+ # 3) Save metadata (initial filtering)
90
+ is_trait_available = trait_row is not None
91
+ _ = validate_and_save_cohort_info(
92
+ is_final=False,
93
+ cohort=cohort,
94
+ info_path=json_path,
95
+ is_gene_available=is_gene_available,
96
+ is_trait_available=is_trait_available
97
+ )
98
+
99
+ # 4) Clinical feature extraction (skipped because trait_row is None)
100
+ # If trait_row were available, we would use:
101
+ # selected_clinical_df = geo_select_clinical_features(
102
+ # clinical_df=clinical_data,
103
+ # trait=trait,
104
+ # trait_row=trait_row,
105
+ # convert_trait=convert_trait,
106
+ # age_row=age_row,
107
+ # convert_age=convert_age,
108
+ # gender_row=gender_row,
109
+ # convert_gender=convert_gender
110
+ # )
111
+ # preview = preview_df(selected_clinical_df)
112
+ # selected_clinical_df.to_csv(out_clinical_data_file, index=True)
output/preprocess/Amyotrophic_Lateral_Sclerosis/code/GSE61322.py ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Amyotrophic_Lateral_Sclerosis"
6
+ cohort = "GSE61322"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Amyotrophic_Lateral_Sclerosis"
10
+ in_cohort_dir = "../DATA/GEO/Amyotrophic_Lateral_Sclerosis/GSE61322"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z1/preprocess/Amyotrophic_Lateral_Sclerosis/GSE61322.csv"
14
+ out_gene_data_file = "./output/z1/preprocess/Amyotrophic_Lateral_Sclerosis/gene_data/GSE61322.csv"
15
+ out_clinical_data_file = "./output/z1/preprocess/Amyotrophic_Lateral_Sclerosis/clinical_data/GSE61322.csv"
16
+ json_path = "./output/z1/preprocess/Amyotrophic_Lateral_Sclerosis/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 # Expression microarray study; likely gene expression data
43
+
44
+ # 2) Variable availability and converters
45
+
46
+ # Given the sample characteristics, ALS-specific trait information is not available.
47
+ # The dataset appears focused on AOA2; 'diagnosis' distinguishes AOA2 affected vs carrier.
48
+ trait_row = None # No ALS information available
49
+ age_row = None # No age field in the sample characteristics dictionary
50
+ gender_row = None # No gender/sex field in the sample characteristics dictionary
51
+
52
+ def _extract_value(x):
53
+ if x is None:
54
+ return None
55
+ s = str(x).strip().strip('"').strip("'")
56
+ if ":" in s:
57
+ s = s.split(":", 1)[1]
58
+ return s.strip()
59
+
60
+ def convert_trait(x):
61
+ # Binary: ALS presence (1) vs non-ALS (0)
62
+ v = _extract_value(x)
63
+ if v is None or v == "":
64
+ return None
65
+ vl = v.lower()
66
+ # Positive ALS indicators
67
+ als_pos = ["amyotrophic lateral sclerosis", "als4", "als"]
68
+ if any(k in vl for k in als_pos):
69
+ return 1
70
+ # Negative ALS indicators (dataset-specific: AOA2, carrier, control, healthy)
71
+ als_neg = [
72
+ "aoa2", "ataxia with oculomotor apraxia", "carrier", "control",
73
+ "healthy", "normal", "wild type", "wt", "non-als", "no als"
74
+ ]
75
+ if any(k in vl for k in als_neg):
76
+ return 0
77
+ # Ambiguous dataset-specific fields
78
+ if vl in {"affected", "presumed", "definite"}:
79
+ # In this dataset, 'affected' relates to AOA2; treat as non-ALS
80
+ return 0
81
+ # Unknown/NA patterns
82
+ if vl in {"na", "n/a", "not available", "unknown", "none"}:
83
+ return None
84
+ return None
85
+
86
+ def convert_age(x):
87
+ # Continuous: years
88
+ v = _extract_value(x)
89
+ if v is None or v == "":
90
+ return None
91
+ vl = v.lower()
92
+ # Handle common NA tokens
93
+ if vl in {"na", "n/a", "not available", "unknown"}:
94
+ return None
95
+ # Extract first number
96
+ nums = re.findall(r"\d+\.?\d*", vl)
97
+ if not nums:
98
+ return None
99
+ try:
100
+ val = float(nums[0])
101
+ except ValueError:
102
+ return None
103
+ # Unit handling
104
+ if "month" in vl:
105
+ return round(val / 12.0, 3)
106
+ return val
107
+
108
+ def convert_gender(x):
109
+ # Binary: female -> 0, male -> 1
110
+ v = _extract_value(x)
111
+ if v is None or v == "":
112
+ return None
113
+ vl = v.lower()
114
+ if vl in {"male", "m", "man"}:
115
+ return 1
116
+ if vl in {"female", "f", "woman"}:
117
+ return 0
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 (skip since trait_row is None)
131
+ # If trait_row becomes available in future, uncomment and use:
132
+ # if trait_row is not None:
133
+ # selected = 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
+ # preview = preview_df(selected, n=5)
144
+ # os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
145
+ # selected.to_csv(out_clinical_data_file, index=True)
output/preprocess/Amyotrophic_Lateral_Sclerosis/code/GSE68607.py ADDED
@@ -0,0 +1,209 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Amyotrophic_Lateral_Sclerosis"
6
+ cohort = "GSE68607"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Amyotrophic_Lateral_Sclerosis"
10
+ in_cohort_dir = "../DATA/GEO/Amyotrophic_Lateral_Sclerosis/GSE68607"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z1/preprocess/Amyotrophic_Lateral_Sclerosis/GSE68607.csv"
14
+ out_gene_data_file = "./output/z1/preprocess/Amyotrophic_Lateral_Sclerosis/gene_data/GSE68607.csv"
15
+ out_clinical_data_file = "./output/z1/preprocess/Amyotrophic_Lateral_Sclerosis/clinical_data/GSE68607.csv"
16
+ json_path = "./output/z1/preprocess/Amyotrophic_Lateral_Sclerosis/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ import os
40
+ import re
41
+
42
+ # 1) Gene expression availability (Affymetrix Human Exon 1.0 ST -> mRNA expression)
43
+ is_gene_available = True
44
+
45
+ # 2) Variable availability and converters
46
+ # From the sample characteristics, trait (ALS vs Control) is in key 1: 'patient group: ...'
47
+ trait_row = 1
48
+
49
+ # Age and gender are not available in the provided characteristics
50
+ age_row = None
51
+ gender_row = None
52
+
53
+ def _after_colon(x):
54
+ if x is None:
55
+ return None
56
+ s = str(x)
57
+ parts = s.split(":", 1)
58
+ return parts[1].strip() if len(parts) > 1 else s.strip()
59
+
60
+ def convert_trait(x):
61
+ v = _after_colon(x)
62
+ if v is None or v == "":
63
+ return None
64
+ vl = v.lower()
65
+ # Any ALS subtype counts as case; controls as 0
66
+ if "control" in vl:
67
+ return 0
68
+ if "als" in vl:
69
+ return 1
70
+ return None
71
+
72
+ def convert_age(x):
73
+ v = _after_colon(x)
74
+ if not v:
75
+ return None
76
+ vl = v.lower()
77
+ # Extract first integer/float found
78
+ m = re.search(r"(\d+(\.\d+)?)", vl)
79
+ if not m:
80
+ return None
81
+ try:
82
+ return float(m.group(1))
83
+ except Exception:
84
+ return None
85
+
86
+ def convert_gender(x):
87
+ v = _after_colon(x)
88
+ if not v:
89
+ return None
90
+ vl = v.strip().lower()
91
+ # Map female->0, male->1
92
+ if vl in {"female", "f", "woman", "women"}:
93
+ return 0
94
+ if vl in {"male", "m", "man", "men"}:
95
+ return 1
96
+ # Heuristics for embedded strings
97
+ if "female" in vl:
98
+ return 0
99
+ if "male" in vl:
100
+ return 1
101
+ return None
102
+
103
+ # 3) Save metadata via 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 if available
114
+ if trait_row is not None:
115
+ selected_clinical_df = geo_select_clinical_features(
116
+ clinical_df=clinical_data,
117
+ trait=trait,
118
+ trait_row=trait_row,
119
+ convert_trait=convert_trait
120
+ # age_row and gender_row are None by default and thus omitted
121
+ )
122
+ clinical_preview = preview_df(selected_clinical_df, n=5)
123
+
124
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
125
+ selected_clinical_df.to_csv(out_clinical_data_file, index=True)
126
+
127
+ # Step 3: Gene Data Extraction
128
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
129
+ gene_data = get_genetic_data(matrix_file)
130
+
131
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
132
+ print(gene_data.index[:20])
133
+
134
+ # Step 4: Gene Identifier Review
135
+ requires_gene_mapping = True
136
+ print(f"requires_gene_mapping = {requires_gene_mapping}")
137
+
138
+ # Step 5: Gene Annotation
139
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
140
+ gene_annotation = get_gene_annotation(soft_file)
141
+
142
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
143
+ print("Gene annotation preview:")
144
+ print(preview_df(gene_annotation))
145
+
146
+ # Step 6: Gene Identifier Mapping
147
+ # Map ENST transcript IDs to gene symbols using annotation
148
+ # Identifier column in annotation matches gene_data index: 'ID' (e.g., ENST0000...)
149
+ # Gene symbol column in annotation: 'ORF' (e.g., DDX11L10, WASH5P)
150
+ prob_col = 'ID'
151
+ gene_col = 'ORF'
152
+
153
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=prob_col, gene_col=gene_col)
154
+
155
+ # Convert probe/transcript-level data to gene-level expression
156
+ gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
157
+
158
+ # Step 7: Data Normalization and Linking
159
+ import os
160
+ import json
161
+
162
+ # 1. Normalize gene symbols and save gene data
163
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
164
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
165
+ normalized_gene_data.to_csv(out_gene_data_file)
166
+
167
+ # 2. Link the clinical and genetic data
168
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
169
+
170
+ # Derive availability flags just before final validation (ensure native Python bools)
171
+ is_gene_available_final = bool((normalized_gene_data.shape[0] > 0) and (normalized_gene_data.shape[1] > 0))
172
+ is_trait_available_final = bool((trait in linked_data.columns) and bool(linked_data[trait].notna().any()))
173
+
174
+ # 3. Handle missing values
175
+ linked_data = handle_missing_values(linked_data, trait)
176
+
177
+ # 4. Bias assessment and removal of biased demographic features
178
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
179
+ is_trait_biased = bool(is_trait_biased)
180
+
181
+ # Defensive: ensure the cohort info JSON is a valid dict if it exists
182
+ if os.path.exists(json_path):
183
+ try:
184
+ with open(json_path, "r") as f:
185
+ _ = json.load(f)
186
+ except Exception:
187
+ with open(json_path, "w") as f:
188
+ json.dump({}, f)
189
+
190
+ # 5. Final validation and metadata saving
191
+ note = (
192
+ "INFO: ENST transcript IDs mapped to gene symbols via ORF; gene symbols normalized by NCBI synonyms; "
193
+ f"Age/Gender unavailable in this series; post-QC samples: {len(unbiased_linked_data)}"
194
+ )
195
+ is_usable = validate_and_save_cohort_info(
196
+ is_final=True,
197
+ cohort=cohort,
198
+ info_path=json_path,
199
+ is_gene_available=is_gene_available_final,
200
+ is_trait_available=is_trait_available_final,
201
+ is_biased=is_trait_biased,
202
+ df=unbiased_linked_data,
203
+ note=note
204
+ )
205
+
206
+ # 6. Save linked data if usable
207
+ if is_usable:
208
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
209
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Amyotrophic_Lateral_Sclerosis/code/GSE68608.py ADDED
@@ -0,0 +1,195 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Amyotrophic_Lateral_Sclerosis"
6
+ cohort = "GSE68608"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Amyotrophic_Lateral_Sclerosis"
10
+ in_cohort_dir = "../DATA/GEO/Amyotrophic_Lateral_Sclerosis/GSE68608"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z1/preprocess/Amyotrophic_Lateral_Sclerosis/GSE68608.csv"
14
+ out_gene_data_file = "./output/z1/preprocess/Amyotrophic_Lateral_Sclerosis/gene_data/GSE68608.csv"
15
+ out_clinical_data_file = "./output/z1/preprocess/Amyotrophic_Lateral_Sclerosis/clinical_data/GSE68608.csv"
16
+ json_path = "./output/z1/preprocess/Amyotrophic_Lateral_Sclerosis/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 # Splicing dysregulation study in motor neurons implies gene expression data (not miRNA/methylation only)
44
+
45
+ # 2. Variable Availability and Data Type Conversion
46
+
47
+ # Based on the sample characteristics dictionary in the prompt:
48
+ # 0 -> subject id (not used for analysis)
49
+ # 1 -> patient group: ALS due to mutated C9ORF72 / Neurologically healthy, non-disease control (trait)
50
+ # 2 -> tissue: Laser captured motor neurons (constant, not useful)
51
+ trait_row = 1
52
+ age_row = None
53
+ gender_row = None
54
+
55
+ def _after_colon(value):
56
+ if value is None:
57
+ return None
58
+ parts = str(value).split(':', 1)
59
+ return parts[1].strip() if len(parts) > 1 else str(value).strip()
60
+
61
+ def convert_trait(value):
62
+ v = _after_colon(value)
63
+ if v is None:
64
+ return None
65
+ vl = v.lower()
66
+ # Cases: ALS patients with C9ORF72 mutation
67
+ if ('als' in vl) or ('patient' in vl) or ('mutated' in vl) or ('c9orf72' in vl):
68
+ return 1
69
+ # Controls: healthy / non-disease
70
+ if ('control' in vl) or ('healthy' in vl) or ('non-disease' in vl) or ('neurologically healthy' in vl):
71
+ return 0
72
+ return None
73
+
74
+ def convert_age(value):
75
+ v = _after_colon(value)
76
+ if v is None:
77
+ return None
78
+ vl = v.lower()
79
+ # Extract first numeric value
80
+ m = re.search(r'[-+]?\d*\.?\d+', vl)
81
+ if not m:
82
+ return None
83
+ num = float(m.group())
84
+ # Convert months to years if clearly specified
85
+ if 'month' in vl and 'year' not in vl:
86
+ return round(num / 12.0, 3)
87
+ return num
88
+
89
+ def convert_gender(value):
90
+ v = _after_colon(value)
91
+ if v is None:
92
+ return None
93
+ vl = v.strip().lower()
94
+ if vl in {'male', 'm', 'man', 'boy'}:
95
+ return 1
96
+ if vl in {'female', 'f', 'woman', 'girl'}:
97
+ return 0
98
+ return None
99
+
100
+ # 3. Save Metadata (initial filtering)
101
+ is_trait_available = trait_row is not None
102
+ _ = validate_and_save_cohort_info(
103
+ is_final=False,
104
+ cohort=cohort,
105
+ info_path=json_path,
106
+ is_gene_available=is_gene_available,
107
+ is_trait_available=is_trait_available
108
+ )
109
+
110
+ # 4. Clinical Feature Extraction (only if trait data available)
111
+ if trait_row is not None:
112
+ selected_clinical_df = geo_select_clinical_features(
113
+ clinical_df=clinical_data,
114
+ trait=trait,
115
+ trait_row=trait_row,
116
+ convert_trait=convert_trait,
117
+ age_row=age_row,
118
+ convert_age=convert_age if age_row is not None else None,
119
+ gender_row=gender_row,
120
+ convert_gender=convert_gender if gender_row is not None else None
121
+ )
122
+ preview = preview_df(selected_clinical_df)
123
+ print("Clinical features preview:", preview)
124
+
125
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
126
+ selected_clinical_df.to_csv(out_clinical_data_file)
127
+
128
+ # Step 3: Gene Data Extraction
129
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
130
+ gene_data = get_genetic_data(matrix_file)
131
+
132
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
133
+ print(gene_data.index[:20])
134
+
135
+ # Step 4: Gene Identifier Review
136
+ # Affymetrix probe set IDs (e.g., '1007_s_at') are not human gene symbols and require mapping.
137
+ print("requires_gene_mapping = True")
138
+
139
+ # Step 5: Gene Annotation
140
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
141
+ gene_annotation = get_gene_annotation(soft_file)
142
+
143
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
144
+ print("Gene annotation preview:")
145
+ print(preview_df(gene_annotation))
146
+
147
+ # Step 6: Gene Identifier Mapping
148
+ # Decide the appropriate columns for probe IDs and gene symbols based on the preview
149
+ probe_col = 'ID'
150
+ gene_col = 'Gene Symbol'
151
+
152
+ # 2. Get gene mapping dataframe
153
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=probe_col, gene_col=gene_col)
154
+
155
+ # 3. Apply mapping to convert probe-level data to gene-level expression
156
+ gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
157
+
158
+ # Step 7: Data Normalization and Linking
159
+ import os
160
+
161
+ # 1. Normalize the obtained gene data 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 the clinical and genetic data
167
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
168
+
169
+ # Compute availability flags based on actual data before processing
170
+ is_gene_available_fin = (normalized_gene_data.shape[0] > 0 and normalized_gene_data.shape[1] > 0)
171
+ is_trait_available_fin = trait in linked_data.columns
172
+
173
+ # 3. Handle missing values in the linked data
174
+ linked_data = handle_missing_values(linked_data, trait)
175
+
176
+ # 4. Determine whether the trait and demographic features are severely biased; remove biased demographics
177
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
178
+
179
+ # 5. Final validation and save cohort info
180
+ note = "INFO: Trait available; no age/gender provided by dataset. Affymetrix probe IDs mapped to gene symbols; motor neuron LCM samples."
181
+ is_usable = validate_and_save_cohort_info(
182
+ is_final=True,
183
+ cohort=cohort,
184
+ info_path=json_path,
185
+ is_gene_available=is_gene_available_fin,
186
+ is_trait_available=is_trait_available_fin,
187
+ is_biased=is_trait_biased,
188
+ df=unbiased_linked_data,
189
+ note=note
190
+ )
191
+
192
+ # 6. Save linked data if usable
193
+ if is_usable:
194
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
195
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Amyotrophic_Lateral_Sclerosis/code/GSE95810.py ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Amyotrophic_Lateral_Sclerosis"
6
+ cohort = "GSE95810"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Amyotrophic_Lateral_Sclerosis"
10
+ in_cohort_dir = "../DATA/GEO/Amyotrophic_Lateral_Sclerosis/GSE95810"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z1/preprocess/Amyotrophic_Lateral_Sclerosis/GSE95810.csv"
14
+ out_gene_data_file = "./output/z1/preprocess/Amyotrophic_Lateral_Sclerosis/gene_data/GSE95810.csv"
15
+ out_clinical_data_file = "./output/z1/preprocess/Amyotrophic_Lateral_Sclerosis/clinical_data/GSE95810.csv"
16
+ json_path = "./output/z1/preprocess/Amyotrophic_Lateral_Sclerosis/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ import re
40
+
41
+ # 1. Gene Expression Data Availability
42
+ is_gene_available = True # Series title indicates gene expression data
43
+
44
+ # 2. Variable Availability and Data Type Conversion
45
+
46
+ # Based on provided Sample Characteristics, only amyloid beta 42 levels are present.
47
+ # No ALS trait, age, or gender information is available.
48
+ trait_row = None
49
+ age_row = None
50
+ gender_row = None
51
+
52
+ def _extract_value(cell):
53
+ if cell is None:
54
+ return None
55
+ if not isinstance(cell, str):
56
+ return cell
57
+ parts = cell.split(":", 1)
58
+ return parts[1].strip() if len(parts) > 1 else cell.strip()
59
+
60
+ def convert_trait(x):
61
+ val = _extract_value(x)
62
+ if val is None:
63
+ return None
64
+ s = str(val).strip().lower()
65
+ # Positive for ALS
66
+ if "amyotrophic lateral sclerosis" in s or re.search(r"\bals\b", s):
67
+ return 1
68
+ # Negative for non-ALS (e.g., AD, control)
69
+ if any(k in s for k in ["control", "healthy", "normal", "non-als", "non als", "non-carrier", "non carrier",
70
+ "alzheimer", "alzheimers", "pre-symptomatic", "pre-symptomatic alzheimer", "ad"]):
71
+ return 0
72
+ if s in {"1", "0"}:
73
+ return int(s)
74
+ return None
75
+
76
+ def convert_age(x):
77
+ val = _extract_value(x)
78
+ if val is None:
79
+ return None
80
+ s = str(val).strip().lower()
81
+ # Handle months
82
+ m = re.search(r"([\d\.]+)\s*(month|mo|months)", s)
83
+ if m:
84
+ try:
85
+ return float(m.group(1)) / 12.0
86
+ except:
87
+ return None
88
+ # Handle years
89
+ m = re.search(r"([\d\.]+)", s)
90
+ if m:
91
+ try:
92
+ return float(m.group(1))
93
+ except:
94
+ return None
95
+ return None
96
+
97
+ def convert_gender(x):
98
+ val = _extract_value(x)
99
+ if val is None:
100
+ return None
101
+ s = str(val).strip().lower()
102
+ if s in {"male", "m", "man", "men"}:
103
+ return 1
104
+ if s in {"female", "f", "woman", "women"}:
105
+ return 0
106
+ return None
107
+
108
+ # 3. Save Metadata (initial filtering)
109
+ is_trait_available = trait_row is not None
110
+ _ = validate_and_save_cohort_info(
111
+ is_final=False,
112
+ cohort=cohort,
113
+ info_path=json_path,
114
+ is_gene_available=is_gene_available,
115
+ is_trait_available=is_trait_available
116
+ )
117
+
118
+ # 4. Clinical Feature Extraction (skip because trait_row is None)
119
+ # If trait_row becomes available in future steps, uncomment the following:
120
+ # if trait_row is not None:
121
+ # selected_clinical_df = geo_select_clinical_features(
122
+ # clinical_df=clinical_data,
123
+ # trait=trait,
124
+ # trait_row=trait_row,
125
+ # convert_trait=convert_trait,
126
+ # age_row=age_row,
127
+ # convert_age=convert_age,
128
+ # gender_row=gender_row,
129
+ # convert_gender=convert_gender
130
+ # )
131
+ # preview = preview_df(selected_clinical_df)
132
+ # os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
133
+ # selected_clinical_df.to_csv(out_clinical_data_file)
134
+
135
+ # Step 3: Gene Data Extraction
136
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
137
+ gene_data = get_genetic_data(matrix_file)
138
+
139
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
140
+ print(gene_data.index[:20])
141
+
142
+ # Step 4: Gene Identifier Review
143
+ print("requires_gene_mapping = False")
output/preprocess/Amyotrophic_Lateral_Sclerosis/code/TCGA.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Amyotrophic_Lateral_Sclerosis"
6
+
7
+ # Input paths
8
+ tcga_root_dir = "../DATA/TCGA"
9
+
10
+ # Output paths
11
+ out_data_file = "./output/z1/preprocess/Amyotrophic_Lateral_Sclerosis/TCGA.csv"
12
+ out_gene_data_file = "./output/z1/preprocess/Amyotrophic_Lateral_Sclerosis/gene_data/TCGA.csv"
13
+ out_clinical_data_file = "./output/z1/preprocess/Amyotrophic_Lateral_Sclerosis/clinical_data/TCGA.csv"
14
+ json_path = "./output/z1/preprocess/Amyotrophic_Lateral_Sclerosis/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 appropriate TCGA cohort directory for ALS (likely none)
22
+ synonyms = [
23
+ "amyotrophic lateral sclerosis",
24
+ "als",
25
+ "motor neuron disease",
26
+ "lou gehrig"
27
+ ]
28
+
29
+ tcga_subdirs = [d for d in os.listdir(tcga_root_dir) if os.path.isdir(os.path.join(tcga_root_dir, d))]
30
+ lc_subdirs = [d.lower() for d in tcga_subdirs]
31
+
32
+ selected_idx = None
33
+ for i, d in enumerate(lc_subdirs):
34
+ if any(s in d for s in synonyms):
35
+ selected_idx = i
36
+ break
37
+
38
+ tcga_selected_dir = None if selected_idx is None else tcga_subdirs[selected_idx]
39
+
40
+ clinical_df = None
41
+ genetic_df = None
42
+ clinical_file_path = None
43
+ genetic_file_path = None
44
+
45
+ if tcga_selected_dir is None:
46
+ print("No suitable TCGA cohort found for trait 'Amyotrophic Lateral Sclerosis'. Skipping TCGA for this trait.")
47
+ # Record as unavailable and complete
48
+ _ = validate_and_save_cohort_info(
49
+ is_final=False,
50
+ cohort="TCGA",
51
+ info_path=json_path,
52
+ is_gene_available=False,
53
+ is_trait_available=False
54
+ )
55
+ else:
56
+ # Step 2: Identify clinical and genetic data file paths
57
+ cohort_dir = os.path.join(tcga_root_dir, tcga_selected_dir)
58
+ clinical_file_path, genetic_file_path = tcga_get_relevant_filepaths(cohort_dir)
59
+
60
+ # Step 3: Load both files as DataFrames
61
+ clinical_df = pd.read_csv(clinical_file_path, sep='\t', index_col=0, low_memory=False)
62
+ genetic_df = pd.read_csv(genetic_file_path, sep='\t', index_col=0, low_memory=False)
63
+
64
+ # Step 4: Print column names of the clinical data
65
+ print(list(clinical_df.columns))
output/preprocess/Amyotrophic_Lateral_Sclerosis/cohort_info.json CHANGED
@@ -1,112 +1 @@
1
- {
2
- "GSE95810": {
3
- "is_usable": false,
4
- "is_gene_available": false,
5
- "is_trait_available": false,
6
- "is_available": false,
7
- "is_biased": null,
8
- "has_age": null,
9
- "has_gender": null,
10
- "sample_size": null
11
- },
12
- "GSE68608": {
13
- "is_usable": false,
14
- "is_gene_available": false,
15
- "is_trait_available": true,
16
- "is_available": false,
17
- "is_biased": null,
18
- "has_age": null,
19
- "has_gender": null,
20
- "sample_size": null
21
- },
22
- "GSE68607": {
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": 69
31
- },
32
- "GSE61322": {
33
- "is_usable": true,
34
- "is_gene_available": true,
35
- "is_trait_available": true,
36
- "is_available": true,
37
- "is_biased": false,
38
- "has_age": false,
39
- "has_gender": false,
40
- "sample_size": 33
41
- },
42
- "GSE52937": {
43
- "is_usable": true,
44
- "is_gene_available": true,
45
- "is_trait_available": true,
46
- "is_available": true,
47
- "is_biased": false,
48
- "has_age": false,
49
- "has_gender": false,
50
- "sample_size": 54
51
- },
52
- "GSE26927": {
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": true,
59
- "has_gender": true,
60
- "sample_size": 118
61
- },
62
- "GSE212134": {
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
- "GSE212131": {
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
- "GSE139384": {
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
- "GSE118336": {
93
- "is_usable": false,
94
- "is_gene_available": false,
95
- "is_trait_available": true,
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": false,
104
- "is_gene_available": false,
105
- "is_trait_available": false,
106
- "is_available": false,
107
- "is_biased": null,
108
- "has_age": null,
109
- "has_gender": null,
110
- "sample_size": null
111
- }
112
- }
 
1
+ {"GSE95810": {"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}, "GSE68608": {"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": 11, "note": "INFO: Trait available; no age/gender provided by dataset. Affymetrix probe IDs mapped to gene symbols; motor neuron LCM samples."}, "GSE68607": {"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": 69, "note": "INFO: ENST transcript IDs mapped to gene symbols via ORF; gene symbols normalized by NCBI synonyms; Age/Gender unavailable in this series; post-QC samples: 69"}, "GSE61322": {"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}, "GSE52937": {"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}, "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: Platform Illumina HumanRef-8 v2; multiple CNS diseases present; trait encoded as ALS=1, others=0; gene symbols normalized via NCBI synonyms."}, "GSE212134": {"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}, "GSE212131": {"is_usable": false, "is_gene_available": true, "is_trait_available": false, "is_available": false, "is_biased": null, "has_age": null, "has_gender": null, "sample_size": null, "note": "INFO: Trait unavailable in this series; only gender present. Skipping linkage and marking cohort as not usable for association analysis."}, "GSE139384": {"is_usable": true, "is_gene_available": true, "is_trait_available": true, "is_available": true, "is_biased": false, "has_age": true, "has_gender": true, "sample_size": 33, "note": "INFO: Illumina HumanHT-12 v4 platform; probe->gene mapping applied using SOFT annotation; multi-mapped probes split equally and summed per gene; gene symbols normalized via NCBI synonyms; trait mapped as ALS=1, non-ALS (PDC/AD/Control)=0."}, "GSE118336": {"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": 60, "note": "INFO: Trait derived from genotype (FUS H517D) in iPSC-derived MNs; HTA2.0 array."}, "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/Angelman_Syndrome/code/GSE43900.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Angelman_Syndrome"
6
+ cohort = "GSE43900"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Angelman_Syndrome"
10
+ in_cohort_dir = "../DATA/GEO/Angelman_Syndrome/GSE43900"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z1/preprocess/Angelman_Syndrome/GSE43900.csv"
14
+ out_gene_data_file = "./output/z1/preprocess/Angelman_Syndrome/gene_data/GSE43900.csv"
15
+ out_clinical_data_file = "./output/z1/preprocess/Angelman_Syndrome/clinical_data/GSE43900.csv"
16
+ json_path = "./output/z1/preprocess/Angelman_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
+ # Determine data availability based on provided background and sample characteristics
40
+ is_gene_available = True # Likely gene expression data (not miRNA/methylation)
41
+ trait_row = None # No human trait (Angelman Syndrome) info available
42
+ age_row = None # No age information
43
+ gender_row = None # No gender information
44
+
45
+ # Conversion functions (defined for interface compatibility; not used since rows are None)
46
+ def _extract_value(x):
47
+ if x is None:
48
+ return None
49
+ try:
50
+ # Typical format: "key: value"
51
+ parts = str(x).split(":", 1)
52
+ return parts[1].strip() if len(parts) > 1 else str(x).strip()
53
+ except Exception:
54
+ return None
55
+
56
+ def convert_trait(x):
57
+ # No trait information available in this dataset; return None
58
+ return None
59
+
60
+ def convert_age(x):
61
+ # No age information; return None
62
+ return None
63
+
64
+ def convert_gender(x):
65
+ # No gender information; return None
66
+ return None
67
+
68
+ # Initial filtering metadata save
69
+ is_trait_available = trait_row is not None
70
+ _ = validate_and_save_cohort_info(
71
+ is_final=False,
72
+ cohort=cohort,
73
+ info_path=json_path,
74
+ is_gene_available=is_gene_available,
75
+ is_trait_available=is_trait_available
76
+ )
77
+
78
+ # Clinical feature extraction is skipped because trait_row is None
79
+ # (If trait_row were available, we would call geo_select_clinical_features and save the output.)
output/preprocess/Angelman_Syndrome/code/TCGA.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Angelman_Syndrome"
6
+
7
+ # Input paths
8
+ tcga_root_dir = "../DATA/TCGA"
9
+
10
+ # Output paths
11
+ out_data_file = "./output/z1/preprocess/Angelman_Syndrome/TCGA.csv"
12
+ out_gene_data_file = "./output/z1/preprocess/Angelman_Syndrome/gene_data/TCGA.csv"
13
+ out_clinical_data_file = "./output/z1/preprocess/Angelman_Syndrome/clinical_data/TCGA.csv"
14
+ json_path = "./output/z1/preprocess/Angelman_Syndrome/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 Angelman Syndrome (none expected)
22
+ available_dirs = [d for d in os.listdir(tcga_root_dir) if os.path.isdir(os.path.join(tcga_root_dir, d))]
23
+ search_terms = {"angelman", "ube3a"}
24
+ matching_dirs = [d for d in available_dirs if any(term in d.lower() for term in search_terms)]
25
+
26
+ selected_dir = None
27
+ if matching_dirs:
28
+ # If multiple, choose the most specific (heuristic: longest name)
29
+ selected_dir = sorted(matching_dirs, key=len, reverse=True)[0]
30
+
31
+ if selected_dir is None:
32
+ # No suitable TCGA cancer cohort matches Angelman Syndrome; record and stop
33
+ _ = validate_and_save_cohort_info(
34
+ is_final=False,
35
+ cohort="TCGA",
36
+ info_path=json_path,
37
+ is_gene_available=False,
38
+ is_trait_available=False
39
+ )
40
+ else:
41
+ cohort_dir = os.path.join(tcga_root_dir, selected_dir)
42
+
43
+ # Step 2: Identify clinical and genetic file paths
44
+ clinical_file_path, genetic_file_path = tcga_get_relevant_filepaths(cohort_dir)
45
+
46
+ # Step 3: Load both files as DataFrames
47
+ clinical_df = pd.read_csv(clinical_file_path, sep='\t', index_col=0, low_memory=False, compression='infer')
48
+ genetic_df = pd.read_csv(genetic_file_path, sep='\t', index_col=0, low_memory=False, compression='infer')
49
+
50
+ # Step 4: Print clinical column names
51
+ print(clinical_df.columns.tolist())
output/preprocess/Angelman_Syndrome/cohort_info.json CHANGED
@@ -1,22 +1 @@
1
- {
2
- "GSE43900": {
3
- "is_usable": false,
4
- "is_gene_available": false,
5
- "is_trait_available": false,
6
- "is_available": false,
7
- "is_biased": null,
8
- "has_age": null,
9
- "has_gender": null,
10
- "sample_size": null
11
- },
12
- "TCGA": {
13
- "is_usable": false,
14
- "is_gene_available": false,
15
- "is_trait_available": false,
16
- "is_available": false,
17
- "is_biased": null,
18
- "has_age": null,
19
- "has_gender": null,
20
- "sample_size": null
21
- }
22
- }
 
1
+ {"GSE43900": {"is_usable": false, "is_gene_available": true, "is_trait_available": false, "is_available": false, "is_biased": null, "has_age": null, "has_gender": null, "sample_size": null, "note": null}, "TCGA": {"is_usable": false, "is_gene_available": false, "is_trait_available": false, "is_available": false, "is_biased": null, "has_age": null, "has_gender": null, "sample_size": null, "note": null}}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
output/preprocess/Aniridia/clinical_data/GSE137997.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
2
- 1.0,0.0,,,,,,,,,,,,,,,,,,,,,,
3
- 20.0,28.0,38.0,57.0,26.0,18.0,36.0,42.0,55.0,54.0,34.0,51.0,46.0,52.0,53.0,40.0,39.0,59.0,32.0,37.0,29.0,19.0,25.0,22.0
4
- 0.0,1.0,0.0,,,,,,,,,,,,,,,,,,,,,
 
1
+ ,GSM4096349,GSM4096350,GSM4096351,GSM4096352,GSM4096353,GSM4096354,GSM4096355,GSM4096356,GSM4096357,GSM4096358,GSM4096359,GSM4096360,GSM4096361,GSM4096362,GSM4096363,GSM4096364,GSM4096365,GSM4096366,GSM4096367,GSM4096368,GSM4096369,GSM4096370,GSM4096371,GSM4096372,GSM4096373,GSM4096374,GSM4096375,GSM4096376,GSM4096377,GSM4096378,GSM4096379,GSM4096380,GSM4096381,GSM4096382,GSM4096383,GSM4096384,GSM4096385,GSM4096386,GSM4096387,GSM4096388
2
+ Aniridia,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,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
3
+ Age,20.0,20.0,28.0,20.0,38.0,57.0,26.0,18.0,36.0,42.0,18.0,42.0,36.0,28.0,55.0,54.0,34.0,51.0,46.0,52.0,53.0,54.0,40.0,55.0,57.0,28.0,39.0,59.0,20.0,32.0,37.0,34.0,28.0,28.0,29.0,19.0,25.0,25.0,34.0,22.0
4
+ Gender,0.0,0.0,0.0,0.0,0.0,1.0,0.0,1.0,0.0,0.0,0.0,0.0,1.0,0.0,0.0,1.0,1.0,0.0,0.0,0.0,0.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,0.0,0.0,0.0,1.0,0.0,0.0,1.0,0.0,0.0
output/preprocess/Aniridia/code/GSE137996.py ADDED
@@ -0,0 +1,195 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Aniridia"
6
+ cohort = "GSE137996"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Aniridia"
10
+ in_cohort_dir = "../DATA/GEO/Aniridia/GSE137996"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z1/preprocess/Aniridia/GSE137996.csv"
14
+ out_gene_data_file = "./output/z1/preprocess/Aniridia/gene_data/GSE137996.csv"
15
+ out_clinical_data_file = "./output/z1/preprocess/Aniridia/clinical_data/GSE137996.csv"
16
+ json_path = "./output/z1/preprocess/Aniridia/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ import os
40
+ import re
41
+
42
+ # 1. Gene Expression Data Availability
43
+ is_gene_available = True # mRNA profiling present (not purely miRNA/methylation)
44
+
45
+ # 2. Variable Availability and Converters
46
+ # Identified rows from the Sample Characteristics Dictionary
47
+ trait_row = 2 # 'disease: AAK' vs 'disease: healthy control'
48
+ age_row = 0 # 'age: ...'
49
+ gender_row = 1 # 'gender: F', 'gender: W', 'gender: M'
50
+
51
+ def _extract_value(x):
52
+ if x is None:
53
+ return ""
54
+ s = str(x)
55
+ return s.split(":", 1)[1].strip() if ":" in s else s.strip()
56
+
57
+ def convert_trait(x):
58
+ val = _extract_value(x).lower()
59
+ case_set = {
60
+ 'aak',
61
+ 'aniridia',
62
+ 'congenital aniridia',
63
+ 'aniridia-associated keratopathy',
64
+ 'aniridia associated keratopathy'
65
+ }
66
+ control_set = {'healthy control', 'healthy', 'control', 'normal'}
67
+ if val in case_set:
68
+ return 1
69
+ if val in control_set:
70
+ return 0
71
+ return None
72
+
73
+ def convert_age(x):
74
+ val = _extract_value(x)
75
+ m = re.search(r'[-+]?\d+\.?\d*', val)
76
+ if m:
77
+ try:
78
+ v = float(m.group())
79
+ return v
80
+ except Exception:
81
+ return None
82
+ return None
83
+
84
+ def convert_gender(x):
85
+ val = _extract_value(x).lower()
86
+ # Heuristics: M/male/man -> 1; F/female/woman/W -> 0
87
+ if val in {'m', 'male', 'man'} or val.startswith('m'):
88
+ return 1
89
+ if val in {'f', 'female', 'woman', 'w'} or val.startswith('f') or val.startswith('w'):
90
+ return 0
91
+ return None
92
+
93
+ # 3. Save Metadata (initial filtering)
94
+ is_trait_available = trait_row is not None
95
+ _ = validate_and_save_cohort_info(
96
+ is_final=False,
97
+ cohort=cohort,
98
+ info_path=json_path,
99
+ is_gene_available=is_gene_available,
100
+ is_trait_available=is_trait_available
101
+ )
102
+
103
+ # 4. Clinical Feature Extraction (only if clinical data available)
104
+ if trait_row is not None:
105
+ selected_clinical_df = geo_select_clinical_features(
106
+ clinical_df=clinical_data,
107
+ trait=trait,
108
+ trait_row=trait_row,
109
+ convert_trait=convert_trait,
110
+ age_row=age_row,
111
+ convert_age=convert_age,
112
+ gender_row=gender_row,
113
+ convert_gender=convert_gender
114
+ )
115
+ preview = preview_df(selected_clinical_df, n=5)
116
+ print(preview)
117
+
118
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
119
+ selected_clinical_df.to_csv(out_clinical_data_file, index=True)
120
+
121
+ # Step 3: Gene Data Extraction
122
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
123
+ gene_data = get_genetic_data(matrix_file)
124
+
125
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
126
+ print(gene_data.index[:20])
127
+
128
+ # Step 4: Gene Identifier Review
129
+ print("requires_gene_mapping = True")
130
+
131
+ # Step 5: Gene Annotation
132
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
133
+ gene_annotation = get_gene_annotation(soft_file)
134
+
135
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
136
+ print("Gene annotation preview:")
137
+ print(preview_df(gene_annotation))
138
+
139
+ # Step 6: Gene Identifier Mapping
140
+ # Identify the appropriate columns for probe IDs and gene symbols based on the annotation preview
141
+ probe_col = 'ID'
142
+ gene_symbol_col = 'GENE_SYMBOL'
143
+
144
+ # 2. Create the mapping dataframe
145
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=probe_col, gene_col=gene_symbol_col)
146
+
147
+ # 3. Apply the mapping to convert probe-level data to gene-level expression
148
+ gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
149
+
150
+ # Step 7: Data Normalization and Linking
151
+ import os
152
+
153
+ # 1. Normalize gene symbols and save gene expression data
154
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
155
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
156
+ normalized_gene_data.to_csv(out_gene_data_file)
157
+
158
+ # 2. Link the clinical and genetic data
159
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
160
+
161
+ # Flags for availability before stringent missing handling (ensure native Python bool)
162
+ is_gene_available_flag = bool(normalized_gene_data.shape[0] > 0 and normalized_gene_data.shape[1] > 0)
163
+ is_trait_available_flag = bool((trait in list(linked_data.columns)) and linked_data[trait].notna().any())
164
+
165
+ # 3. Handle missing values
166
+ linked_data = handle_missing_values(linked_data, trait)
167
+
168
+ # 4. Bias evaluation and removal of biased demographics
169
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
170
+
171
+ # Ensure columns are a Python list to avoid numpy.bool_ in membership checks inside the validator
172
+ unbiased_linked_data.columns = list(unbiased_linked_data.columns)
173
+ is_trait_biased = bool(is_trait_biased)
174
+
175
+ # 5. Final validation and metadata saving
176
+ note = (
177
+ f"INFO: Normalized gene symbols and linked with clinical data. "
178
+ f"Gene matrix shape (normalized): {normalized_gene_data.shape}. "
179
+ f"Linked data shape after QC: {unbiased_linked_data.shape}."
180
+ )
181
+ is_usable = validate_and_save_cohort_info(
182
+ is_final=True,
183
+ cohort=cohort,
184
+ info_path=json_path,
185
+ is_gene_available=is_gene_available_flag,
186
+ is_trait_available=is_trait_available_flag,
187
+ is_biased=is_trait_biased,
188
+ df=unbiased_linked_data,
189
+ note=note
190
+ )
191
+
192
+ # 6. Save linked data if usable
193
+ if is_usable:
194
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
195
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Aniridia/code/GSE137997.py ADDED
@@ -0,0 +1,152 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Aniridia"
6
+ cohort = "GSE137997"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Aniridia"
10
+ in_cohort_dir = "../DATA/GEO/Aniridia/GSE137997"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z1/preprocess/Aniridia/GSE137997.csv"
14
+ out_gene_data_file = "./output/z1/preprocess/Aniridia/gene_data/GSE137997.csv"
15
+ out_clinical_data_file = "./output/z1/preprocess/Aniridia/clinical_data/GSE137997.csv"
16
+ json_path = "./output/z1/preprocess/Aniridia/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 # mRNA expression is indicated in the series title; suitable for gene expression analysis.
41
+
42
+ # 2) Variable availability and conversion functions
43
+
44
+ # Rows identified from the provided sample characteristics dictionary:
45
+ # 0: age, 1: gender, 2: disease (AAK vs healthy control)
46
+ trait_row = 2
47
+ age_row = 0
48
+ gender_row = 1
49
+
50
+ # Conversion helpers
51
+ import os
52
+ import re
53
+
54
+ def _extract_value(x):
55
+ if x is None:
56
+ return None
57
+ if isinstance(x, str):
58
+ parts = x.split(":", 1)
59
+ val = parts[1].strip() if len(parts) > 1 else x.strip()
60
+ return val if val != "" else None
61
+ return x
62
+
63
+ # trait: binary (0=control, 1=Aniridia/AAK)
64
+ def convert_trait(x):
65
+ v = _extract_value(x)
66
+ if v is None:
67
+ return None
68
+ vl = v.strip().lower()
69
+ # Exact matches first
70
+ if vl in {"healthy control", "control", "healthy", "normal"}:
71
+ return 0
72
+ if vl in {"aak", "aniridia", "aniridia-associated keratopathy", "aniridia associated keratopathy"}:
73
+ return 1
74
+ # Substring fallback
75
+ if "healthy" in vl and "control" in vl:
76
+ return 0
77
+ if "aak" in vl or "aniridia" in vl:
78
+ return 1
79
+ if vl in {"na", "n/a", "unknown", "null"}:
80
+ return None
81
+ return None
82
+
83
+ # age: continuous (years)
84
+ def convert_age(x):
85
+ v = _extract_value(x)
86
+ if v is None:
87
+ return None
88
+ m = re.search(r"[-+]?\d*\.?\d+", v)
89
+ if m:
90
+ try:
91
+ return float(m.group())
92
+ except:
93
+ return None
94
+ return None
95
+
96
+ # gender: binary (0=female, 1=male)
97
+ def convert_gender(x):
98
+ v = _extract_value(x)
99
+ if v is None:
100
+ return None
101
+ vl = v.strip().lower()
102
+ if vl in {"f", "female", "woman", "w"}:
103
+ return 0
104
+ if vl in {"m", "male", "man"}:
105
+ return 1
106
+ if vl in {"na", "n/a", "unknown", "null"}:
107
+ return None
108
+ if len(vl) == 1:
109
+ if vl == "f":
110
+ return 0
111
+ if vl == "m":
112
+ return 1
113
+ return None
114
+
115
+ # 3) Save metadata (initial filtering)
116
+ is_trait_available = trait_row is not None
117
+ _ = validate_and_save_cohort_info(
118
+ is_final=False,
119
+ cohort=cohort,
120
+ info_path=json_path,
121
+ is_gene_available=is_gene_available,
122
+ is_trait_available=is_trait_available
123
+ )
124
+
125
+ # 4) Clinical feature extraction (only if trait_row is available)
126
+ if trait_row is not None:
127
+ selected_clinical_df = geo_select_clinical_features(
128
+ clinical_df=clinical_data,
129
+ trait=trait,
130
+ trait_row=trait_row,
131
+ convert_trait=convert_trait,
132
+ age_row=age_row,
133
+ convert_age=convert_age,
134
+ gender_row=gender_row,
135
+ convert_gender=convert_gender
136
+ )
137
+ clinical_features_preview = preview_df(selected_clinical_df)
138
+ print(clinical_features_preview)
139
+ # Save clinical data
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
+ requires_gene_mapping = True
152
+ print(f"requires_gene_mapping = {requires_gene_mapping}")
output/preprocess/Aniridia/code/GSE204791.py ADDED
@@ -0,0 +1,198 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Aniridia"
6
+ cohort = "GSE204791"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Aniridia"
10
+ in_cohort_dir = "../DATA/GEO/Aniridia/GSE204791"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z1/preprocess/Aniridia/GSE204791.csv"
14
+ out_gene_data_file = "./output/z1/preprocess/Aniridia/gene_data/GSE204791.csv"
15
+ out_clinical_data_file = "./output/z1/preprocess/Aniridia/clinical_data/GSE204791.csv"
16
+ json_path = "./output/z1/preprocess/Aniridia/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ import re
40
+
41
+ # 1) Gene expression data availability
42
+ is_gene_available = True # mRNA microarray data are described in the background
43
+
44
+ # 2) Variable availability and conversion
45
+
46
+ # Based on the sample characteristics:
47
+ # 0: 'age: ...' -> available
48
+ # 1: 'gender: M/F' -> available
49
+ # 2: 'disease: KC/healthy...' -> this does not capture Aniridia; trait is therefore unavailable here
50
+ trait_row = None
51
+ age_row = 0
52
+ gender_row = 1
53
+
54
+ def _after_colon(s: str) -> str:
55
+ if s is None:
56
+ return ""
57
+ parts = str(s).split(":", 1)
58
+ return parts[1].strip() if len(parts) > 1 else str(s).strip()
59
+
60
+ def convert_trait(x):
61
+ """
62
+ Map to Aniridia presence:
63
+ - 1 if mentions aniridia/AAK/PAX6 mutation explicitly
64
+ - 0 if indicates healthy control
65
+ - None otherwise (e.g., keratoconus, unspecified)
66
+ """
67
+ val = _after_colon(x).lower()
68
+ if not val:
69
+ return None
70
+ if any(k in val for k in ["aniridia", "aak", "pax6"]):
71
+ return 1
72
+ if "healthy" in val or "control" in val:
73
+ return 0
74
+ if "kc" in val or "keratoconus" in val:
75
+ return None
76
+ return None
77
+
78
+ def convert_age(x):
79
+ val = _after_colon(x)
80
+ if not val:
81
+ return None
82
+ # Extract first integer/float in the string
83
+ m = re.search(r"[-+]?\d*\.?\d+", val)
84
+ if not m:
85
+ return None
86
+ try:
87
+ age_val = float(m.group())
88
+ # Age must be within a plausible human range
89
+ if 0 <= age_val <= 120:
90
+ return age_val
91
+ except Exception:
92
+ pass
93
+ return None
94
+
95
+ def convert_gender(x):
96
+ val = _after_colon(x).strip().lower()
97
+ if not val:
98
+ return None
99
+ if val in ["f", "female", "woman", "women"]:
100
+ return 0
101
+ if val in ["m", "male", "man", "men"]:
102
+ return 1
103
+ return None
104
+
105
+ # 3) Save metadata (initial filtering)
106
+ is_trait_available = trait_row is not None
107
+ _ = validate_and_save_cohort_info(
108
+ is_final=False,
109
+ cohort=cohort,
110
+ info_path=json_path,
111
+ is_gene_available=is_gene_available,
112
+ is_trait_available=is_trait_available
113
+ )
114
+
115
+ # 4) Clinical feature extraction: skip because trait_row is None
116
+ # (If trait_row becomes available in future steps, use geo_select_clinical_features and preview_df, then save CSV.)
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
+ # IDs like 'A_19_P...' (Agilent probe IDs) and '(+)E1A_r60_1' are not human gene symbols.
127
+ requires_gene_mapping = True
128
+ print(f"requires_gene_mapping = {requires_gene_mapping}")
129
+
130
+ # Step 5: Gene Annotation
131
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
132
+ gene_annotation = get_gene_annotation(soft_file)
133
+
134
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
135
+ print("Gene annotation preview:")
136
+ print(preview_df(gene_annotation))
137
+
138
+ # Step 6: Gene Identifier Mapping
139
+ # Decide which annotation column best matches the probe IDs in the expression data
140
+ candidate_probe_cols = [col for col in ['ID', 'SPOT_ID'] if col in gene_annotation.columns]
141
+ if not candidate_probe_cols:
142
+ raise ValueError("No suitable probe ID column found in annotation (expected 'ID' or 'SPOT_ID').")
143
+
144
+ overlaps = {}
145
+ for col in candidate_probe_cols:
146
+ ann_ids = gene_annotation[col].astype(str).str.strip()
147
+ overlaps[col] = ann_ids.isin(gene_data.index).sum()
148
+
149
+ probe_col = max(overlaps, key=overlaps.get)
150
+
151
+ # Decide the gene symbol column
152
+ symbol_col = 'GENE_SYMBOL' if 'GENE_SYMBOL' in gene_annotation.columns else None
153
+ if symbol_col is None:
154
+ raise ValueError("No suitable gene symbol column found in annotation (expected 'GENE_SYMBOL').")
155
+
156
+ # Build mapping and convert probe-level data to gene-level data
157
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=probe_col, gene_col=symbol_col)
158
+ gene_data = apply_gene_mapping(gene_data, mapping_df)
159
+
160
+ # Step 7: Data Normalization and Linking
161
+ # 1. Normalize the obtained gene data and save gene-only data
162
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
163
+ normalized_gene_data.to_csv(out_gene_data_file)
164
+
165
+ # 2-6. Proceed only if clinical data with trait is available (selected_clinical_data created in Step 2 when trait_row != None)
166
+ if 'selected_clinical_data' in globals() and selected_clinical_data is not None:
167
+ # Link clinical and genetic data
168
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_data, normalized_gene_data)
169
+
170
+ # Handle missing values
171
+ linked_data = handle_missing_values(linked_data, trait)
172
+
173
+ # Bias checking and removal of biased demographic covariates
174
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
175
+
176
+ # Final validation and save cohort info
177
+ is_usable = validate_and_save_cohort_info(
178
+ True,
179
+ cohort,
180
+ json_path,
181
+ True, # gene data available
182
+ True, # trait data available
183
+ is_trait_biased,
184
+ unbiased_linked_data
185
+ )
186
+
187
+ # Save linked data if usable
188
+ if is_usable:
189
+ unbiased_linked_data.to_csv(out_data_file)
190
+ else:
191
+ # Trait data unavailable; record metadata (initial filter) and do not attempt linking or saving linked data
192
+ validate_and_save_cohort_info(
193
+ is_final=False,
194
+ cohort=cohort,
195
+ info_path=json_path,
196
+ is_gene_available=True,
197
+ is_trait_available=False
198
+ )
output/preprocess/Aniridia/code/TCGA.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Aniridia"
6
+
7
+ # Input paths
8
+ tcga_root_dir = "../DATA/TCGA"
9
+
10
+ # Output paths
11
+ out_data_file = "./output/z1/preprocess/Aniridia/TCGA.csv"
12
+ out_gene_data_file = "./output/z1/preprocess/Aniridia/gene_data/TCGA.csv"
13
+ out_clinical_data_file = "./output/z1/preprocess/Aniridia/clinical_data/TCGA.csv"
14
+ json_path = "./output/z1/preprocess/Aniridia/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 relevant TCGA cohort directory for the trait "Aniridia"
22
+ subdirs = [d for d in os.listdir(tcga_root_dir) if os.path.isdir(os.path.join(tcga_root_dir, d))]
23
+
24
+ # Heuristic keyword scoring to approximate phenotypic overlap with "Aniridia"
25
+ keywords_weights = [
26
+ ("aniridia", 10),
27
+ ("iris", 6),
28
+ ("ocular", 5),
29
+ ("eye", 4),
30
+ ("uveal", 4),
31
+ ("uvea", 4),
32
+ ("retina", 3),
33
+ ("optic", 2),
34
+ ("ophthalm", 2)
35
+ ]
36
+
37
+ def score_dir(name: str) -> int:
38
+ ln = name.lower()
39
+ return sum(w for k, w in keywords_weights if k in ln)
40
+
41
+ scored = [(d, score_dir(d)) for d in subdirs]
42
+ scored.sort(key=lambda x: x[1], reverse=True)
43
+ selected_dir = scored[0][0] if scored and scored[0][1] > 0 else None
44
+
45
+ if selected_dir is None:
46
+ # No suitable cohort; record and exit step gracefully
47
+ validate_and_save_cohort_info(
48
+ is_final=False,
49
+ cohort="TCGA",
50
+ info_path=json_path,
51
+ is_gene_available=False,
52
+ is_trait_available=False
53
+ )
54
+ print("No suitable TCGA cohort directory found for the trait. Skipping.")
55
+ else:
56
+ cohort_dir = os.path.join(tcga_root_dir, selected_dir)
57
+
58
+ # 2) Identify clinical and genetic file paths
59
+ clinical_file_path, genetic_file_path = tcga_get_relevant_filepaths(cohort_dir)
60
+
61
+ # 3) Load both files as DataFrames
62
+ clinical_df = pd.read_csv(clinical_file_path, sep='\t', index_col=0, low_memory=False, compression='infer')
63
+ genetic_df = pd.read_csv(genetic_file_path, sep='\t', index_col=0, low_memory=False, compression='infer')
64
+
65
+ # Keep references for downstream steps
66
+ SELECTED_TCGA_DIR = selected_dir
67
+ SELECTED_CLINICAL_PATH = clinical_file_path
68
+ SELECTED_GENETIC_PATH = genetic_file_path
69
+ TCGA_CLINICAL_DF = clinical_df
70
+ TCGA_GENETIC_DF = genetic_df
71
+
72
+ # 4) Print the column names of the clinical data
73
+ print(list(clinical_df.columns))
output/preprocess/Aniridia/cohort_info.json CHANGED
@@ -1,42 +1 @@
1
- {
2
- "GSE204791": {
3
- "is_usable": true,
4
- "is_gene_available": true,
5
- "is_trait_available": true,
6
- "is_available": true,
7
- "is_biased": false,
8
- "has_age": true,
9
- "has_gender": true,
10
- "sample_size": 31
11
- },
12
- "GSE137997": {
13
- "is_usable": false,
14
- "is_gene_available": true,
15
- "is_trait_available": true,
16
- "is_available": true,
17
- "is_biased": true,
18
- "has_age": true,
19
- "has_gender": true,
20
- "sample_size": 64
21
- },
22
- "GSE137996": {
23
- "is_usable": true,
24
- "is_gene_available": true,
25
- "is_trait_available": true,
26
- "is_available": true,
27
- "is_biased": false,
28
- "has_age": true,
29
- "has_gender": true,
30
- "sample_size": 40
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": 80
41
- }
42
- }
 
1
+ {"GSE204791": {"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}, "GSE137996": {"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": 40, "note": "INFO: Normalized gene symbols and linked with clinical data. Gene matrix shape (normalized): (20778, 40). Linked data shape after QC: (40, 20781)."}}