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

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/Allergies/code/TCGA.py +71 -0
  2. output/preprocess/Allergies/gene_data/GSE270312.csv +0 -0
  3. output/preprocess/Alopecia/code/GSE148346.py +189 -0
  4. output/preprocess/Alopecia/cohort_info.json +1 -52
  5. output/preprocess/Type_2_Diabetes/code/GSE271700.py +447 -0
  6. output/preprocess/Type_2_Diabetes/code/GSE281144.py +382 -0
  7. output/preprocess/Type_2_Diabetes/code/GSE98887.py +216 -0
  8. output/preprocess/Type_2_Diabetes/code/TCGA.py +106 -0
  9. output/preprocess/Type_2_Diabetes/gene_data/GSE271700.csv +0 -0
  10. output/preprocess/Type_2_Diabetes/gene_data/GSE281144.csv +0 -0
  11. output/preprocess/Underweight/code/GSE130563.py +218 -0
  12. output/preprocess/Underweight/code/GSE131835.py +175 -0
  13. output/preprocess/Underweight/code/GSE50982.py +234 -0
  14. output/preprocess/Underweight/code/GSE57802.py +205 -0
  15. output/preprocess/Underweight/code/GSE84954.py +305 -0
  16. output/preprocess/Underweight/code/TCGA.py +14 -0
  17. output/preprocess/Underweight/cohort_info.json +1 -62
  18. output/preprocess/Uterine_Carcinosarcoma/GSE32507.csv +0 -0
  19. output/preprocess/Uterine_Carcinosarcoma/clinical_data/GSE32507.csv +2 -2
  20. output/preprocess/Uterine_Carcinosarcoma/code/GSE32507.py +193 -0
  21. output/preprocess/Uterine_Carcinosarcoma/code/GSE36133.py +134 -0
  22. output/preprocess/Uterine_Carcinosarcoma/code/GSE36138.py +120 -0
  23. output/preprocess/Uterine_Carcinosarcoma/code/GSE68950.py +222 -0
  24. output/preprocess/Uterine_Carcinosarcoma/code/TCGA.py +358 -0
  25. output/preprocess/Uterine_Carcinosarcoma/cohort_info.json +1 -52
  26. output/preprocess/Uterine_Corpus_Endometrial_Carcinoma/GSE32507.csv +0 -0
  27. output/preprocess/Uterine_Corpus_Endometrial_Carcinoma/clinical_data/GSE32507.csv +2 -2
  28. output/preprocess/Uterine_Corpus_Endometrial_Carcinoma/code/GSE32507.py +211 -0
  29. output/preprocess/Uterine_Corpus_Endometrial_Carcinoma/code/TCGA.py +250 -0
  30. output/preprocess/Uterine_Corpus_Endometrial_Carcinoma/cohort_info.json +1 -22
  31. output/preprocess/Vitamin_D_Levels/GSE76324.csv +0 -0
  32. output/preprocess/Vitamin_D_Levels/clinical_data/GSE129604.csv +3 -3
  33. output/preprocess/Vitamin_D_Levels/clinical_data/GSE34450.csv +2 -2
  34. output/preprocess/Vitamin_D_Levels/clinical_data/GSE76324.csv +2 -2
  35. output/preprocess/Vitamin_D_Levels/code/GSE118723.py +208 -0
  36. output/preprocess/Vitamin_D_Levels/code/GSE123993.py +215 -0
  37. output/preprocess/Vitamin_D_Levels/code/GSE129604.py +204 -0
  38. output/preprocess/Vitamin_D_Levels/code/GSE33544.py +129 -0
  39. output/preprocess/Vitamin_D_Levels/code/GSE34450.py +184 -0
  40. output/preprocess/Vitamin_D_Levels/code/GSE35925.py +215 -0
  41. output/preprocess/Vitamin_D_Levels/code/GSE76324.py +202 -0
  42. output/preprocess/Vitamin_D_Levels/code/GSE86406.py +249 -0
  43. output/preprocess/Vitamin_D_Levels/code/TCGA.py +60 -0
  44. output/preprocess/Vitamin_D_Levels/cohort_info.json +1 -72
  45. output/preprocess/Von_Hippel_Lindau/code/GSE33093.py +213 -0
  46. output/preprocess/Von_Hippel_Lindau/code/TCGA.py +272 -0
  47. output/preprocess/Von_Hippel_Lindau/cohort_info.json +1 -22
  48. output/preprocess/Von_Willebrand_Disease/clinical_data/GSE27597.csv +4 -4
  49. output/preprocess/Von_Willebrand_Disease/code/GSE27597.py +181 -0
  50. output/preprocess/Von_Willebrand_Disease/code/TCGA.py +65 -0
output/preprocess/Allergies/code/TCGA.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Allergies"
6
+
7
+ # Input paths
8
+ tcga_root_dir = "../DATA/TCGA"
9
+
10
+ # Output paths
11
+ out_data_file = "./output/z1/preprocess/Allergies/TCGA.csv"
12
+ out_gene_data_file = "./output/z1/preprocess/Allergies/gene_data/TCGA.csv"
13
+ out_clinical_data_file = "./output/z1/preprocess/Allergies/clinical_data/TCGA.csv"
14
+ json_path = "./output/z1/preprocess/Allergies/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 appropriate TCGA subdirectory for the trait "Allergies"
22
+ # Since TCGA cohorts are cancer types and none relate to allergies, we attempt a keyword search.
23
+ keywords = [
24
+ "allerg", "hypersens", "atopy", "atopic", "asthma", "urticaria", "rhinitis", "eczema", "hayfever", "hay_fever"
25
+ ]
26
+
27
+ # List available TCGA subdirectories
28
+ available_subdirs = [d for d in os.listdir(tcga_root_dir) if os.path.isdir(os.path.join(tcga_root_dir, d))]
29
+
30
+ # Find candidates whose names contain any allergy-related keyword
31
+ candidates = [d for d in available_subdirs if any(k in d.lower() for k in keywords)]
32
+
33
+ selected_dir = None
34
+ if len(candidates) > 0:
35
+ # If multiple matches, choose the one with the longest keyword overlap (more specific)
36
+ def score_dir(name: str) -> int:
37
+ lname = name.lower()
38
+ return sum(lname.count(k) for k in keywords)
39
+
40
+ candidates.sort(key=score_dir, reverse=True)
41
+ selected_dir = candidates[0]
42
+
43
+ # If no suitable directory found, mark as skipped and stop here
44
+ if selected_dir is None:
45
+ print("No TCGA cohort directory matches the target trait 'Allergies'. Skipping this trait.")
46
+ # Record as unavailable for this trait
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
+ clinical_df = None
55
+ genetic_df = None
56
+ else:
57
+ print(f"Selected TCGA cohort directory: {selected_dir}")
58
+ cohort_dir = os.path.join(tcga_root_dir, selected_dir)
59
+
60
+ # Step 2: Identify clinical and genetic file paths
61
+ clinical_file_path, genetic_file_path = tcga_get_relevant_filepaths(cohort_dir)
62
+ print(f"Clinical file: {clinical_file_path}")
63
+ print(f"Genetic file: {genetic_file_path}")
64
+
65
+ # Step 3: Load both files
66
+ clinical_df = pd.read_csv(clinical_file_path, sep="\t", index_col=0, low_memory=False)
67
+ genetic_df = pd.read_csv(genetic_file_path, sep="\t", index_col=0, low_memory=False)
68
+
69
+ # Step 4: Print column names of the clinical data
70
+ print("Clinical data columns:")
71
+ print(list(clinical_df.columns))
output/preprocess/Allergies/gene_data/GSE270312.csv ADDED
The diff for this file is too large to render. See raw diff
 
output/preprocess/Alopecia/code/GSE148346.py ADDED
@@ -0,0 +1,189 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Alopecia"
6
+ cohort = "GSE148346"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Alopecia"
10
+ in_cohort_dir = "../DATA/GEO/Alopecia/GSE148346"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z1/preprocess/Alopecia/GSE148346.csv"
14
+ out_gene_data_file = "./output/z1/preprocess/Alopecia/gene_data/GSE148346.csv"
15
+ out_clinical_data_file = "./output/z1/preprocess/Alopecia/clinical_data/GSE148346.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 data availability
40
+ is_gene_available = True # Based on study design (biopsy transcriptomic biomarkers), gene expression data is likely available.
41
+
42
+ # Step 2: Variable availability and conversion functions
43
+ trait_row = 3 # 'tissue disease state: LS/NL' -> can be used as binary disease state (lesional vs non-lesional)
44
+ age_row = None
45
+ gender_row = None
46
+
47
+ def _after_colon(val):
48
+ if val is None:
49
+ return None
50
+ if not isinstance(val, str):
51
+ val = str(val)
52
+ parts = val.split(":", 1)
53
+ return parts[1].strip() if len(parts) == 2 else val.strip()
54
+
55
+ def convert_trait(x):
56
+ v = _after_colon(x)
57
+ if v is None:
58
+ return None
59
+ v_low = v.strip().lower()
60
+ # Map lesional vs non-lesional to 1/0
61
+ if v_low in {"ls", "lesional", "lesion", "lesional scalp", "lesional skin"}:
62
+ return 1
63
+ if v_low in {"nl", "non-lesional", "nonlesional", "non lesional", "nonlesion", "non-lesion", "non-lesional scalp"}:
64
+ return 0
65
+ return None
66
+
67
+ def convert_age(x):
68
+ v = _after_colon(x)
69
+ if v is None:
70
+ return None
71
+ v_low = v.lower()
72
+ # Remove common units/labels
73
+ for token in ["years", "year", "yrs", "yr", "y", "age", " "]:
74
+ v_low = v_low.replace(token, "")
75
+ v_clean = v_low.strip().replace("+", "")
76
+ try:
77
+ return float(v_clean)
78
+ except Exception:
79
+ # Try to extract any leading number
80
+ import re
81
+ m = re.search(r"(\d+(\.\d+)?)", v_low)
82
+ return float(m.group(1)) if m else None
83
+
84
+ def convert_gender(x):
85
+ v = _after_colon(x)
86
+ if v is None:
87
+ return None
88
+ v_low = v.strip().lower()
89
+ if v_low in {"female", "f", "woman", "girl"}:
90
+ return 0
91
+ if v_low in {"male", "m", "man", "boy"}:
92
+ return 1
93
+ return None
94
+
95
+ # Step 3: Save metadata (initial filtering)
96
+ is_trait_available = trait_row is not None
97
+ _ = validate_and_save_cohort_info(
98
+ is_final=False,
99
+ cohort=cohort,
100
+ info_path=json_path,
101
+ is_gene_available=is_gene_available,
102
+ is_trait_available=is_trait_available
103
+ )
104
+
105
+ # Step 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 if age_row is not None else None,
114
+ gender_row=gender_row,
115
+ convert_gender=convert_gender if gender_row is not None else None
116
+ )
117
+ preview_output = preview_df(selected_clinical_df, n=5)
118
+ print(preview_output)
119
+ # Save selected clinical features
120
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
121
+ selected_clinical_df.to_csv(out_clinical_data_file)
122
+
123
+ # Step 3: Gene Data Extraction
124
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
125
+ gene_data = get_genetic_data(matrix_file)
126
+
127
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
128
+ print(gene_data.index[:20])
129
+
130
+ # Step 4: Gene Identifier Review
131
+ # Affymetrix probe set IDs (e.g., 1007_s_at, 1405_i_at) are not human gene symbols and require mapping
132
+ requires_gene_mapping = True
133
+ print(f"requires_gene_mapping = {requires_gene_mapping}")
134
+
135
+ # Step 5: Gene Annotation
136
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
137
+ gene_annotation = get_gene_annotation(soft_file)
138
+
139
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
140
+ print("Gene annotation preview:")
141
+ print(preview_df(gene_annotation))
142
+
143
+ # Step 6: Gene Identifier Mapping
144
+ # 1. Decide the appropriate columns for mapping:
145
+ # - Probe identifiers in gene expression data match the 'ID' column in annotation.
146
+ # - Gene symbols are in the 'Gene Symbol' column.
147
+
148
+ # 2. Extract mapping dataframe from gene_annotation
149
+ mapping_df = get_gene_mapping(annotation=gene_annotation, prob_col='ID', gene_col='Gene Symbol')
150
+
151
+ # 3. Apply mapping to convert probe-level data to gene-level expression
152
+ gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
153
+
154
+ # Step 7: Data Normalization and Linking
155
+ import os
156
+
157
+ # 1. Normalize gene symbols and save
158
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
159
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
160
+ normalized_gene_data.to_csv(out_gene_data_file)
161
+
162
+ # 2. Link clinical and genetic data
163
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
164
+
165
+ # 3. Handle missing values
166
+ linked_data = handle_missing_values(linked_data, trait)
167
+
168
+ # 4. Bias check and remove biased demographic features
169
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
170
+
171
+ # 5. Final validation and save cohort info
172
+ is_gene_available_final = (normalized_gene_data.shape[0] > 0) and (normalized_gene_data.shape[1] > 0)
173
+ is_trait_available_final = (trait in linked_data.columns)
174
+
175
+ is_usable = validate_and_save_cohort_info(
176
+ is_final=True,
177
+ cohort=cohort,
178
+ info_path=json_path,
179
+ is_gene_available=is_gene_available_final,
180
+ is_trait_available=is_trait_available_final,
181
+ is_biased=is_trait_biased,
182
+ df=unbiased_linked_data,
183
+ note=""
184
+ )
185
+
186
+ # 6. Save linked data if usable
187
+ if is_usable:
188
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
189
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Alopecia/cohort_info.json CHANGED
@@ -1,52 +1 @@
1
- {
2
- "GSE80342": {
3
- "is_usable": false,
4
- "is_gene_available": true,
5
- "is_trait_available": true,
6
- "is_available": true,
7
- "is_biased": true,
8
- "has_age": true,
9
- "has_gender": true,
10
- "sample_size": 31
11
- },
12
- "GSE66664": {
13
- "is_usable": true,
14
- "is_gene_available": true,
15
- "is_trait_available": true,
16
- "is_available": true,
17
- "is_biased": false,
18
- "has_age": false,
19
- "has_gender": false,
20
- "sample_size": 140
21
- },
22
- "GSE18876": {
23
- "is_usable": false,
24
- "is_gene_available": true,
25
- "is_trait_available": false,
26
- "is_available": false,
27
- "is_biased": null,
28
- "has_age": null,
29
- "has_gender": null,
30
- "sample_size": null
31
- },
32
- "GSE148346": {
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": 129
41
- },
42
- "TCGA": {
43
- "is_usable": false,
44
- "is_gene_available": false,
45
- "is_trait_available": false,
46
- "is_available": false,
47
- "is_biased": null,
48
- "has_age": null,
49
- "has_gender": null,
50
- "sample_size": null
51
- }
52
- }
 
1
+ {"GSE81071": {"is_usable": false, "is_gene_available": true, "is_trait_available": false, "is_available": false, "is_biased": null, "has_age": null, "has_gender": null, "sample_size": null, "note": "INFO: Trait not available; skipped linking and QC. No SYMBOL column available in annotation; kept Entrez-indexed matrix."}, "GSE80342": {"is_usable": false, "is_gene_available": true, "is_trait_available": true, "is_available": true, "is_biased": true, "has_age": true, "has_gender": true, "sample_size": 31, "note": "INFO: Samples=31, Genes=19845, Age_included=True, Gender_included=True."}, "GSE66664": {"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": 140, "note": "INFO: DP cell line dataset; trait derived from 'cell line: BAB'(1) vs 'BAN'(0). Male-only; no age available. DHT dose/time present but not included as covariates."}, "GSE18876": {"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}, "GSE148346": {"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": 129, "note": ""}, "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/Type_2_Diabetes/code/GSE271700.py ADDED
@@ -0,0 +1,447 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Type_2_Diabetes"
6
+ cohort = "GSE271700"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Type_2_Diabetes"
10
+ in_cohort_dir = "../DATA/GEO/Type_2_Diabetes/GSE271700"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z6/preprocess/Type_2_Diabetes/GSE271700.csv"
14
+ out_gene_data_file = "./output/z6/preprocess/Type_2_Diabetes/gene_data/GSE271700.csv"
15
+ out_clinical_data_file = "./output/z6/preprocess/Type_2_Diabetes/clinical_data/GSE271700.csv"
16
+ json_path = "./output/z6/preprocess/Type_2_Diabetes/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
+ # Gene expression data availability
40
+ is_gene_available = True # Whole-genome microarray indicates gene expression data.
41
+
42
+ # Variable availability (Responder/Non-Responder used as proxy for T2D remission status)
43
+ trait_row = 3
44
+ age_row = 1
45
+ gender_row = 0
46
+
47
+ def _after_colon(x):
48
+ if x is None:
49
+ return None
50
+ if isinstance(x, str):
51
+ parts = x.split(":", 1)
52
+ val = parts[1] if len(parts) > 1 else parts[0]
53
+ val = val.strip()
54
+ return val if val != "" else None
55
+ return None
56
+
57
+ def convert_trait(x):
58
+ # Map Responder -> 0 (no T2D, remission), Non-Responder -> 1 (has T2D, persistent)
59
+ val = _after_colon(x)
60
+ if val is None:
61
+ return None
62
+ v = val.strip().lower()
63
+ if "non" in v and "responder" in v:
64
+ return 1
65
+ if "responder" in v:
66
+ return 0
67
+ if "remission" in v:
68
+ return 0
69
+ if "persistent" in v:
70
+ return 1
71
+ if "no diabetes" in v or "without diabetes" in v:
72
+ return 0
73
+ if "diabetes" in v:
74
+ return 1
75
+ return None
76
+
77
+ def convert_age(x):
78
+ val = _after_colon(x)
79
+ if val is None:
80
+ return None
81
+ try:
82
+ return float(val)
83
+ except Exception:
84
+ import re
85
+ nums = re.findall(r"[\d.]+", val)
86
+ return float(nums[0]) if nums else None
87
+
88
+ def convert_gender(x):
89
+ val = _after_colon(x)
90
+ if val is None:
91
+ return None
92
+ v = val.strip().lower()
93
+ if v in {"female", "f"}:
94
+ return 0
95
+ if v in {"male", "m"}:
96
+ return 1
97
+ return None
98
+
99
+ # Trait availability determined by trait_row
100
+ is_trait_available = trait_row is not None
101
+
102
+ # Initial filtering and save metadata
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
+ # Clinical feature extraction
112
+ if trait_row is not None:
113
+ selected_clinical_df = geo_select_clinical_features(
114
+ clinical_df=clinical_data,
115
+ trait=trait,
116
+ trait_row=trait_row,
117
+ convert_trait=convert_trait,
118
+ age_row=age_row,
119
+ convert_age=convert_age,
120
+ gender_row=gender_row,
121
+ convert_gender=convert_gender
122
+ )
123
+ clinical_preview = preview_df(selected_clinical_df)
124
+
125
+ import os
126
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
127
+ selected_clinical_df.to_csv(out_clinical_data_file)
128
+
129
+ # Step 3: Gene Data Extraction
130
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
131
+ gene_data = get_genetic_data(matrix_file)
132
+
133
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
134
+ print(gene_data.index[:20])
135
+
136
+ # Step 4: Gene Identifier Review
137
+ print("requires_gene_mapping = True")
138
+
139
+ # Step 5: Gene Annotation
140
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
141
+ gene_annotation = get_gene_annotation(soft_file)
142
+
143
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
144
+ print("Gene annotation preview:")
145
+ print(preview_df(gene_annotation))
146
+
147
+ # Step 6: Gene Identifier Mapping
148
+ import os
149
+ import io
150
+ import gzip
151
+ import re
152
+ import pandas as pd
153
+
154
+ # Preserve original probe-level data
155
+ probe_level_data = gene_data.copy()
156
+
157
+ def _pick_probe_id_col(df: pd.DataFrame) -> str:
158
+ candidates = ['ID', 'ID_REF', 'PROBE_ID', 'Probe ID', 'SPOT_ID', 'Probe Set ID', 'Probe.Set.ID']
159
+ for c in candidates:
160
+ if c in df.columns:
161
+ return c
162
+ # Heuristic for Affy-like IDs
163
+ def affy_like_ratio(series: pd.Series, n: int = 2000) -> float:
164
+ s = series.astype(str).head(n)
165
+ return s.str.contains(r'(?:_at|_s_at|_x_at)$', regex=True).mean()
166
+ ratios = {c: affy_like_ratio(df[c]) for c in df.columns}
167
+ return max(ratios, key=ratios.get)
168
+
169
+ def _symbol_candidates(df: pd.DataFrame):
170
+ # Prioritized list of columns that may contain gene symbols
171
+ priority_names = [
172
+ r'^Gene[\s._-]*Symbol$', r'^GENE[\s._-]*SYMBOL$', r'^Symbol$', r'^SYMBOL$',
173
+ r'Gene\.Symbol', r'gene[\s._-]*symbol', r'symbol'
174
+ ]
175
+ # Expand to include plausible text columns for fallback
176
+ fallback_patterns = [
177
+ r'Gene[\s._-]*Title', r'GENE[\s._-]*TITLE', r'Gene[\s._-]*Name', r'GENE[\s._-]*NAME',
178
+ r'Gene[\s._-]*Assignment', r'GENE[\s._-]*ASSIGN', r'DESCRIPTION', r'Definition', r'Product', r'title', r'description'
179
+ ]
180
+
181
+ cols = list(df.columns)
182
+ # Priority matches
183
+ pri = []
184
+ for pat in priority_names:
185
+ pri.extend([c for c in cols if re.search(pat, str(c), flags=re.I)])
186
+ # Unique while preserving order
187
+ seen = set()
188
+ pri = [c for c in pri if not (c in seen or seen.add(c))]
189
+
190
+ # Fallbacks
191
+ fb = []
192
+ for pat in fallback_patterns:
193
+ fb.extend([c for c in cols if re.search(pat, str(c), flags=re.I)])
194
+ seen = set()
195
+ fb = [c for c in fb if (c not in pri) and not (c in seen or seen.add(c))]
196
+
197
+ return pri + fb
198
+
199
+ def _extractability_score(series: pd.Series, n: int = 2000) -> float:
200
+ s = series.astype(str).head(n)
201
+ extracted = s.map(extract_human_gene_symbols)
202
+ return extracted.map(lambda x: len(x) > 0).mean()
203
+
204
+ def _build_mapping_from_annotation(df: pd.DataFrame) -> pd.DataFrame:
205
+ if df is None or df.empty:
206
+ return pd.DataFrame(columns=['ID', 'Gene'])
207
+ probe_col = _pick_probe_id_col(df)
208
+ symbol_cols = _symbol_candidates(df)
209
+ best_col = None
210
+ best_score = -1.0
211
+ for c in symbol_cols:
212
+ try:
213
+ score = _extractability_score(df[c])
214
+ except Exception:
215
+ continue
216
+ if score > best_score:
217
+ best_score = score
218
+ best_col = c
219
+ # Early stop if a perfect match is found
220
+ if score >= 0.9:
221
+ break
222
+ if best_col is None or best_score <= 0:
223
+ return pd.DataFrame(columns=['ID', 'Gene'])
224
+ try:
225
+ mapping = get_gene_mapping(df, prob_col=probe_col, gene_col=best_col)
226
+ except Exception:
227
+ mapping = pd.DataFrame(columns=['ID', 'Gene'])
228
+ return mapping
229
+
230
+ def _read_gpl_soft_platform_table(path: str) -> pd.DataFrame:
231
+ # Extract lines between !platform_table_begin and !platform_table_end
232
+ def _read_lines(open_fn):
233
+ lines = []
234
+ with open_fn(path, 'rt') as fh:
235
+ in_table = False
236
+ for line in fh:
237
+ line = line.rstrip('\n')
238
+ if line.startswith('!platform_table_begin'):
239
+ in_table = True
240
+ continue
241
+ if line.startswith('!platform_table_end'):
242
+ break
243
+ if in_table:
244
+ lines.append(line)
245
+ return lines
246
+
247
+ lines = []
248
+ try:
249
+ lines = _read_lines(gzip.open)
250
+ except Exception:
251
+ try:
252
+ lines = _read_lines(open)
253
+ except Exception:
254
+ lines = []
255
+
256
+ if not lines:
257
+ return pd.DataFrame()
258
+ table_str = '\n'.join(lines)
259
+ try:
260
+ return pd.read_csv(io.StringIO(table_str), sep='\t', low_memory=False, on_bad_lines='skip')
261
+ except Exception:
262
+ return pd.DataFrame()
263
+
264
+ def _read_gpl_annot_file(path: str) -> pd.DataFrame:
265
+ try:
266
+ return pd.read_csv(path, sep='\t', compression='gzip', low_memory=False, on_bad_lines='skip')
267
+ except Exception:
268
+ try:
269
+ return pd.read_csv(path, sep='\t', low_memory=False, on_bad_lines='skip')
270
+ except Exception:
271
+ return pd.DataFrame()
272
+
273
+ # Try multiple sources to obtain mapping
274
+ mapping_df = pd.DataFrame(columns=['ID', 'Gene'])
275
+ chosen_probe_col = None
276
+ chosen_symbol_col = None
277
+ mapping_source = None
278
+
279
+ # 1) Try platform table embedded in the provided SOFT file
280
+ platform_df = _read_gpl_soft_platform_table(soft_file)
281
+ if not platform_df.empty:
282
+ tmp_map = _build_mapping_from_annotation(platform_df)
283
+ if not tmp_map.empty:
284
+ mapping_df = tmp_map
285
+ mapping_source = 'SERIES_SOFT_PLATFORM'
286
+ # Infer chosen columns for logging
287
+ chosen_probe_col = _pick_probe_id_col(platform_df)
288
+ chosen_symbol_col = [c for c in _symbol_candidates(platform_df) if c in platform_df.columns][0] if _symbol_candidates(platform_df) else None
289
+
290
+ # 2) Search for GPL files in the cohort directory if needed
291
+ if mapping_df.empty:
292
+ files = os.listdir(in_cohort_dir)
293
+ gpl_annot_files = [os.path.join(in_cohort_dir, f) for f in files if ('gpl' in f.lower() and 'annot' in f.lower())]
294
+ gpl_soft_files = [os.path.join(in_cohort_dir, f) for f in files if ('gpl' in f.lower() and 'soft' in f.lower())]
295
+
296
+ candidate_platform_dfs = []
297
+ for p in gpl_annot_files:
298
+ dfp = _read_gpl_annot_file(p)
299
+ if not dfp.empty:
300
+ candidate_platform_dfs.append(('GPL_ANNOT', dfp, p))
301
+ for p in gpl_soft_files:
302
+ dfp = _read_gpl_soft_platform_table(p)
303
+ if not dfp.empty:
304
+ candidate_platform_dfs.append(('GPL_SOFT', dfp, p))
305
+
306
+ for src, dfp, pth in candidate_platform_dfs:
307
+ tmp_map = _build_mapping_from_annotation(dfp)
308
+ if not tmp_map.empty:
309
+ mapping_df = tmp_map
310
+ mapping_source = src
311
+ chosen_probe_col = _pick_probe_id_col(dfp)
312
+ # Best symbol col (for logging) by score
313
+ syms = _symbol_candidates(dfp)
314
+ if syms:
315
+ scores = {c: _extractability_score(dfp[c]) for c in syms}
316
+ chosen_symbol_col = max(scores, key=scores.get)
317
+ break
318
+
319
+ # 3) Recursive search in the trait directory if still not found
320
+ if mapping_df.empty:
321
+ candidate_platform_dfs = []
322
+ for root, dirs, files in os.walk(in_trait_dir):
323
+ for f in files:
324
+ fl = f.lower()
325
+ if ('gpl' in fl) and (('annot' in fl) or ('soft' in fl)):
326
+ full = os.path.join(root, f)
327
+ if 'annot' in fl:
328
+ dfp = _read_gpl_annot_file(full)
329
+ if not dfp.empty:
330
+ candidate_platform_dfs.append(('GPL_ANNOT', dfp, full))
331
+ elif 'soft' in fl:
332
+ dfp = _read_gpl_soft_platform_table(full)
333
+ if not dfp.empty:
334
+ candidate_platform_dfs.append(('GPL_SOFT', dfp, full))
335
+ # Prefer annot over soft
336
+ candidate_platform_dfs.sort(key=lambda x: 0 if x[0]=='GPL_ANNOT' else 1)
337
+ for src, dfp, pth in candidate_platform_dfs:
338
+ tmp_map = _build_mapping_from_annotation(dfp)
339
+ if not tmp_map.empty:
340
+ mapping_df = tmp_map
341
+ mapping_source = src
342
+ chosen_probe_col = _pick_probe_id_col(dfp)
343
+ syms = _symbol_candidates(dfp)
344
+ if syms:
345
+ scores = {c: _extractability_score(dfp[c]) for c in syms}
346
+ chosen_symbol_col = max(scores, key=scores.get)
347
+ break
348
+
349
+ print(f"Mapping source: {mapping_source if mapping_source else 'None'}")
350
+ print(f"Selected probe ID column: {chosen_probe_col if chosen_probe_col else 'None'}")
351
+ print(f"Selected gene symbol column: {chosen_symbol_col if chosen_symbol_col else 'None'}")
352
+ print(f"Mapping size: {len(mapping_df) if not mapping_df.empty else 0}")
353
+
354
+ # Apply mapping or keep probe-level data as fallback
355
+ mapped_gene_data = None
356
+ if not mapping_df.empty:
357
+ try:
358
+ mapped_gene_data = apply_gene_mapping(expression_df=probe_level_data, mapping_df=mapping_df)
359
+ except Exception:
360
+ mapped_gene_data = None
361
+
362
+ if mapped_gene_data is not None and not mapped_gene_data.empty:
363
+ gene_data = mapped_gene_data
364
+ print(f"Gene mapping completed: {probe_level_data.shape[0]} probes -> {gene_data.shape[0]} genes.")
365
+ else:
366
+ gene_data = probe_level_data
367
+ print("WARNING: Gene mapping failed or produced empty result. Falling back to probe-level data.")
368
+
369
+ # Step 7: Data Normalization and Linking
370
+ import os
371
+ import re
372
+ import pandas as pd
373
+
374
+ # Detect Affymetrix-like probe IDs using a robust ratio computation
375
+ def _is_probe_level_index(index, n_check: int = 2000) -> bool:
376
+ pat = re.compile(r'.*_(?:at|s_at|x_at)$', flags=re.IGNORECASE)
377
+ sample = [str(x) for x in list(index)[:min(len(index), n_check)]]
378
+ if not sample:
379
+ return False
380
+ hits = sum(1 for x in sample if pat.match(x))
381
+ ratio = hits / len(sample)
382
+ return ratio >= 0.5
383
+
384
+ # Ensure we can access the clinical dataframe (fallback to file if needed)
385
+ try:
386
+ selected_clinical_df # noqa: F401
387
+ except NameError:
388
+ if os.path.exists(out_clinical_data_file):
389
+ selected_clinical_df = pd.read_csv(out_clinical_data_file, index_col=0)
390
+ else:
391
+ raise
392
+
393
+ note_msgs = []
394
+
395
+ # 1. Normalize gene data only if index already looks like gene symbols
396
+ gene_df_to_use = gene_data
397
+ attempted_normalization = False
398
+ if not _is_probe_level_index(gene_df_to_use.index):
399
+ attempted_normalization = True
400
+ try:
401
+ tmp_norm = normalize_gene_symbols_in_index(gene_df_to_use.copy())
402
+ except Exception as e:
403
+ tmp_norm = pd.DataFrame()
404
+ note_msgs.append(f"ERROR: Normalization failed with error: {e}")
405
+
406
+ if tmp_norm is not None and not tmp_norm.empty:
407
+ normalized_gene_data = tmp_norm
408
+ else:
409
+ normalized_gene_data = gene_df_to_use
410
+ note_msgs.append("WARNING: Normalization yielded empty result; using original gene matrix.")
411
+ else:
412
+ normalized_gene_data = gene_df_to_use
413
+ note_msgs.append("INFO: Probe-level identifiers detected (e.g., '_at' suffix). Mapping to symbols failed earlier; skipping gene symbol normalization and keeping probe-level data.")
414
+
415
+ # Ensure output directory exists and save gene data
416
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
417
+ normalized_gene_data.to_csv(out_gene_data_file)
418
+
419
+ # 2. Link the clinical and genetic data
420
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
421
+
422
+ # 3. Handle missing values in the linked data
423
+ linked_data = handle_missing_values(linked_data, trait)
424
+
425
+ # 4. Determine whether the trait and some demographic features are severely biased, and remove biased features.
426
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
427
+
428
+ # 5. Conduct quality check and save the cohort information.
429
+ is_gene_available_flag = (normalized_gene_data.shape[0] > 0 and normalized_gene_data.shape[1] > 0)
430
+ is_trait_available_flag = trait in selected_clinical_df.index
431
+
432
+ note = " ".join(note_msgs) if note_msgs else "INFO: No special notes."
433
+ is_usable = validate_and_save_cohort_info(
434
+ is_final=True,
435
+ cohort=cohort,
436
+ info_path=json_path,
437
+ is_gene_available=is_gene_available_flag,
438
+ is_trait_available=is_trait_available_flag,
439
+ is_biased=is_trait_biased,
440
+ df=unbiased_linked_data,
441
+ note=note
442
+ )
443
+
444
+ # 6. If the linked data is usable, save it
445
+ if is_usable:
446
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
447
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Type_2_Diabetes/code/GSE281144.py ADDED
@@ -0,0 +1,382 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Type_2_Diabetes"
6
+ cohort = "GSE281144"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Type_2_Diabetes"
10
+ in_cohort_dir = "../DATA/GEO/Type_2_Diabetes/GSE281144"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z6/preprocess/Type_2_Diabetes/GSE281144.csv"
14
+ out_gene_data_file = "./output/z6/preprocess/Type_2_Diabetes/gene_data/GSE281144.csv"
15
+ out_clinical_data_file = "./output/z6/preprocess/Type_2_Diabetes/clinical_data/GSE281144.csv"
16
+ json_path = "./output/z6/preprocess/Type_2_Diabetes/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
+ is_gene_available = True # Microarray gene expression mentioned in background info
44
+
45
+ # 2) Variable availability
46
+ trait_row = 1 # 'diabetes status: Control' vs 'Diabetic'
47
+ age_row = None # No age information in the sample characteristics
48
+ gender_row = 0 # 'Sex: Female' / 'Sex: Male'
49
+
50
+ # 2.2) Converters
51
+ def _after_colon_lower(x):
52
+ if x is None:
53
+ return None
54
+ s = str(x)
55
+ if ':' in s:
56
+ s = s.split(':', 1)[1]
57
+ s = s.strip().lower()
58
+ return s if s else None
59
+
60
+ def convert_trait(x):
61
+ s = _after_colon_lower(x)
62
+ if s is None:
63
+ return None
64
+ # Positive diabetes indicators
65
+ if any(k in s for k in ['diabetic', 'type 2', 't2d', 'dm2', 'type ii']):
66
+ return 1
67
+ # Negative diabetes indicators
68
+ if any(k in s for k in ['control', 'non-diabetic', 'nondiabetic', 'without diabetes', 'no diabetes', 'normoglycemic']):
69
+ return 0
70
+ # Generic yes/no if context only has diabetes status
71
+ if s in ['yes', 'y', 'true', 'positive', '+']:
72
+ return 1
73
+ if s in ['no', 'n', 'false', 'negative', '-']:
74
+ return 0
75
+ # If the original field includes 'diabetes' keyword try a final heuristic
76
+ orig = str(x).lower()
77
+ if 'diab' in orig:
78
+ if 'control' in orig or 'non' in orig:
79
+ return 0
80
+ return 1
81
+ return None
82
+
83
+ def convert_age(x):
84
+ s = _after_colon_lower(x)
85
+ if s is None:
86
+ return None
87
+ m = re.search(r'(\d+(\.\d+)?)', s)
88
+ if not m:
89
+ return None
90
+ try:
91
+ return float(m.group(1))
92
+ except Exception:
93
+ return None
94
+
95
+ def convert_gender(x):
96
+ s = _after_colon_lower(x)
97
+ if s is None:
98
+ return None
99
+ # Map female -> 0, male -> 1
100
+ if s in ['female', 'f', 'woman', 'girl']:
101
+ return 0
102
+ if s in ['male', 'm', 'man', 'boy']:
103
+ return 1
104
+ # Heuristics
105
+ if 'female' in s:
106
+ return 0
107
+ if 'male' in s:
108
+ return 1
109
+ return None
110
+
111
+ # 3) Initial filtering and save metadata
112
+ is_trait_available = trait_row is not None
113
+ _ = validate_and_save_cohort_info(
114
+ is_final=False,
115
+ cohort=cohort,
116
+ info_path=json_path,
117
+ is_gene_available=is_gene_available,
118
+ is_trait_available=is_trait_available
119
+ )
120
+
121
+ # 4) Clinical feature extraction (only if clinical data available)
122
+ if trait_row is not None:
123
+ selected_clinical_df = geo_select_clinical_features(
124
+ clinical_df=clinical_data,
125
+ trait=trait,
126
+ trait_row=trait_row,
127
+ convert_trait=convert_trait,
128
+ age_row=age_row,
129
+ convert_age=convert_age if age_row is not None else None,
130
+ gender_row=gender_row,
131
+ convert_gender=convert_gender
132
+ )
133
+ # Preview and save
134
+ preview = preview_df(selected_clinical_df, n=5)
135
+ print(preview)
136
+ selected_clinical_df.to_csv(out_clinical_data_file)
137
+
138
+ # Step 3: Gene Data Extraction
139
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
140
+ gene_data = get_genetic_data(matrix_file)
141
+
142
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
143
+ print(gene_data.index[:20])
144
+
145
+ # Step 4: Gene Identifier Review
146
+ requires_gene_mapping = True
147
+ print(f"requires_gene_mapping = {requires_gene_mapping}")
148
+
149
+ # Step 5: Gene Annotation
150
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
151
+ gene_annotation = get_gene_annotation(soft_file)
152
+
153
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
154
+ print("Gene annotation preview:")
155
+ print(preview_df(gene_annotation))
156
+
157
+ # Step 6: Gene Identifier Mapping
158
+ import os
159
+ import re
160
+ import pandas as pd
161
+
162
+ # Keep original expression data
163
+ expr_df = gene_data.copy()
164
+
165
+ # Prepare expression ID sets (exact and stripped suffix like '_st')
166
+ expr_ids = expr_df.index.astype(str)
167
+ expr_ids_set = set(expr_ids)
168
+ expr_ids_stripped = expr_ids.str.replace(r'_[^_]+$', '', regex=True)
169
+ expr_ids_stripped_set = set(expr_ids_stripped)
170
+
171
+ def compute_overlap(series: pd.Series) -> tuple:
172
+ vals = series.astype(str).str.strip()
173
+ exact = int(vals.isin(expr_ids_set).sum())
174
+ stripped_vals = vals.str.replace(r'_[^_]+$', '', regex=True)
175
+ stripped = int(stripped_vals.isin(expr_ids_stripped_set).sum())
176
+ return exact, stripped
177
+
178
+ def collect_probe_col_candidates(df: pd.DataFrame) -> list:
179
+ preferred = [
180
+ 'probeset_id', 'Probe Set ID', 'probesetid', 'probeset',
181
+ 'ID', 'ID_REF', 'ProbeSet ID', 'probeset identifier',
182
+ 'transcript_cluster_id', 'Transcript Cluster ID'
183
+ ]
184
+ cands = []
185
+ for c in df.columns:
186
+ cl = c.lower()
187
+ if (('probe' in cl or 'id' in cl or 'transcript' in cl) and df[c].dtype != 'float') or (c in preferred):
188
+ cands.append(c)
189
+ pref_set = [c for c in preferred if c in df.columns]
190
+ others = [c for c in cands if c not in pref_set]
191
+ return pref_set + others
192
+
193
+ def collect_gene_symbol_candidates(df: pd.DataFrame) -> list:
194
+ known = [
195
+ 'gene_symbol', 'Gene Symbol', 'Symbol', 'GENE_SYMBOL',
196
+ 'gene_assignment', 'mrna_assignment', 'gene symbols'
197
+ ]
198
+ cands = [c for c in known if c in df.columns]
199
+ cands += [c for c in df.columns if ('gene' in c.lower()) and (c not in cands)]
200
+ return cands
201
+
202
+ # Prefer platform-specific annotation if available; otherwise fall back to family SOFT
203
+ annotation_sources = []
204
+ annotation_sources.append((gene_annotation, os.path.basename(soft_file)))
205
+ for f in os.listdir(in_cohort_dir):
206
+ path = os.path.join(in_cohort_dir, f)
207
+ fl = f.lower()
208
+ if f == os.path.basename(soft_file):
209
+ continue
210
+ try:
211
+ if ('gpl' in fl and fl.endswith('.soft.gz')) or ('annot' in fl and fl.endswith('.gz')):
212
+ try:
213
+ df = pd.read_csv(path, compression='gzip', sep='\t', low_memory=False, on_bad_lines='skip')
214
+ except Exception:
215
+ df = pd.read_csv(path, compression='gzip', sep=',', low_memory=False, on_bad_lines='skip')
216
+ annotation_sources.append((df, f))
217
+ elif (fl.endswith('.txt.gz') or fl.endswith('.tsv.gz')) and fl.endswith('.gz'):
218
+ try:
219
+ df = pd.read_csv(path, compression='gzip', sep='\t', low_memory=False, on_bad_lines='skip')
220
+ except Exception:
221
+ df = pd.read_csv(path, compression='gzip', sep=',', low_memory=False, on_bad_lines='skip')
222
+ annotation_sources.append((df, f))
223
+ elif fl.endswith('.csv.gz'):
224
+ df = pd.read_csv(path, compression='gzip', low_memory=False, on_bad_lines='skip')
225
+ annotation_sources.append((df, f))
226
+ except Exception as e:
227
+ print(f"Skipping {f} due to error while reading: {e}")
228
+
229
+ best = {
230
+ 'overlap_exact': -1,
231
+ 'overlap_stripped': -1,
232
+ 'probe_col': None,
233
+ 'gene_col': None,
234
+ 'df': None,
235
+ 'source': None
236
+ }
237
+
238
+ for ann_df, source in annotation_sources:
239
+ if not isinstance(ann_df, pd.DataFrame) or ann_df.shape[1] == 0:
240
+ continue
241
+ probe_cols = collect_probe_col_candidates(ann_df)
242
+ gene_cols = collect_gene_symbol_candidates(ann_df)
243
+ if not probe_cols or not gene_cols:
244
+ continue
245
+ for pcol in probe_cols:
246
+ try:
247
+ exact, stripped = compute_overlap(ann_df[pcol])
248
+ except Exception:
249
+ continue
250
+ # Choose gene column (prefer ones with 'symbol' or 'assignment')
251
+ gcol = None
252
+ for cand in gene_cols:
253
+ if cand in ann_df.columns:
254
+ gcol = cand
255
+ break
256
+ if exact > best['overlap_exact'] or (exact == best['overlap_exact'] and stripped > best['overlap_stripped']):
257
+ best.update({
258
+ 'overlap_exact': exact,
259
+ 'overlap_stripped': stripped,
260
+ 'probe_col': pcol,
261
+ 'gene_col': gcol,
262
+ 'df': ann_df,
263
+ 'source': source
264
+ })
265
+
266
+ print(f"Selected annotation source: {best['source']}")
267
+ print(f"Probe column candidate: {best['probe_col']}")
268
+ print(f"Gene column candidate: {best['gene_col']}")
269
+ print(f"Overlap (exact): {best['overlap_exact']}, Overlap (stripped): {best['overlap_stripped']}")
270
+
271
+ if (best['overlap_exact'] <= 0) and (best['overlap_stripped'] <= 0):
272
+ tried_sources = [name for _, name in annotation_sources]
273
+ raise ValueError(
274
+ f"No overlap between expression probe IDs and any annotation columns. "
275
+ f"Tried sources: {tried_sources}. "
276
+ f"Expression IDs example: {list(expr_ids[:5])}"
277
+ )
278
+
279
+ # Show a small sample of intersecting IDs for verification
280
+ ann_ids_series = best['df'][best['probe_col']].astype(str).str.strip()
281
+ ann_ids_set = set(ann_ids_series)
282
+ intersection_exact = list(expr_ids_set & ann_ids_set)
283
+ if not intersection_exact:
284
+ # Try stripped
285
+ ann_ids_stripped_set = set(ann_ids_series.str.replace(r'_[^_]+$', '', regex=True))
286
+ intersection_stripped = list(expr_ids_stripped_set & ann_ids_stripped_set)
287
+ print("Sample intersecting IDs (stripped):", intersection_stripped[:10])
288
+ else:
289
+ print("Sample intersecting IDs (exact):", intersection_exact[:10])
290
+
291
+ # Build mapping dataframe (ID + raw gene text)
292
+ raw_mapping_df = get_gene_mapping(best['df'], prob_col=best['probe_col'], gene_col=best['gene_col'])
293
+
294
+ # Deterministic parsing of Affymetrix-style "gene_assignment" field to symbols
295
+ def symbols_from_assignment(text: str) -> list:
296
+ if not isinstance(text, str) or not text.strip():
297
+ return []
298
+ symbols = []
299
+ # Split entries by ' /// ' and then fields by ' // '
300
+ for entry in text.split('///'):
301
+ parts = [p.strip() for p in entry.split('//')]
302
+ if len(parts) >= 2:
303
+ sym = parts[1].strip().strip('"')
304
+ if not sym or sym in {'---', 'NULL'}:
305
+ continue
306
+ u = sym.upper()
307
+ # Exclusions: transcript IDs, non-gene placeholders, miRNA/LOC/LINC etc.
308
+ if re.match(r'^(NR_|XR_|XM_|NM_|ENST|ENSG|OTTHUMT|OTTHUMG|UC)', u):
309
+ continue
310
+ if re.match(r'^(LOC\d+|LINC\d+)', u):
311
+ continue
312
+ if u.startswith('MIR') or u.startswith('SCARNA') or u.startswith('SNORD') or u.startswith('RNU'):
313
+ continue
314
+ # Keep plausible symbols: uppercase letters/digits/hyphens or C#ORF#
315
+ if re.match(r'^(?:[A-Z0-9-]{2,20}|C\d+ORF\d+)$', u):
316
+ symbols.append(u)
317
+ # Deduplicate in order
318
+ return list(dict.fromkeys(symbols))
319
+
320
+ # Clean mapping: produce a gene-only string that apply_gene_mapping will parse cleanly
321
+ clean_mapping = raw_mapping_df.copy()
322
+ clean_mapping['GeneList'] = clean_mapping['Gene'].apply(symbols_from_assignment)
323
+ clean_mapping = clean_mapping[clean_mapping['GeneList'].map(len) > 0].copy()
324
+ clean_mapping['Gene'] = clean_mapping['GeneList'].apply(lambda lst: ' '.join(lst))
325
+ clean_mapping = clean_mapping[['ID', 'Gene']]
326
+
327
+ # Decide whether to use exact or stripped mapping for probe IDs
328
+ use_stripped = best['overlap_stripped'] > best['overlap_exact']
329
+
330
+ # Prepare expression dataframe aligned to the mapping ID format
331
+ if use_stripped:
332
+ expr_tmp = expr_df.copy()
333
+ expr_tmp.index = expr_tmp.index.to_series().str.replace(r'_[^_]+$', '', regex=True)
334
+ if expr_tmp.index.duplicated().any():
335
+ expr_tmp = expr_tmp.groupby(expr_tmp.index).mean()
336
+ expression_for_mapping = expr_tmp
337
+ else:
338
+ expression_for_mapping = expr_df
339
+
340
+ print("Preview of cleaned mapping_df:")
341
+ print(clean_mapping.head(5))
342
+
343
+ # Apply mapping to convert probe-level to gene-level
344
+ gene_data = apply_gene_mapping(expression_df=expression_for_mapping, mapping_df=clean_mapping)
345
+
346
+ # Quick sanity check
347
+ print("Gene-level data shape:", gene_data.shape)
348
+ print("Gene-level preview (first 5 genes):")
349
+ print(gene_data.head(5))
350
+
351
+ # Step 7: Data Normalization and Linking
352
+ import os
353
+ import pandas as pd
354
+
355
+ # 1. Normalize gene symbols and save
356
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
357
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
358
+ normalized_gene_data.to_csv(out_gene_data_file)
359
+
360
+ # Ensure clinical features are available in the current context
361
+ if 'selected_clinical_df' not in globals():
362
+ selected_clinical_df = pd.read_csv(out_clinical_data_file, index_col=0)
363
+
364
+ # 2. Link clinical and genetic data
365
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
366
+
367
+ # 3. Handle missing values
368
+ linked_data = handle_missing_values(linked_data, trait)
369
+
370
+ # 4. Assess bias and remove biased demographic features
371
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
372
+
373
+ # 5. Final validation and save cohort info
374
+ note = "INFO: Age unavailable; Gender available; Affymetrix-style mapping applied."
375
+ is_usable = validate_and_save_cohort_info(
376
+ True, cohort, json_path, True, True, is_trait_biased, unbiased_linked_data, note=note
377
+ )
378
+
379
+ # 6. Save linked data if usable
380
+ if is_usable:
381
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
382
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Type_2_Diabetes/code/GSE98887.py ADDED
@@ -0,0 +1,216 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Type_2_Diabetes"
6
+ cohort = "GSE98887"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Type_2_Diabetes"
10
+ in_cohort_dir = "../DATA/GEO/Type_2_Diabetes/GSE98887"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z6/preprocess/Type_2_Diabetes/GSE98887.csv"
14
+ out_gene_data_file = "./output/z6/preprocess/Type_2_Diabetes/gene_data/GSE98887.csv"
15
+ out_clinical_data_file = "./output/z6/preprocess/Type_2_Diabetes/clinical_data/GSE98887.csv"
16
+ json_path = "./output/z6/preprocess/Type_2_Diabetes/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 (scRNA-Seq -> gene expression data present)
44
+ is_gene_available = True
45
+
46
+ # 2) Variable availability from the provided Sample Characteristics Dictionary
47
+ # Only 'tissue: inlet cells' is available and constant; trait/age/gender not available.
48
+ trait_row = None
49
+ age_row = None
50
+ gender_row = None
51
+
52
+ # 2.2 Conversion functions
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) == 2 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
+ s = v.lower().strip()
65
+ s = s.replace("–", "-").replace("—", "-")
66
+
67
+ # Exclude Type 1 diabetes explicitly (not our trait label)
68
+ if re.search(r"\b(type\s*1|type[-\s]?i|t1d)\b", s):
69
+ return None
70
+
71
+ # Negative/control indications first to avoid substring collisions (e.g., "non-diabetic")
72
+ neg_patterns = [
73
+ r"\bnon[-\s]?diabet\w*\b",
74
+ r"\bcontrol(s)?\b",
75
+ r"\bhealthy\b",
76
+ r"\bnormo?glyc\w*\b",
77
+ r"\bno diabetes\b",
78
+ r"\bnormal\b",
79
+ r"\bhc\b"
80
+ ]
81
+ if any(re.search(pat, s) for pat in neg_patterns):
82
+ return 0
83
+
84
+ # Positive (T2D) indications
85
+ pos_patterns = [
86
+ r"\btype\s*2\b.*diabet\w*",
87
+ r"\btype[-\s]?ii\b.*diabet\w*",
88
+ r"\bt2d(m)?\b",
89
+ r"\bdm2\b",
90
+ r"\btype2\b.*diabet\w*",
91
+ r"\bdiabetic\b" # falls back to dataset context; kept but neg handled above
92
+ ]
93
+ if any(re.search(pat, s) for pat in pos_patterns):
94
+ return 1
95
+
96
+ # Case/Control shorthand
97
+ if s == "case":
98
+ return 1
99
+ if s == "control":
100
+ return 0
101
+
102
+ # Prediabetes/IGT/ambiguous -> None
103
+ ambig_patterns = [r"\bpre[-\s]?diabet\w*\b", r"\bigt\b", r"impaired glucose"]
104
+ if any(re.search(pat, s) for pat in ambig_patterns):
105
+ return None
106
+
107
+ return None
108
+
109
+ def convert_age(x):
110
+ v = _after_colon(x)
111
+ if v is None or v == "":
112
+ return None
113
+ m = re.findall(r"[-+]?\d*\.?\d+", v)
114
+ if not m:
115
+ return None
116
+ try:
117
+ val = float(m[0])
118
+ if val < 0 or val > 120:
119
+ return None
120
+ return int(val) if val.is_integer() else val
121
+ except Exception:
122
+ return None
123
+
124
+ def convert_gender(x):
125
+ v = _after_colon(x)
126
+ if v is None or v == "":
127
+ return None
128
+ s = v.strip().lower()
129
+ if s in ["female", "f", "woman", "girl", "xx"]:
130
+ return 0
131
+ if s in ["male", "m", "man", "boy", "xy"]:
132
+ return 1
133
+ return None
134
+
135
+ # 3) Initial filtering metadata save
136
+ is_trait_available = trait_row is not None
137
+ _ = validate_and_save_cohort_info(
138
+ is_final=False,
139
+ cohort=cohort,
140
+ info_path=json_path,
141
+ is_gene_available=is_gene_available,
142
+ is_trait_available=is_trait_available
143
+ )
144
+
145
+ # 4) Clinical feature extraction (skip because trait_row is None)
146
+ if trait_row is not None:
147
+ selected_clinical = geo_select_clinical_features(
148
+ clinical_df=clinical_data,
149
+ trait=trait,
150
+ trait_row=trait_row,
151
+ convert_trait=convert_trait,
152
+ age_row=age_row,
153
+ convert_age=convert_age,
154
+ gender_row=gender_row,
155
+ convert_gender=convert_gender
156
+ )
157
+ _ = preview_df(selected_clinical)
158
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
159
+ selected_clinical.to_csv(out_clinical_data_file, index=True)
160
+
161
+ # Step 3: Gene Data Extraction
162
+ import io
163
+ import gzip
164
+ import pandas as pd
165
+
166
+ # 1. Try the standard extractor
167
+ gene_data = get_genetic_data(matrix_file)
168
+
169
+ # Diagnostics
170
+ print("After get_genetic_data:")
171
+ print(" shape:", gene_data.shape)
172
+ print(" first columns:", list(gene_data.columns[:10]))
173
+ print(" first index values:", list(gene_data.index[:5]))
174
+
175
+ # 2. If empty, try a robust manual parser for the matrix section
176
+ if gene_data.shape[0] == 0 or len(gene_data.index) == 0:
177
+ print("Standard parsing returned empty. Attempting manual parsing between matrix begin/end markers...")
178
+ lines = []
179
+ in_table = False
180
+ with gzip.open(matrix_file, 'rt') as fh:
181
+ for line in fh:
182
+ s = line.rstrip('\n')
183
+ if "!series_matrix_table_begin" in s:
184
+ in_table = True
185
+ continue
186
+ if "!series_matrix_table_end" in s:
187
+ break
188
+ if in_table:
189
+ lines.append(s)
190
+ if lines:
191
+ text = "\n".join(lines)
192
+ try:
193
+ df = pd.read_csv(io.StringIO(text), sep='\t', low_memory=False)
194
+ # Normalize ID column
195
+ if 'ID_REF' in df.columns:
196
+ df = df.rename(columns={'ID_REF': 'ID'})
197
+ elif 'ID' not in df.columns:
198
+ # Fallback: assume first column is the identifier
199
+ first_col = df.columns[0]
200
+ df = df.rename(columns={first_col: 'ID'})
201
+ df['ID'] = df['ID'].astype(str)
202
+ df = df.set_index('ID')
203
+ gene_data = df
204
+ except Exception as e:
205
+ print(f"Manual parsing failed with error: {e}")
206
+
207
+ # Final diagnostics and first 20 IDs
208
+ print("Final gene_data diagnostics:")
209
+ print(" shape:", gene_data.shape)
210
+ print(" first columns:", list(gene_data.columns[:10]))
211
+ print(" first index values:", list(gene_data.index[:5]))
212
+ print(gene_data.index[:20])
213
+
214
+ if gene_data.shape[0] == 0:
215
+ print("WARNING: The series matrix appears to be missing or empty (common for some scRNA-Seq GEO entries).")
216
+ print("Consider checking supplementary files or platform annotations for expression data.")
output/preprocess/Type_2_Diabetes/code/TCGA.py ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Type_2_Diabetes"
6
+
7
+ # Input paths
8
+ tcga_root_dir = "../DATA/TCGA"
9
+
10
+ # Output paths
11
+ out_data_file = "./output/z6/preprocess/Type_2_Diabetes/TCGA.csv"
12
+ out_gene_data_file = "./output/z6/preprocess/Type_2_Diabetes/gene_data/TCGA.csv"
13
+ out_clinical_data_file = "./output/z6/preprocess/Type_2_Diabetes/clinical_data/TCGA.csv"
14
+ json_path = "./output/z6/preprocess/Type_2_Diabetes/cohort_info.json"
15
+
16
+
17
+ # Step 1: Initial Data Loading
18
+ import os
19
+ import pandas as pd
20
+
21
+ # Discover available 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
+ # Identify cohort directories that could match Type 2 Diabetes (none expected in TCGA cancer cohorts)
25
+ keywords = [
26
+ "diabetes", "type_2", "type 2", "t2d", "dm2", "type ii", "non-insulin-dependent", "niddm"
27
+ ]
28
+ candidate_dirs = [d for d in all_subdirs if any(k in d.lower() for k in keywords)]
29
+
30
+ selected_dir = None
31
+ if len(candidate_dirs) > 0:
32
+ # If multiple, choose the most specific (longest name)
33
+ selected_dir = sorted(candidate_dirs, key=lambda x: len(x), reverse=True)[0]
34
+
35
+ if selected_dir is None:
36
+ # No suitable TCGA cohort for Type 2 Diabetes; record and stop further processing in this step
37
+ _ = validate_and_save_cohort_info(
38
+ is_final=False,
39
+ cohort="TCGA",
40
+ info_path=json_path,
41
+ is_gene_available=False,
42
+ is_trait_available=False
43
+ )
44
+ else:
45
+ cohort_dir = os.path.join(tcga_root_dir, selected_dir)
46
+ clinical_file_path, genetic_file_path = tcga_get_relevant_filepaths(cohort_dir)
47
+
48
+ # Load dataframes (handle gz if present)
49
+ compression_clin = 'gzip' if clinical_file_path.endswith('.gz') else None
50
+ compression_gen = 'gzip' if genetic_file_path.endswith('.gz') else None
51
+
52
+ clinical_df = pd.read_csv(clinical_file_path, sep='\t', index_col=0, low_memory=False, compression=compression_clin)
53
+ genetic_df = pd.read_csv(genetic_file_path, sep='\t', index_col=0, low_memory=False, compression=compression_gen)
54
+
55
+ print(clinical_df.columns.tolist())
56
+
57
+ # Step 2: Initial Data Loading
58
+ import os
59
+ import pandas as pd
60
+
61
+ # Provided subdirectories (from instruction)
62
+ available_subdirs = [
63
+ 'TCGA_lower_grade_glioma_and_glioblastoma_(GBMLGG)', 'TCGA_Uterine_Carcinosarcoma_(UCS)', 'TCGA_Thyroid_Cancer_(THCA)',
64
+ 'TCGA_Thymoma_(THYM)', 'TCGA_Testicular_Cancer_(TGCT)', 'TCGA_Stomach_Cancer_(STAD)', 'TCGA_Sarcoma_(SARC)',
65
+ 'TCGA_Rectal_Cancer_(READ)', 'TCGA_Prostate_Cancer_(PRAD)', 'TCGA_Pheochromocytoma_Paraganglioma_(PCPG)',
66
+ 'TCGA_Pancreatic_Cancer_(PAAD)', 'TCGA_Ovarian_Cancer_(OV)', 'TCGA_Ocular_melanomas_(UVM)', 'TCGA_Mesothelioma_(MESO)',
67
+ 'TCGA_Melanoma_(SKCM)', 'TCGA_Lung_Squamous_Cell_Carcinoma_(LUSC)', 'TCGA_Lung_Cancer_(LUNG)',
68
+ 'TCGA_Lung_Adenocarcinoma_(LUAD)', 'TCGA_Lower_Grade_Glioma_(LGG)', 'TCGA_Liver_Cancer_(LIHC)',
69
+ 'TCGA_Large_Bcell_Lymphoma_(DLBC)', 'TCGA_Kidney_Papillary_Cell_Carcinoma_(KIRP)', 'TCGA_Kidney_Clear_Cell_Carcinoma_(KIRC)',
70
+ 'TCGA_Kidney_Chromophobe_(KICH)', 'TCGA_Head_and_Neck_Cancer_(HNSC)', 'TCGA_Glioblastoma_(GBM)', 'TCGA_Esophageal_Cancer_(ESCA)',
71
+ 'TCGA_Endometrioid_Cancer_(UCEC)', 'TCGA_Colon_and_Rectal_Cancer_(COADREAD)', 'TCGA_Colon_Cancer_(COAD)',
72
+ 'TCGA_Cervical_Cancer_(CESC)', 'TCGA_Breast_Cancer_(BRCA)', 'TCGA_Bladder_Cancer_(BLCA)', 'TCGA_Bile_Duct_Cancer_(CHOL)',
73
+ 'TCGA_Adrenocortical_Cancer_(ACC)', 'TCGA_Acute_Myeloid_Leukemia_(LAML)'
74
+ ]
75
+
76
+ # Filter to those that actually exist in filesystem (defensive)
77
+ existing_subdirs = [d for d in available_subdirs if os.path.isdir(os.path.join(tcga_root_dir, d))]
78
+
79
+ # Identify cohort directories that could match Type 2 Diabetes (none expected in TCGA cancer cohorts)
80
+ keywords = ["diabetes", "type_2", "type 2", "t2d", "dm2", "type ii", "non-insulin-dependent", "niddm"]
81
+ candidate_dirs = [d for d in existing_subdirs if any(k in d.lower() for k in keywords)]
82
+
83
+ selected_dir = None
84
+ if len(candidate_dirs) > 0:
85
+ selected_dir = sorted(candidate_dirs, key=lambda x: len(x), reverse=True)[0]
86
+
87
+ if selected_dir is None:
88
+ # No suitable TCGA cohort for Type 2 Diabetes; record and stop further processing in this step
89
+ _ = validate_and_save_cohort_info(
90
+ is_final=False,
91
+ cohort="TCGA",
92
+ info_path=json_path,
93
+ is_gene_available=False,
94
+ is_trait_available=False
95
+ )
96
+ else:
97
+ cohort_dir = os.path.join(tcga_root_dir, selected_dir)
98
+ clinical_file_path, genetic_file_path = tcga_get_relevant_filepaths(cohort_dir)
99
+
100
+ compression_clin = 'gzip' if clinical_file_path.endswith('.gz') else None
101
+ compression_gen = 'gzip' if genetic_file_path.endswith('.gz') else None
102
+
103
+ clinical_df = pd.read_csv(clinical_file_path, sep='\t', index_col=0, low_memory=False, compression=compression_clin)
104
+ genetic_df = pd.read_csv(genetic_file_path, sep='\t', index_col=0, low_memory=False, compression=compression_gen)
105
+
106
+ print(clinical_df.columns.tolist())
output/preprocess/Type_2_Diabetes/gene_data/GSE271700.csv CHANGED
The diff for this file is too large to render. See raw diff
 
output/preprocess/Type_2_Diabetes/gene_data/GSE281144.csv CHANGED
The diff for this file is too large to render. See raw diff
 
output/preprocess/Underweight/code/GSE130563.py ADDED
@@ -0,0 +1,218 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Underweight"
6
+ cohort = "GSE130563"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Underweight"
10
+ in_cohort_dir = "../DATA/GEO/Underweight/GSE130563"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z6/preprocess/Underweight/GSE130563.csv"
14
+ out_gene_data_file = "./output/z6/preprocess/Underweight/gene_data/GSE130563.csv"
15
+ out_clinical_data_file = "./output/z6/preprocess/Underweight/clinical_data/GSE130563.csv"
16
+ json_path = "./output/z6/preprocess/Underweight/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 data per series description
43
+
44
+ # 2) Variable availability and converters
45
+ # Trait: Underweight is not available in this dataset (no BMI/weight status)
46
+ trait_row = None
47
+
48
+ # Age: available at key 4
49
+ age_row = 4
50
+
51
+ # Gender: available at key 1
52
+ gender_row = 1
53
+
54
+ def convert_trait(v):
55
+ # Underweight not available in this cohort
56
+ return None
57
+
58
+ def _extract_value_after_colon(v):
59
+ if v is None:
60
+ return None
61
+ s = str(v)
62
+ if ':' in s:
63
+ s = s.split(':', 1)[1]
64
+ return s.strip()
65
+
66
+ def convert_age(v):
67
+ s = _extract_value_after_colon(v)
68
+ if not s or s.lower() in {"n/a", "na", "nan", "unknown", "n.d. (not determined)", "nd", "n.d."}:
69
+ return None
70
+ # extract first number (integer or float)
71
+ m = re.search(r"[-+]?\d*\.?\d+", s)
72
+ if not m:
73
+ return None
74
+ try:
75
+ val = float(m.group(0))
76
+ return val
77
+ except Exception:
78
+ return None
79
+
80
+ def convert_gender(v):
81
+ s = _extract_value_after_colon(v)
82
+ if not s:
83
+ return None
84
+ s = s.strip().lower()
85
+ # Map female -> 0, male -> 1
86
+ if s in {"f", "female"}:
87
+ return 0
88
+ if s in {"m", "male"}:
89
+ return 1
90
+ return None
91
+
92
+ # 3) Save metadata (initial filtering)
93
+ is_trait_available = trait_row is not None
94
+ _ = validate_and_save_cohort_info(
95
+ is_final=False,
96
+ cohort=cohort,
97
+ info_path=json_path,
98
+ is_gene_available=is_gene_available,
99
+ is_trait_available=is_trait_available
100
+ )
101
+
102
+ # 4) Clinical feature extraction (skip if trait not available)
103
+ if trait_row is not None:
104
+ selected_clinical_df = geo_select_clinical_features(
105
+ clinical_df=clinical_data,
106
+ trait=trait,
107
+ trait_row=trait_row,
108
+ convert_trait=convert_trait,
109
+ age_row=age_row,
110
+ convert_age=convert_age,
111
+ gender_row=gender_row,
112
+ convert_gender=convert_gender
113
+ )
114
+ _preview = preview_df(selected_clinical_df)
115
+ 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
+ print("requires_gene_mapping = True")
126
+
127
+ # Step 5: Gene Annotation
128
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
129
+ gene_annotation = get_gene_annotation(soft_file)
130
+
131
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
132
+ print("Gene annotation preview:")
133
+ print(preview_df(gene_annotation))
134
+
135
+ # Step 6: Gene Identifier Mapping
136
+ # Identify the probe ID column in the annotation
137
+ id_col = None
138
+ for cand in ['ID', 'ID_REF', 'ProbeID', 'PROBEID']:
139
+ if cand in gene_annotation.columns:
140
+ id_col = cand
141
+ break
142
+
143
+ # Heuristically identify a gene symbol column: pick the column where a reasonable fraction of entries
144
+ # yield human-like gene symbols via extract_human_gene_symbols
145
+ gene_col = None
146
+ best_frac = 0.0
147
+ threshold = 0.1 # require at least 10% of sampled entries to look like gene symbols
148
+
149
+ if id_col is not None:
150
+ candidate_cols = [c for c in gene_annotation.columns if c != id_col]
151
+ else:
152
+ candidate_cols = list(gene_annotation.columns)
153
+
154
+ for c in candidate_cols:
155
+ ser = gene_annotation[c].dropna().astype(str).head(1000)
156
+ if ser.empty:
157
+ continue
158
+ frac = ser.map(lambda x: len(extract_human_gene_symbols(x)) > 0).mean()
159
+ if frac > best_frac:
160
+ best_frac = frac
161
+ gene_col = c
162
+
163
+ # Build mapping and convert probe-level data to gene-level if the selected gene column looks valid
164
+ mapping_succeeded = False
165
+ if id_col is not None and gene_col is not None and best_frac >= threshold:
166
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=id_col, gene_col=gene_col)
167
+
168
+ n_total_probes = gene_data.shape[0]
169
+ n_mapping_rows = len(mapping_df)
170
+ n_mapping_rows_in_expr = (mapping_df['ID'].isin(gene_data.index)).sum()
171
+ n_unique_probes_in_expr = mapping_df.loc[mapping_df['ID'].isin(gene_data.index), 'ID'].nunique()
172
+
173
+ # Estimate number of genes that can be mapped
174
+ tmp = mapping_df.copy()
175
+ tmp['Gene'] = tmp['Gene'].apply(extract_human_gene_symbols)
176
+ tmp = tmp.explode('Gene').dropna(subset=['Gene'])
177
+ n_unique_genes_est = tmp['Gene'].nunique()
178
+
179
+ print(f"Probe IDs in expression: {n_total_probes}")
180
+ print(f"Annotation rows: {n_mapping_rows}")
181
+ print(f"Annotation rows matching expression probes: {n_mapping_rows_in_expr} (unique probes: {n_unique_probes_in_expr})")
182
+ print(f"Estimated unique genes from annotation column '{gene_col}': {n_unique_genes_est}")
183
+
184
+ # Only proceed if we have a reasonable number of genes
185
+ if n_unique_genes_est >= 100:
186
+ probe_data = gene_data
187
+ gene_data_mapped = apply_gene_mapping(probe_data, mapping_df)
188
+ print(f"Mapped gene-level dataframe shape: {gene_data_mapped.shape}")
189
+ # Sanity check: ensure non-empty and fewer rows than probes (typical for mapping)
190
+ if gene_data_mapped.shape[0] > 0:
191
+ gene_data = gene_data_mapped
192
+ mapping_succeeded = True
193
+
194
+ if not mapping_succeeded:
195
+ print("WARNING: No valid gene symbol column found or mapping produced too few genes. "
196
+ "Keeping probe-level data without mapping.")
197
+
198
+ # Step 7: Data Normalization and Linking
199
+ # Normalize gene symbols; if normalization yields no genes (likely due to probe-level IDs), fall back to probe-level data
200
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
201
+ if normalized_gene_data.shape[0] > 0:
202
+ normalized_gene_data.to_csv(out_gene_data_file)
203
+ else:
204
+ # Fallback: save original probe-level expression since trait is unavailable and mapping failed
205
+ gene_data.to_csv(out_gene_data_file)
206
+
207
+ # Trait is unavailable (from Step 2), so skip linking and downstream steps.
208
+ is_trait_available = False
209
+ is_gene_available = True # Gene expression data is present (at least at probe-level)
210
+
211
+ # Record metadata using initial filtering mode to avoid abnormality override
212
+ _ = validate_and_save_cohort_info(
213
+ is_final=False,
214
+ cohort=cohort,
215
+ info_path=json_path,
216
+ is_gene_available=is_gene_available,
217
+ is_trait_available=is_trait_available
218
+ )
output/preprocess/Underweight/code/GSE131835.py ADDED
@@ -0,0 +1,175 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Underweight"
6
+ cohort = "GSE131835"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Underweight"
10
+ in_cohort_dir = "../DATA/GEO/Underweight/GSE131835"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z6/preprocess/Underweight/GSE131835.csv"
14
+ out_gene_data_file = "./output/z6/preprocess/Underweight/gene_data/GSE131835.csv"
15
+ out_clinical_data_file = "./output/z6/preprocess/Underweight/clinical_data/GSE131835.csv"
16
+ json_path = "./output/z6/preprocess/Underweight/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 Clariom S Microarray indicates mRNA gene expression data.
41
+
42
+ # Step 2: Identify variable availability
43
+ # Trait: Underweight is not explicitly provided; BMI cannot be computed with the single-row extraction constraint.
44
+ trait_row = None
45
+
46
+ # Age and Gender are available
47
+ age_row = 3
48
+ gender_row = 2
49
+
50
+ # Step 2.2: Define converters
51
+ def _extract_value(x):
52
+ if x is None:
53
+ return None
54
+ if isinstance(x, str):
55
+ parts = x.split(":", 1)
56
+ val = parts[1].strip() if len(parts) > 1 else x.strip()
57
+ if val in ["", "N/A", "NA", "na", "NaN", "nan", "None", "null"]:
58
+ return None
59
+ return val
60
+ return x
61
+
62
+ def convert_trait(x):
63
+ # Underweight not available in this dataset under a single key; return None
64
+ return None
65
+
66
+ def convert_age(x):
67
+ v = _extract_value(x)
68
+ if v is None:
69
+ return None
70
+ try:
71
+ # Age in years, continuous
72
+ return float(v)
73
+ except Exception:
74
+ return None
75
+
76
+ def convert_gender(x):
77
+ v = _extract_value(x)
78
+ if v is None:
79
+ return None
80
+ v_lower = str(v).strip().lower()
81
+ if v_lower in ["male", "m"]:
82
+ return 1
83
+ if v_lower in ["female", "f"]:
84
+ return 0
85
+ return None
86
+
87
+ # Step 3: Initial filtering metadata
88
+ is_trait_available = trait_row is not None
89
+ _ = validate_and_save_cohort_info(
90
+ is_final=False,
91
+ cohort=cohort,
92
+ info_path=json_path,
93
+ is_gene_available=is_gene_available,
94
+ is_trait_available=is_trait_available
95
+ )
96
+
97
+ # Step 4: Clinical feature extraction (skip since trait_row is None)
98
+ # If trait_row were available:
99
+ # selected_clinical_df = geo_select_clinical_features(
100
+ # clinical_df=clinical_data,
101
+ # trait=trait,
102
+ # trait_row=trait_row,
103
+ # convert_trait=convert_trait,
104
+ # age_row=age_row,
105
+ # convert_age=convert_age,
106
+ # gender_row=gender_row,
107
+ # convert_gender=convert_gender
108
+ # )
109
+ # preview = preview_df(selected_clinical_df, n=5)
110
+ # os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
111
+ # selected_clinical_df.to_csv(out_clinical_data_file)
112
+
113
+ # Step 3: Gene Data Extraction
114
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
115
+ gene_data = get_genetic_data(matrix_file)
116
+
117
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
118
+ print(gene_data.index[:20])
119
+
120
+ # Step 4: Gene Identifier Review
121
+ print("requires_gene_mapping = True")
122
+
123
+ # Step 5: Gene Annotation
124
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
125
+ gene_annotation = get_gene_annotation(soft_file)
126
+
127
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
128
+ print("Gene annotation preview:")
129
+ print(preview_df(gene_annotation))
130
+
131
+ # Step 6: Gene Identifier Mapping
132
+ # Identify the appropriate columns for mapping: 'ID' for probe IDs and 'ORF' for gene symbols
133
+ mapping_df = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='ORF')
134
+
135
+ # Apply the mapping to convert probe-level data to gene-level expression
136
+ gene_data = apply_gene_mapping(gene_data, mapping_df)
137
+
138
+ # Step 7: Data Normalization and Linking
139
+ # 1. Normalize gene symbols and save gene-level data
140
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
141
+ import os
142
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
143
+ normalized_gene_data.to_csv(out_gene_data_file)
144
+
145
+ # 2-6. Since trait data was not extracted earlier (trait_row was None), skip linking and finalize metadata
146
+ try:
147
+ trait_available = (trait_row is not None)
148
+ except NameError:
149
+ trait_available = False
150
+
151
+ if trait_available and ('selected_clinical_data' in locals()) and (selected_clinical_data is not None):
152
+ # Full pipeline if trait and clinical data are available (not expected for this cohort)
153
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_data, normalized_gene_data)
154
+ linked_data = handle_missing_values(linked_data, trait)
155
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
156
+ is_usable = validate_and_save_cohort_info(
157
+ True, cohort, json_path, True, True, is_trait_biased, unbiased_linked_data
158
+ )
159
+ if is_usable:
160
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
161
+ unbiased_linked_data.to_csv(out_data_file)
162
+ else:
163
+ # Trait unavailable: perform final validation, mark dataset as not available for analysis
164
+ note = "INFO: Trait not available; cannot link clinical and genetic data."
165
+ temp_df = normalized_gene_data.T # non-empty df to avoid false abnormality override
166
+ _ = validate_and_save_cohort_info(
167
+ is_final=True,
168
+ cohort=cohort,
169
+ info_path=json_path,
170
+ is_gene_available=True,
171
+ is_trait_available=False,
172
+ is_biased=True, # ignored since dataset is not available
173
+ df=temp_df,
174
+ note=note
175
+ )
output/preprocess/Underweight/code/GSE50982.py ADDED
@@ -0,0 +1,234 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Underweight"
6
+ cohort = "GSE50982"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Underweight"
10
+ in_cohort_dir = "../DATA/GEO/Underweight/GSE50982"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z6/preprocess/Underweight/GSE50982.csv"
14
+ out_gene_data_file = "./output/z6/preprocess/Underweight/gene_data/GSE50982.csv"
15
+ out_clinical_data_file = "./output/z6/preprocess/Underweight/clinical_data/GSE50982.csv"
16
+ json_path = "./output/z6/preprocess/Underweight/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
+ # This series is a cell-line experiment with knockdown and EGF treatment, consistent with mRNA expression profiling.
44
+ is_gene_available = True
45
+
46
+ # 2) Variable availability (from Sample Characteristics Dictionary)
47
+ # No human clinical variables are present; only cell line, knockdown days, and treatment.
48
+ trait_row = None # Underweight status not available
49
+ age_row = None # Age not available
50
+ gender_row = None # Gender not available
51
+
52
+ # 2.2) Converters
53
+ def _after_colon(x):
54
+ if x is None:
55
+ return None
56
+ if isinstance(x, str):
57
+ parts = x.split(":", 1)
58
+ x = parts[1] if len(parts) > 1 else parts[0]
59
+ return x.strip()
60
+ return x
61
+
62
+ def convert_trait(x):
63
+ # Binary: underweight (1) vs not (0)
64
+ v = _after_colon(x)
65
+ if v is None:
66
+ return None
67
+ s = str(v).strip().lower()
68
+
69
+ # Numeric BMI extraction
70
+ nums = re.findall(r"[-+]?\d*\.?\d+", s)
71
+ if nums:
72
+ try:
73
+ val = float(nums[0])
74
+ # Heuristic: treat as BMI if in a plausible range
75
+ if 10 <= val <= 60:
76
+ return 1 if val < 18.5 else 0
77
+ except Exception:
78
+ pass
79
+
80
+ # Keyword heuristics
81
+ positive_kw = ["underweight", "cachexia", "malnourished", "low bmi", "bmi<18.5"]
82
+ negative_kw = ["normal weight", "healthy weight", "non-underweight"]
83
+ if any(k in s for k in positive_kw):
84
+ return 1
85
+ if any(k in s for k in negative_kw):
86
+ return 0
87
+
88
+ # Avoid mapping generic "case/control" or "yes/no" without context
89
+ return None
90
+
91
+ def convert_age(x):
92
+ v = _after_colon(x)
93
+ if v is None:
94
+ return None
95
+ s = str(v).lower()
96
+ nums = re.findall(r"[-+]?\d*\.?\d+", s)
97
+ if not nums:
98
+ return None
99
+ try:
100
+ age = float(nums[0])
101
+ # Basic plausibility for human age
102
+ if 0 <= age <= 120:
103
+ return age
104
+ except Exception:
105
+ return None
106
+ return None
107
+
108
+ def convert_gender(x):
109
+ v = _after_colon(x)
110
+ if v is None:
111
+ return None
112
+ s = str(v).strip().lower()
113
+ # female -> 0, male -> 1
114
+ female_terms = {"female", "f", "woman", "girl"}
115
+ male_terms = {"male", "m", "man", "boy"}
116
+ if s in female_terms:
117
+ return 0
118
+ if s in male_terms:
119
+ return 1
120
+ return None
121
+
122
+ # 3) Initial filtering and save metadata
123
+ is_trait_available = trait_row is not None
124
+ _ = validate_and_save_cohort_info(
125
+ is_final=False,
126
+ cohort=cohort,
127
+ info_path=json_path,
128
+ is_gene_available=is_gene_available,
129
+ is_trait_available=is_trait_available
130
+ )
131
+
132
+ # 4) Clinical feature extraction (skip since trait_row is None)
133
+ if trait_row is not None:
134
+ selected_clinical_df = geo_select_clinical_features(
135
+ clinical_df=clinical_data,
136
+ trait=trait,
137
+ trait_row=trait_row,
138
+ convert_trait=convert_trait,
139
+ age_row=age_row,
140
+ convert_age=convert_age,
141
+ gender_row=gender_row,
142
+ convert_gender=convert_gender
143
+ )
144
+ _ = preview_df(selected_clinical_df)
145
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
146
+ selected_clinical_df.to_csv(out_clinical_data_file, index=True)
147
+
148
+ # Step 3: Gene Data Extraction
149
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
150
+ gene_data = get_genetic_data(matrix_file)
151
+
152
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
153
+ print(gene_data.index[:20])
154
+
155
+ # Step 4: Gene Identifier Review
156
+ requires_gene_mapping = True
157
+ print(f"requires_gene_mapping = {requires_gene_mapping}")
158
+
159
+ # Step 5: Gene Annotation
160
+ # 1. Extract gene annotation data from the SOFT file
161
+ gene_annotation = get_gene_annotation(soft_file)
162
+
163
+ # 2. Preview column names and first few values to identify probe and gene symbol columns
164
+ print("Gene annotation columns:")
165
+ print(list(gene_annotation.columns))
166
+
167
+ print("\nGene annotation preview (first 5 rows as dict):")
168
+ print(preview_df(gene_annotation))
169
+
170
+ # Step 6: Gene Identifier Mapping
171
+ # 1-2. Decide mapping columns and extract mapping dataframe
172
+ # Probe identifiers match the 'ID' column; gene symbols are in the 'Symbol' column.
173
+ mapping_df = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='Symbol')
174
+
175
+ # 3. Apply mapping to convert probe-level data to gene-level expression
176
+ gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
177
+
178
+ # Step 7: Data Normalization and Linking
179
+ import os
180
+ import pandas as pd
181
+
182
+ # 1) Normalize gene symbols and save gene data
183
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
184
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
185
+ normalized_gene_data.to_csv(out_gene_data_file)
186
+
187
+ # 2-6) Handle absence of clinical trait data gracefully
188
+ if 'selected_clinical_data' in globals() and isinstance(selected_clinical_data, pd.DataFrame):
189
+ # Link clinical and genetic data
190
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_data, normalized_gene_data)
191
+
192
+ # Ensure trait column exists before proceeding
193
+ if trait in linked_data.columns:
194
+ # 3. Handle missing values
195
+ linked_data = handle_missing_values(linked_data, trait)
196
+
197
+ # 4. Bias checking and remove biased demographic features
198
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
199
+
200
+ # 5. Final validation and save cohort info
201
+ note = "INFO: Linked data generated with clinical features and normalized gene expression."
202
+ is_usable = validate_and_save_cohort_info(
203
+ is_final=True,
204
+ cohort=cohort,
205
+ info_path=json_path,
206
+ is_gene_available=True,
207
+ is_trait_available=True,
208
+ is_biased=is_trait_biased,
209
+ df=unbiased_linked_data,
210
+ note=note
211
+ )
212
+
213
+ # 6. Save usable linked data
214
+ if is_usable:
215
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
216
+ unbiased_linked_data.to_csv(out_data_file)
217
+ else:
218
+ # Trait column missing unexpectedly; record unusable with initial filtering to avoid abnormality override
219
+ _ = validate_and_save_cohort_info(
220
+ is_final=False,
221
+ cohort=cohort,
222
+ info_path=json_path,
223
+ is_gene_available=True,
224
+ is_trait_available=False
225
+ )
226
+ else:
227
+ # No clinical data extracted (cell line model); record unusable with initial filtering to avoid abnormality override
228
+ _ = validate_and_save_cohort_info(
229
+ is_final=False,
230
+ cohort=cohort,
231
+ info_path=json_path,
232
+ is_gene_available=True,
233
+ is_trait_available=False
234
+ )
output/preprocess/Underweight/code/GSE57802.py ADDED
@@ -0,0 +1,205 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Underweight"
6
+ cohort = "GSE57802"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Underweight"
10
+ in_cohort_dir = "../DATA/GEO/Underweight/GSE57802"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z6/preprocess/Underweight/GSE57802.csv"
14
+ out_gene_data_file = "./output/z6/preprocess/Underweight/gene_data/GSE57802.csv"
15
+ out_clinical_data_file = "./output/z6/preprocess/Underweight/clinical_data/GSE57802.csv"
16
+ json_path = "./output/z6/preprocess/Underweight/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ import os
40
+ import re
41
+ import pandas as pd
42
+
43
+ # 1. Gene Expression Data Availability
44
+ is_gene_available = True # Transcriptome profiling of LCLs => gene expression data likely available
45
+
46
+ # 2. Variable Availability and Data Type Conversion
47
+
48
+ # Keys in Sample Characteristics Dictionary:
49
+ # trait (Underweight inferred from genotype: duplication -> underweight)
50
+ trait_row = 4 # 'genotype: 600kbdel/600kbdup/Control'
51
+ # age
52
+ age_row = 2 # 'age: ...'
53
+ # gender
54
+ gender_row = 1 # 'gender: M/F'
55
+
56
+ def _after_colon(x):
57
+ if x is None:
58
+ return None
59
+ s = str(x)
60
+ parts = s.split(':', 1)
61
+ return parts[1].strip() if len(parts) > 1 else s.strip()
62
+
63
+ def convert_trait(x):
64
+ """
65
+ Binary: Underweight (1) vs not (0)
66
+ Heuristic:
67
+ - genotype: '600kbdup' => 1; '600kbdel' or 'Control' => 0
68
+ - copy number 16p11.2: 3 => 1; 1 or 2 => 0
69
+ """
70
+ val = _after_colon(x)
71
+ if val is None or val == '':
72
+ return None
73
+ lv = val.lower()
74
+ # Textual mapping
75
+ if 'dup' in lv:
76
+ return 1
77
+ if 'del' in lv or 'control' in lv or 'wt' in lv:
78
+ return 0
79
+ # Numeric mapping (e.g., copy number)
80
+ try:
81
+ n = float(val)
82
+ if n == 3:
83
+ return 1
84
+ if n in (1, 2):
85
+ return 0
86
+ except Exception:
87
+ pass
88
+ return None
89
+
90
+ def convert_age(x):
91
+ """
92
+ Continuous: age in years (float). 'NA' -> None
93
+ """
94
+ val = _after_colon(x)
95
+ if val is None:
96
+ return None
97
+ lv = val.strip().lower()
98
+ if lv in {'na', 'n/a', '', 'nan'}:
99
+ return None
100
+ try:
101
+ return float(val)
102
+ except Exception:
103
+ return None
104
+
105
+ def convert_gender(x):
106
+ """
107
+ Binary: female -> 0, male -> 1
108
+ """
109
+ val = _after_colon(x)
110
+ if val is None:
111
+ return None
112
+ lv = val.strip().lower()
113
+ if lv in {'m', 'male'}:
114
+ return 1
115
+ if lv in {'f', 'female'}:
116
+ return 0
117
+ return None
118
+
119
+ # 3. Save Metadata (initial filtering)
120
+ is_trait_available = trait_row is not None
121
+ _ = validate_and_save_cohort_info(
122
+ is_final=False,
123
+ cohort=cohort,
124
+ info_path=json_path,
125
+ is_gene_available=is_gene_available,
126
+ is_trait_available=is_trait_available
127
+ )
128
+
129
+ # 4. Clinical Feature Extraction (only if clinical data is available)
130
+ if is_trait_available:
131
+ selected_clinical_df = geo_select_clinical_features(
132
+ clinical_df=clinical_data,
133
+ trait=trait,
134
+ trait_row=trait_row,
135
+ convert_trait=convert_trait,
136
+ age_row=age_row,
137
+ convert_age=convert_age,
138
+ gender_row=gender_row,
139
+ convert_gender=convert_gender
140
+ )
141
+ # Preview and save
142
+ print(preview_df(selected_clinical_df))
143
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
144
+ selected_clinical_df.to_csv(out_clinical_data_file)
145
+
146
+ # Step 3: Gene Data Extraction
147
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
148
+ gene_data = get_genetic_data(matrix_file)
149
+
150
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
151
+ print(gene_data.index[:20])
152
+
153
+ # Step 4: Gene Identifier Review
154
+ print("requires_gene_mapping = True")
155
+
156
+ # Step 5: Gene Annotation
157
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
158
+ gene_annotation = get_gene_annotation(soft_file)
159
+
160
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
161
+ print("Gene annotation preview:")
162
+ print(preview_df(gene_annotation))
163
+
164
+ # Step 6: Gene Identifier Mapping
165
+ # 1-2. Identify the appropriate columns for probe IDs and gene symbols and extract mapping dataframe
166
+ probe_col = 'ID'
167
+ gene_symbol_col = 'Gene Symbol'
168
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=probe_col, gene_col=gene_symbol_col)
169
+
170
+ # 3. Apply the mapping to convert probe-level data to gene-level expression data
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
+
176
+ # 1. Normalize the obtained gene data with the 'normalize_gene_symbols_in_index' function from the library.
177
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
178
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
179
+ normalized_gene_data.to_csv(out_gene_data_file)
180
+
181
+ # 2. Link the clinical and genetic data with the 'geo_link_clinical_genetic_data' function from the library.
182
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
183
+
184
+ # 3. Handle missing values in the linked data
185
+ linked_data = handle_missing_values(linked_data, trait)
186
+
187
+ # 4. Determine whether the trait and some demographic features are severely biased, and remove biased features.
188
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
189
+
190
+ # 5. Conduct quality check and save the cohort information.
191
+ is_usable = validate_and_save_cohort_info(
192
+ True,
193
+ cohort,
194
+ json_path,
195
+ is_gene_available,
196
+ is_trait_available,
197
+ is_trait_biased,
198
+ unbiased_linked_data,
199
+ note="INFO: Probe-to-gene mapping applied; trait inferred from 16p11.2 duplication vs others."
200
+ )
201
+
202
+ # 6. If the linked data is usable, save it as a CSV file to 'out_data_file'.
203
+ if is_usable:
204
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
205
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Underweight/code/GSE84954.py ADDED
@@ -0,0 +1,305 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Underweight"
6
+ cohort = "GSE84954"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Underweight"
10
+ in_cohort_dir = "../DATA/GEO/Underweight/GSE84954"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z6/preprocess/Underweight/GSE84954.csv"
14
+ out_gene_data_file = "./output/z6/preprocess/Underweight/gene_data/GSE84954.csv"
15
+ out_clinical_data_file = "./output/z6/preprocess/Underweight/clinical_data/GSE84954.csv"
16
+ json_path = "./output/z6/preprocess/Underweight/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ import os
40
+ import re
41
+
42
+ # 1. Gene Expression Data Availability
43
+ is_gene_available = True # Microarray gene expression data from tissues (not miRNA/methylation)
44
+
45
+ # 2. Variable Availability and Data Type Conversion
46
+
47
+ # Heuristic: Use 'disease' to infer Underweight/cachexia status.
48
+ # Rationale: The study compares end-stage liver disease (cachexia context) vs. Crigler-Najjar controls.
49
+ # Map end-stage liver disease subtypes/Alagille to 1 (underweight/cachexia context) and Crigler-Najjar to 0 (controls).
50
+ trait_row = 1 # 'disease' field
51
+ age_row = None
52
+ gender_row = None
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) == 2 else x.strip()
60
+ return val if val != "" else None
61
+ return x
62
+
63
+ def convert_trait(x):
64
+ # Binary: 1 = underweight/cachexia context (chronic liver disease subtypes, Alagille)
65
+ # 0 = control (Crigler-Najjar)
66
+ val = _extract_value(x)
67
+ if val is None:
68
+ return None
69
+ v = val.lower()
70
+ if "crigler" in v: # controls
71
+ return 0
72
+ positive_signals = [
73
+ "chronic liver disease", "alagille", "biliary atresia", "ba",
74
+ "biliary cirrhosis", "bc", "neonatal sclerosing cholangitis", "nsc",
75
+ "alpha-1-antitrypsin", "a1at", "a1-at", "a1 at"
76
+ ]
77
+ if any(sig in v for sig in positive_signals):
78
+ return 1
79
+ return None
80
+
81
+ def convert_age(x):
82
+ # Continuous age in years if possible
83
+ val = _extract_value(x)
84
+ if val is None:
85
+ return None
86
+ v = val.lower()
87
+ try:
88
+ return float(v)
89
+ except:
90
+ pass
91
+ m = re.search(r'([0-9]*\.?[0-9]+)\s*(year|yr|y|month|mo|m(?!ale)|day|d)s?', v)
92
+ if m:
93
+ num = float(m.group(1))
94
+ unit = m.group(2)
95
+ if unit in ["year", "yr", "y"]:
96
+ return num
97
+ if unit in ["month", "mo", "m"]:
98
+ return num / 12.0
99
+ if unit in ["day", "d"]:
100
+ return num / 365.0
101
+ return None
102
+
103
+ def convert_gender(x):
104
+ # Binary: female=0, male=1
105
+ val = _extract_value(x)
106
+ if val is None:
107
+ return None
108
+ v = val.strip().lower()
109
+ if v in ["female", "f", "girl", "woman", "women"]:
110
+ return 0
111
+ if v in ["male", "m", "boy", "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
126
+ if trait_row is not None:
127
+ # Ensure clinical_data exists (expected from previous step)
128
+ if "clinical_data" not in globals() or clinical_data is None:
129
+ raise RuntimeError("clinical_data not found; please ensure it is loaded from the previous step before running feature extraction.")
130
+
131
+ selected_clinical_df = geo_select_clinical_features(
132
+ clinical_df=clinical_data,
133
+ trait=trait,
134
+ trait_row=trait_row,
135
+ convert_trait=convert_trait,
136
+ age_row=age_row,
137
+ convert_age=convert_age,
138
+ gender_row=gender_row,
139
+ convert_gender=convert_gender
140
+ )
141
+ preview = preview_df(selected_clinical_df)
142
+ print(preview)
143
+
144
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
145
+ selected_clinical_df.to_csv(out_clinical_data_file)
146
+
147
+ # Step 3: Gene Data Extraction
148
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
149
+ gene_data = get_genetic_data(matrix_file)
150
+
151
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
152
+ print(gene_data.index[:20])
153
+
154
+ # Step 4: Gene Identifier Review
155
+ # The provided identifiers are numeric probe IDs, not human gene symbols.
156
+ print("requires_gene_mapping = True")
157
+
158
+ # Step 5: Gene Annotation
159
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
160
+ gene_annotation = get_gene_annotation(soft_file)
161
+
162
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
163
+ print("Gene annotation preview:")
164
+ print(preview_df(gene_annotation))
165
+
166
+ # Step 6: Gene Identifier Mapping
167
+ import os
168
+ import re
169
+ import json
170
+ import pandas as pd
171
+
172
+ # Preserve the original probe-level matrix for mapping
173
+ probe_level_data = gene_data.copy()
174
+
175
+ # 1) Identify probe ID column and try to find a usable gene symbol column
176
+ probe_col = 'ID' # matches both annotation and probe-level data
177
+
178
+ def pick_gene_symbol_column(df, min_symbol_frac: float = 0.05):
179
+ priority_names = [
180
+ 'Gene Symbol', 'GENE_SYMBOL', 'Gene symbol', 'SYMBOL', 'Symbol',
181
+ 'Gene Symbols', 'GENE_SYMBOLS', 'gene_symbol', 'gene symbols',
182
+ 'Gene name', 'GENE_NAME', 'gene_name', 'gene assignment', 'GENE_ASSIGNMENT'
183
+ ]
184
+ cols = [c for c in df.columns if c != probe_col]
185
+ prioritized = [c for c in cols if any(pn.lower() == str(c).lower() for pn in priority_names)]
186
+ if not prioritized:
187
+ prioritized = [c for c in cols if re.search(r'symbol|gene|assign', str(c), re.I)]
188
+ candidates = prioritized if prioritized else cols
189
+
190
+ scores = {}
191
+ best_col = None
192
+ best_score = -1.0
193
+ for c in candidates:
194
+ s = df[c].dropna().astype(str)
195
+ if s.empty:
196
+ scores[c] = 0.0
197
+ continue
198
+ sample = s.head(10000)
199
+ hits = sample.map(lambda x: 1 if len(extract_human_gene_symbols(x)) > 0 else 0)
200
+ score = float(hits.mean())
201
+ scores[c] = score
202
+ if score > best_score:
203
+ best_score = score
204
+ best_col = c
205
+
206
+ print("Candidate gene symbol columns and scores (fraction with >=1 symbol):")
207
+ for cname, sc in sorted(scores.items(), key=lambda x: -x[1]):
208
+ print(f" {cname}: {sc:.3f}")
209
+
210
+ if best_col is None or best_score < min_symbol_frac:
211
+ return None, 0.0
212
+ return best_col, best_score
213
+
214
+ gene_symbol_col, score = pick_gene_symbol_column(gene_annotation)
215
+ if gene_symbol_col:
216
+ print(f"Selected gene symbol column: {gene_symbol_col} (score={score:.3f})")
217
+ else:
218
+ print("No direct gene symbol column found in the platform annotation. Attempting fallbacks...")
219
+
220
+ mapping_df = pd.DataFrame(columns=['ID', 'Gene'])
221
+
222
+ # 2) Primary mapping if a gene symbol column is available
223
+ if gene_symbol_col:
224
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=probe_col, gene_col=gene_symbol_col)
225
+
226
+ # 2b) Fallback: try RefSeq accession (GB_ACC) -> symbol via metadata mapping file if available
227
+ if mapping_df.empty:
228
+ if 'GB_ACC' in gene_annotation.columns:
229
+ refseq_series = gene_annotation[['ID', 'GB_ACC']].dropna()
230
+ refseq_series['GB_ACC'] = refseq_series['GB_ACC'].astype(str)
231
+ refseq_map_path = "./metadata/refseq_to_gene_symbol.json"
232
+ symbol_from_refseq = None
233
+ if os.path.exists(refseq_map_path):
234
+ try:
235
+ with open(refseq_map_path, "r") as f:
236
+ symbol_from_refseq = json.load(f)
237
+ except Exception as e:
238
+ print(f"WARNING: Failed to load RefSeq->Symbol mapping file: {e}")
239
+ if symbol_from_refseq:
240
+ refseq_series['Gene'] = refseq_series['GB_ACC'].map(symbol_from_refseq)
241
+ mapping_df = refseq_series[['ID', 'Gene']].dropna()
242
+ # Keep only plausible human gene symbols
243
+ mapping_df['Gene'] = mapping_df['Gene'].astype(str)
244
+ mapping_df = mapping_df[mapping_df['Gene'].map(lambda x: len(extract_human_gene_symbols(x)) > 0)]
245
+ else:
246
+ print("INFO: No RefSeq->Symbol mapping file found. Skipping RefSeq-based mapping fallback.")
247
+
248
+ # 2c) If still empty, fail gracefully: record unavailability and stop mapping
249
+ if mapping_df.empty:
250
+ print("ERROR: Could not derive probe->gene mapping for this platform (likely a tiling array without gene symbols).")
251
+ # Ensure we have clinical data to record metadata
252
+ try:
253
+ clinical_df_for_meta = selected_clinical_df.T if 'selected_clinical_df' in globals() else None
254
+ if clinical_df_for_meta is None or clinical_df_for_meta.empty:
255
+ if os.path.exists(out_clinical_data_file):
256
+ clinical_df_for_meta = pd.read_csv(out_clinical_data_file, index_col=0).T
257
+ except Exception:
258
+ clinical_df_for_meta = None
259
+
260
+ note = ("ERROR: Platform annotation lacks usable gene symbols; IDs appear to be genomic tiling probes. "
261
+ "Probe-to-gene mapping not feasible.")
262
+ _ = validate_and_save_cohort_info(
263
+ is_final=True,
264
+ cohort=cohort,
265
+ info_path=json_path,
266
+ is_gene_available=False,
267
+ is_trait_available=True,
268
+ is_biased=False,
269
+ df=(clinical_df_for_meta if clinical_df_for_meta is not None else pd.DataFrame({"Underweight": []})),
270
+ note=note
271
+ )
272
+ else:
273
+ # 3) Apply mapping to convert probe-level data to gene-level expression
274
+ print("Mapping preview (first 5 rows):")
275
+ print(mapping_df.head())
276
+ gene_data = apply_gene_mapping(expression_df=probe_level_data, mapping_df=mapping_df)
277
+
278
+ if gene_data.empty or gene_data.shape[1] == 0:
279
+ print("ERROR: Resulting gene-level expression is empty after applying mapping.")
280
+ # Record metadata as above
281
+ try:
282
+ clinical_df_for_meta = selected_clinical_df.T if 'selected_clinical_df' in globals() else None
283
+ if clinical_df_for_meta is None or clinical_df_for_meta.empty:
284
+ if os.path.exists(out_clinical_data_file):
285
+ clinical_df_for_meta = pd.read_csv(out_clinical_data_file, index_col=0).T
286
+ except Exception:
287
+ clinical_df_for_meta = None
288
+
289
+ note = ("ERROR: Mapping produced empty gene-level data. "
290
+ "This likely reflects lack of valid gene identifiers in platform annotation.")
291
+ _ = validate_and_save_cohort_info(
292
+ is_final=True,
293
+ cohort=cohort,
294
+ info_path=json_path,
295
+ is_gene_available=False,
296
+ is_trait_available=True,
297
+ is_biased=False,
298
+ df=(clinical_df_for_meta if clinical_df_for_meta is not None else pd.DataFrame({"Underweight": []})),
299
+ note=note
300
+ )
301
+ else:
302
+ print(f"Gene-level data shape: {gene_data.shape}")
303
+ # Optionally save gene-level data for downstream steps
304
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
305
+ gene_data.to_csv(out_gene_data_file)
output/preprocess/Underweight/code/TCGA.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Underweight"
6
+
7
+ # Input paths
8
+ tcga_root_dir = "../DATA/TCGA"
9
+
10
+ # Output paths
11
+ out_data_file = "./output/z6/preprocess/Underweight/TCGA.csv"
12
+ out_gene_data_file = "./output/z6/preprocess/Underweight/gene_data/TCGA.csv"
13
+ out_clinical_data_file = "./output/z6/preprocess/Underweight/clinical_data/TCGA.csv"
14
+ json_path = "./output/z6/preprocess/Underweight/cohort_info.json"
output/preprocess/Underweight/cohort_info.json CHANGED
@@ -1,62 +1 @@
1
- {
2
- "GSE84954": {
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": 37
11
- },
12
- "GSE57802": {
13
- "is_usable": true,
14
- "is_gene_available": true,
15
- "is_trait_available": true,
16
- "is_available": true,
17
- "is_biased": false,
18
- "has_age": true,
19
- "has_gender": true,
20
- "sample_size": 99
21
- },
22
- "GSE50982": {
23
- "is_usable": false,
24
- "is_gene_available": false,
25
- "is_trait_available": false,
26
- "is_available": false,
27
- "is_biased": null,
28
- "has_age": null,
29
- "has_gender": null,
30
- "sample_size": null
31
- },
32
- "GSE131835": {
33
- "is_usable": true,
34
- "is_gene_available": true,
35
- "is_trait_available": true,
36
- "is_available": true,
37
- "is_biased": false,
38
- "has_age": true,
39
- "has_gender": true,
40
- "sample_size": 48
41
- },
42
- "GSE130563": {
43
- "is_usable": true,
44
- "is_gene_available": true,
45
- "is_trait_available": true,
46
- "is_available": true,
47
- "is_biased": false,
48
- "has_age": true,
49
- "has_gender": true,
50
- "sample_size": 38
51
- },
52
- "TCGA": {
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": 183
61
- }
62
- }
 
1
+ {"GSE84954": {"is_usable": false, "is_gene_available": false, "is_trait_available": true, "is_available": false, "is_biased": null, "has_age": null, "has_gender": null, "sample_size": null, "note": "ERROR: Platform annotation lacks usable gene symbols; IDs appear to be genomic tiling probes. Probe-to-gene mapping not feasible."}, "GSE57802": {"is_usable": true, "is_gene_available": true, "is_trait_available": true, "is_available": true, "is_biased": false, "has_age": true, "has_gender": true, "sample_size": 99, "note": "INFO: Probe-to-gene mapping applied; trait inferred from 16p11.2 duplication vs others."}, "GSE50982": {"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}, "GSE131835": {"is_usable": false, "is_gene_available": true, "is_trait_available": false, "is_available": false, "is_biased": null, "has_age": null, "has_gender": null, "sample_size": null, "note": "INFO: Trait not available; cannot link clinical and genetic data."}, "GSE130563": {"is_usable": false, "is_gene_available": true, "is_trait_available": false, "is_available": false, "is_biased": null, "has_age": null, "has_gender": null, "sample_size": null, "note": null}}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
output/preprocess/Uterine_Carcinosarcoma/GSE32507.csv CHANGED
The diff for this file is too large to render. See raw diff
 
output/preprocess/Uterine_Carcinosarcoma/clinical_data/GSE32507.csv CHANGED
@@ -1,2 +1,2 @@
1
- ,0
2
- Uterine_Carcinosarcoma,1.0
 
1
+ ,GSM804806,GSM804807,GSM804808,GSM804809,GSM804810,GSM804811,GSM804812,GSM804813,GSM804814,GSM804815,GSM804816,GSM804817,GSM804818,GSM804819,GSM804820,GSM804821,GSM804822,GSM804823,GSM804824,GSM804825,GSM804826,GSM804827,GSM804828,GSM804829,GSM804830,GSM804831,GSM804832,GSM804833,GSM804834,GSM804835,GSM804836,GSM804837,GSM804838,GSM804839,GSM804840,GSM804841,GSM804842,GSM804843,GSM804844,GSM804845,GSM804846,GSM804847,GSM804848,GSM804849,GSM804850,GSM804851
2
+ Uterine_Carcinosarcoma,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,1.0,1.0,0.0,0.0,1.0,1.0,1.0,1.0,0.0,0.0,1.0,0.0,0.0,0.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0
output/preprocess/Uterine_Carcinosarcoma/code/GSE32507.py ADDED
@@ -0,0 +1,193 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Uterine_Carcinosarcoma"
6
+ cohort = "GSE32507"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Uterine_Carcinosarcoma"
10
+ in_cohort_dir = "../DATA/GEO/Uterine_Carcinosarcoma/GSE32507"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z6/preprocess/Uterine_Carcinosarcoma/GSE32507.csv"
14
+ out_gene_data_file = "./output/z6/preprocess/Uterine_Carcinosarcoma/gene_data/GSE32507.csv"
15
+ out_clinical_data_file = "./output/z6/preprocess/Uterine_Carcinosarcoma/clinical_data/GSE32507.csv"
16
+ json_path = "./output/z6/preprocess/Uterine_Carcinosarcoma/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ import os
40
+ import pandas as pd
41
+
42
+ # 1) Gene expression availability (cDNA microarray => gene expression is available)
43
+ is_gene_available = True
44
+
45
+ # 2) Variable availability
46
+ # Trait (Uterine_Carcinosarcoma): can be inferred from "tissue" field
47
+ trait_row = 0
48
+
49
+ # Age and Gender are not available in the provided characteristics
50
+ age_row = None
51
+ gender_row = None
52
+
53
+ # 2.2) Converters
54
+ def _extract_value(cell):
55
+ if pd.isna(cell):
56
+ return None
57
+ s = str(cell)
58
+ # Take the substring after the last colon, which is usually the value
59
+ if ':' in s:
60
+ s = s.split(':')[-1]
61
+ return s.strip()
62
+
63
+ def convert_trait(cell):
64
+ val = _extract_value(cell)
65
+ if val is None:
66
+ return None
67
+ low = val.lower()
68
+ # Prioritize carcinosarcoma mapping to avoid substring issues with 'sarcoma'
69
+ if ('carcinosarcoma' in low) or ('malignant mixed müllerian' in low) or ('malignant mixed mullerian' in low) or (low == 'cs'):
70
+ return 1
71
+ # Non-CS uterine tumors in this study act as controls
72
+ if ('endometrioid' in low) or ('adenocarcinoma' in low) or ('sarcoma' in low) or (low in {'ec','us'}):
73
+ return 0
74
+ return None
75
+
76
+ def convert_age(cell):
77
+ # Not used (age_row is None), but provided for completeness
78
+ val = _extract_value(cell)
79
+ if val is None:
80
+ return None
81
+ # Extract first numeric token (e.g., "65 years" -> 65)
82
+ import re
83
+ m = re.search(r'(\d+(\.\d+)?)', val)
84
+ if m:
85
+ try:
86
+ return float(m.group(1))
87
+ except Exception:
88
+ return None
89
+ return None
90
+
91
+ def convert_gender(cell):
92
+ # Not used (gender_row is None), but provided for completeness
93
+ val = _extract_value(cell)
94
+ if val is None:
95
+ return None
96
+ low = val.lower()
97
+ if 'female' in low or low in {'f'}:
98
+ return 0
99
+ if 'male' in low or low in {'m'}:
100
+ return 1
101
+ return None
102
+
103
+ # 3) Save metadata (initial filtering)
104
+ is_trait_available = trait_row is not None
105
+ _ = validate_and_save_cohort_info(
106
+ is_final=False,
107
+ cohort=cohort,
108
+ info_path=json_path,
109
+ is_gene_available=is_gene_available,
110
+ is_trait_available=is_trait_available
111
+ )
112
+
113
+ # 4) Clinical feature extraction (only if trait_row is 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=age_row,
121
+ convert_age=None,
122
+ gender_row=gender_row,
123
+ convert_gender=None
124
+ )
125
+ preview = preview_df(selected_clinical_df)
126
+ print("Preview of selected clinical features:", preview)
127
+
128
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
129
+ selected_clinical_df.to_csv(out_clinical_data_file)
130
+
131
+ # Step 3: Gene Data Extraction
132
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
133
+ gene_data = get_genetic_data(matrix_file)
134
+
135
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
136
+ print(gene_data.index[:20])
137
+
138
+ # Step 4: Gene Identifier Review
139
+ print("requires_gene_mapping = True")
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 the columns for probe IDs and gene symbols based on annotation preview
151
+ probe_id_col = 'ID'
152
+ gene_symbol_col = 'GENE_SYMBOL'
153
+
154
+ # 2) Build the mapping dataframe
155
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=probe_id_col, gene_col=gene_symbol_col)
156
+
157
+ # 3) Apply mapping to convert probe-level data to gene-level expression
158
+ gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
159
+
160
+ # Step 7: Data Normalization and Linking
161
+ import os
162
+
163
+ # 1. Normalize gene symbols and save gene-level data
164
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
165
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
166
+ normalized_gene_data.to_csv(out_gene_data_file)
167
+
168
+ # 2. Link clinical and genetic data
169
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
170
+
171
+ # 3. Handle missing values
172
+ linked_data = handle_missing_values(linked_data, trait)
173
+
174
+ # 4. Bias assessment and removal of biased covariates
175
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
176
+
177
+ # 5. Final validation and metadata saving
178
+ note_msg = "INFO: Only trait available; no age or gender annotations. Gene symbols normalized via NCBI synonym mapping."
179
+ is_usable = validate_and_save_cohort_info(
180
+ is_final=True,
181
+ cohort=cohort,
182
+ info_path=json_path,
183
+ is_gene_available=True,
184
+ is_trait_available=True,
185
+ is_biased=is_trait_biased,
186
+ df=unbiased_linked_data,
187
+ note=note_msg
188
+ )
189
+
190
+ # 6. Save linked dataset 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/Uterine_Carcinosarcoma/code/GSE36133.py ADDED
@@ -0,0 +1,134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Uterine_Carcinosarcoma"
6
+ cohort = "GSE36133"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Uterine_Carcinosarcoma"
10
+ in_cohort_dir = "../DATA/GEO/Uterine_Carcinosarcoma/GSE36133"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z6/preprocess/Uterine_Carcinosarcoma/GSE36133.csv"
14
+ out_gene_data_file = "./output/z6/preprocess/Uterine_Carcinosarcoma/gene_data/GSE36133.csv"
15
+ out_clinical_data_file = "./output/z6/preprocess/Uterine_Carcinosarcoma/clinical_data/GSE36133.csv"
16
+ json_path = "./output/z6/preprocess/Uterine_Carcinosarcoma/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ # Step 1: Determine gene expression data availability
40
+ is_gene_available = True # CCLE series contains gene expression data (not pure miRNA/methylation)
41
+
42
+ # Step 2: Variable availability and converters
43
+
44
+ # Based on the provided sample characteristics dictionary, there is no explicit field for uterine carcinosarcoma.
45
+ # Available keys:
46
+ # 0 -> primary site (e.g., 'primary site: endometrium', etc.)
47
+ # 1 -> histology (e.g., 'histology: carcinoma', 'histology: sarcoma', etc.)
48
+ # 2 -> histology subtype1 (does not include carcinosarcoma)
49
+ # Therefore, trait (Uterine Carcinosarcoma) cannot be reliably inferred from any single key. Age and gender are absent.
50
+ trait_row = None
51
+ age_row = None
52
+ gender_row = None
53
+
54
+ def _get_value_after_colon(x):
55
+ if x is None:
56
+ return None
57
+ s = str(x)
58
+ if ':' in s:
59
+ s = s.split(':', 1)[1]
60
+ return s.strip().strip('"').strip()
61
+
62
+ def convert_trait(x):
63
+ # Not used since trait_row is None, but implemented for completeness:
64
+ # Map to 1 if value clearly indicates carcinosarcoma/MMMT, else 0; unknown -> None.
65
+ val = _get_value_after_colon(x)
66
+ if val is None or val == '' or val.lower() in {'na', 'n/a', 'null', 'none', 'unknown'}:
67
+ return None
68
+ v = val.lower().replace(' ', '_')
69
+ keywords = ['carcinosarcoma', 'malignant_mixed_mullerian', 'mmmt', 'malignant_mixed_müllerian']
70
+ if any(k in v for k in keywords):
71
+ return 1
72
+ # If we are confident it's not carcinosarcoma
73
+ return 0
74
+
75
+ def convert_age(x):
76
+ # Continuous age if present; return float or None
77
+ val = _get_value_after_colon(x)
78
+ if val is None:
79
+ return None
80
+ v = val.lower().replace('years', '').replace('year', '').strip()
81
+ if v in {'na', 'n/a', 'null', 'none', 'unknown', ''}:
82
+ return None
83
+ try:
84
+ return float(v)
85
+ except Exception:
86
+ # try to extract number
87
+ import re
88
+ m = re.search(r'[-+]?\d*\.?\d+', v)
89
+ if m:
90
+ try:
91
+ return float(m.group(0))
92
+ except Exception:
93
+ return None
94
+ return None
95
+
96
+ def convert_gender(x):
97
+ # Binary: female -> 0, male -> 1; unknown -> None
98
+ val = _get_value_after_colon(x)
99
+ if val is None:
100
+ return None
101
+ v = val.strip().lower()
102
+ if v in {'female', 'f', 'woman', 'women'}:
103
+ return 0
104
+ if v in {'male', 'm', 'man', 'men'}:
105
+ return 1
106
+ if v in {'na', 'n/a', 'null', 'none', 'unknown', ''}:
107
+ return None
108
+ return None
109
+
110
+ # Step 3: Save metadata (initial filtering)
111
+ is_trait_available = trait_row is not None
112
+ _ = validate_and_save_cohort_info(
113
+ is_final=False,
114
+ cohort=cohort,
115
+ info_path=json_path,
116
+ is_gene_available=is_gene_available,
117
+ is_trait_available=is_trait_available
118
+ )
119
+
120
+ # Step 4: Clinical Feature Extraction (skip because trait_row is None)
121
+ if trait_row is not None:
122
+ selected_clinical_df = geo_select_clinical_features(
123
+ clinical_df=clinical_data,
124
+ trait=trait,
125
+ trait_row=trait_row,
126
+ convert_trait=convert_trait,
127
+ age_row=age_row,
128
+ convert_age=convert_age,
129
+ gender_row=gender_row,
130
+ convert_gender=convert_gender
131
+ )
132
+ preview = preview_df(selected_clinical_df, n=5)
133
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
134
+ selected_clinical_df.to_csv(out_clinical_data_file, index=True)
output/preprocess/Uterine_Carcinosarcoma/code/GSE36138.py ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Uterine_Carcinosarcoma"
6
+ cohort = "GSE36138"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Uterine_Carcinosarcoma"
10
+ in_cohort_dir = "../DATA/GEO/Uterine_Carcinosarcoma/GSE36138"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z6/preprocess/Uterine_Carcinosarcoma/GSE36138.csv"
14
+ out_gene_data_file = "./output/z6/preprocess/Uterine_Carcinosarcoma/gene_data/GSE36138.csv"
15
+ out_clinical_data_file = "./output/z6/preprocess/Uterine_Carcinosarcoma/clinical_data/GSE36138.csv"
16
+ json_path = "./output/z6/preprocess/Uterine_Carcinosarcoma/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ # Step 1: Determine gene expression availability based on background info (SNP array -> not gene expression)
40
+ is_gene_available = False
41
+
42
+ # Step 2: Variable availability and conversion functions
43
+ # Based on the sample characteristics, there is no explicit or inferable uterine carcinosarcoma label, nor age/gender for human subjects in CCLE cell lines.
44
+ trait_row = None
45
+ age_row = None
46
+ gender_row = None
47
+
48
+ def _after_colon(x):
49
+ if x is None:
50
+ return None
51
+ s = str(x)
52
+ parts = s.split(":", 1)
53
+ val = parts[1] if len(parts) > 1 else parts[0]
54
+ val = val.strip().strip('"').strip()
55
+ return val if val != "" else None
56
+
57
+ def convert_trait(x):
58
+ v = _after_colon(x)
59
+ if v is None:
60
+ return None
61
+ v_low = v.lower()
62
+ # Positive mappings
63
+ positive_terms = [
64
+ "carcinosarcoma",
65
+ "mmmt",
66
+ "malignant mixed mullerian tumor",
67
+ "malignant mixed müllerian tumor",
68
+ "uterine carcinosarcoma"
69
+ ]
70
+ if any(t in v_low for t in positive_terms):
71
+ return 1
72
+ # Otherwise treat as non-trait if clearly a different histology/site label
73
+ return 0
74
+
75
+ def convert_age(x):
76
+ v = _after_colon(x)
77
+ if v is None:
78
+ return None
79
+ v = v.replace("years", "").replace("year", "").replace("yrs", "").replace("yr", "").strip()
80
+ try:
81
+ return float(v)
82
+ except Exception:
83
+ return None
84
+
85
+ def convert_gender(x):
86
+ v = _after_colon(x)
87
+ if v is None:
88
+ return None
89
+ v_low = v.lower()
90
+ if v_low in ["female", "f", "0", "woman", "women"]:
91
+ return 0
92
+ if v_low in ["male", "m", "1", "man", "men"]:
93
+ return 1
94
+ return None
95
+
96
+ # Step 3: Initial filtering and save metadata
97
+ is_trait_available = trait_row is not None
98
+ _ = validate_and_save_cohort_info(
99
+ is_final=False,
100
+ cohort=cohort,
101
+ info_path=json_path,
102
+ is_gene_available=is_gene_available,
103
+ is_trait_available=is_trait_available
104
+ )
105
+
106
+ # Step 4: Clinical feature extraction (skip because trait_row is None)
107
+ if trait_row is not None:
108
+ selected_clinical_df = geo_select_clinical_features(
109
+ clinical_df=clinical_data,
110
+ trait=trait,
111
+ trait_row=trait_row,
112
+ convert_trait=convert_trait,
113
+ age_row=age_row,
114
+ convert_age=convert_age,
115
+ gender_row=gender_row,
116
+ convert_gender=convert_gender
117
+ )
118
+ _ = preview_df(selected_clinical_df)
119
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
120
+ selected_clinical_df.to_csv(out_clinical_data_file)
output/preprocess/Uterine_Carcinosarcoma/code/GSE68950.py ADDED
@@ -0,0 +1,222 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Uterine_Carcinosarcoma"
6
+ cohort = "GSE68950"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Uterine_Carcinosarcoma"
10
+ in_cohort_dir = "../DATA/GEO/Uterine_Carcinosarcoma/GSE68950"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z6/preprocess/Uterine_Carcinosarcoma/GSE68950.csv"
14
+ out_gene_data_file = "./output/z6/preprocess/Uterine_Carcinosarcoma/gene_data/GSE68950.csv"
15
+ out_clinical_data_file = "./output/z6/preprocess/Uterine_Carcinosarcoma/clinical_data/GSE68950.csv"
16
+ json_path = "./output/z6/preprocess/Uterine_Carcinosarcoma/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ import os
40
+ import pandas as pd
41
+
42
+ # 1) Gene expression availability
43
+ is_gene_available = True # Assay Type indicates Gene Expression (Affymetrix HT_HG-U133A)
44
+
45
+ # 2) Variable availability setup
46
+ candidate_trait_row = 1 # 'disease state' is the closest field for trait mapping
47
+ age_row = None # Not available in the provided characteristics
48
+ gender_row = None # Not available in the provided characteristics
49
+
50
+ # Converters
51
+ def _extract_value(x):
52
+ if x is None or (isinstance(x, float) and pd.isna(x)):
53
+ return None
54
+ s = str(x)
55
+ if ':' in s:
56
+ s = s.split(':', 1)[1]
57
+ return s.strip()
58
+
59
+ def convert_trait(x):
60
+ v = _extract_value(x)
61
+ if v is None:
62
+ return None
63
+ s = v.lower()
64
+ # Map carcinosarcoma cases to 1; others to 0
65
+ if 'carcinosarcoma' in s:
66
+ return 1
67
+ return 0
68
+
69
+ def convert_age(x):
70
+ return None # Not available
71
+
72
+ def convert_gender(x):
73
+ return None # Not available
74
+
75
+ # 2.1/2.2) Determine actual trait availability; enforce constant-feature check
76
+ trait_row = None
77
+ if candidate_trait_row in clinical_data.index:
78
+ raw_vals = clinical_data.loc[candidate_trait_row]
79
+ converted_vals = pd.Series([convert_trait(v) for v in raw_vals])
80
+ unique_non_missing = converted_vals.dropna().nunique()
81
+ # Require at least two classes (e.g., both 0 and 1) for availability
82
+ if unique_non_missing >= 2:
83
+ trait_row = candidate_trait_row
84
+
85
+ # 3) Initial filtering metadata saving
86
+ is_trait_available = trait_row is not None
87
+ _ = validate_and_save_cohort_info(
88
+ is_final=False,
89
+ cohort=cohort,
90
+ info_path=json_path,
91
+ is_gene_available=is_gene_available,
92
+ is_trait_available=is_trait_available
93
+ )
94
+
95
+ # 4) Clinical feature extraction: only proceed if trait is available
96
+ if is_trait_available:
97
+ selected_clinical_df = geo_select_clinical_features(
98
+ clinical_df=clinical_data,
99
+ trait=trait,
100
+ trait_row=trait_row,
101
+ convert_trait=convert_trait,
102
+ age_row=age_row,
103
+ convert_age=convert_age,
104
+ gender_row=gender_row,
105
+ convert_gender=convert_gender
106
+ )
107
+ clinical_preview = preview_df(selected_clinical_df)
108
+ print("Clinical data preview:", clinical_preview)
109
+
110
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
111
+ selected_clinical_df.to_csv(out_clinical_data_file)
112
+
113
+ # Step 3: Gene Data Extraction
114
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
115
+ gene_data = get_genetic_data(matrix_file)
116
+
117
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
118
+ print(gene_data.index[:20])
119
+
120
+ # Step 4: Gene Identifier Review
121
+ requires_gene_mapping = True
122
+ print(f"requires_gene_mapping = {requires_gene_mapping}")
123
+
124
+ # Step 5: Gene Annotation
125
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
126
+ gene_annotation = get_gene_annotation(soft_file)
127
+
128
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
129
+ print("Gene annotation preview:")
130
+ print(preview_df(gene_annotation))
131
+
132
+ # Step 6: Gene Identifier Mapping
133
+ # Identify annotation columns for probe IDs and gene symbols based on the preview
134
+ probe_col = 'ID'
135
+ gene_symbol_col = 'Gene Symbol'
136
+
137
+ # Build the mapping dataframe
138
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=probe_col, gene_col=gene_symbol_col)
139
+
140
+ # Apply mapping to convert probe-level data to gene-level expression
141
+ gene_data = apply_gene_mapping(gene_data, mapping_df)
142
+
143
+ # Step 7: Data Normalization and Linking
144
+ import os
145
+ import json
146
+ import pandas as pd
147
+
148
+ # 1. Normalize gene symbols and save gene expression data
149
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
150
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
151
+ normalized_gene_data.to_csv(out_gene_data_file)
152
+
153
+ # Ensure clinical features are available (reload if not in memory)
154
+ if 'selected_clinical_df' not in globals() or selected_clinical_df is None:
155
+ if os.path.exists(out_clinical_data_file):
156
+ selected_clinical_df = pd.read_csv(out_clinical_data_file, index_col=0)
157
+
158
+ # If clinical data isn't available, we cannot proceed with linking and final validation
159
+ if 'selected_clinical_df' in globals() and selected_clinical_df is not None:
160
+ # 2. Link clinical and genetic data
161
+ raw_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(raw_linked_data, trait)
165
+
166
+ # 4. Determine bias and remove biased demographic features
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 bools to avoid serialization issues
171
+ is_gene_available_flag = bool((normalized_gene_data.shape[0] > 0) and (normalized_gene_data.shape[1] > 0))
172
+ is_trait_available_flag = bool((trait in raw_linked_data.columns) and raw_linked_data[trait].notna().any())
173
+ is_trait_biased = bool(is_trait_biased)
174
+
175
+ note = ("INFO: Trait derived from 'disease state' in cancer cell lines; distribution is extremely imbalanced "
176
+ "for Uterine_Carcinosarcoma (only a very small number of positives), likely unusable for association.")
177
+
178
+ try:
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_flag,
184
+ is_trait_available=is_trait_available_flag,
185
+ is_biased=is_trait_biased,
186
+ df=unbiased_linked_data,
187
+ note=note
188
+ )
189
+ except TypeError:
190
+ # Fallback: write a sanitized record converting booleans to ints
191
+ is_available = bool(is_gene_available_flag and is_trait_available_flag)
192
+ is_usable_calc = bool(is_available and (is_trait_biased is False))
193
+ sanitized_record = {
194
+ "is_usable": int(is_usable_calc),
195
+ "is_gene_available": int(is_gene_available_flag),
196
+ "is_trait_available": int(is_trait_available_flag),
197
+ "is_available": int(is_available),
198
+ "is_biased": int(is_trait_biased) if is_available else None,
199
+ "has_age": int('Age' in unbiased_linked_data.columns) if is_available else None,
200
+ "has_gender": int('Gender' in unbiased_linked_data.columns) if is_available else None,
201
+ "sample_size": int(len(unbiased_linked_data)) if is_available else None,
202
+ "note": note
203
+ }
204
+
205
+ trait_directory = os.path.dirname(json_path)
206
+ os.makedirs(trait_directory, exist_ok=True)
207
+ if not os.path.exists(json_path):
208
+ with open(json_path, 'w') as f:
209
+ json.dump({}, f)
210
+ with open(json_path, 'r') as f:
211
+ records = json.load(f)
212
+ records[cohort] = sanitized_record
213
+ temp_path = json_path + ".tmp"
214
+ with open(temp_path, 'w') as f:
215
+ json.dump(records, f)
216
+ os.replace(temp_path, json_path)
217
+ is_usable = is_usable_calc
218
+
219
+ # 6. Save linked data if usable
220
+ if is_usable:
221
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
222
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Uterine_Carcinosarcoma/code/TCGA.py ADDED
@@ -0,0 +1,358 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Uterine_Carcinosarcoma"
6
+
7
+ # Input paths
8
+ tcga_root_dir = "../DATA/TCGA"
9
+
10
+ # Output paths
11
+ out_data_file = "./output/z6/preprocess/Uterine_Carcinosarcoma/TCGA.csv"
12
+ out_gene_data_file = "./output/z6/preprocess/Uterine_Carcinosarcoma/gene_data/TCGA.csv"
13
+ out_clinical_data_file = "./output/z6/preprocess/Uterine_Carcinosarcoma/clinical_data/TCGA.csv"
14
+ json_path = "./output/z6/preprocess/Uterine_Carcinosarcoma/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
22
+ all_entries = [d for d in os.listdir(tcga_root_dir) if os.path.isdir(os.path.join(tcga_root_dir, d))]
23
+ priority_matches = [d for d in all_entries if 'uterine_carcinosarcoma' in d.lower()]
24
+ if not priority_matches:
25
+ priority_matches = [d for d in all_entries if '(ucs)' in d.lower() or 'ucs' in d.lower()]
26
+
27
+ selected_dir = priority_matches[0] if priority_matches else None
28
+
29
+ if selected_dir is None:
30
+ # No suitable directory found -> mark as unavailable and skip
31
+ _ = validate_and_save_cohort_info(
32
+ is_final=False,
33
+ cohort="TCGA",
34
+ info_path=json_path,
35
+ is_gene_available=False,
36
+ is_trait_available=False
37
+ )
38
+ clinical_df = None
39
+ genetic_df = None
40
+ else:
41
+ cohort_dir = os.path.join(tcga_root_dir, selected_dir)
42
+ # 2) Identify file paths for clinical and genetic data
43
+ clinical_file_path, genetic_file_path = tcga_get_relevant_filepaths(cohort_dir)
44
+
45
+ # 3) Load both files
46
+ clinical_df = pd.read_csv(clinical_file_path, sep="\t", index_col=0, low_memory=False)
47
+ genetic_df = pd.read_csv(genetic_file_path, sep="\t", index_col=0, low_memory=False)
48
+
49
+ # 4) Print clinical column names
50
+ print(clinical_df.columns.tolist())
51
+
52
+ # Step 2: Find Candidate Demographic Features
53
+ import os
54
+ import re
55
+ import pandas as pd
56
+
57
+ def find_cohort_dir(root):
58
+ dirs = [os.path.join(root, d) for d in os.listdir(root) if os.path.isdir(os.path.join(root, d))]
59
+ prioritized = [d for d in dirs if any(k in os.path.basename(d).lower() for k in ['ucs', 'uterine', 'carcinosarcoma'])]
60
+ return prioritized[0] if prioritized else (dirs[0] if dirs else root)
61
+
62
+ def load_tcga_clinical_df(root_dir):
63
+ cohort_dir = find_cohort_dir(root_dir)
64
+ clinical_fp, _ = tcga_get_relevant_filepaths(cohort_dir)
65
+ try:
66
+ df = pd.read_csv(clinical_fp, sep="\t", index_col=0, dtype=str, low_memory=False)
67
+ except Exception:
68
+ df = pd.read_csv(clinical_fp, sep=",", index_col=0, dtype=str, low_memory=False)
69
+ return df
70
+
71
+ clinical_df = load_tcga_clinical_df(tcga_root_dir)
72
+ all_cols = list(clinical_df.columns)
73
+
74
+ # Improved heuristics to avoid false positives like "usage" and "stage"
75
+ age_token = re.compile(r'(^|[^a-z0-9])age([^a-z0-9]|$)')
76
+
77
+ candidate_age_cols = []
78
+ for c in all_cols:
79
+ cl = c.lower()
80
+ if cl == "days_to_birth":
81
+ candidate_age_cols.append(c)
82
+ elif age_token.search(cl):
83
+ candidate_age_cols.append(c)
84
+
85
+ candidate_gender_cols = [c for c in all_cols if c.lower() in {"gender", "sex"}]
86
+
87
+ def dedup(seq):
88
+ seen = set()
89
+ out = []
90
+ for x in seq:
91
+ if x not in seen:
92
+ seen.add(x)
93
+ out.append(x)
94
+ return out
95
+
96
+ candidate_age_cols = dedup(candidate_age_cols)
97
+ candidate_gender_cols = dedup(candidate_gender_cols)
98
+
99
+ print(f"candidate_age_cols = {candidate_age_cols}")
100
+ print(f"candidate_gender_cols = {candidate_gender_cols}")
101
+
102
+ if candidate_age_cols:
103
+ age_preview = preview_df(clinical_df[candidate_age_cols], n=5)
104
+ print(age_preview)
105
+
106
+ if candidate_gender_cols:
107
+ gender_preview = preview_df(clinical_df[candidate_gender_cols], n=5)
108
+ print(gender_preview)
109
+
110
+ # Step 3: Select Demographic Features
111
+ # Select the best age and gender columns from candidates using preview dictionaries only.
112
+ # If the preview dictionary is missing or empty, set the corresponding selection to None.
113
+
114
+ # Retrieve candidate lists
115
+ candidate_age_cols = locals().get("candidate_age_cols", []) or []
116
+ candidate_gender_cols = locals().get("candidate_gender_cols", []) or []
117
+
118
+ # Retrieve preview dictionaries (expect standardized names from previous step)
119
+ age_preview_dict = locals().get("age_values_dict", {}) or {}
120
+ gender_preview_dict = locals().get("gender_values_dict", {}) or {}
121
+
122
+ def _is_missing(x):
123
+ if x is None:
124
+ return True
125
+ s = str(x).strip()
126
+ return s == "" or s.lower() in {"na", "nan", "none", "null", "unknown", "not reported"}
127
+
128
+ def _safe_list(x):
129
+ return list(x) if isinstance(x, (list, tuple)) else []
130
+
131
+ def _age_value(x):
132
+ # Use library converter; returns an int if any digits are present
133
+ try:
134
+ v = tcga_convert_age(x)
135
+ return v if isinstance(v, int) else None
136
+ except Exception:
137
+ return None
138
+
139
+ def _age_plausible(x):
140
+ v = _age_value(x)
141
+ return v is not None and 0 <= v <= 120
142
+
143
+ def _gender_recognized(x):
144
+ try:
145
+ v = tcga_convert_gender(x)
146
+ return v in (0, 1)
147
+ except Exception:
148
+ return False
149
+
150
+ # Select age column using preview dict only
151
+ age_col = None
152
+ if isinstance(age_preview_dict, dict) and len(age_preview_dict) > 0 and candidate_age_cols:
153
+ best_score = None
154
+ best_col = None
155
+ for col in candidate_age_cols:
156
+ samples = _safe_list(age_preview_dict.get(col, []))
157
+ if not samples:
158
+ continue
159
+ n = len(samples)
160
+ missing = sum(_is_missing(v) for v in samples)
161
+ plausible = sum(_age_plausible(v) for v in samples)
162
+ # Require at least 3 plausible values and <=60% missing
163
+ if plausible >= 3 and (missing / max(n, 1)) <= 0.6:
164
+ name_bonus = 2 if col == "age_at_initial_pathologic_diagnosis" else (1 if "age" in col.lower() else 0)
165
+ score = (plausible * 2) - missing + name_bonus
166
+ if best_score is None or score > best_score:
167
+ best_score = score
168
+ best_col = col
169
+ age_col = best_col # May remain None if no suitable column
170
+
171
+ # Select gender column using preview dict only
172
+ gender_col = None
173
+ if isinstance(gender_preview_dict, dict) and len(gender_preview_dict) > 0 and candidate_gender_cols:
174
+ best_score = None
175
+ best_col = None
176
+ for col in candidate_gender_cols:
177
+ samples = _safe_list(gender_preview_dict.get(col, []))
178
+ if not samples:
179
+ continue
180
+ n = len(samples)
181
+ missing = sum(_is_missing(v) for v in samples)
182
+ recognized = sum(_gender_recognized(v) for v in samples)
183
+ # Require at least 3 recognizable values and <=60% missing
184
+ if recognized >= 3 and (missing / max(n, 1)) <= 0.6:
185
+ name_bonus = 2 if col.lower() == "gender" else (1 if "sex" in col.lower() else 0)
186
+ score = (recognized * 2) - missing + name_bonus
187
+ if best_score is None or score > best_score:
188
+ best_score = score
189
+ best_col = col
190
+ gender_col = best_col # May remain None if no suitable column
191
+
192
+ # Explicitly print chosen columns
193
+ print(f"Selected age_col: {age_col}")
194
+ print(f"Selected gender_col: {gender_col}")
195
+
196
+ # Step 4: Select Demographic Features
197
+ import math
198
+
199
+ # Initialize defaults
200
+ age_col = None
201
+ gender_col = None
202
+
203
+ def is_missing(val):
204
+ if val is None:
205
+ return True
206
+ if isinstance(val, float) and math.isnan(val):
207
+ return True
208
+ if isinstance(val, str) and val.strip() == "":
209
+ return True
210
+ return False
211
+
212
+ def iter_candidate_dicts(target='age'):
213
+ # Search globals for dicts that likely store candidate samples
214
+ # Preference: variable names containing the target keyword
215
+ for var_name, var_val in globals().items():
216
+ if not isinstance(var_val, dict):
217
+ continue
218
+ name_lower = var_name.lower()
219
+ if target in name_lower and any(k for k in var_val.keys()):
220
+ yield var_name, var_val
221
+ # Fallback: consider any dicts that look like {col_name: [samples...]}
222
+ for var_name, var_val in globals().items():
223
+ if not isinstance(var_val, dict):
224
+ continue
225
+ if any(isinstance(k, str) for k in var_val.keys()) and any(
226
+ isinstance(v, (list, tuple)) for v in var_val.values()
227
+ ):
228
+ yield var_name, var_val
229
+
230
+ def choose_best_column(candidate_dicts, converter, min_valid=3):
231
+ best_col = None
232
+ best_score = (-1, -1) # (valid_count, total_non_missing)
233
+ seen_cols = set()
234
+
235
+ for _, d in candidate_dicts:
236
+ for col, samples in d.items():
237
+ if col in seen_cols:
238
+ continue
239
+ seen_cols.add(col)
240
+ if not isinstance(samples, (list, tuple)) or len(samples) == 0:
241
+ continue
242
+
243
+ total = 0
244
+ valid = 0
245
+ for s in samples:
246
+ if is_missing(s):
247
+ continue
248
+ total += 1
249
+ conv = converter(s)
250
+ if conv is not None:
251
+ valid += 1
252
+
253
+ # Require minimum validity across the previewed items
254
+ if total == 0 or valid < min_valid:
255
+ continue
256
+
257
+ score = (valid, total)
258
+ if score > best_score:
259
+ best_score = score
260
+ best_col = col
261
+
262
+ return best_col
263
+
264
+ # Collect candidate dictionaries and pick columns
265
+ age_candidate_dicts = list(iter_candidate_dicts(target='age'))
266
+ gender_candidate_dicts = list(iter_candidate_dicts(target='gender'))
267
+
268
+ # Choose age column using tcga_convert_age
269
+ age_col_selected = choose_best_column(age_candidate_dicts, tcga_convert_age, min_valid=2)
270
+ # Choose gender column using tcga_convert_gender
271
+ gender_col_selected = choose_best_column(gender_candidate_dicts, tcga_convert_gender, min_valid=2)
272
+
273
+ # Assign to required variables, defaulting to None if not found
274
+ age_col = age_col_selected if age_col_selected else None
275
+ gender_col = gender_col_selected if gender_col_selected else None
276
+
277
+ # Explicitly print out chosen columns
278
+ print(f"Selected age_col: {age_col}")
279
+ print(f"Selected gender_col: {gender_col}")
280
+
281
+ # Step 5: Feature Engineering and Validation
282
+ import os
283
+ import pandas as pd
284
+
285
+ # 1) Extract and standardize clinical features
286
+ age_col = locals().get("age_col", None)
287
+ gender_col = locals().get("gender_col", None)
288
+
289
+ selected_clinical_df = tcga_select_clinical_features(
290
+ clinical_df=clinical_df,
291
+ trait=trait,
292
+ age_col=age_col,
293
+ gender_col=gender_col
294
+ )
295
+
296
+ # 2) Normalize gene symbols in the gene expression data
297
+ def _normalize_gene_axis(df: pd.DataFrame) -> pd.DataFrame:
298
+ # Try as-is (assume genes are rows)
299
+ try:
300
+ ng1 = normalize_gene_symbols_in_index(df.copy())
301
+ except Exception:
302
+ ng1 = pd.DataFrame()
303
+
304
+ # If very few genes recognized, try transposed (assume genes are columns)
305
+ if ng1.shape[0] < 100:
306
+ try:
307
+ ng2 = normalize_gene_symbols_in_index(df.T.copy())
308
+ except Exception:
309
+ ng2 = pd.DataFrame()
310
+ return ng2 if ng2.shape[0] > ng1.shape[0] else ng1
311
+ else:
312
+ return ng1
313
+
314
+ normalized_gene_df = _normalize_gene_axis(genetic_df)
315
+
316
+ # Save normalized gene data
317
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
318
+ normalized_gene_df.to_csv(out_gene_data_file)
319
+
320
+ # 3) Link clinical and genetic data on sample IDs
321
+ common_samples = selected_clinical_df.index.intersection(normalized_gene_df.columns)
322
+ linked_data = pd.concat(
323
+ [selected_clinical_df.loc[common_samples], normalized_gene_df.loc[:, common_samples].T],
324
+ axis=1
325
+ )
326
+
327
+ # 4) Handle missing values
328
+ processed_df = handle_missing_values(linked_data, trait_col=trait)
329
+
330
+ # 5) Determine bias and remove biased demographic features
331
+ is_biased, processed_df = judge_and_remove_biased_features(processed_df, trait=trait)
332
+ is_biased = bool(is_biased)
333
+
334
+ # 6) Final validation and save cohort info (ensure native Python bools for JSON)
335
+ is_gene_available = bool((normalized_gene_df.shape[0] > 0) and (normalized_gene_df.shape[1] > 0))
336
+ is_trait_available = bool((trait in linked_data.columns) and (int(linked_data[trait].notna().sum()) > 0))
337
+
338
+ note = (
339
+ f"INFO: Selected age column '{age_col}', gender column '{gender_col}'. "
340
+ f"Linked {len(common_samples)} of {len(selected_clinical_df)} clinical samples with gene expression. "
341
+ f"Gene symbols normalized using NCBI synonyms; retained {normalized_gene_df.shape[0]} genes."
342
+ )
343
+
344
+ is_usable = validate_and_save_cohort_info(
345
+ is_final=True,
346
+ cohort="TCGA",
347
+ info_path=json_path,
348
+ is_gene_available=is_gene_available,
349
+ is_trait_available=is_trait_available,
350
+ is_biased=is_biased,
351
+ df=processed_df,
352
+ note=note
353
+ )
354
+
355
+ # 7) Save linked data only if usable
356
+ if is_usable:
357
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
358
+ processed_df.to_csv(out_data_file)
output/preprocess/Uterine_Carcinosarcoma/cohort_info.json CHANGED
@@ -1,52 +1 @@
1
- {
2
- "GSE68950": {
3
- "is_usable": false,
4
- "is_gene_available": true,
5
- "is_trait_available": true,
6
- "is_available": true,
7
- "is_biased": true,
8
- "has_age": false,
9
- "has_gender": false,
10
- "sample_size": 798
11
- },
12
- "GSE36138": {
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
- "GSE36133": {
23
- "is_usable": false,
24
- "is_gene_available": false,
25
- "is_trait_available": false,
26
- "is_available": false,
27
- "is_biased": null,
28
- "has_age": null,
29
- "has_gender": null,
30
- "sample_size": null
31
- },
32
- "GSE32507": {
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": 46
41
- },
42
- "TCGA": {
43
- "is_usable": false,
44
- "is_gene_available": true,
45
- "is_trait_available": true,
46
- "is_available": true,
47
- "is_biased": true,
48
- "has_age": true,
49
- "has_gender": false,
50
- "sample_size": 57
51
- }
52
- }
 
1
+ {"GSE68950": {"is_usable": false, "is_gene_available": true, "is_trait_available": true, "is_available": true, "is_biased": true, "has_age": false, "has_gender": false, "sample_size": 798, "note": "INFO: Trait derived from 'disease state' in cancer cell lines; distribution is extremely imbalanced for Uterine_Carcinosarcoma (only a very small number of positives), likely unusable for association."}, "GSE36138": {"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}, "GSE36133": {"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}, "GSE32507": {"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": 46, "note": "INFO: Only trait available; no age or gender annotations. Gene symbols normalized via NCBI synonym mapping."}, "TCGA": {"is_usable": false, "is_gene_available": true, "is_trait_available": true, "is_available": true, "is_biased": true, "has_age": true, "has_gender": false, "sample_size": 57, "note": "INFO: Selected age column 'age_at_initial_pathologic_diagnosis', gender column 'gender'. Linked 57 of 57 clinical samples with gene expression. Gene symbols normalized using NCBI synonyms; retained 19848 genes."}}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
output/preprocess/Uterine_Corpus_Endometrial_Carcinoma/GSE32507.csv CHANGED
The diff for this file is too large to render. See raw diff
 
output/preprocess/Uterine_Corpus_Endometrial_Carcinoma/clinical_data/GSE32507.csv CHANGED
@@ -1,2 +1,2 @@
1
- Sample_ID,characteristics_ch1
2
- 0.0,0.0
 
1
+ ,GSM804806,GSM804807,GSM804808,GSM804809,GSM804810,GSM804811,GSM804812,GSM804813,GSM804814,GSM804815,GSM804816,GSM804817,GSM804818,GSM804819,GSM804820,GSM804821,GSM804822,GSM804823,GSM804824,GSM804825,GSM804826,GSM804827,GSM804828,GSM804829,GSM804830,GSM804831,GSM804832,GSM804833,GSM804834,GSM804835,GSM804836,GSM804837,GSM804838,GSM804839,GSM804840,GSM804841,GSM804842,GSM804843,GSM804844,GSM804845,GSM804846,GSM804847,GSM804848,GSM804849,GSM804850,GSM804851
2
+ Uterine_Corpus_Endometrial_Carcinoma,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,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,0.0,0.0,0.0,1.0,1.0,0.0,0.0,0.0,0.0
output/preprocess/Uterine_Corpus_Endometrial_Carcinoma/code/GSE32507.py ADDED
@@ -0,0 +1,211 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Uterine_Corpus_Endometrial_Carcinoma"
6
+ cohort = "GSE32507"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Uterine_Corpus_Endometrial_Carcinoma"
10
+ in_cohort_dir = "../DATA/GEO/Uterine_Corpus_Endometrial_Carcinoma/GSE32507"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z6/preprocess/Uterine_Corpus_Endometrial_Carcinoma/GSE32507.csv"
14
+ out_gene_data_file = "./output/z6/preprocess/Uterine_Corpus_Endometrial_Carcinoma/gene_data/GSE32507.csv"
15
+ out_clinical_data_file = "./output/z6/preprocess/Uterine_Corpus_Endometrial_Carcinoma/clinical_data/GSE32507.csv"
16
+ json_path = "./output/z6/preprocess/Uterine_Corpus_Endometrial_Carcinoma/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ import os
40
+ import re
41
+ import pandas as pd
42
+
43
+ # 1) Gene expression availability based on background: cDNA microarray => gene expression available
44
+ is_gene_available = True
45
+
46
+ # 2) Identify rows for variables from Sample Characteristics Dictionary
47
+ # From the provided dictionary:
48
+ # {0: ['tissue: endometrioid adenocarcinoma', 'tissue: carcinosarcoma', 'tissue: sarcoma'],
49
+ # 1: ['carcinosarcoma status: : heterologous', 'carcinosarcoma status: : homologous']}
50
+ trait_row = 0 # 'tissue' distinguishes EC vs CS/US
51
+ age_row = None
52
+ gender_row = None
53
+
54
+ # 2.2 Conversion functions
55
+ def _parse_after_colon(x):
56
+ if x is None:
57
+ return None
58
+ try:
59
+ # Handle cases with multiple colons, take the last segment
60
+ return str(x).split(':')[-1].strip()
61
+ except Exception:
62
+ return None
63
+
64
+ def convert_trait(x):
65
+ v = _parse_after_colon(x)
66
+ if v is None:
67
+ return None
68
+ v_low = v.lower()
69
+ # Map endometrioid adenocarcinoma (EC) to 1; carcinosarcoma (CS) and sarcoma (US) to 0
70
+ if ('endometrioid' in v_low) and ('adenocarcinoma' in v_low or 'carcinoma' in v_low):
71
+ return 1
72
+ if ('carcinosarcoma' in v_low) or ('sarcoma' in v_low):
73
+ return 0
74
+ # Conservative fallback
75
+ return None
76
+
77
+ def convert_age(x):
78
+ # Not used (no age available), but provided for completeness
79
+ v = _parse_after_colon(x)
80
+ if v is None:
81
+ return None
82
+ v_low = v.lower()
83
+ # Extract numeric value
84
+ m = re.search(r'(\d+(\.\d+)?)', v_low)
85
+ if not m:
86
+ return None
87
+ val = float(m.group(1))
88
+ # Heuristics for units if present
89
+ if 'month' in v_low:
90
+ return val / 12.0
91
+ # default to years
92
+ return val
93
+
94
+ def convert_gender(x):
95
+ # Not used (no gender available), but provided for completeness
96
+ v = _parse_after_colon(x)
97
+ if v is None:
98
+ return None
99
+ v_low = v.lower()
100
+ if v_low in ['male', 'm', 'man']:
101
+ return 1
102
+ if v_low in ['female', 'f', 'woman', 'women']:
103
+ return 0
104
+ return None
105
+
106
+ # 3) Save metadata using initial filtering
107
+ is_trait_available = trait_row is not None
108
+ _ = validate_and_save_cohort_info(
109
+ is_final=False,
110
+ cohort=cohort,
111
+ info_path=json_path,
112
+ is_gene_available=is_gene_available,
113
+ is_trait_available=is_trait_available
114
+ )
115
+
116
+ # 4) Clinical feature extraction (only if trait is available)
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
+ preview = preview_df(selected_clinical_df, n=5)
129
+ print(preview)
130
+
131
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
132
+ selected_clinical_df.to_csv(out_clinical_data_file)
133
+
134
+ # Step 3: Gene Data Extraction
135
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
136
+ gene_data = get_genetic_data(matrix_file)
137
+
138
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
139
+ print(gene_data.index[:20])
140
+
141
+ # Step 4: Gene Identifier Review
142
+ print("requires_gene_mapping = True")
143
+
144
+ # Step 5: Gene Annotation
145
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
146
+ gene_annotation = get_gene_annotation(soft_file)
147
+
148
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
149
+ print("Gene annotation preview:")
150
+ print(preview_df(gene_annotation))
151
+
152
+ # Step 6: Gene Identifier Mapping
153
+ # Identify the appropriate columns in the annotation for probe IDs and gene symbols
154
+ probe_col = 'ID'
155
+ symbol_col = 'GENE_SYMBOL'
156
+
157
+ # Build mapping dataframe
158
+ mapping_df = get_gene_mapping(gene_annotation, probe_col, symbol_col)
159
+
160
+ # Apply mapping to convert probe-level data to gene-level data
161
+ gene_data = apply_gene_mapping(gene_data, mapping_df)
162
+
163
+ # Step 7: Data Normalization and Linking
164
+ import os
165
+ import pandas as pd
166
+
167
+ # 1. Normalize gene symbols and save gene data
168
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
169
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
170
+ normalized_gene_data.to_csv(out_gene_data_file)
171
+
172
+ # Ensure we have the clinical dataframe in memory; fallback to loading from disk if needed
173
+ try:
174
+ selected_clinical_df
175
+ except NameError:
176
+ selected_clinical_df = pd.read_csv(out_clinical_data_file, index_col=0)
177
+
178
+ # 2. Link the clinical and genetic data
179
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
180
+
181
+ # 3. Handle missing values
182
+ linked_data = handle_missing_values(linked_data, trait)
183
+
184
+ # 4. Bias checking; remove biased demographic features if necessary
185
+ is_trait_biased_raw, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
186
+ is_trait_biased = bool(is_trait_biased_raw)
187
+
188
+ # 5. Final quality validation and save metadata
189
+ gene_cols_in_linked = [c for c in unbiased_linked_data.columns if c not in [trait, 'Age', 'Gender']]
190
+ is_gene_available_final = bool(len(gene_cols_in_linked) > 0)
191
+ is_trait_available_final = bool((trait in unbiased_linked_data.columns) and (unbiased_linked_data[trait].notna().any()))
192
+
193
+ note = ("INFO: Trait derived from 'tissue': endometrioid adenocarcinoma mapped to 1; "
194
+ "carcinosarcoma/sarcoma mapped to 0. No age/gender available in clinical. "
195
+ "Probes mapped via GENE_SYMBOL and normalized to NCBI standard symbols.")
196
+
197
+ is_usable = validate_and_save_cohort_info(
198
+ is_final=True,
199
+ cohort=cohort,
200
+ info_path=json_path,
201
+ is_gene_available=is_gene_available_final,
202
+ is_trait_available=is_trait_available_final,
203
+ is_biased=is_trait_biased,
204
+ df=unbiased_linked_data,
205
+ note=note
206
+ )
207
+
208
+ # 6. Save linked data if usable
209
+ if is_usable:
210
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
211
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Uterine_Corpus_Endometrial_Carcinoma/code/TCGA.py ADDED
@@ -0,0 +1,250 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Uterine_Corpus_Endometrial_Carcinoma"
6
+
7
+ # Input paths
8
+ tcga_root_dir = "../DATA/TCGA"
9
+
10
+ # Output paths
11
+ out_data_file = "./output/z6/preprocess/Uterine_Corpus_Endometrial_Carcinoma/TCGA.csv"
12
+ out_gene_data_file = "./output/z6/preprocess/Uterine_Corpus_Endometrial_Carcinoma/gene_data/TCGA.csv"
13
+ out_clinical_data_file = "./output/z6/preprocess/Uterine_Corpus_Endometrial_Carcinoma/clinical_data/TCGA.csv"
14
+ json_path = "./output/z6/preprocess/Uterine_Corpus_Endometrial_Carcinoma/cohort_info.json"
15
+
16
+
17
+ # Step 1: Initial Data Loading
18
+ import os
19
+ import pandas as pd
20
+
21
+ # Step 1: Select the most relevant TCGA cohort directory for Uterine Corpus Endometrial Carcinoma (UCEC)
22
+ subdirs = [d for d in os.listdir(tcga_root_dir) if os.path.isdir(os.path.join(tcga_root_dir, d))]
23
+
24
+ def score_dir(name: str) -> int:
25
+ lname = name.lower()
26
+ score = 0
27
+ if "(ucec)" in lname:
28
+ score += 100
29
+ if "ucec" in lname:
30
+ score += 50
31
+ if "endometrial" in lname or "endometrioid" in lname:
32
+ score += 30
33
+ if "uterine" in lname:
34
+ score += 10
35
+ if "carcinosarcoma" in lname or "(ucs)" in lname:
36
+ score -= 1000
37
+ return score
38
+
39
+ scored = [(d, score_dir(d)) for d in subdirs]
40
+ scored.sort(key=lambda x: x[1], reverse=True)
41
+ selected_dir = scored[0][0] if scored and scored[0][1] > 0 else None
42
+
43
+ if selected_dir is None:
44
+ # No suitable directory found; record and exit early for this trait
45
+ validate_and_save_cohort_info(
46
+ is_final=False,
47
+ cohort="TCGA",
48
+ info_path=json_path,
49
+ is_gene_available=False,
50
+ is_trait_available=False
51
+ )
52
+ else:
53
+ cohort_dir = os.path.join(tcga_root_dir, selected_dir)
54
+
55
+ # Step 2: Identify clinicalMatrix and PANCAN files
56
+ clinical_file_path, genetic_file_path = tcga_get_relevant_filepaths(cohort_dir)
57
+
58
+ # Step 3: Load both files as DataFrames
59
+ clinical_df = pd.read_csv(clinical_file_path, sep='\t', index_col=0, low_memory=False)
60
+ genetic_df = pd.read_csv(genetic_file_path, sep='\t', index_col=0, low_memory=False)
61
+
62
+ # Step 4: Print clinical column names
63
+ print(clinical_df.columns.tolist())
64
+
65
+ # Step 2: Find Candidate Demographic Features
66
+ # Identify candidate columns for age and gender from the provided column list
67
+ column_list = ['CDE_ID_3226963', '_INTEGRATION', '_PANCAN_CNA_PANCAN_K8', '_PANCAN_Cluster_Cluster_PANCAN', '_PANCAN_DNAMethyl_PANCAN', '_PANCAN_DNAMethyl_UCEC', '_PANCAN_RPPA_PANCAN_K8', '_PANCAN_UNC_RNAseq_PANCAN_K16', '_PANCAN_miRNA_PANCAN', '_PANCAN_mirna_UCEC', '_PANCAN_mutation_PANCAN', '_PATIENT', '_cohort', '_primary_disease', '_primary_site', 'additional_pharmaceutical_therapy', 'additional_radiation_therapy', 'additional_surgery_locoregional_procedure', 'additional_treatment_completion_success_outcome', 'age_at_initial_pathologic_diagnosis', 'aln_pos_ihc', 'aln_pos_light_micro', 'bcr_followup_barcode', 'bcr_patient_barcode', 'bcr_sample_barcode', 'birth_control_pill_history_usage_category', 'clinical_stage', 'colorectal_cancer', 'days_to_additional_surgery_metastatic_procedure', 'days_to_birth', 'days_to_collection', 'days_to_death', 'days_to_initial_pathologic_diagnosis', 'days_to_last_followup', 'days_to_last_known_alive', 'days_to_new_tumor_event_additional_surgery_procedure', 'days_to_new_tumor_event_after_initial_treatment', 'diabetes', 'disease_code', 'followup_case_report_form_submission_reason', 'form_completion_date', 'gender', 'height', 'histological_type', 'history_of_neoadjuvant_treatment', 'horm_ther', 'hypertension', 'icd_10', 'icd_o_3_histology', 'icd_o_3_site', 'informed_consent_verified', 'init_pathology_dx_method_other', 'initial_pathologic_diagnosis_method', 'initial_weight', 'is_ffpe', 'lost_follow_up', 'menopause_status', 'neoplasm_histologic_grade', 'new_neoplasm_event_occurrence_anatomic_site', 'new_neoplasm_event_type', 'new_neoplasm_occurrence_anatomic_site_text', 'new_tumor_event_additional_surgery_procedure', 'new_tumor_event_after_initial_treatment', 'oct_embedded', 'other_dx', 'pathology_report_file_name', 'patient_id', 'pct_tumor_invasion', 'peritoneal_wash', 'person_neoplasm_cancer_status', 'pln_pos_ihc', 'pln_pos_light_micro', 'postoperative_rx_tx', 'pregnancies', 'primary_therapy_outcome_success', 'prior_tamoxifen_administered_usage_category', 'project_code', 'radiation_therapy', 'recurrence_second_surgery_neoplasm_surgical_procedure_name', 'recurrence_second_surgery_neoplasm_surgical_procedure_name_other', 'residual_disease_post_new_tumor_event_margin_status', 'residual_tumor', 'sample_type', 'sample_type_id', 'surgical_approach', 'system_version', 'targeted_molecular_therapy', 'tissue_prospective_collection_indicator', 'tissue_retrospective_collection_indicator', 'tissue_source_site', 'total_aor_lnp', 'total_aor_lnr', 'total_pelv_lnp', 'total_pelv_lnr', 'tumor_tissue_site', 'vial_number', 'vital_status', 'weight', 'year_of_initial_pathologic_diagnosis', '_GENOMIC_ID_TCGA_UCEC_exp_HiSeqV2_PANCAN', '_GENOMIC_ID_data/public/TCGA/UCEC/miRNA_GA_gene', '_GENOMIC_ID_TCGA_UCEC_PDMRNAseq', '_GENOMIC_ID_TCGA_UCEC_exp_HiSeqV2_percentile', '_GENOMIC_ID_TCGA_UCEC_RPPA_RBN', '_GENOMIC_ID_TCGA_UCEC_RPPA', '_GENOMIC_ID_TCGA_UCEC_PDMarrayCNV', '_GENOMIC_ID_TCGA_UCEC_miRNA_GA', '_GENOMIC_ID_TCGA_UCEC_exp_HiSeqV2_exon', '_GENOMIC_ID_TCGA_UCEC_mutation_broad_gene', '_GENOMIC_ID_TCGA_UCEC_mutation_wustl_gene', '_GENOMIC_ID_TCGA_UCEC_mutation', '_GENOMIC_ID_TCGA_UCEC_exp_HiSeqV2', '_GENOMIC_ID_TCGA_UCEC_PDMarray', '_GENOMIC_ID_TCGA_UCEC_miRNA_HiSeq', '_GENOMIC_ID_TCGA_UCEC_exp_GAV2', '_GENOMIC_ID_TCGA_UCEC_gistic2thd', '_GENOMIC_ID_TCGA_UCEC_G4502A_07_3', '_GENOMIC_ID_TCGA_UCEC_gistic2', '_GENOMIC_ID_data/public/TCGA/UCEC/miRNA_HiSeq_gene', '_GENOMIC_ID_TCGA_UCEC_PDMRNAseqCNV', '_GENOMIC_ID_TCGA_UCEC_hMethyl450', '_GENOMIC_ID_TCGA_UCEC_hMethyl27', '_GENOMIC_ID_TCGA_UCEC_exp_GAV2_exon']
68
+
69
+ columns_set = set(column_list)
70
+
71
+ candidate_age_cols = []
72
+ if 'age_at_initial_pathologic_diagnosis' in columns_set:
73
+ candidate_age_cols.append('age_at_initial_pathologic_diagnosis')
74
+ if 'days_to_birth' in columns_set:
75
+ candidate_age_cols.append('days_to_birth')
76
+
77
+ candidate_gender_cols = []
78
+ if 'gender' in columns_set:
79
+ candidate_gender_cols.append('gender')
80
+
81
+ print(f"candidate_age_cols = {candidate_age_cols}")
82
+ print(f"candidate_gender_cols = {candidate_gender_cols}")
83
+
84
+ # Extract and preview candidate columns if clinical data is available or can be loaded
85
+ selected_cols = list(dict.fromkeys(candidate_age_cols + candidate_gender_cols))
86
+
87
+ if selected_cols:
88
+ import os
89
+ import glob
90
+ import pandas as pd
91
+
92
+ clinical_df_available = 'clinical_df' in globals() and isinstance(globals().get('clinical_df', None), pd.DataFrame)
93
+ if not clinical_df_available:
94
+ # Try to locate and load the clinical matrix for UCEC
95
+ dirs = [d for d in glob.glob(os.path.join(tcga_root_dir, '*')) if os.path.isdir(d)]
96
+ cohort_dir = None
97
+ for d in dirs:
98
+ if os.path.basename(d).upper() == 'UCEC':
99
+ cohort_dir = d
100
+ break
101
+ if cohort_dir is None:
102
+ for d in dirs:
103
+ base = os.path.basename(d)
104
+ if 'UCEC' in base.upper() or 'uterine' in base.lower():
105
+ cohort_dir = d
106
+ break
107
+ if cohort_dir is None:
108
+ cohort_dir = os.path.join(tcga_root_dir, 'UCEC')
109
+
110
+ try:
111
+ clinical_file_path, _ = tcga_get_relevant_filepaths(cohort_dir)
112
+ clinical_df = pd.read_table(clinical_file_path, sep='\t', header=0)
113
+ except Exception:
114
+ clinical_df = None
115
+
116
+ # Preview if data loaded successfully and columns exist
117
+ if isinstance(globals().get('clinical_df', None), pd.DataFrame):
118
+ existing_cols = [c for c in selected_cols if c in clinical_df.columns]
119
+ if existing_cols:
120
+ preview = preview_df(clinical_df[existing_cols], n=5)
121
+ print(preview)
122
+ else:
123
+ print({})
124
+ else:
125
+ print({})
126
+ else:
127
+ print({})
128
+
129
+ # Step 3: Select Demographic Features
130
+ # Select best demographic columns from candidates based on name heuristics and available previews
131
+
132
+ # Initialize defaults
133
+ age_col = None
134
+ gender_col = None
135
+
136
+ # Heuristic scoring for age columns: prefer 'age', avoid 'days'/'birth'
137
+ def score_age_col(col_name: str) -> int:
138
+ name = col_name.lower()
139
+ score = 0
140
+ if "age" in name:
141
+ score += 2
142
+ if "pathologic" in name or "diagnosis" in name:
143
+ score += 1
144
+ if "days" in name or "birth" in name:
145
+ score -= 2
146
+ return score
147
+
148
+ # Heuristic selection for age
149
+ if 'candidate_age_cols' in globals() and isinstance(candidate_age_cols, list) and len(candidate_age_cols) > 0:
150
+ scored = sorted(candidate_age_cols, key=lambda c: score_age_col(c), reverse=True)
151
+ # Ensure the top choice has a non-negative score; otherwise set to None
152
+ top = scored[0]
153
+ if score_age_col(top) >= 0:
154
+ age_col = top
155
+ else:
156
+ age_col = None
157
+ else:
158
+ age_col = None
159
+
160
+ # Heuristic selection for gender
161
+ if 'candidate_gender_cols' in globals() and isinstance(candidate_gender_cols, list) and len(candidate_gender_cols) > 0:
162
+ # Prefer 'gender' or 'sex'
163
+ pref_order = sorted(candidate_gender_cols, key=lambda c: (("gender" in c.lower()) or ("sex" in c.lower())), reverse=True)
164
+ gender_col = pref_order[0]
165
+ else:
166
+ gender_col = None
167
+
168
+ # Helper to retrieve preview values if previously stored in any dict in globals
169
+ def _get_preview_values(col_name):
170
+ if col_name is None:
171
+ return None
172
+ for var_name, obj in list(globals().items()):
173
+ if isinstance(obj, dict) and col_name in obj:
174
+ return obj.get(col_name, None)
175
+ return None
176
+
177
+ # Print explicit information
178
+ print(f"Selected age_col: {age_col}")
179
+ age_preview_vals = _get_preview_values(age_col)
180
+ if age_preview_vals is not None:
181
+ print(f"Preview values for {age_col}: {age_preview_vals}")
182
+
183
+ print(f"Selected gender_col: {gender_col}")
184
+ gender_preview_vals = _get_preview_values(gender_col)
185
+ if gender_preview_vals is not None:
186
+ print(f"Preview values for {gender_col}: {gender_preview_vals}")
187
+
188
+ # Step 4: Feature Engineering and Validation
189
+ import os
190
+ import pandas as pd
191
+
192
+ # 1) Extract and standardize clinical features (trait, Age, Gender)
193
+ selected_clinical_df = tcga_select_clinical_features(
194
+ clinical_df=clinical_df,
195
+ trait=trait,
196
+ age_col=age_col,
197
+ gender_col=gender_col
198
+ )
199
+
200
+ # 2) Normalize gene symbols and save normalized gene expression data
201
+ normalized_gene_df = normalize_gene_symbols_in_index(genetic_df) # genes x samples
202
+
203
+ # Ensure output directory exists and save normalized gene data
204
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
205
+ normalized_gene_df.to_csv(out_gene_data_file)
206
+
207
+ # 3) Link clinical and genetic data on sample IDs
208
+ # clinical: samples x features; genes: genes x samples -> transpose to samples x genes
209
+ linked_data = selected_clinical_df.join(normalized_gene_df.T, how='inner')
210
+
211
+ # 4) Handle missing values as specified
212
+ linked_data = handle_missing_values(linked_data, trait)
213
+
214
+ # 5) Determine bias; remove biased demographic features while keeping trait
215
+ trait_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)
216
+
217
+ # 6) Final quality validation and save cohort info
218
+ covariate_cols = [trait, 'Age', 'Gender']
219
+ gene_cols_count = len([c for c in linked_data.columns if c not in covariate_cols])
220
+ is_gene_available = gene_cols_count > 0
221
+ is_trait_available = (trait in linked_data.columns) and (linked_data[trait].notna().sum() > 0) and (len(linked_data) > 0)
222
+
223
+ # Prepare an informational note
224
+ label_counts = linked_data[trait].value_counts(dropna=False).to_dict() if trait in linked_data.columns else {}
225
+ has_age = 'Age' in linked_data.columns
226
+ has_gender = 'Gender' in linked_data.columns
227
+ note_parts = [
228
+ f"Samples={len(linked_data)}",
229
+ f"Genes={gene_cols_count}",
230
+ f"Trait_counts={label_counts}",
231
+ f"HasAge={has_age}",
232
+ f"HasGender={has_gender}"
233
+ ]
234
+ note = "INFO: " + "; ".join(note_parts)
235
+
236
+ is_usable = validate_and_save_cohort_info(
237
+ is_final=True,
238
+ cohort="TCGA",
239
+ info_path=json_path,
240
+ is_gene_available=is_gene_available,
241
+ is_trait_available=is_trait_available,
242
+ is_biased=trait_biased,
243
+ df=linked_data,
244
+ note=note
245
+ )
246
+
247
+ # 7) Save linked data only if usable
248
+ if is_usable:
249
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
250
+ linked_data.to_csv(out_data_file)
output/preprocess/Uterine_Corpus_Endometrial_Carcinoma/cohort_info.json CHANGED
@@ -1,22 +1 @@
1
- {
2
- "GSE32507": {
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": 46
11
- },
12
- "TCGA": {
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": 201
21
- }
22
- }
 
1
+ {"GSE32507": {"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": 46, "note": "INFO: Trait derived from 'tissue': endometrioid adenocarcinoma mapped to 1; carcinosarcoma/sarcoma mapped to 0. No age/gender available in clinical. Probes mapped via GENE_SYMBOL and normalized to NCBI standard symbols."}, "TCGA": {"is_usable": true, "is_gene_available": true, "is_trait_available": true, "is_available": true, "is_biased": false, "has_age": true, "has_gender": false, "sample_size": 201, "note": "INFO: Samples=201; Genes=19848; Trait_counts={1: 177, 0: 24}; HasAge=True; HasGender=False"}}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
output/preprocess/Vitamin_D_Levels/GSE76324.csv ADDED
The diff for this file is too large to render. See raw diff
 
output/preprocess/Vitamin_D_Levels/clinical_data/GSE129604.csv CHANGED
@@ -1,3 +1,3 @@
1
- 0
2
- 1.0
3
- ""
 
1
+ ,GSM3716832,GSM3716833,GSM3716834,GSM3716835,GSM3716836,GSM3716837,GSM3716838,GSM3716839,GSM3716840,GSM3716841,GSM3716842,GSM3716843,GSM3716844,GSM3716845,GSM3716846,GSM3716847,GSM3716848,GSM3716849,GSM3716850,GSM3716851,GSM3716852,GSM3716853,GSM3716854,GSM3716855,GSM3716856,GSM3716857,GSM3716858,GSM3716859,GSM3716860,GSM3716861,GSM3716862,GSM3716863,GSM3716864,GSM3716865,GSM3716866,GSM3716867,GSM3716868,GSM3716869,GSM3716870,GSM3716871,GSM3716872,GSM3716873,GSM3716874,GSM3716875,GSM3716876,GSM3716877,GSM3716878,GSM3716879,GSM3716880,GSM3716881,GSM3716882,GSM3716883,GSM3716884,GSM3716885,GSM3716886,GSM3716887,GSM3716888,GSM3716889,GSM3716890,GSM3716891,GSM3716892,GSM3716893,GSM3716894,GSM3716895,GSM3716896,GSM3716897,GSM3716898,GSM3716899,GSM3716900,GSM3716901,GSM3716902,GSM3716903,GSM3716904,GSM3716905,GSM3716906,GSM3716907,GSM3716908,GSM3716909,GSM3716910,GSM3716911,GSM3716912,GSM3716913,GSM3716914,GSM3716915,GSM3716916,GSM3716917,GSM3716918,GSM3716919,GSM3716920,GSM3716921,GSM3716922,GSM3716923,GSM3716924,GSM3716925,GSM3716926,GSM3716927,GSM3716928,GSM3716929,GSM3716930,GSM3716931,GSM3716932,GSM3716933,GSM3716934,GSM3716935,GSM3716936,GSM3716937,GSM3716938,GSM3716939,GSM3716940,GSM3716941,GSM3716942,GSM3716943,GSM3716944,GSM3716945,GSM3716946,GSM3716947,GSM3716948,GSM3716949,GSM3716950,GSM3716951,GSM3716952,GSM3716953,GSM3716954,GSM3716955,GSM3716956,GSM3716957,GSM3716958,GSM3716959,GSM3716960,GSM3716961,GSM3716962,GSM3716963,GSM3716964,GSM3716965,GSM3716966,GSM3716967,GSM3716968,GSM3716969,GSM3716970,GSM3716971,GSM3716972
2
+ Vitamin_D_Levels,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.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,1.0,1.0,0.0,0.0,1.0,1.0,0.0,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,0.0,1.0,1.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,0.0,1.0,1.0,1.0,1.0,0.0,0.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,1.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,1.0,1.0,0.0,0.0,1.0,1.0,0.0,0.0,0.0,0.0,1.0,0.0,1.0,1.0,0.0,0.0,1.0,1.0,0.0,0.0,1.0,1.0,0.0,0.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,1.0,1.0,0.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,1.0,1.0
3
+ Gender,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,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,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
output/preprocess/Vitamin_D_Levels/clinical_data/GSE34450.csv CHANGED
@@ -1,2 +1,2 @@
1
- 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,130,131
2
- ,1.0,,,,,,,,,,1.0,1.0,1.0,,1.0,,,1.0,,,0.0,1.0,0.0,,,1.0,,,,1.0,,1.0,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
 
1
+ ,GSM549681,GSM549682,GSM549683,GSM549684,GSM549685,GSM549689,GSM549690,GSM549691,GSM549692,GSM549693,GSM549694,GSM549695,GSM549698,GSM549703,GSM549705,GSM549707,GSM549713,GSM549715,GSM549716,GSM549717,GSM549718,GSM549719,GSM549720,GSM549721,GSM549722,GSM549723,GSM549724,GSM549725,GSM549726,GSM549727,GSM549728,GSM549729,GSM549730,GSM549731,GSM549732,GSM549733,GSM549734,GSM549735,GSM549736,GSM549737,GSM549738,GSM549739,GSM549740,GSM549744,GSM549745,GSM549746,GSM549747,GSM549758,GSM549764,GSM549771,GSM549773,GSM549775,GSM549778,GSM549779,GSM549780,GSM549781,GSM549782,GSM549783,GSM549784,GSM549785,GSM549786,GSM549787,GSM549788,GSM549789,GSM549790,GSM549791,GSM549792,GSM549793,GSM549794,GSM549795,GSM549796,GSM549797,GSM549798,GSM549799,GSM549800,GSM549801,GSM549802,GSM549803,GSM549804,GSM549805,GSM549806,GSM549807,GSM549808,GSM549809,GSM549810,GSM549811,GSM549812,GSM549813,GSM599910,GSM599911,GSM599912,GSM599913,GSM599915,GSM599916,GSM599917,GSM599918,GSM599919,GSM599920,GSM599921,GSM631346,GSM631351,GSM631353,GSM631354,GSM631356,GSM631357,GSM631359,GSM631364,GSM631365,GSM631366,GSM631367,GSM631369,GSM631370,GSM631371,GSM631372,GSM631373,GSM631374,GSM631375,GSM631376,GSM631377,GSM631378,GSM631379,GSM631380,GSM631381,GSM631382,GSM631383,GSM631384,GSM631385,GSM631386,GSM631387,GSM631389,GSM631390,GSM631391
2
+ Vitamin_D_Levels,,,,,,,,,,,,,1.0,,,1.0,,,1.0,,,0.0,1.0,0.0,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
output/preprocess/Vitamin_D_Levels/clinical_data/GSE76324.csv CHANGED
@@ -1,2 +1,2 @@
1
- ID_REF,GSM549681,GSM549682,GSM549683,GSM549684,GSM549685,GSM549686,GSM549687,GSM549688,GSM549689,GSM549690,GSM549691,GSM549692,GSM549693,GSM549694,GSM549695,GSM549696,GSM549697,GSM549698,GSM549699,GSM549700,GSM549701,GSM549702,GSM549703,GSM549704,GSM549705,GSM549706,GSM549707,GSM549708,GSM549709,GSM549710,GSM549711,GSM549712,GSM549713,GSM549714,GSM549715,GSM549716,GSM549717,GSM549718,GSM549719,GSM549720,GSM549721,GSM549722,GSM549723,GSM549724,GSM549725,GSM549726,GSM549727,GSM549728,GSM549729,GSM549730,GSM549731,GSM549732,GSM549733,GSM549734,GSM549735,GSM549736,GSM549737,GSM549738,GSM549739,GSM549740,GSM549741,GSM549742,GSM549743,GSM549744,GSM549745,GSM549746,GSM549747,GSM549748,GSM549749,GSM549750,GSM549751,GSM549752,GSM549753,GSM549754,GSM549755,GSM549756,GSM549757,GSM549758,GSM549759,GSM549760,GSM549761,GSM549762,GSM549763,GSM549764,GSM549765,GSM549766,GSM549767,GSM549768,GSM549769,GSM549770,GSM549771,GSM549772,GSM549773,GSM549774,GSM549775,GSM549776,GSM549777,GSM549778,GSM549779,GSM549780,GSM549781,GSM549782,GSM549783,GSM549784,GSM549785,GSM549786,GSM549787,GSM549788,GSM549789,GSM549790,GSM549791,GSM549792,GSM549793,GSM549794,GSM549795,GSM549796,GSM549797,GSM549798,GSM549799,GSM549800,GSM549801,GSM549802,GSM549803,GSM549804,GSM549805,GSM549806,GSM549807,GSM549809,GSM549810,GSM549811,GSM549813,GSM631340,GSM631341,GSM631342,GSM631343,GSM631344,GSM631345,GSM631346,GSM631347,GSM631348,GSM631349,GSM631350,GSM631351,GSM631352,GSM631353,GSM631354,GSM631355,GSM631356,GSM631357,GSM631358,GSM631359,GSM631360,GSM631361,GSM631362,GSM631363,GSM631364,GSM631365,GSM631366,GSM631367,GSM631368,GSM631369,GSM631370,GSM631371,GSM631372,GSM631373,GSM631374,GSM631375,GSM631376,GSM631377,GSM631378,GSM631379,GSM631380,GSM631381,GSM631382,GSM631383,GSM631384,GSM631385,GSM631386,GSM631387,GSM631388,GSM631389,GSM631390,GSM631391,GSM1056118,GSM1056119,GSM1056120,GSM1056121,GSM1056123,GSM1056124,GSM1056125,GSM1056126,GSM1056127,GSM1056128,GSM1056129,GSM1056130,GSM1056131,GSM1056132,GSM1056133,GSM1056134,GSM1056135,GSM1056136,GSM1056138,GSM1056139,GSM1056140,GSM1056141,GSM1056142,GSM1056143,GSM1056144,GSM1056145,GSM1056147,GSM1056148,GSM1056149,GSM1056150,GSM1056153,GSM1575535,GSM1575536,GSM1575537
2
- ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
 
1
+ ,GSM549681,GSM549682,GSM549683,GSM549684,GSM549685,GSM549686,GSM549687,GSM549688,GSM549689,GSM549690,GSM549691,GSM549692,GSM549693,GSM549694,GSM549695,GSM549696,GSM549697,GSM549698,GSM549699,GSM549700,GSM549701,GSM549702,GSM549703,GSM549704,GSM549705,GSM549706,GSM549707,GSM549708,GSM549709,GSM549710,GSM549711,GSM549712,GSM549713,GSM549714,GSM549715,GSM549716,GSM549717,GSM549718,GSM549719,GSM549720,GSM549721,GSM549722,GSM549723,GSM549724,GSM549725,GSM549726,GSM549727,GSM549728,GSM549729,GSM549730,GSM549731,GSM549732,GSM549733,GSM549734,GSM549735,GSM549736,GSM549737,GSM549738,GSM549739,GSM549740,GSM549741,GSM549742,GSM549743,GSM549744,GSM549745,GSM549746,GSM549747,GSM549748,GSM549749,GSM549750,GSM549751,GSM549752,GSM549753,GSM549754,GSM549755,GSM549756,GSM549757,GSM549758,GSM549759,GSM549760,GSM549761,GSM549762,GSM549763,GSM549764,GSM549765,GSM549766,GSM549767,GSM549768,GSM549769,GSM549770,GSM549771,GSM549772,GSM549773,GSM549774,GSM549775,GSM549776,GSM549777,GSM549778,GSM549779,GSM549780,GSM549781,GSM549782,GSM549783,GSM549784,GSM549785,GSM549786,GSM549787,GSM549788,GSM549789,GSM549790,GSM549791,GSM549792,GSM549793,GSM549794,GSM549795,GSM549796,GSM549797,GSM549798,GSM549799,GSM549800,GSM549801,GSM549802,GSM549803,GSM549804,GSM549805,GSM549806,GSM549807,GSM549809,GSM549810,GSM549811,GSM549813,GSM631340,GSM631341,GSM631342,GSM631343,GSM631344,GSM631345,GSM631346,GSM631347,GSM631348,GSM631349,GSM631350,GSM631351,GSM631352,GSM631353,GSM631354,GSM631355,GSM631356,GSM631357,GSM631358,GSM631359,GSM631360,GSM631361,GSM631362,GSM631363,GSM631364,GSM631365,GSM631366,GSM631367,GSM631368,GSM631369,GSM631370,GSM631371,GSM631372,GSM631373,GSM631374,GSM631375,GSM631376,GSM631377,GSM631378,GSM631379,GSM631380,GSM631381,GSM631382,GSM631383,GSM631384,GSM631385,GSM631386,GSM631387,GSM631388,GSM631389,GSM631390,GSM631391,GSM1056118,GSM1056119,GSM1056120,GSM1056121,GSM1056123,GSM1056124,GSM1056125,GSM1056126,GSM1056127,GSM1056128,GSM1056129,GSM1056130,GSM1056131,GSM1056132,GSM1056133,GSM1056134,GSM1056135,GSM1056136,GSM1056138,GSM1056139,GSM1056140,GSM1056141,GSM1056142,GSM1056143,GSM1056144,GSM1056145,GSM1056147,GSM1056148,GSM1056149,GSM1056150,GSM1056153,GSM1575535,GSM1575536,GSM1575537
2
+ Vitamin_D_Levels,,0.5,,,,,,,,,,,,,0.5,1.0,,1.0,,0.0,1.0,,0.5,,,,1.0,0.0,0.5,,0.0,,,1.0,,1.0,,,0.0,1.0,0.0,,,0.5,,,,0.5,,0.5,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
output/preprocess/Vitamin_D_Levels/code/GSE118723.py ADDED
@@ -0,0 +1,208 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Vitamin_D_Levels"
6
+ cohort = "GSE118723"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Vitamin_D_Levels"
10
+ in_cohort_dir = "../DATA/GEO/Vitamin_D_Levels/GSE118723"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z6/preprocess/Vitamin_D_Levels/GSE118723.csv"
14
+ out_gene_data_file = "./output/z6/preprocess/Vitamin_D_Levels/gene_data/GSE118723.csv"
15
+ out_clinical_data_file = "./output/z6/preprocess/Vitamin_D_Levels/clinical_data/GSE118723.csv"
16
+ json_path = "./output/z6/preprocess/Vitamin_D_Levels/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ import re
40
+
41
+ # 1) Gene expression availability (scRNA-seq of iPSCs => gene expression available)
42
+ is_gene_available = True
43
+
44
+ # 2) Variable availability (based on provided Sample Characteristics Dictionary)
45
+ # No Vitamin D, age, or gender information present
46
+ trait_row = None
47
+ age_row = None
48
+ gender_row = None
49
+
50
+ # 2.2) Conversion functions
51
+
52
+ def _extract_value_after_colon(x: str) -> str:
53
+ if x is None:
54
+ return None
55
+ if isinstance(x, str):
56
+ parts = x.split(":", 1)
57
+ return parts[1].strip() if len(parts) > 1 else x.strip()
58
+ return x
59
+
60
+ def convert_trait(x):
61
+ """
62
+ Convert Vitamin D levels to continuous (float, e.g., ng/mL or nmol/L if present).
63
+ Extracts the first numeric value found after the colon; returns None if not parseable.
64
+ """
65
+ try:
66
+ s = _extract_value_after_colon(x)
67
+ if s is None:
68
+ return None
69
+ match = re.search(r"[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?", s)
70
+ return float(match.group()) if match else None
71
+ except Exception:
72
+ return None
73
+
74
+ def convert_age(x):
75
+ """
76
+ Convert age to continuous (float years).
77
+ Extract the first numeric value after the colon; returns None if not parseable.
78
+ """
79
+ try:
80
+ s = _extract_value_after_colon(x)
81
+ if s is None:
82
+ return None
83
+ match = re.search(r"[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?", s)
84
+ return float(match.group()) if match else None
85
+ except Exception:
86
+ return None
87
+
88
+ def convert_gender(x):
89
+ """
90
+ Convert gender to binary: female -> 0, male -> 1.
91
+ Supports common synonyms. Returns None if unknown.
92
+ Uses exact token checks first, then word-boundary regex to avoid substring issues (e.g., 'female' containing 'male').
93
+ """
94
+ s = _extract_value_after_colon(x)
95
+ if s is None:
96
+ return None
97
+ v = str(s).strip().lower()
98
+
99
+ # Exact tokens first
100
+ if v in {"female", "f", "woman", "girl"}:
101
+ return 0
102
+ if v in {"male", "m", "man", "boy"}:
103
+ return 1
104
+
105
+ # Word-boundary regex fallback
106
+ if re.search(r"\bfemale\b", v):
107
+ return 0
108
+ if re.search(r"\bmale\b", v):
109
+ return 1
110
+
111
+ return None
112
+
113
+ # 3) Save metadata with initial filtering
114
+ is_trait_available = trait_row is not None
115
+ _ = validate_and_save_cohort_info(
116
+ is_final=False,
117
+ cohort=cohort,
118
+ info_path=json_path,
119
+ is_gene_available=is_gene_available,
120
+ is_trait_available=is_trait_available
121
+ )
122
+
123
+ # 4) Clinical feature extraction: skipped because trait_row is None (no clinical trait data available)
124
+ # If trait_row becomes available in future steps, you can uncomment and use the following:
125
+ # selected_clinical_df = geo_select_clinical_features(
126
+ # clinical_df=clinical_data,
127
+ # trait=trait,
128
+ # trait_row=trait_row,
129
+ # convert_trait=convert_trait,
130
+ # age_row=age_row,
131
+ # convert_age=convert_age,
132
+ # gender_row=gender_row,
133
+ # convert_gender=convert_gender
134
+ # )
135
+ # preview = preview_df(selected_clinical_df, n=5)
136
+ # os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
137
+ # selected_clinical_df.to_csv(out_clinical_data_file)
138
+
139
+ # Step 3: Gene Data Extraction
140
+ import os
141
+ import gzip
142
+ import pandas as pd
143
+
144
+ # 1) Extract gene expression data with robust fallback
145
+ print(f"Selected matrix_file: {matrix_file}")
146
+
147
+ # Primary attempt using library
148
+ try:
149
+ gene_data = get_genetic_data(matrix_file)
150
+ except Exception as e:
151
+ print(f"get_genetic_data failed with error: {e}")
152
+ gene_data = pd.DataFrame()
153
+
154
+ # Fallback if empty
155
+ if gene_data.shape[0] == 0:
156
+ skip_rows = None
157
+ try:
158
+ with gzip.open(matrix_file, 'rt') as fh:
159
+ for i, line in enumerate(fh):
160
+ if "!series_matrix_table_begin" in line:
161
+ skip_rows = i + 1
162
+ break
163
+ except Exception as e:
164
+ print(f"Error locating marker: {e}")
165
+
166
+ if skip_rows is not None:
167
+ try:
168
+ df_try = pd.read_csv(
169
+ matrix_file,
170
+ compression='gzip',
171
+ sep='\t',
172
+ skiprows=skip_rows,
173
+ engine='python',
174
+ dtype=str,
175
+ comment='!',
176
+ on_bad_lines='skip',
177
+ header=0
178
+ )
179
+ # Clean column names (strip quotes/whitespace)
180
+ df_try.columns = [str(c).strip().strip('"').strip("'") for c in df_try.columns]
181
+
182
+ # Normalize first column as ID
183
+ first_col = df_try.columns[0]
184
+ if first_col in ["ID_REF", "ID"]:
185
+ df_try = df_try.rename(columns={first_col: "ID"})
186
+ else:
187
+ # Force first column to ID if header is unconventional
188
+ df_try = df_try.rename(columns={first_col: "ID"})
189
+
190
+ # Clean ID column and set index
191
+ df_try["ID"] = df_try["ID"].astype(str).str.strip().str.strip('"').str.strip("'")
192
+ df_try = df_try[df_try["ID"].notna() & (df_try["ID"] != "")]
193
+ df_try = df_try.set_index("ID")
194
+
195
+ # Also strip quotes/whitespace in values
196
+ df_try = df_try.apply(lambda col: col.astype(str).str.strip().str.strip('"').str.strip("'"))
197
+
198
+ gene_data = df_try
199
+ except Exception as e:
200
+ print(f"Fallback read failed with error: {e}")
201
+ gene_data = pd.DataFrame()
202
+
203
+ print("Parsed gene_data shape:", getattr(gene_data, "shape", None))
204
+
205
+ # 2) Print the first 20 row IDs (gene or probe identifiers)
206
+ first_ids = list(gene_data.index[:20])
207
+ print("First 20 row IDs:")
208
+ print(first_ids)
output/preprocess/Vitamin_D_Levels/code/GSE123993.py ADDED
@@ -0,0 +1,215 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Vitamin_D_Levels"
6
+ cohort = "GSE123993"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Vitamin_D_Levels"
10
+ in_cohort_dir = "../DATA/GEO/Vitamin_D_Levels/GSE123993"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z6/preprocess/Vitamin_D_Levels/GSE123993.csv"
14
+ out_gene_data_file = "./output/z6/preprocess/Vitamin_D_Levels/gene_data/GSE123993.csv"
15
+ out_clinical_data_file = "./output/z6/preprocess/Vitamin_D_Levels/clinical_data/GSE123993.csv"
16
+ json_path = "./output/z6/preprocess/Vitamin_D_Levels/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ import re
40
+
41
+ # 1) Gene expression availability
42
+ is_gene_available = True # Affymetrix HuGene 2.1ST arrays -> whole-genome expression
43
+
44
+ # 2) Variable availability
45
+ # From the sample characteristics:
46
+ # 0: tissue
47
+ # 1: Sex
48
+ # 2: subject id
49
+ # 3: intervention group
50
+ # 4: time of sampling
51
+ trait_row = None # No direct Vitamin D level per sample; cannot be mapped to a single key
52
+ age_row = None # No per-sample age provided
53
+ gender_row = 1 # 'Sex: Male/Female'
54
+
55
+ # 2.2) Converters and data type choices
56
+ trait_type = 'continuous'
57
+ age_type = 'continuous'
58
+ gender_type = 'binary'
59
+
60
+ def _extract_value(cell):
61
+ if cell is None:
62
+ return None
63
+ if isinstance(cell, str):
64
+ parts = cell.split(':', 1)
65
+ return parts[1].strip() if len(parts) > 1 else cell.strip()
66
+ return cell
67
+
68
+ def convert_trait(x):
69
+ # Expect numeric vitamin D concentration if available; here it's not used since trait_row is None.
70
+ v = _extract_value(x)
71
+ if v is None:
72
+ return None
73
+ # Extract first float-like number
74
+ m = re.search(r'[-+]?\d*\.?\d+', str(v))
75
+ if m:
76
+ try:
77
+ return float(m.group())
78
+ except Exception:
79
+ return None
80
+ return None
81
+
82
+ def convert_age(x):
83
+ v = _extract_value(x)
84
+ if v is None:
85
+ return None
86
+ # Extract age as the first integer/float found
87
+ m = re.search(r'[-+]?\d*\.?\d+', str(v))
88
+ if m:
89
+ try:
90
+ return float(m.group())
91
+ except Exception:
92
+ return None
93
+ return None
94
+
95
+ def convert_gender(x):
96
+ v = _extract_value(x)
97
+ if v is None:
98
+ return None
99
+ s = str(v).strip().lower()
100
+ if s in ['male', 'm']:
101
+ return 1
102
+ if s in ['female', 'f']:
103
+ return 0
104
+ return None
105
+
106
+ # 3) Save metadata (initial filtering)
107
+ is_trait_available = trait_row is not None
108
+ _ = validate_and_save_cohort_info(
109
+ is_final=False,
110
+ cohort=cohort,
111
+ info_path=json_path,
112
+ is_gene_available=is_gene_available,
113
+ is_trait_available=is_trait_available
114
+ )
115
+
116
+ # 4) Clinical feature extraction (skip if trait is not available)
117
+ if trait_row is not None:
118
+ selected = geo_select_clinical_features(
119
+ clinical_df=clinical_data,
120
+ trait=trait,
121
+ trait_row=trait_row,
122
+ convert_trait=convert_trait,
123
+ age_row=age_row,
124
+ convert_age=convert_age,
125
+ gender_row=gender_row,
126
+ convert_gender=convert_gender
127
+ )
128
+ preview = preview_df(selected)
129
+ print(preview)
130
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
131
+ selected.to_csv(out_clinical_data_file)
132
+
133
+ # Step 3: Gene Data Extraction
134
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
135
+ gene_data = get_genetic_data(matrix_file)
136
+
137
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
138
+ print(gene_data.index[:20])
139
+
140
+ # Step 4: Gene Identifier Review
141
+ print("requires_gene_mapping = True")
142
+
143
+ # Step 5: Gene Annotation
144
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
145
+ gene_annotation = get_gene_annotation(soft_file)
146
+
147
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
148
+ print("Gene annotation preview:")
149
+ print(preview_df(gene_annotation))
150
+
151
+ # Step 6: Gene Identifier Mapping
152
+ # Determine columns for mapping based on annotation preview:
153
+ # - Probe identifier matches 'ID' (numeric probeset IDs like '1665xxxx')
154
+ # - Gene symbols are embedded in 'gene_assignment'
155
+ prob_col = 'ID'
156
+ gene_col = 'gene_assignment'
157
+
158
+ # Build the mapping dataframe
159
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=prob_col, gene_col=gene_col)
160
+
161
+ # Apply mapping: convert probe-level data to gene-level data
162
+ probe_data = gene_data # preserve original probe-level data
163
+ gene_data = apply_gene_mapping(expression_df=probe_data, mapping_df=mapping_df)
164
+
165
+ # Step 7: Data Normalization and Linking
166
+ import os
167
+
168
+ # 1) Normalize gene symbols and save gene-level 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 only if clinical features (including trait) were extracted
174
+ is_usable = False
175
+ if 'selected_clinical_data' in locals() and selected_clinical_data is not None and trait in selected_clinical_data.index:
176
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_data, normalized_gene_data)
177
+
178
+ # 3) Handle missing values
179
+ linked_data = handle_missing_values(linked_data, trait)
180
+
181
+ # 4) Bias checks and removal of biased covariates
182
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
183
+
184
+ # 5) Final validation and save cohort info
185
+ is_usable = validate_and_save_cohort_info(
186
+ is_final=True,
187
+ cohort=cohort,
188
+ info_path=json_path,
189
+ is_gene_available=True,
190
+ is_trait_available=True,
191
+ is_biased=is_trait_biased,
192
+ df=unbiased_linked_data,
193
+ note="INFO: Linked data created from gene-level normalized expression and available clinical features."
194
+ )
195
+
196
+ # 6) Save linked data only if usable
197
+ if is_usable:
198
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
199
+ unbiased_linked_data.to_csv(out_data_file)
200
+
201
+ else:
202
+ # Trait not available -> cannot link; still record final metadata without marking gene as unavailable
203
+ # Use gene data (transposed) as df for validation to avoid false flagging gene availability
204
+ df_for_validation = normalized_gene_data.T
205
+ is_usable = validate_and_save_cohort_info(
206
+ is_final=True,
207
+ cohort=cohort,
208
+ info_path=json_path,
209
+ is_gene_available=True,
210
+ is_trait_available=False,
211
+ is_biased=False,
212
+ df=df_for_validation,
213
+ note="WARNING: Trait not available; cannot link clinical and genetic data for this cohort."
214
+ )
215
+ # Do not save out_data_file when trait is not available
output/preprocess/Vitamin_D_Levels/code/GSE129604.py ADDED
@@ -0,0 +1,204 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Vitamin_D_Levels"
6
+ cohort = "GSE129604"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Vitamin_D_Levels"
10
+ in_cohort_dir = "../DATA/GEO/Vitamin_D_Levels/GSE129604"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z6/preprocess/Vitamin_D_Levels/GSE129604.csv"
14
+ out_gene_data_file = "./output/z6/preprocess/Vitamin_D_Levels/gene_data/GSE129604.csv"
15
+ out_clinical_data_file = "./output/z6/preprocess/Vitamin_D_Levels/clinical_data/GSE129604.csv"
16
+ json_path = "./output/z6/preprocess/Vitamin_D_Levels/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 # Whole blood whole-genome expression per background
44
+
45
+ # 2. Variable Availability and Data Type Conversion
46
+
47
+ # Keys from Sample Characteristics Dictionary:
48
+ # 0: Sex
49
+ # 1: tissue
50
+ # 2: agent (Placebo, BPH, VitD+BPH, VitD, VitD-Pep-C-VitDPep)
51
+ # 3: time point
52
+
53
+ # Trait: Infer Vitamin D exposure from 'agent' (contains VitD -> 1, else -> 0)
54
+ trait_row = 2
55
+
56
+ # Age: Not available in the sample characteristics
57
+ age_row = None
58
+
59
+ # Gender: Available under 'Sex'
60
+ gender_row = 0
61
+
62
+ def _extract_value(x: str) -> str:
63
+ if x is None:
64
+ return ""
65
+ parts = str(x).split(":", 1)
66
+ val = parts[1] if len(parts) > 1 else parts[0]
67
+ return val.strip()
68
+
69
+ def convert_trait(x):
70
+ val = _extract_value(x).lower()
71
+ if val == "":
72
+ return None
73
+ # Map presence of vitamin D in the agent to 1, otherwise 0
74
+ if "vitd" in val:
75
+ return 1
76
+ if "placebo" in val or "bph" in val:
77
+ return 0
78
+ return None
79
+
80
+ def convert_age(x):
81
+ # Generic parser: extract numeric value if present, else None
82
+ val = _extract_value(x)
83
+ if val == "":
84
+ return None
85
+ m = re.search(r"[-+]?\d*\.?\d+", val)
86
+ return float(m.group()) if m else None
87
+
88
+ def convert_gender(x):
89
+ val = _extract_value(x).lower()
90
+ if val in ["male", "m"]:
91
+ return 1
92
+ if val in ["female", "f"]:
93
+ return 0
94
+ return None
95
+
96
+ # 3. Save Metadata (initial filtering)
97
+ is_trait_available = trait_row is not None
98
+ _ = validate_and_save_cohort_info(
99
+ is_final=False,
100
+ cohort=cohort,
101
+ info_path=json_path,
102
+ is_gene_available=is_gene_available,
103
+ is_trait_available=is_trait_available
104
+ )
105
+
106
+ # 4. Clinical Feature Extraction (only if trait available)
107
+ if trait_row is not None:
108
+ selected_clinical_df = geo_select_clinical_features(
109
+ clinical_df=clinical_data,
110
+ trait=trait,
111
+ trait_row=trait_row,
112
+ convert_trait=convert_trait,
113
+ age_row=age_row,
114
+ convert_age=None if age_row is None else convert_age,
115
+ gender_row=gender_row,
116
+ convert_gender=convert_gender
117
+ )
118
+ clinical_preview = preview_df(selected_clinical_df)
119
+ # Save clinical data
120
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
121
+ selected_clinical_df.to_csv(out_clinical_data_file)
122
+ print(clinical_preview)
123
+
124
+ # Step 3: Gene Data Extraction
125
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
126
+ gene_data = get_genetic_data(matrix_file)
127
+
128
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
129
+ print(gene_data.index[:20])
130
+
131
+ # Step 4: Gene Identifier Review
132
+ # The observed identifiers (e.g., 'AFFX-BkGr-GC03_st') are Affymetrix control/probeset IDs, not human gene symbols.
133
+ requires_gene_mapping = True
134
+ print(f"requires_gene_mapping = {requires_gene_mapping}")
135
+
136
+ # Step 5: Gene Annotation
137
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
138
+ gene_annotation = get_gene_annotation(soft_file)
139
+
140
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
141
+ print("Gene annotation preview:")
142
+ print(preview_df(gene_annotation))
143
+
144
+ # Step 6: Gene Identifier Mapping
145
+ # Decide columns for probe IDs and gene symbols in the annotation
146
+ id_col = 'probeset_id' if 'probeset_id' in gene_annotation.columns else 'ID'
147
+ if 'SPOT_ID.1' in gene_annotation.columns:
148
+ gene_col = 'SPOT_ID.1'
149
+ elif 'SPOT_ID' in gene_annotation.columns:
150
+ gene_col = 'SPOT_ID'
151
+ else:
152
+ # Fallback: if no obvious gene column, use the most descriptive text column available
153
+ # This is a safeguard; in this dataset SPOT_ID.1 exists per preview.
154
+ text_cols = [c for c in gene_annotation.columns if gene_annotation[c].dtype == object]
155
+ gene_col = text_cols[-1] if text_cols else id_col # worst case fallback
156
+
157
+ # 2. Build mapping dataframe
158
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=id_col, gene_col=gene_col)
159
+
160
+ # 3. Apply mapping to convert probe-level to gene-level expression
161
+ gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
162
+
163
+ # Step 7: Data Normalization and Linking
164
+ import os
165
+
166
+ # 1. Normalize gene symbols and save gene expression data
167
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
168
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
169
+ normalized_gene_data.to_csv(out_gene_data_file)
170
+
171
+ # 2. Link clinical and genetic data
172
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
173
+
174
+ # 3. Handle missing values
175
+ linked_data = handle_missing_values(linked_data, trait)
176
+
177
+ # 4. Assess bias and remove biased demographic features
178
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
179
+
180
+ # Compute availability flags for final validation
181
+ is_gene_available_final = (normalized_gene_data.shape[0] > 0) and (normalized_gene_data.shape[1] > 0)
182
+ is_trait_available_final = (trait in selected_clinical_df.index) and (not selected_clinical_df.loc[trait].isna().all())
183
+
184
+ note = (
185
+ "INFO: Trait derived from 'agent' field (presence of 'VitD' => 1, otherwise 0). "
186
+ "Age not provided; Gender parsed from 'Sex'. Randomized crossover design with two time points retained."
187
+ )
188
+
189
+ # 5. Final validation and save cohort metadata
190
+ is_usable = validate_and_save_cohort_info(
191
+ is_final=True,
192
+ cohort=cohort,
193
+ info_path=json_path,
194
+ is_gene_available=is_gene_available_final,
195
+ is_trait_available=is_trait_available_final,
196
+ is_biased=is_trait_biased,
197
+ df=unbiased_linked_data,
198
+ note=note
199
+ )
200
+
201
+ # 6. Save linked data if usable
202
+ if is_usable:
203
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
204
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Vitamin_D_Levels/code/GSE33544.py ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Vitamin_D_Levels"
6
+ cohort = "GSE33544"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Vitamin_D_Levels"
10
+ in_cohort_dir = "../DATA/GEO/Vitamin_D_Levels/GSE33544"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z6/preprocess/Vitamin_D_Levels/GSE33544.csv"
14
+ out_gene_data_file = "./output/z6/preprocess/Vitamin_D_Levels/gene_data/GSE33544.csv"
15
+ out_clinical_data_file = "./output/z6/preprocess/Vitamin_D_Levels/clinical_data/GSE33544.csv"
16
+ json_path = "./output/z6/preprocess/Vitamin_D_Levels/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 (based on series description: expression of light chain V genes)
42
+ is_gene_available = True
43
+
44
+ # 2) Variable availability (from provided Sample Characteristics Dictionary)
45
+ # Trait is Vitamin_D_Levels, which is not present in this dataset
46
+ trait_row = None
47
+ age_row = None
48
+ gender_row = None
49
+
50
+ # 2.2) Converters (defined for completeness; they won't be used since rows are None)
51
+ def _after_colon(x):
52
+ if x is None:
53
+ return None
54
+ s = str(x)
55
+ parts = s.split(":", 1)
56
+ return parts[1].strip() if len(parts) == 2 else s.strip()
57
+
58
+ def convert_trait(x):
59
+ # Expecting continuous vitamin D levels (e.g., "vitamin d: 25 ng/ml")
60
+ v = _after_colon(x)
61
+ if not v:
62
+ return None
63
+ # Extract first float-like token
64
+ m = re.search(r'[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?', v)
65
+ if m:
66
+ try:
67
+ return float(m.group(0))
68
+ except:
69
+ return None
70
+ # Map qualitative descriptors if ever encountered
71
+ low_map = {"deficient": 0.0, "insufficient": 0.0}
72
+ high_map = {"sufficient": 1.0, "normal": 1.0}
73
+ vl = v.lower()
74
+ if vl in low_map:
75
+ return low_map[vl]
76
+ if vl in high_map:
77
+ return high_map[vl]
78
+ return None
79
+
80
+ def convert_age(x):
81
+ # Continuous age in years
82
+ v = _after_colon(x)
83
+ if not v:
84
+ return None
85
+ m = re.search(r'[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?', v)
86
+ if m:
87
+ try:
88
+ return float(m.group(0))
89
+ except:
90
+ return None
91
+ return None
92
+
93
+ def convert_gender(x):
94
+ # Binary: female -> 0, male -> 1
95
+ v = _after_colon(x)
96
+ if not v:
97
+ return None
98
+ vl = v.strip().lower()
99
+ if vl in {"male", "m", "man", "boy"}:
100
+ return 1
101
+ if vl in {"female", "f", "woman", "girl"}:
102
+ return 0
103
+ return None
104
+
105
+ # 3) Save metadata (initial filtering)
106
+ is_trait_available = trait_row is not None
107
+ _ = validate_and_save_cohort_info(
108
+ is_final=False,
109
+ cohort=cohort,
110
+ info_path=json_path,
111
+ is_gene_available=is_gene_available,
112
+ is_trait_available=is_trait_available
113
+ )
114
+
115
+ # 4) Clinical feature extraction (skip because trait_row is None)
116
+ # If trait data were available, we would run:
117
+ # selected_clinical = geo_select_clinical_features(
118
+ # clinical_df=clinical_data,
119
+ # trait=trait,
120
+ # trait_row=trait_row,
121
+ # convert_trait=convert_trait,
122
+ # age_row=age_row,
123
+ # convert_age=convert_age,
124
+ # gender_row=gender_row,
125
+ # convert_gender=convert_gender
126
+ # )
127
+ # preview = preview_df(selected_clinical)
128
+ # os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
129
+ # selected_clinical.to_csv(out_clinical_data_file)
output/preprocess/Vitamin_D_Levels/code/GSE34450.py ADDED
@@ -0,0 +1,184 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Vitamin_D_Levels"
6
+ cohort = "GSE34450"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Vitamin_D_Levels"
10
+ in_cohort_dir = "../DATA/GEO/Vitamin_D_Levels/GSE34450"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z6/preprocess/Vitamin_D_Levels/GSE34450.csv"
14
+ out_gene_data_file = "./output/z6/preprocess/Vitamin_D_Levels/gene_data/GSE34450.csv"
15
+ out_clinical_data_file = "./output/z6/preprocess/Vitamin_D_Levels/clinical_data/GSE34450.csv"
16
+ json_path = "./output/z6/preprocess/Vitamin_D_Levels/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 (based on background: microarray gene expression study)
43
+ is_gene_available = True
44
+
45
+ # 2) Variable availability and conversion functions
46
+
47
+ # Trait (Vitamin D Levels) identified under "serum 25-oh-d" with categories in row 3
48
+ trait_row = 3
49
+
50
+ # Age and Gender not available in the provided characteristics
51
+ age_row = None
52
+ gender_row = None
53
+
54
+ def convert_trait(x):
55
+ if pd.isna(x):
56
+ return None
57
+ s = str(x)
58
+ parts = s.split(':', 1)
59
+ key = parts[0].strip().lower()
60
+ val = parts[1].strip().lower() if len(parts) == 2 else ''
61
+ # Only process if the key indicates serum 25-OH-D (vitamin D)
62
+ if 'serum 25-oh-d' in key:
63
+ if 'low' in val:
64
+ return 0
65
+ if 'high' in val:
66
+ return 1
67
+ if 'mid' in val or 'medium' in val:
68
+ return None
69
+ return None
70
+ return None
71
+
72
+ def convert_age(x):
73
+ # Not available for this cohort
74
+ return None
75
+
76
+ def convert_gender(x):
77
+ # Not available for this cohort
78
+ return None
79
+
80
+ # 3) Save initial metadata
81
+ is_trait_available = trait_row is not None
82
+ _ = validate_and_save_cohort_info(
83
+ is_final=False,
84
+ cohort=cohort,
85
+ info_path=json_path,
86
+ is_gene_available=is_gene_available,
87
+ is_trait_available=is_trait_available
88
+ )
89
+
90
+ # 4) Clinical feature extraction (only if trait_row is available)
91
+ if trait_row is not None:
92
+ selected_clinical_df = geo_select_clinical_features(
93
+ clinical_df=clinical_data,
94
+ trait=trait,
95
+ trait_row=trait_row,
96
+ convert_trait=convert_trait,
97
+ age_row=age_row,
98
+ convert_age=convert_age,
99
+ gender_row=gender_row,
100
+ convert_gender=convert_gender
101
+ )
102
+ clinical_preview = preview_df(selected_clinical_df, n=5)
103
+
104
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
105
+ selected_clinical_df.to_csv(out_clinical_data_file, index=True)
106
+
107
+ # Step 3: Gene Data Extraction
108
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
109
+ gene_data = get_genetic_data(matrix_file)
110
+
111
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
112
+ print(gene_data.index[:20])
113
+
114
+ # Step 4: Gene Identifier Review
115
+ requires_gene_mapping = True
116
+ print(f"requires_gene_mapping = {requires_gene_mapping}")
117
+
118
+ # Step 5: Gene Annotation
119
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
120
+ gene_annotation = get_gene_annotation(soft_file)
121
+
122
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
123
+ print("Gene annotation preview:")
124
+ print(preview_df(gene_annotation))
125
+
126
+ # Step 6: Gene Identifier Mapping
127
+ # Identify the annotation columns for probe IDs and gene symbols
128
+ probe_col = 'ID'
129
+ gene_symbol_col = 'Gene Symbol'
130
+
131
+ # Build mapping dataframe from annotation
132
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=probe_col, gene_col=gene_symbol_col)
133
+
134
+ # Apply mapping to convert probe-level data to gene-level expression
135
+ gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
136
+
137
+ # Step 7: Data Normalization and Linking
138
+ import os
139
+
140
+ # 1. Normalize gene symbols and save gene data
141
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
142
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
143
+ normalized_gene_data.to_csv(out_gene_data_file)
144
+
145
+ # 2. Link clinical and genetic data
146
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
147
+
148
+ # 3. Handle missing values
149
+ linked_data = handle_missing_values(linked_data, trait)
150
+
151
+ # 4. Assess bias and remove biased demographic features (guard against empty data after missing value handling)
152
+ if len(linked_data) > 0:
153
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
154
+ else:
155
+ is_trait_biased = True
156
+ unbiased_linked_data = linked_data # keep structure for validation
157
+
158
+ # 5. Final validation and metadata saving
159
+ # Cast to built-in bool to avoid numpy.bool_ serialization issues
160
+ is_gene_available_final = bool((normalized_gene_data.shape[0] > 0) and (normalized_gene_data.shape[1] > 0))
161
+ is_trait_available_final = bool((trait in unbiased_linked_data.columns) and bool(unbiased_linked_data[trait].notna().any()))
162
+ is_trait_biased = bool(is_trait_biased)
163
+
164
+ note = (
165
+ "INFO: Probe-level data mapped to gene-level and normalized using NCBI synonyms. "
166
+ "Samples with 'mid' vitamin D were treated as missing for the trait and removed during filtering. "
167
+ "Note: Series note indicates many samples lack processed data; effective sample size may be reduced."
168
+ )
169
+
170
+ is_usable = validate_and_save_cohort_info(
171
+ is_final=True,
172
+ cohort=cohort,
173
+ info_path=json_path,
174
+ is_gene_available=is_gene_available_final,
175
+ is_trait_available=is_trait_available_final,
176
+ is_biased=is_trait_biased,
177
+ df=unbiased_linked_data,
178
+ note=note
179
+ )
180
+
181
+ # 6. Save linked dataset only if usable
182
+ if is_usable:
183
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
184
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Vitamin_D_Levels/code/GSE35925.py ADDED
@@ -0,0 +1,215 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Vitamin_D_Levels"
6
+ cohort = "GSE35925"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Vitamin_D_Levels"
10
+ in_cohort_dir = "../DATA/GEO/Vitamin_D_Levels/GSE35925"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z6/preprocess/Vitamin_D_Levels/GSE35925.csv"
14
+ out_gene_data_file = "./output/z6/preprocess/Vitamin_D_Levels/gene_data/GSE35925.csv"
15
+ out_clinical_data_file = "./output/z6/preprocess/Vitamin_D_Levels/clinical_data/GSE35925.csv"
16
+ json_path = "./output/z6/preprocess/Vitamin_D_Levels/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
+ # Affymetrix U133 Plus 2.0 microarray -> mRNA gene expression data
45
+ is_gene_available = True
46
+
47
+ # 2) Variable availability based on Sample Characteristics Dictionary
48
+ # Provided dictionary:
49
+ # 0: ['gender: female'] -> constant; exclude
50
+ # 1: ['age: 66', 'age: 63', ...] -> available
51
+ # No explicit Vitamin D levels in characteristics -> not available
52
+ trait_row = None
53
+ age_row = 1
54
+ gender_row = None # constant 'female' only
55
+
56
+ # 2.2) Converters
57
+ def _extract_after_colon(value: str) -> str:
58
+ if value is None:
59
+ return ""
60
+ parts = str(value).split(":", 1)
61
+ return parts[1].strip() if len(parts) == 2 else str(value).strip()
62
+
63
+ def _extract_number(s: str):
64
+ if s is None:
65
+ return None
66
+ m = re.search(r'[-+]?\d*\.?\d+', str(s))
67
+ if not m:
68
+ return None
69
+ try:
70
+ num = float(m.group())
71
+ # Return int when it's an integer value
72
+ return int(num) if num.is_integer() else num
73
+ except Exception:
74
+ return None
75
+
76
+ # Trait: Vitamin D levels (expected continuous, e.g., ng/mL), but not available here.
77
+ def convert_trait(x):
78
+ val = _extract_after_colon(x)
79
+ # Extract numeric value if present (e.g., "28 ng/mL" -> 28)
80
+ return _extract_number(val)
81
+
82
+ # Age: continuous
83
+ def convert_age(x):
84
+ val = _extract_after_colon(x)
85
+ return _extract_number(val)
86
+
87
+ # Gender: binary female=0, male=1
88
+ def convert_gender(x):
89
+ val = _extract_after_colon(x).strip().lower()
90
+ if val in {"f", "female", "woman", "women"}:
91
+ return 0
92
+ if val in {"m", "male", "man", "men"}:
93
+ return 1
94
+ return None
95
+
96
+ # 3) Initial filtering and save metadata
97
+ is_trait_available = trait_row is not None
98
+ _ = validate_and_save_cohort_info(
99
+ is_final=False,
100
+ cohort=cohort,
101
+ info_path=json_path,
102
+ is_gene_available=is_gene_available,
103
+ is_trait_available=is_trait_available
104
+ )
105
+
106
+ # 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)
119
+ print(preview)
120
+
121
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
122
+ selected_clinical_df.to_csv(out_clinical_data_file)
123
+
124
+ # Step 3: Gene Data Extraction
125
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
126
+ gene_data = get_genetic_data(matrix_file)
127
+
128
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
129
+ print(gene_data.index[:20])
130
+
131
+ # Step 4: Gene Identifier Review
132
+ requires_gene_mapping = True
133
+ print(f"requires_gene_mapping = {requires_gene_mapping}")
134
+
135
+ # Step 5: Gene Annotation
136
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
137
+ gene_annotation = get_gene_annotation(soft_file)
138
+
139
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
140
+ print("Gene annotation preview:")
141
+ print(preview_df(gene_annotation))
142
+
143
+ # Step 6: Gene Identifier Mapping
144
+ # 1-2) Identify annotation columns and build mapping dataframe
145
+ id_col = 'ID' # Probe identifier column matches gene_data index like '1007_s_at'
146
+ gene_symbol_col = 'Gene Symbol' # Column containing gene symbols
147
+
148
+ gene_mapping = get_gene_mapping(gene_annotation, prob_col=id_col, gene_col=gene_symbol_col)
149
+
150
+ # 3) Apply mapping to convert probe-level data to gene-level expression
151
+ gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=gene_mapping)
152
+
153
+ # Step 7: Data Normalization and Linking
154
+ import os
155
+
156
+ # 1) Normalize gene symbols and save gene-level data
157
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
158
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
159
+ normalized_gene_data.to_csv(out_gene_data_file)
160
+
161
+ # Determine if trait is available from previous steps
162
+ has_trait = ('trait_row' in globals()) and (trait_row is not None)
163
+
164
+ if has_trait:
165
+ # Recompute clinical features to ensure availability in this step
166
+ selected_clinical_data = geo_select_clinical_features(
167
+ clinical_df=clinical_data,
168
+ trait=trait,
169
+ trait_row=trait_row,
170
+ convert_trait=convert_trait,
171
+ age_row=age_row if 'age_row' in globals() else None,
172
+ convert_age=convert_age if 'convert_age' in globals() else None,
173
+ gender_row=gender_row if 'gender_row' in globals() else None,
174
+ convert_gender=convert_gender if 'convert_gender' in globals() else None
175
+ )
176
+
177
+ # 2) Link clinical and genetic data
178
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_data, normalized_gene_data)
179
+
180
+ # 3) Handle missing values
181
+ linked_data = handle_missing_values(linked_data, trait)
182
+
183
+ # 4) Bias checks
184
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
185
+
186
+ # 5) Final validation and save cohort info
187
+ is_usable = validate_and_save_cohort_info(
188
+ is_final=True,
189
+ cohort=cohort,
190
+ info_path=json_path,
191
+ is_gene_available=True,
192
+ is_trait_available=True,
193
+ is_biased=is_trait_biased,
194
+ df=unbiased_linked_data,
195
+ note="INFO: Linked clinical and gene data with trait available."
196
+ )
197
+
198
+ # 6) Save usable linked data
199
+ if is_usable:
200
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
201
+ unbiased_linked_data.to_csv(out_data_file)
202
+
203
+ else:
204
+ # Trait not available: skip linking and downstream processing, but record metadata
205
+ note = f"INFO: Trait '{trait}' not available in clinical annotations; skipping linking. Only gene expression saved."
206
+ _ = validate_and_save_cohort_info(
207
+ is_final=True,
208
+ cohort=cohort,
209
+ info_path=json_path,
210
+ is_gene_available=True,
211
+ is_trait_available=False,
212
+ is_biased=False,
213
+ df=normalized_gene_data.T, # Use sample-oriented view for consistency
214
+ note=note
215
+ )
output/preprocess/Vitamin_D_Levels/code/GSE76324.py ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Vitamin_D_Levels"
6
+ cohort = "GSE76324"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Vitamin_D_Levels"
10
+ in_cohort_dir = "../DATA/GEO/Vitamin_D_Levels/GSE76324"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z6/preprocess/Vitamin_D_Levels/GSE76324.csv"
14
+ out_gene_data_file = "./output/z6/preprocess/Vitamin_D_Levels/gene_data/GSE76324.csv"
15
+ out_clinical_data_file = "./output/z6/preprocess/Vitamin_D_Levels/clinical_data/GSE76324.csv"
16
+ json_path = "./output/z6/preprocess/Vitamin_D_Levels/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ import os
40
+
41
+ # 1) Gene expression availability
42
+ is_gene_available = True # Microarray transcriptome study (mRNA), not miRNA/methylation
43
+
44
+ # 2) Variable availability and conversion
45
+
46
+ # From the provided Sample Characteristics Dictionary:
47
+ # Choose row 3 for trait because it contains only serum 25-oh-d categories (row 2 mixes smoking status and vitamin D).
48
+ trait_row = 3
49
+
50
+ # No explicit age or gender fields in the provided keys
51
+ age_row = None
52
+ gender_row = None
53
+
54
+ def _extract_value_after_colon(x):
55
+ if x is None:
56
+ return None
57
+ try:
58
+ s = str(x)
59
+ except Exception:
60
+ return None
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
+ # Map categorical vitamin D levels to a continuous scale: low=0.0, mid=0.5, high=1.0
67
+ val = _extract_value_after_colon(x)
68
+ if val is None:
69
+ return None
70
+ v = val.strip().lower()
71
+ if "low" in v:
72
+ return 0.0
73
+ if "mid" in v or "intermediate" in v or "medium" in v:
74
+ return 0.5
75
+ if "high" in v:
76
+ return 1.0
77
+ try:
78
+ num = float(v)
79
+ return num
80
+ except Exception:
81
+ return None
82
+
83
+ def convert_age(x):
84
+ # Not used (age_row is None); implemented for completeness
85
+ val = _extract_value_after_colon(x)
86
+ if val is None:
87
+ return None
88
+ v = val.lower()
89
+ import re
90
+ nums = re.findall(r"[-+]?\d*\.\d+|\d+", v)
91
+ if not nums:
92
+ return None
93
+ try:
94
+ age = float(nums[0])
95
+ if 0 <= age <= 120:
96
+ return age
97
+ return None
98
+ except Exception:
99
+ return None
100
+
101
+ def convert_gender(x):
102
+ # Not used (gender_row is None); implemented for completeness
103
+ val = _extract_value_after_colon(x)
104
+ if val is None:
105
+ return None
106
+ v = val.strip().lower()
107
+ if v in {"female", "f", "woman", "women"}:
108
+ return 0
109
+ if v in {"male", "m", "man", "men"}:
110
+ return 1
111
+ if "female" in v:
112
+ return 0
113
+ if "male" in v:
114
+ return 1
115
+ return None
116
+
117
+ # 3) Save metadata (initial filtering)
118
+ is_trait_available = trait_row is not None
119
+ _ = validate_and_save_cohort_info(
120
+ is_final=False,
121
+ cohort=cohort,
122
+ info_path=json_path,
123
+ is_gene_available=is_gene_available,
124
+ is_trait_available=is_trait_available
125
+ )
126
+
127
+ # 4) Clinical Feature Extraction (only if trait_row is available)
128
+ if trait_row is not None:
129
+ selected_clinical_df = geo_select_clinical_features(
130
+ clinical_df=clinical_data,
131
+ trait=trait,
132
+ trait_row=trait_row,
133
+ convert_trait=convert_trait,
134
+ age_row=age_row,
135
+ convert_age=convert_age,
136
+ gender_row=gender_row,
137
+ convert_gender=convert_gender
138
+ )
139
+ clinical_preview = preview_df(selected_clinical_df)
140
+ print(clinical_preview)
141
+ # Save clinical data
142
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
143
+ selected_clinical_df.to_csv(out_clinical_data_file)
144
+
145
+ # Step 3: Gene Data Extraction
146
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
147
+ gene_data = get_genetic_data(matrix_file)
148
+
149
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
150
+ print(gene_data.index[:20])
151
+
152
+ # Step 4: Gene Identifier Review
153
+ requires_gene_mapping = True
154
+ print(f"requires_gene_mapping = {requires_gene_mapping}")
155
+
156
+ # Step 5: Gene Annotation
157
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
158
+ gene_annotation = get_gene_annotation(soft_file)
159
+
160
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
161
+ print("Gene annotation preview:")
162
+ print(preview_df(gene_annotation))
163
+
164
+ # Step 6: Gene Identifier Mapping
165
+ # Determine appropriate columns for mapping: probe ID ('ID') and gene symbol ('Gene Symbol')
166
+ mapping_df = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='Gene Symbol')
167
+
168
+ # Apply the mapping to convert probe-level expression to gene-level expression
169
+ gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
170
+
171
+ # Step 7: Data Normalization and Linking
172
+ import os
173
+ import pandas as pd
174
+
175
+ # 1. Normalize and save gene data
176
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
177
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
178
+ normalized_gene_data.to_csv(out_gene_data_file)
179
+
180
+ # 2. Link the clinical and genetic data
181
+ if 'selected_clinical_df' not in globals():
182
+ selected_clinical_df = pd.read_csv(out_clinical_data_file, index_col=0)
183
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
184
+
185
+ # 3. Handle missing values
186
+ linked_data = handle_missing_values(linked_data, trait)
187
+
188
+ # 4. Bias assessment
189
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
190
+
191
+ # 5. Final validation and save metadata
192
+ is_gene_available = (normalized_gene_data.shape[0] > 0) and (normalized_gene_data.shape[1] > 0)
193
+ is_trait_available = trait in selected_clinical_df.index
194
+ note = "INFO: Trait derived from categorical serum 25-OH-D levels; Age/Gender not available in sample characteristics."
195
+ is_usable = validate_and_save_cohort_info(
196
+ True, cohort, json_path, is_gene_available, is_trait_available, is_trait_biased, unbiased_linked_data, note
197
+ )
198
+
199
+ # 6. Save linked data if usable
200
+ if is_usable:
201
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
202
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Vitamin_D_Levels/code/GSE86406.py ADDED
@@ -0,0 +1,249 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Vitamin_D_Levels"
6
+ cohort = "GSE86406"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Vitamin_D_Levels"
10
+ in_cohort_dir = "../DATA/GEO/Vitamin_D_Levels/GSE86406"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z6/preprocess/Vitamin_D_Levels/GSE86406.csv"
14
+ out_gene_data_file = "./output/z6/preprocess/Vitamin_D_Levels/gene_data/GSE86406.csv"
15
+ out_clinical_data_file = "./output/z6/preprocess/Vitamin_D_Levels/clinical_data/GSE86406.csv"
16
+ json_path = "./output/z6/preprocess/Vitamin_D_Levels/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) Determine data availability
43
+ is_gene_available = True # Microarray gene expression data described in the background
44
+ trait_row = None # No sample-level Vitamin D level data available in characteristics
45
+ age_row = 1 # 'age: ...'
46
+ gender_row = 2 # 'gender: ...'
47
+
48
+ # 2) Converters
49
+ def _after_colon(x: str) -> str:
50
+ if x is None:
51
+ return ""
52
+ if isinstance(x, str):
53
+ parts = x.split(":", 1)
54
+ return parts[1].strip() if len(parts) == 2 else x.strip()
55
+ return str(x)
56
+
57
+ def convert_trait(x):
58
+ # Not used since trait_row is None; provide a generic numeric extractor for robustness.
59
+ val = _after_colon(x).lower()
60
+ # Extract first numeric value if present (e.g., "35 ng/mL" -> 35.0)
61
+ m = re.search(r'-?\d+\.?\d*', val)
62
+ if m:
63
+ try:
64
+ return float(m.group())
65
+ except Exception:
66
+ return None
67
+ return None
68
+
69
+ def convert_age(x):
70
+ val = _after_colon(x)
71
+ m = re.search(r'-?\d+\.?\d*', val)
72
+ if m:
73
+ try:
74
+ return float(m.group())
75
+ except Exception:
76
+ return None
77
+ return None
78
+
79
+ def convert_gender(x):
80
+ val = _after_colon(x).strip().lower()
81
+ if val in {"m", "male", "man", "men"}:
82
+ return 1
83
+ if val in {"f", "female", "woman", "women"}:
84
+ return 0
85
+ return None
86
+
87
+ # 3) Save metadata (initial filtering)
88
+ is_trait_available = trait_row is not None
89
+ _ = validate_and_save_cohort_info(
90
+ is_final=False,
91
+ cohort=cohort,
92
+ info_path=json_path,
93
+ is_gene_available=is_gene_available,
94
+ is_trait_available=is_trait_available
95
+ )
96
+
97
+ # 4) Clinical feature extraction (skip because trait_row is None)
98
+ if trait_row is not None:
99
+ selected_clinical_df = geo_select_clinical_features(
100
+ clinical_df=clinical_data,
101
+ trait=trait,
102
+ trait_row=trait_row,
103
+ convert_trait=convert_trait,
104
+ age_row=age_row,
105
+ convert_age=convert_age,
106
+ gender_row=gender_row,
107
+ convert_gender=convert_gender
108
+ )
109
+ preview = preview_df(selected_clinical_df)
110
+ print(preview)
111
+
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
+ # The observed identifiers like '16650001', '16650003', etc., are numeric feature IDs (e.g., Agilent Feature Numbers),
124
+ # not human gene symbols. They require mapping to official gene symbols via platform annotations.
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 os
138
+ import json
139
+ import pandas as pd
140
+
141
+ # Try to use the platform (GPL) SOFT file for richer annotation; fall back to the earlier soft_file.
142
+ files = os.listdir(in_cohort_dir)
143
+ gpl_softs = [f for f in files if ('soft' in f.lower()) and ('gpl' in f.lower())]
144
+ soft_for_annotation = os.path.join(in_cohort_dir, gpl_softs[0]) if gpl_softs else soft_file
145
+
146
+ # Load annotation from the chosen SOFT
147
+ gene_annotation = get_gene_annotation(soft_for_annotation)
148
+
149
+ # 1) Decide probe ID column
150
+ probe_col_candidates = [
151
+ 'ID', 'ID_REF', 'PROBE_ID', 'ProbeName', 'PROBEID', 'Composite Element REF', 'CompositeElementID', 'SPOT_ID'
152
+ ]
153
+ probe_col = next((c for c in probe_col_candidates if c in gene_annotation.columns), None)
154
+ if probe_col is None:
155
+ raise ValueError(f"Probe/ID column not found in gene annotation. Available columns: {list(gene_annotation.columns)}")
156
+
157
+ # 2) Decide gene symbol column by testing contents with extract_human_gene_symbols
158
+ symbol_col_candidates_ordered = [
159
+ # highly preferred symbol columns
160
+ 'Gene Symbol', 'GENE_SYMBOL', 'GENE_SYMBOLS', 'Symbol', 'SYMBOL', 'Gene symbol', 'GENE SYMBOL',
161
+ 'GeneSymbols', 'GENE_SYMBOL (primary)',
162
+ # common fallbacks that often include symbols in mixed text
163
+ 'gene_assignment', 'GENE_ASSIGNMENT', 'Gene Assignment',
164
+ 'GENE_NAME', 'Gene Name', 'GENE TITLE', 'GENE_TITLE', 'DESCRIPTION', 'Description'
165
+ ]
166
+ existing_symbol_cols = [c for c in symbol_col_candidates_ordered if c in gene_annotation.columns]
167
+
168
+ def column_has_symbol_like(col_name: str, df, sample_n: int = 2000, min_fraction: float = 0.05) -> bool:
169
+ s = df[col_name].dropna().astype(str)
170
+ if s.empty:
171
+ return False
172
+ s = s.sample(min(len(s), sample_n), random_state=0) if len(s) > sample_n else s
173
+ hits = sum(1 for x in s if len(extract_human_gene_symbols(x)) > 0)
174
+ return (hits / len(s)) >= min_fraction
175
+
176
+ gene_col = None
177
+ for c in existing_symbol_cols:
178
+ if column_has_symbol_like(c, gene_annotation):
179
+ gene_col = c
180
+ break
181
+
182
+ mapping_performed = False
183
+ note = None
184
+
185
+ def try_apply_mapping_with_columns(annotation_df: pd.DataFrame, id_col: str, symbol_col: str) -> pd.DataFrame:
186
+ mapping_df_local = get_gene_mapping(annotation_df, prob_col=id_col, gene_col=symbol_col)
187
+ if mapping_df_local.shape[0] == 0:
188
+ return pd.DataFrame()
189
+ mapped_gene_df_local = apply_gene_mapping(gene_data, mapping_df_local)
190
+ return mapped_gene_df_local
191
+
192
+ mapped_gene_df = pd.DataFrame()
193
+
194
+ # First attempt: use a true symbol-like column if found
195
+ if gene_col is not None:
196
+ mapped_gene_df = try_apply_mapping_with_columns(gene_annotation, probe_col, gene_col)
197
+
198
+ # Fallback: attempt RefSeq accession -> symbol mapping if first attempt failed
199
+ def load_refseq_map() -> dict:
200
+ candidates = [
201
+ "./metadata/refseq_to_symbol.json",
202
+ "./metadata/refseq_to_symbol.tsv",
203
+ "./metadata/refseq2symbol.tsv",
204
+ "./metadata/refseq_symbol_map.tsv"
205
+ ]
206
+ for p in candidates:
207
+ if os.path.exists(p):
208
+ if p.endswith(".json"):
209
+ with open(p, "r") as f:
210
+ d = json.load(f)
211
+ return d
212
+ else:
213
+ try:
214
+ df_map = pd.read_csv(p, sep=None, engine='python', dtype=str)
215
+ except Exception:
216
+ df_map = pd.read_csv(p, sep='\t', dtype=str)
217
+ df_map.columns = [c.strip().lower() for c in df_map.columns]
218
+ # Heuristic: find refseq and symbol columns
219
+ ref_col = next((c for c in df_map.columns if 'refseq' in c or c in {'gb_acc', 'accession'}), None)
220
+ sym_col = next((c for c in df_map.columns if 'symbol' in c), None)
221
+ if ref_col and sym_col:
222
+ return dict(zip(df_map[ref_col].astype(str), df_map[sym_col].astype(str)))
223
+ return {}
224
+
225
+ if (mapped_gene_df.shape[0] == 0 or mapped_gene_df.shape[1] == 0):
226
+ if 'GB_ACC' in gene_annotation.columns:
227
+ refseq_map = load_refseq_map()
228
+ if refseq_map:
229
+ temp = gene_annotation[[probe_col, 'GB_ACC']].dropna().copy()
230
+ temp['Gene'] = temp['GB_ACC'].map(refseq_map)
231
+ temp = temp.dropna(subset=['Gene'])
232
+ if temp.shape[0] > 0:
233
+ # Build mapping_df in the expected format
234
+ mapping_df = temp.rename(columns={probe_col: 'ID'})[['ID', 'Gene']]
235
+ mapped_gene_df = apply_gene_mapping(gene_data, mapping_df)
236
+
237
+ # Finalize: replace gene_data only if mapping produced a valid matrix
238
+ if mapped_gene_df is not None and mapped_gene_df.shape[0] > 0 and mapped_gene_df.shape[1] > 0:
239
+ gene_data = mapped_gene_df
240
+ mapping_performed = True
241
+ print(f"Mapping succeeded using probe_col='{probe_col}' and "
242
+ f"gene_col='{gene_col if gene_col is not None else 'GB_ACC->Symbol (fallback)'}'. "
243
+ f"Gene-level matrix shape: {gene_data.shape}")
244
+ else:
245
+ note = ("WARNING: Gene symbol mapping could not be completed. "
246
+ "Keeping probe-level data for downstream steps.")
247
+ print(note)
248
+
249
+ print(f"mapping_performed = {mapping_performed}")
output/preprocess/Vitamin_D_Levels/code/TCGA.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Vitamin_D_Levels"
6
+
7
+ # Input paths
8
+ tcga_root_dir = "../DATA/TCGA"
9
+
10
+ # Output paths
11
+ out_data_file = "./output/z6/preprocess/Vitamin_D_Levels/TCGA.csv"
12
+ out_gene_data_file = "./output/z6/preprocess/Vitamin_D_Levels/gene_data/TCGA.csv"
13
+ out_clinical_data_file = "./output/z6/preprocess/Vitamin_D_Levels/clinical_data/TCGA.csv"
14
+ json_path = "./output/z6/preprocess/Vitamin_D_Levels/cohort_info.json"
15
+
16
+
17
+ # Step 1: Initial Data Loading
18
+ import os
19
+
20
+ # Step 1: Select the most relevant TCGA cohort directory for Vitamin D related phenotypes
21
+ subdirs = [d for d in os.listdir(tcga_root_dir) if os.path.isdir(os.path.join(tcga_root_dir, d))]
22
+
23
+ # Prioritized keywords related to Vitamin D
24
+ keywords = [
25
+ "vitamin d", "25-hydroxyvitamin d", "25(oh)d", "calcidiol", "calcitriol",
26
+ "cholecalciferol", "vit d", "vitamin_d", "vit_d"
27
+ ]
28
+
29
+ selected_dir = None
30
+ for kw in keywords:
31
+ for d in subdirs:
32
+ if kw in d.lower():
33
+ selected_dir = d
34
+ break
35
+ if selected_dir:
36
+ break
37
+
38
+ if not selected_dir:
39
+ # No suitable cohort found; mark as unavailable and skip
40
+ validate_and_save_cohort_info(
41
+ is_final=False,
42
+ cohort="TCGA",
43
+ info_path=json_path,
44
+ is_gene_available=False,
45
+ is_trait_available=False
46
+ )
47
+ clinical_df = None
48
+ genetic_df = None
49
+ print(f"No suitable TCGA cohort found for trait: {trait}. Skipping.")
50
+ else:
51
+ # Step 2: Identify clinical and genetic file paths
52
+ cohort_dir = os.path.join(tcga_root_dir, selected_dir)
53
+ clinical_file_path, genetic_file_path = tcga_get_relevant_filepaths(cohort_dir)
54
+
55
+ # Step 3: Load both files
56
+ clinical_df = pd.read_csv(clinical_file_path, sep='\t', index_col=0, low_memory=False)
57
+ genetic_df = pd.read_csv(genetic_file_path, sep='\t', index_col=0, low_memory=False)
58
+
59
+ # Step 4: Print clinical column names
60
+ print(clinical_df.columns.tolist())
output/preprocess/Vitamin_D_Levels/cohort_info.json CHANGED
@@ -1,72 +1 @@
1
- {
2
- "GSE86406": {
3
- "is_usable": false,
4
- "is_gene_available": true,
5
- "is_trait_available": false,
6
- "is_available": false,
7
- "is_biased": null,
8
- "has_age": null,
9
- "has_gender": null,
10
- "sample_size": null
11
- },
12
- "GSE35925": {
13
- "is_usable": false,
14
- "is_gene_available": true,
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
- "GSE34450": {
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": 132
31
- },
32
- "GSE33544": {
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
- "GSE123993": {
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": 44
51
- },
52
- "GSE118723": {
53
- "is_usable": false,
54
- "is_gene_available": true,
55
- "is_trait_available": false,
56
- "is_available": false,
57
- "is_biased": null,
58
- "has_age": null,
59
- "has_gender": null,
60
- "sample_size": null
61
- },
62
- "TCGA": {
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
- }
 
1
+ {"GSE86406": {"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}, "GSE76324": {"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": 19, "note": "INFO: Trait derived from categorical serum 25-OH-D levels; Age/Gender not available in sample characteristics."}, "GSE35925": {"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 'Vitamin_D_Levels' not available in clinical annotations; skipping linking. Only gene expression saved."}, "GSE34450": {"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": 6, "note": "INFO: Probe-level data mapped to gene-level and normalized using NCBI synonyms. Samples with 'mid' vitamin D were treated as missing for the trait and removed during filtering. Note: Series note indicates many samples lack processed data; effective sample size may be reduced."}, "GSE33544": {"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}, "GSE129604": {"is_usable": true, "is_gene_available": true, "is_trait_available": true, "is_available": true, "is_biased": false, "has_age": false, "has_gender": true, "sample_size": 141, "note": "INFO: Trait derived from 'agent' field (presence of 'VitD' => 1, otherwise 0). Age not provided; Gender parsed from 'Sex'. Randomized crossover design with two time points retained."}, "GSE123993": {"is_usable": false, "is_gene_available": true, "is_trait_available": false, "is_available": false, "is_biased": null, "has_age": null, "has_gender": null, "sample_size": null, "note": "WARNING: Trait not available; cannot link clinical and genetic data for this cohort."}, "GSE118723": {"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/Von_Hippel_Lindau/code/GSE33093.py ADDED
@@ -0,0 +1,213 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Von_Hippel_Lindau"
6
+ cohort = "GSE33093"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Von_Hippel_Lindau"
10
+ in_cohort_dir = "../DATA/GEO/Von_Hippel_Lindau/GSE33093"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z6/preprocess/Von_Hippel_Lindau/GSE33093.csv"
14
+ out_gene_data_file = "./output/z6/preprocess/Von_Hippel_Lindau/gene_data/GSE33093.csv"
15
+ out_clinical_data_file = "./output/z6/preprocess/Von_Hippel_Lindau/clinical_data/GSE33093.csv"
16
+ json_path = "./output/z6/preprocess/Von_Hippel_Lindau/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 information and characteristics
40
+ is_gene_available = True # Gene expression is indicated in the series title/summary; not miRNA/methylation-specific.
41
+
42
+ # No explicit VHL status, age, or gender in the provided sample characteristics dictionary.
43
+ trait_row = None
44
+ age_row = None
45
+ gender_row = None
46
+
47
+ # Converters
48
+ def _after_colon(x: str) -> str:
49
+ if x is None:
50
+ return None
51
+ if isinstance(x, str):
52
+ parts = x.split(":", 1)
53
+ val = parts[1] if len(parts) > 1 else parts[0]
54
+ return val.strip() if isinstance(val, str) else val
55
+ return x
56
+
57
+ def convert_trait(x):
58
+ # Binary: 1 = VHL mutated/inactivated/loss; 0 = VHL wild type; None = unknown
59
+ v = _after_colon(x)
60
+ if v is None:
61
+ return None
62
+ s = str(v).strip().lower()
63
+ if s in {"vhl wt", "vhl wild type", "wild type", "wt", "wild-type"}:
64
+ return 0
65
+ if any(tok in s for tok in ["mut", "mutation", "mutant", "inactivat", "loss", "deleted", "del", "loh"]):
66
+ return 1
67
+ if "vhl" in s:
68
+ # Heuristic: if mentions VHL without explicit WT keywords, treat as unknown
69
+ return None
70
+ return None
71
+
72
+ def convert_age(x):
73
+ # Continuous age in years
74
+ v = _after_colon(x)
75
+ if v is None:
76
+ return None
77
+ s = str(v).strip().lower().replace("years", "").replace("year", "").replace("yrs", "").replace("yr", "")
78
+ s = s.replace("yo", "").replace("y/o", "").strip()
79
+ try:
80
+ return float(s)
81
+ except:
82
+ # Extract first number if present
83
+ import re
84
+ m = re.search(r"(\d+(\.\d+)?)", s)
85
+ return float(m.group(1)) if m else None
86
+
87
+ def convert_gender(x):
88
+ # Binary: female -> 0, male -> 1
89
+ v = _after_colon(x)
90
+ if v is None:
91
+ return None
92
+ s = str(v).strip().lower()
93
+ if s in {"male", "m"}:
94
+ return 1
95
+ if s in {"female", "f"}:
96
+ return 0
97
+ return None
98
+
99
+ # Initial filtering and save cohort metadata
100
+ is_trait_available = trait_row is not None
101
+ _ = validate_and_save_cohort_info(
102
+ is_final=False,
103
+ cohort=cohort,
104
+ info_path=json_path,
105
+ is_gene_available=is_gene_available,
106
+ is_trait_available=is_trait_available
107
+ )
108
+
109
+ # Clinical feature extraction is skipped because trait_row is None (no clinical trait data available).
110
+
111
+ # Step 3: Gene Data Extraction
112
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
113
+ gene_data = get_genetic_data(matrix_file)
114
+
115
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
116
+ print(gene_data.index[:20])
117
+
118
+ # Step 4: Gene Identifier Review
119
+ requires_gene_mapping = True
120
+ print(f"requires_gene_mapping = {requires_gene_mapping}")
121
+
122
+ # Step 5: Gene Annotation
123
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
124
+ gene_annotation = get_gene_annotation(soft_file)
125
+
126
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
127
+ print("Gene annotation preview:")
128
+ print(preview_df(gene_annotation))
129
+
130
+ # Step 6: Gene Identifier Mapping
131
+ # Decide the appropriate columns for mapping based on previous previews
132
+ probe_id_col = 'ID' # Matches the probe identifiers in gene_data (e.g., '1', '2', ...)
133
+ gene_symbol_col = 'GENE_SYMBOL' # Column containing gene symbols
134
+
135
+ # 2. Build the mapping dataframe
136
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=probe_id_col, gene_col=gene_symbol_col)
137
+
138
+ # 3. Apply mapping to convert probe-level data to gene-level expression
139
+ gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
140
+
141
+ # Step 7: Data Normalization and Linking
142
+ import os
143
+
144
+ # 1. Normalize gene symbols and save gene-level data
145
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
146
+
147
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
148
+ normalized_gene_data.to_csv(out_gene_data_file)
149
+
150
+ # Determine availability flags based on earlier steps
151
+ is_gene_available = True
152
+ try:
153
+ is_trait_available = (trait_row is not None)
154
+ except NameError:
155
+ is_trait_available = False
156
+
157
+ if is_trait_available:
158
+ # Ensure clinical features are extracted if not already present
159
+ if 'selected_clinical_data' not in globals() and 'selected_clinical_data' not in locals():
160
+ selected_clinical_data = geo_select_clinical_features(
161
+ clinical_df=clinical_data,
162
+ trait=trait,
163
+ trait_row=trait_row,
164
+ convert_trait=convert_trait,
165
+ age_row=age_row,
166
+ convert_age=convert_age,
167
+ gender_row=gender_row,
168
+ convert_gender=convert_gender
169
+ )
170
+
171
+ # 2. Link clinical and genetic data
172
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_data, normalized_gene_data)
173
+
174
+ # 3. Handle missing values
175
+ linked_data = handle_missing_values(linked_data, trait)
176
+
177
+ # 4. Bias assessment (trait required to validate usability)
178
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
179
+
180
+ # 5. Final validation and cohort info saving
181
+ note = "INFO: Linked data generated with gene symbol normalization; clinical trait available."
182
+ is_usable = validate_and_save_cohort_info(
183
+ is_final=True,
184
+ cohort=cohort,
185
+ info_path=json_path,
186
+ is_gene_available=is_gene_available,
187
+ is_trait_available=is_trait_available,
188
+ is_biased=is_trait_biased,
189
+ df=unbiased_linked_data,
190
+ note=note
191
+ )
192
+
193
+ # 6. Save linked data only if usable
194
+ if is_usable:
195
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
196
+ unbiased_linked_data.to_csv(out_data_file)
197
+
198
+ else:
199
+ # No clinical trait available: skip linking and downstream steps
200
+ note = "INFO: Trait data not available in this cohort; only gene data were processed and saved."
201
+ # Provide a non-empty df to pass validation; it won't be considered available due to missing trait
202
+ placeholder_df = normalized_gene_data.T # samples x genes
203
+ _ = validate_and_save_cohort_info(
204
+ is_final=True,
205
+ cohort=cohort,
206
+ info_path=json_path,
207
+ is_gene_available=is_gene_available,
208
+ is_trait_available=False,
209
+ is_biased=False, # ignored because is_available will be False
210
+ df=placeholder_df,
211
+ note=note
212
+ )
213
+ # Do NOT save out_data_file since dataset is not usable without trait
output/preprocess/Von_Hippel_Lindau/code/TCGA.py ADDED
@@ -0,0 +1,272 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Von_Hippel_Lindau"
6
+
7
+ # Input paths
8
+ tcga_root_dir = "../DATA/TCGA"
9
+
10
+ # Output paths
11
+ out_data_file = "./output/z6/preprocess/Von_Hippel_Lindau/TCGA.csv"
12
+ out_gene_data_file = "./output/z6/preprocess/Von_Hippel_Lindau/gene_data/TCGA.csv"
13
+ out_clinical_data_file = "./output/z6/preprocess/Von_Hippel_Lindau/clinical_data/TCGA.csv"
14
+ json_path = "./output/z6/preprocess/Von_Hippel_Lindau/cohort_info.json"
15
+
16
+
17
+ # Step 1: Initial Data Loading
18
+ import os
19
+ import pandas as pd
20
+
21
+ # List available TCGA cohort subdirectories
22
+ subdirs = [d for d in os.listdir(tcga_root_dir) if os.path.isdir(os.path.join(tcga_root_dir, d))]
23
+
24
+ # Select the most relevant cohort for Von Hippel-Lindau (prioritize PCPG, then KIRC)
25
+ preferred_order = [
26
+ 'TCGA_Pheochromocytoma_Paraganglioma_(PCPG)',
27
+ 'TCGA_Kidney_Clear_Cell_Carcinoma_(KIRC)'
28
+ ]
29
+ selected_subdir = None
30
+ for name in preferred_order:
31
+ if name in subdirs:
32
+ selected_subdir = name
33
+ break
34
+
35
+ # Fallback: try to find by keyword if exact names not present
36
+ if selected_subdir is None:
37
+ for d in subdirs:
38
+ d_low = d.lower()
39
+ if ('pheochromocytoma' in d_low) or ('paraganglioma' in d_low) or ('kirc' in d_low) or ('kidney_clear_cell' in d_low):
40
+ selected_subdir = d
41
+ break
42
+
43
+ # If no suitable cohort found, record and exit
44
+ if selected_subdir is None:
45
+ validate_and_save_cohort_info(
46
+ is_final=False,
47
+ cohort='TCGA',
48
+ info_path=json_path,
49
+ is_gene_available=False,
50
+ is_trait_available=False
51
+ )
52
+ else:
53
+ cohort_dir = os.path.join(tcga_root_dir, selected_subdir)
54
+ clinical_path, genetic_path = tcga_get_relevant_filepaths(cohort_dir)
55
+
56
+ # Load dataframes
57
+ clinical_df = pd.read_csv(clinical_path, sep='\t', index_col=0, low_memory=False)
58
+ genetic_df = pd.read_csv(genetic_path, sep='\t', index_col=0, low_memory=False)
59
+
60
+ # Print clinical column names
61
+ print(list(clinical_df.columns))
62
+
63
+ # Step 2: Find Candidate Demographic Features
64
+ # Identify candidate demographic feature columns from the provided list
65
+ provided_columns = ['_INTEGRATION', '_PATIENT', '_cohort', '_primary_disease', '_primary_site', 'age_at_initial_pathologic_diagnosis', 'bcr_followup_barcode', 'bcr_patient_barcode', 'bcr_sample_barcode', 'ct_scan', 'days_to_birth', 'days_to_collection', 'days_to_death', 'days_to_initial_pathologic_diagnosis', 'days_to_last_followup', 'days_to_new_tumor_event_after_initial_treatment', 'disease_detected_on_screening', 'eastern_cancer_oncology_group', 'form_completion_date', 'gender', 'histological_type', 'history_of_neoadjuvant_treatment', 'history_pheo_or_para_anatomic_site', 'history_pheo_or_para_include_benign', 'icd_10', 'icd_o_3_histology', 'icd_o_3_site', 'informed_consent_verified', 'initial_weight', 'is_ffpe', 'karnofsky_performance_score', 'laterality', 'lost_follow_up', 'lymph_node_examined_count', 'new_neoplasm_confirmed_diagnosis_method_name', 'new_neoplasm_event_occurrence_anatomic_site', 'new_neoplasm_event_type', 'new_neoplasm_occurrence_anatomic_site_text', 'new_tumor_event_after_initial_treatment', 'number_of_lymphnodes_positive_by_he', 'oct_embedded', 'other_dx', 'outside_adrenal', 'pathology_report_file_name', 'patient_id', 'performance_status_scale_timing', 'person_neoplasm_cancer_status', 'postoperative_rx_tx', 'primary_lymph_node_presentation_assessment', 'primary_therapy_outcome_success', 'radiation_therapy', 'sample_type', 'sample_type_id', 'tissue_prospective_collection_indicator', 'tissue_retrospective_collection_indicator', 'tissue_source_site', 'tumor_tissue_site', 'tumor_tissue_site_other', 'vial_number', 'vital_status', 'year_of_initial_pathologic_diagnosis', '_GENOMIC_ID_TCGA_PCPG_exp_HiSeqV2_PANCAN', '_GENOMIC_ID_TCGA_PCPG_mutation_bcm_gene', '_GENOMIC_ID_TCGA_PCPG_mutation_broad_gene', '_GENOMIC_ID_TCGA_PCPG_hMethyl450', '_GENOMIC_ID_TCGA_PCPG_gistic2thd', '_GENOMIC_ID_TCGA_PCPG_exp_HiSeqV2', '_GENOMIC_ID_TCGA_PCPG_exp_HiSeqV2_exon', '_GENOMIC_ID_TCGA_PCPG_PDMRNAseqCNV', '_GENOMIC_ID_TCGA_PCPG_miRNA_HiSeq', '_GENOMIC_ID_data/public/TCGA/PCPG/miRNA_HiSeq_gene', '_GENOMIC_ID_TCGA_PCPG_mutation_bcgsc_gene', '_GENOMIC_ID_TCGA_PCPG_RPPA', '_GENOMIC_ID_TCGA_PCPG_mutation_ucsc_maf_gene', '_GENOMIC_ID_TCGA_PCPG_gistic2', '_GENOMIC_ID_TCGA_PCPG_PDMRNAseq', '_GENOMIC_ID_TCGA_PCPG_exp_HiSeqV2_percentile']
66
+
67
+ candidate_age_cols = [c for c in provided_columns if ('age' in c.lower()) or ('birth' in c.lower())]
68
+ candidate_gender_cols = [c for c in provided_columns if ('gender' in c.lower()) or ('sex' in c.lower())]
69
+
70
+ print(f"candidate_age_cols = {candidate_age_cols}")
71
+ print(f"candidate_gender_cols = {candidate_gender_cols}")
72
+
73
+ # Try to locate a clinical dataframe from previous steps
74
+ import pandas as pd
75
+
76
+ df_candidates = []
77
+ for var_name in ['clinical_df', 'clin_df', 'clinical_data', 'tcga_clinical_df', 'df_clinical']:
78
+ if var_name in globals() and isinstance(globals()[var_name], pd.DataFrame):
79
+ df_candidates.append(globals()[var_name])
80
+
81
+ if not df_candidates:
82
+ # Fallback: search any DataFrame in globals that has overlap with candidate columns
83
+ for name, obj in list(globals().items()):
84
+ if isinstance(obj, pd.DataFrame):
85
+ if any(col in obj.columns for col in (candidate_age_cols + candidate_gender_cols)):
86
+ df_candidates.append(obj)
87
+
88
+ clinical_df_to_use = df_candidates[0] if df_candidates else None
89
+
90
+ # Extract and preview candidate columns if clinical data is available
91
+ age_preview = {}
92
+ gender_preview = {}
93
+ if clinical_df_to_use is not None:
94
+ selected_age_cols = [c for c in candidate_age_cols if c in clinical_df_to_use.columns]
95
+ selected_gender_cols = [c for c in candidate_gender_cols if c in clinical_df_to_use.columns]
96
+ if selected_age_cols:
97
+ age_preview = preview_df(clinical_df_to_use[selected_age_cols], n=5)
98
+ if selected_gender_cols:
99
+ gender_preview = preview_df(clinical_df_to_use[selected_gender_cols], n=5)
100
+
101
+ print(f"age_preview = {age_preview}")
102
+ print(f"gender_preview = {gender_preview}")
103
+
104
+ # Step 3: Select Demographic Features
105
+ # Heuristic selection of age and gender columns from previews
106
+
107
+ def is_number(x):
108
+ try:
109
+ float(x)
110
+ return True
111
+ except Exception:
112
+ return False
113
+
114
+ def select_age_column(candidate_cols, preview_dict):
115
+ if not preview_dict or not candidate_cols:
116
+ return None
117
+
118
+ best_col = None
119
+ best_score = -1
120
+
121
+ for col in candidate_cols:
122
+ vals = preview_dict.get(col, [])
123
+ if not vals:
124
+ continue
125
+
126
+ # Clean numeric values
127
+ nums = [float(v) for v in vals if is_number(v)]
128
+
129
+ if not nums:
130
+ continue
131
+
132
+ # Compute scores
133
+ # age-like: values between 0 and 120
134
+ age_like = sum(0 <= v <= 120 for v in nums)
135
+
136
+ # days_to_birth-like: negative values with plausible range up to 120 years
137
+ days_like = sum((v < 0) and (abs(v) <= 120 * 365.25) for v in nums)
138
+
139
+ # Prefer explicit age columns when available
140
+ name_bonus = 1 if 'age' in col.lower() else 0
141
+
142
+ # Final scoring logic:
143
+ # - If column name indicates age, emphasize age_like
144
+ # - Otherwise, consider both patterns
145
+ score = age_like * 2 + days_like + name_bonus
146
+
147
+ if score > best_score:
148
+ best_score = score
149
+ best_col = col
150
+
151
+ return best_col
152
+
153
+ def select_gender_column(candidate_cols, preview_dict):
154
+ if not preview_dict or not candidate_cols:
155
+ return None
156
+
157
+ best_col = None
158
+ best_score = -1
159
+
160
+ valid_tokens = {'male', 'female', 'm', 'f'}
161
+ for col in candidate_cols:
162
+ vals = preview_dict.get(col, [])
163
+ if not vals:
164
+ continue
165
+ cleaned = [str(v).strip().lower() for v in vals if v is not None]
166
+ recognized = sum(v in valid_tokens for v in cleaned)
167
+ name_bonus = 1 if any(tok in col.lower() for tok in ['gender', 'sex']) else 0
168
+ score = recognized * 2 + name_bonus
169
+
170
+ if score > best_score:
171
+ best_score = score
172
+ best_col = col
173
+
174
+ return best_col
175
+
176
+ # Use previews from previous step
177
+ age_col = select_age_column(candidate_age_cols, age_preview) if 'age_preview' in globals() else None
178
+ gender_col = select_gender_column(candidate_gender_cols, gender_preview) if 'gender_preview' in globals() else None
179
+
180
+ # Fallbacks: ensure selected columns have meaningful preview values; else set to None
181
+ if age_col is not None:
182
+ vals = age_preview.get(age_col, [])
183
+ if not vals or all(v is None for v in vals):
184
+ age_col = None
185
+
186
+ if gender_col is not None:
187
+ vals = gender_preview.get(gender_col, [])
188
+ if not vals or all(v is None for v in vals):
189
+ gender_col = None
190
+
191
+ # Explicitly print chosen columns and their preview values
192
+ print("Chosen age_col:", age_col)
193
+ print("Age preview:", age_preview.get(age_col) if age_col else None)
194
+ print("Chosen gender_col:", gender_col)
195
+ print("Gender preview:", gender_preview.get(gender_col) if gender_col else None)
196
+
197
+ # Step 4: Feature Engineering and Validation
198
+ import os
199
+ import pandas as pd
200
+
201
+ # 1) Extract and standardize clinical features (trait, Age, Gender)
202
+ age_col_use = age_col if ('age_col' in globals() and isinstance(age_col, str) and age_col in clinical_df.columns) else None
203
+ gender_col_use = gender_col if ('gender_col' in globals() and isinstance(gender_col, str) and gender_col in clinical_df.columns) else None
204
+
205
+ selected_clinical_df = tcga_select_clinical_features(
206
+ clinical_df=clinical_df,
207
+ trait=trait,
208
+ age_col=age_col_use,
209
+ gender_col=gender_col_use
210
+ )
211
+
212
+ # 2) Normalize gene symbols and save normalized gene data
213
+ gene_df_norm = normalize_gene_symbols_in_index(genetic_df.copy())
214
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
215
+ gene_df_norm.to_csv(out_gene_data_file)
216
+
217
+ # 3) Link clinical and genetic data on sample IDs
218
+ linked_data = selected_clinical_df.join(gene_df_norm.T, how='inner')
219
+
220
+ # 4) Handle missing values systematically
221
+ processed_df = handle_missing_values(linked_data, trait_col=trait)
222
+
223
+ # 5) Determine trait/demographic bias and remove biased demographic features
224
+ trait_biased, processed_df = judge_and_remove_biased_features(processed_df, trait)
225
+
226
+ # 6) Final quality validation and save cohort info
227
+ # Ensure native Python bools
228
+ is_gene_available = bool(gene_df_norm.shape[0] > 0)
229
+ is_trait_available = bool((trait in processed_df.columns) and (processed_df[trait].notna().sum() > 0))
230
+ trait_biased_bool = bool(trait_biased)
231
+
232
+ genes_before = int(genetic_df.shape[0]) if isinstance(genetic_df, pd.DataFrame) else None
233
+ genes_after = int(gene_df_norm.shape[0])
234
+ note = (
235
+ f"INFO: Selected cohort TCGA. Trait from TCGA barcode; Age column='{age_col_use}'; "
236
+ f"Gender column='{gender_col_use}'. Genes normalized using NCBI synonyms; kept {genes_after} of {genes_before} rows."
237
+ )
238
+
239
+ # Defensive retry with explicit casting if JSON serialization fails
240
+ try:
241
+ is_usable = validate_and_save_cohort_info(
242
+ is_final=True,
243
+ cohort='TCGA',
244
+ info_path=json_path,
245
+ is_gene_available=is_gene_available,
246
+ is_trait_available=is_trait_available,
247
+ is_biased=trait_biased_bool,
248
+ df=processed_df,
249
+ note=note
250
+ )
251
+ except TypeError as e:
252
+ print(f"DEBUG: validate_and_save_cohort_info failed with {e}. Retrying after enforcing basic Python types.")
253
+ processed_df_retry = processed_df.copy()
254
+ processed_df_retry.columns = [str(c) for c in processed_df_retry.columns]
255
+ is_usable = validate_and_save_cohort_info(
256
+ is_final=True,
257
+ cohort='TCGA',
258
+ info_path=json_path,
259
+ is_gene_available=bool(is_gene_available),
260
+ is_trait_available=bool(is_trait_available),
261
+ is_biased=bool(trait_biased_bool),
262
+ df=processed_df_retry,
263
+ note=str(note)
264
+ )
265
+
266
+ # 7) Save linked data (and clinical data) if usable
267
+ if is_usable:
268
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
269
+ processed_df.to_csv(out_data_file)
270
+ # Optionally save the standardized clinical table
271
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
272
+ selected_clinical_df.to_csv(out_clinical_data_file)
output/preprocess/Von_Hippel_Lindau/cohort_info.json CHANGED
@@ -1,22 +1 @@
1
- {
2
- "GSE33093": {
3
- "is_usable": false,
4
- "is_gene_available": true,
5
- "is_trait_available": true,
6
- "is_available": true,
7
- "is_biased": true,
8
- "has_age": false,
9
- "has_gender": false,
10
- "sample_size": 44
11
- },
12
- "TCGA": {
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": 187
21
- }
22
- }
 
1
+ {"GSE33093": {"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 data not available in this cohort; only gene data were processed and saved."}, "TCGA": {"is_usable": false, "is_gene_available": true, "is_trait_available": true, "is_available": true, "is_biased": true, "has_age": true, "has_gender": true, "sample_size": 187, "note": "INFO: Selected cohort TCGA. Trait from TCGA barcode; Age column='age_at_initial_pathologic_diagnosis'; Gender column='gender'. Genes normalized using NCBI synonyms; kept 19848 of 20530 rows."}}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
output/preprocess/Von_Willebrand_Disease/clinical_data/GSE27597.csv CHANGED
@@ -1,4 +1,4 @@
1
- 0,1,2,3,4,5,6,7
2
- 0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0
3
- ,,,,,,,
4
- ,,,,1.0,,,
 
1
+ GSM684089,GSM684090,GSM684091,GSM684092,GSM684093,GSM684094,GSM684095,GSM684096,GSM684097,GSM684098,GSM684101,GSM684103,GSM684105,GSM684107,GSM684109,GSM684112,GSM684114,GSM684117,GSM684119,GSM684120,GSM684121,GSM684122,GSM684123,GSM684124,GSM684125,GSM684126,GSM684127,GSM684128,GSM684129,GSM684130,GSM684132,GSM684133,GSM684135,GSM684136,GSM684139,GSM684141,GSM684143,GSM684144,GSM684145,GSM684146,GSM684147,GSM684148,GSM684149,GSM684150,GSM684151,GSM684152,GSM684153,GSM684154,GSM684155,GSM684156,GSM684157,GSM684158,GSM684159,GSM684160,GSM684161,GSM684162,GSM684163,GSM684164,GSM684165,GSM684166,GSM684167,GSM684168,GSM684169,GSM684170
2
+ 0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,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
3
+ 62.0,62.0,62.0,62.0,62.0,62.0,62.0,62.0,61.0,61.0,61.0,61.0,61.0,61.0,61.0,61.0,63.0,63.0,63.0,63.0,63.0,63.0,63.0,63.0,56.0,56.0,56.0,56.0,56.0,56.0,56.0,56.0,55.0,55.0,55.0,55.0,55.0,55.0,55.0,55.0,59.0,59.0,59.0,59.0,59.0,59.0,59.0,59.0,59.0,59.0,59.0,59.0,59.0,59.0,59.0,59.0,62.0,62.0,62.0,62.0,62.0,62.0,62.0,62.0
4
+ 1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,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/Von_Willebrand_Disease/code/GSE27597.py ADDED
@@ -0,0 +1,181 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Von_Willebrand_Disease"
6
+ cohort = "GSE27597"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Von_Willebrand_Disease"
10
+ in_cohort_dir = "../DATA/GEO/Von_Willebrand_Disease/GSE27597"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z6/preprocess/Von_Willebrand_Disease/GSE27597.csv"
14
+ out_gene_data_file = "./output/z6/preprocess/Von_Willebrand_Disease/gene_data/GSE27597.csv"
15
+ out_clinical_data_file = "./output/z6/preprocess/Von_Willebrand_Disease/clinical_data/GSE27597.csv"
16
+ json_path = "./output/z6/preprocess/Von_Willebrand_Disease/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ import os
40
+ import re
41
+
42
+ # 1) Gene expression data availability
43
+ is_gene_available = True # Affymetrix Human Exon/Gene ST arrays indicate mRNA gene expression data
44
+
45
+ # 2) Variable availability and converters based on provided Sample Characteristics Dictionary
46
+ # Keys identified from the dictionary:
47
+ # 7 -> notes: contains 'von Willebrand disease' in some samples (usable for trait)
48
+ # 5 -> age
49
+ # 4 -> Sex
50
+
51
+ trait_row = 7
52
+ age_row = 5
53
+ gender_row = 4
54
+
55
+ def _after_colon(x: str) -> str:
56
+ if x is None:
57
+ return ""
58
+ parts = str(x).split(":", 1)
59
+ return parts[1].strip() if len(parts) > 1 else str(x).strip()
60
+
61
+ def convert_trait(x):
62
+ # Binary: 1 if notes mention von Willebrand disease, else 0
63
+ val = _after_colon(x).lower()
64
+ if val == "" or val in {"na", "n/a", "none", "unknown"}:
65
+ # If explicitly unknown/none, treat as absence (0) rather than missing, since 'none' is informative here.
66
+ return 0
67
+ return 1 if "von willebrand" in val else 0
68
+
69
+ def convert_age(x):
70
+ # Continuous: extract numeric age
71
+ val = _after_colon(x)
72
+ if val is None or val == "":
73
+ return None
74
+ m = re.search(r"[-+]?\d*\.?\d+", val)
75
+ if not m:
76
+ return None
77
+ try:
78
+ return float(m.group(0))
79
+ except Exception:
80
+ return None
81
+
82
+ def convert_gender(x):
83
+ # Binary: female -> 0, male -> 1
84
+ val = _after_colon(x).lower()
85
+ if val.startswith("m"):
86
+ return 1
87
+ if val.startswith("f"):
88
+ return 0
89
+ return None
90
+
91
+ # 3) Initial filtering metadata save
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
+ # 4) Clinical feature extraction (only if trait is available)
102
+ if is_trait_available:
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
+ clinical_preview = preview_df(selected_clinical_df)
114
+ print(clinical_preview)
115
+
116
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
117
+ selected_clinical_df.to_csv(out_clinical_data_file, index=False)
118
+
119
+ # Step 3: Gene Data Extraction
120
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
121
+ gene_data = get_genetic_data(matrix_file)
122
+
123
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
124
+ print(gene_data.index[:20])
125
+
126
+ # Step 4: Gene Identifier Review
127
+ # The observed identifiers are numeric probe IDs (e.g., Affymetrix probesets), not human gene symbols.
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
+ # 1-2. Decide identifier and gene symbol columns and build mapping dataframe
141
+ # Probe identifier column: 'ID' matches the probe IDs in the expression data
142
+ # Gene symbol information column: 'gene_assignment' (contains gene symbols within annotation text)
143
+ mapping_df = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='gene_assignment')
144
+
145
+ # 3. Apply mapping to convert probe-level data to gene-level expression
146
+ gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
147
+
148
+ # Step 7: Data Normalization and Linking
149
+ import os
150
+
151
+ # 1. Normalize gene symbols and save the normalized gene expression data
152
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
153
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
154
+ normalized_gene_data.to_csv(out_gene_data_file)
155
+
156
+ # 2. Link the clinical and genetic data
157
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
158
+
159
+ # 3. Handle missing values systematically
160
+ linked_data = handle_missing_values(linked_data, trait)
161
+
162
+ # 4. Assess bias and remove biased demographic features if necessary
163
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
164
+
165
+ # 5. Final validation and save cohort metadata
166
+ note = "INFO: Trait inferred from 'notes'; highly imbalanced across samples."
167
+ is_usable = validate_and_save_cohort_info(
168
+ is_final=True,
169
+ cohort=cohort,
170
+ info_path=json_path,
171
+ is_gene_available=True,
172
+ is_trait_available=True,
173
+ is_biased=is_trait_biased,
174
+ df=unbiased_linked_data,
175
+ note=note
176
+ )
177
+
178
+ # 6. Save the linked data if usable
179
+ if is_usable:
180
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
181
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Von_Willebrand_Disease/code/TCGA.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Von_Willebrand_Disease"
6
+
7
+ # Input paths
8
+ tcga_root_dir = "../DATA/TCGA"
9
+
10
+ # Output paths
11
+ out_data_file = "./output/z6/preprocess/Von_Willebrand_Disease/TCGA.csv"
12
+ out_gene_data_file = "./output/z6/preprocess/Von_Willebrand_Disease/gene_data/TCGA.csv"
13
+ out_clinical_data_file = "./output/z6/preprocess/Von_Willebrand_Disease/clinical_data/TCGA.csv"
14
+ json_path = "./output/z6/preprocess/Von_Willebrand_Disease/cohort_info.json"
15
+
16
+
17
+ # Step 1: Initial Data Loading
18
+ import os
19
+ import re
20
+ import pandas as pd
21
+
22
+ # Step 1: Identify the most relevant TCGA cohort directory for Von Willebrand Disease (VWD)
23
+ dirs = sorted([d for d in os.listdir(tcga_root_dir) if os.path.isdir(os.path.join(tcga_root_dir, d))])
24
+
25
+ trait_lower = trait.lower()
26
+ # Heuristic keyword set for VWD and related hemostasis/bleeding disorders
27
+ keywords = [
28
+ "von", "willebrand", "vwd", "bleed", "coagul", "hemost", "platelet", "thrombo", "hemorr"
29
+ ]
30
+
31
+ def score_dir(name: str, kws):
32
+ name_l = name.lower()
33
+ return sum(1 for k in kws if k in name_l)
34
+
35
+ scored = [(d, score_dir(d, keywords)) for d in dirs]
36
+ # Select directory with highest score (>0), prefer most specific (highest score), else None
37
+ scored_sorted = sorted(scored, key=lambda x: (-x[1], len(x[0])))
38
+ selected_dir = scored_sorted[0][0] if scored_sorted and scored_sorted[0][1] > 0 else None
39
+
40
+ if selected_dir is None:
41
+ print("No suitable TCGA cohort found for Von Willebrand Disease; skipping TCGA for this trait.")
42
+ # Record unavailability in cohort metadata
43
+ validate_and_save_cohort_info(
44
+ is_final=False,
45
+ cohort="TCGA",
46
+ info_path=json_path,
47
+ is_gene_available=False,
48
+ is_trait_available=False
49
+ )
50
+ else:
51
+ cohort_dir = os.path.join(tcga_root_dir, selected_dir)
52
+ print(f"Selected cohort directory: {selected_dir}")
53
+
54
+ # Step 2: Identify clinicalMatrix and PANCAN file paths
55
+ clinical_file_path, genetic_file_path = tcga_get_relevant_filepaths(cohort_dir)
56
+ print(f"Clinical file: {os.path.basename(clinical_file_path)}")
57
+ print(f"Genetic file: {os.path.basename(genetic_file_path)}")
58
+
59
+ # Step 3: Load both files as DataFrames
60
+ clinical_df = pd.read_csv(clinical_file_path, sep='\t', index_col=0, low_memory=False)
61
+ genetic_df = pd.read_csv(genetic_file_path, sep='\t', index_col=0, low_memory=False)
62
+
63
+ # Step 4: Print clinical column names
64
+ print("Clinical data columns:")
65
+ print(list(clinical_df.columns))