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

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/Testicular_Cancer/code/GSE42647.py +130 -0
  2. output/preprocess/Testicular_Cancer/code/GSE62523.py +197 -0
  3. output/preprocess/Testicular_Cancer/code/TCGA.py +250 -0
  4. output/preprocess/Testicular_Cancer/cohort_info.json +1 -32
  5. output/preprocess/Thymoma/clinical_data/GSE131027.csv +1 -1
  6. output/preprocess/Thymoma/clinical_data/TCGA.csv +127 -0
  7. output/preprocess/Thymoma/code/GSE131027.py +171 -0
  8. output/preprocess/Thymoma/code/GSE29695.py +190 -0
  9. output/preprocess/Thymoma/code/GSE42977.py +252 -0
  10. output/preprocess/Thymoma/code/TCGA.py +424 -0
  11. output/preprocess/Thymoma/cohort_info.json +1 -42
  12. output/preprocess/Thyroid_Cancer/GSE138198.csv +0 -0
  13. output/preprocess/Thyroid_Cancer/GSE58689.csv +0 -0
  14. output/preprocess/Thyroid_Cancer/clinical_data/GSE104006.csv +4 -0
  15. output/preprocess/Thyroid_Cancer/clinical_data/GSE107754.csv +1 -1
  16. output/preprocess/Thyroid_Cancer/clinical_data/GSE138198.csv +1 -1
  17. output/preprocess/Thyroid_Cancer/clinical_data/GSE151179.csv +2 -3
  18. output/preprocess/Thyroid_Cancer/clinical_data/GSE151181.csv +2 -2
  19. output/preprocess/Thyroid_Cancer/clinical_data/GSE58689.csv +2 -1
  20. output/preprocess/Thyroid_Cancer/clinical_data/GSE80022.csv +1 -3
  21. output/preprocess/Thyroid_Cancer/code/GSE104005.py +197 -0
  22. output/preprocess/Thyroid_Cancer/code/GSE104006.py +262 -0
  23. output/preprocess/Thyroid_Cancer/code/GSE107754.py +200 -0
  24. output/preprocess/Thyroid_Cancer/code/GSE138198.py +207 -0
  25. output/preprocess/Thyroid_Cancer/code/GSE151179.py +316 -0
  26. output/preprocess/Thyroid_Cancer/code/GSE151181.py +251 -0
  27. output/preprocess/Thyroid_Cancer/code/GSE58689.py +187 -0
  28. output/preprocess/Thyroid_Cancer/code/GSE76039.py +182 -0
  29. output/preprocess/Thyroid_Cancer/code/GSE80022.py +190 -0
  30. output/preprocess/Thyroid_Cancer/code/GSE82208.py +226 -0
  31. output/preprocess/Thyroid_Cancer/code/TCGA.py +310 -0
  32. output/preprocess/Thyroid_Cancer/cohort_info.json +1 -102
  33. output/preprocess/Thyroid_Cancer/gene_data/GSE151181.csv +1 -0
  34. output/preprocess/Type_1_Diabetes/clinical_data/GSE123086.csv +4 -0
  35. output/preprocess/Type_1_Diabetes/clinical_data/GSE123088.csv +3 -1
  36. output/preprocess/Type_1_Diabetes/clinical_data/GSE156035.csv +3 -3
  37. output/preprocess/Type_1_Diabetes/clinical_data/GSE182870.csv +0 -0
  38. output/preprocess/Type_1_Diabetes/clinical_data/GSE193273.csv +2 -2
  39. output/preprocess/Type_1_Diabetes/code/GSE123086.py +322 -0
  40. output/preprocess/Type_1_Diabetes/code/GSE123088.py +303 -0
  41. output/preprocess/Type_1_Diabetes/code/GSE131528.py +204 -0
  42. output/preprocess/Type_1_Diabetes/code/GSE156035.py +197 -0
  43. output/preprocess/Type_1_Diabetes/code/GSE162622.py +108 -0
  44. output/preprocess/Type_1_Diabetes/code/GSE182870.py +211 -0
  45. output/preprocess/Type_1_Diabetes/code/GSE193273.py +193 -0
  46. output/preprocess/Type_1_Diabetes/code/GSE232310.py +155 -0
  47. output/preprocess/Type_1_Diabetes/code/GSE71799.py +133 -0
  48. output/preprocess/Type_1_Diabetes/code/GSE75062.py +158 -0
  49. output/preprocess/Type_1_Diabetes/code/TCGA.py +78 -0
  50. output/preprocess/Type_1_Diabetes/cohort_info.json +1 -112
output/preprocess/Testicular_Cancer/code/GSE42647.py ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Testicular_Cancer"
6
+ cohort = "GSE42647"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Testicular_Cancer"
10
+ in_cohort_dir = "../DATA/GEO/Testicular_Cancer/GSE42647"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z6/preprocess/Testicular_Cancer/GSE42647.csv"
14
+ out_gene_data_file = "./output/z6/preprocess/Testicular_Cancer/gene_data/GSE42647.csv"
15
+ out_clinical_data_file = "./output/z6/preprocess/Testicular_Cancer/clinical_data/GSE42647.csv"
16
+ json_path = "./output/z6/preprocess/Testicular_Cancer/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ import re
40
+
41
+ # 1) Gene expression data availability (SuperSeries likely includes expression data; not miRNA-only)
42
+ is_gene_available = True
43
+
44
+ # 2) Variable availability from Sample Characteristics Dictionary:
45
+ # Given the dictionary shows constant cell line info and cell type for all samples (cell line dataset),
46
+ # there is no varying human trait/age/gender information useful for association analysis.
47
+ trait_row = None
48
+ age_row = None
49
+ gender_row = None
50
+
51
+ # 2.2) Converters
52
+
53
+ def _after_colon(x: str) -> str:
54
+ if x is None:
55
+ return None
56
+ if not isinstance(x, str):
57
+ x = str(x)
58
+ parts = x.split(":", 1)
59
+ val = parts[1] if len(parts) > 1 else parts[0]
60
+ return val.strip().strip('"').strip()
61
+
62
+ def convert_trait(x):
63
+ v = _after_colon(x)
64
+ if v is None or v == "" or v.lower() in {"na", "n/a", "null", "none", "unknown"}:
65
+ return None
66
+ vl = v.lower()
67
+ # Heuristics: presence of cancer terms => 1; explicit normal/control => 0
68
+ cancer_terms = ["cancer", "carcinoma", "tumor", "tumour", "neoplasm", "malignant", "nt2/d1", "embryonal"]
69
+ normal_terms = ["normal", "control", "healthy", "non-cancer", "noncancer", "adjacent normal"]
70
+ if any(t in vl for t in cancer_terms):
71
+ return 1
72
+ if any(t in vl for t in normal_terms):
73
+ return 0
74
+ return None
75
+
76
+ def convert_age(x):
77
+ v = _after_colon(x)
78
+ if v is None or v == "" or v.lower() in {"na", "n/a", "null", "none", "unknown"}:
79
+ return None
80
+ # Extract a plausible age number
81
+ nums = re.findall(r"\d+\.?\d*", v)
82
+ if not nums:
83
+ return None
84
+ try:
85
+ age = float(nums[0])
86
+ except:
87
+ return None
88
+ # Basic plausibility for human age
89
+ if 0 <= age <= 120:
90
+ return age
91
+ return None
92
+
93
+ def convert_gender(x):
94
+ v = _after_colon(x)
95
+ if v is None or v == "" or v.lower() in {"na", "n/a", "null", "none", "unknown"}:
96
+ return None
97
+ vl = v.lower()
98
+ # map female -> 0, male -> 1
99
+ if any(tok in vl for tok in ["female", "f", "woman", "women", "girl"]):
100
+ return 0
101
+ if any(tok in vl for tok in ["male", "m", "man", "men", "boy"]):
102
+ return 1
103
+ return None
104
+
105
+ # 3) Save metadata (initial filtering)
106
+ is_trait_available = trait_row is not None
107
+ _ = validate_and_save_cohort_info(
108
+ is_final=False,
109
+ cohort=cohort,
110
+ info_path=json_path,
111
+ is_gene_available=is_gene_available,
112
+ is_trait_available=is_trait_available
113
+ )
114
+
115
+ # 4) Clinical Feature Extraction (skip because trait_row is None)
116
+ # If trait_row were 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_df(selected)
129
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
130
+ selected.to_csv(out_clinical_data_file, index=True)
output/preprocess/Testicular_Cancer/code/GSE62523.py ADDED
@@ -0,0 +1,197 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Testicular_Cancer"
6
+ cohort = "GSE62523"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Testicular_Cancer"
10
+ in_cohort_dir = "../DATA/GEO/Testicular_Cancer/GSE62523"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z6/preprocess/Testicular_Cancer/GSE62523.csv"
14
+ out_gene_data_file = "./output/z6/preprocess/Testicular_Cancer/gene_data/GSE62523.csv"
15
+ out_clinical_data_file = "./output/z6/preprocess/Testicular_Cancer/clinical_data/GSE62523.csv"
16
+ json_path = "./output/z6/preprocess/Testicular_Cancer/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ # 1) Gene Expression Data Availability
40
+ is_gene_available = True # 18k cDNA microarray gene expression in HMEC-1 cells
41
+
42
+ # 2) Variable Availability and Data Type Conversion
43
+ # No human subject-level clinical data (cell line experiment), hence not available
44
+ trait_row = None
45
+ age_row = None
46
+ gender_row = None
47
+
48
+ # Define converters per spec (not used since corresponding rows are None)
49
+ def convert_trait(x):
50
+ # Trait is Testicular_Cancer; not applicable in HMEC-1 cell line experiment
51
+ return None
52
+
53
+ def convert_age(x):
54
+ # No age data in this series
55
+ return None
56
+
57
+ def convert_gender(x):
58
+ # No gender data in this series
59
+ return None
60
+
61
+ # 3) Save Metadata (initial filtering)
62
+ is_trait_available = trait_row is not None
63
+ _ = validate_and_save_cohort_info(
64
+ is_final=False,
65
+ cohort=cohort,
66
+ info_path=json_path,
67
+ is_gene_available=is_gene_available,
68
+ is_trait_available=is_trait_available
69
+ )
70
+
71
+ # 4) Clinical Feature Extraction
72
+ # Skipped because trait_row is None (no clinical trait data available)
73
+
74
+ # Step 3: Gene Data Extraction
75
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
76
+ gene_data = get_genetic_data(matrix_file)
77
+
78
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
79
+ print(gene_data.index[:20])
80
+
81
+ # Step 4: Gene Identifier Review
82
+ # The observed identifiers (e.g., '1.1.1.1') are Enzyme Commission (EC) numbers, not human gene symbols.
83
+ print("requires_gene_mapping = True")
84
+
85
+ # Step 5: Gene Annotation
86
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
87
+ gene_annotation = get_gene_annotation(soft_file)
88
+
89
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
90
+ print("Gene annotation preview:")
91
+ print(preview_df(gene_annotation))
92
+
93
+ # Step 6: Gene Identifier Mapping
94
+ # Identify the probe ID column and the gene symbol column in the annotation
95
+ probe_col = 'ID'
96
+ gene_symbol_col = 'Gene symbol'
97
+
98
+ # Build mapping dataframe from probe IDs to gene symbols
99
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=probe_col, gene_col=gene_symbol_col)
100
+
101
+ # Apply mapping to convert probe-level data to gene-level expression
102
+ gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
103
+
104
+ # Step 7: Data Normalization and Linking
105
+ # Ensure probe-mapped gene_data exists; if not, rebuild from available artifacts
106
+ if 'gene_data' not in locals() or gene_data is None or getattr(gene_data, 'empty', True):
107
+ if 'matrix_file' in locals():
108
+ expr_df = get_genetic_data(matrix_file)
109
+ else:
110
+ raise RuntimeError("matrix_file not found; cannot rebuild expression data.")
111
+ # Ensure mapping is available
112
+ if 'mapping_df' not in locals() or mapping_df is None or getattr(mapping_df, 'empty', True):
113
+ if 'gene_annotation' not in locals() or gene_annotation is None or getattr(gene_annotation, 'empty', True):
114
+ if 'soft_file' in locals():
115
+ gene_annotation = get_gene_annotation(soft_file)
116
+ else:
117
+ raise RuntimeError("soft_file not found; cannot rebuild gene annotation/mapping.")
118
+ mapping_df = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='Gene symbol')
119
+ gene_data = apply_gene_mapping(expression_df=expr_df, mapping_df=mapping_df)
120
+
121
+ # 1) Normalize gene symbols and save gene expression data
122
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
123
+ normalized_gene_data.to_csv(out_gene_data_file)
124
+
125
+ # Determine if clinical/trait data are available
126
+ is_trait_available = False
127
+ if 'trait_row' in locals() and trait_row is not None:
128
+ is_trait_available = True
129
+ elif 'selected_clinical_data' in locals():
130
+ is_trait_available = True
131
+
132
+ # 2-6) Conditional pipeline: only if trait/clinical data available
133
+ if is_trait_available:
134
+ # If selected_clinical_data is not prepared yet but rows/functions exist, try to build it
135
+ if 'selected_clinical_data' not in locals():
136
+ if 'clinical_data' in locals() and 'trait_row' in locals() and trait_row is not None and \
137
+ 'convert_trait' in locals():
138
+ # Optional covariates if available
139
+ age_r = age_row if ('age_row' in locals()) else None
140
+ gen_r = gender_row if ('gender_row' in locals()) else None
141
+ conv_age = convert_age if ('convert_age' in locals()) else None
142
+ conv_gen = convert_gender if ('convert_gender' in locals()) else None
143
+ selected_clinical_data = geo_select_clinical_features(
144
+ clinical_df=clinical_data,
145
+ trait=trait,
146
+ trait_row=trait_row,
147
+ convert_trait=convert_trait,
148
+ age_row=age_r,
149
+ convert_age=conv_age,
150
+ gender_row=gen_r,
151
+ convert_gender=conv_gen
152
+ )
153
+ else:
154
+ # Cannot construct clinical data despite is_trait_available being True; fallback to initial filtering
155
+ _ = validate_and_save_cohort_info(
156
+ is_final=False,
157
+ cohort=cohort,
158
+ info_path=json_path,
159
+ is_gene_available=True,
160
+ is_trait_available=False
161
+ )
162
+ raise RuntimeError("Trait/clinical data flagged available but cannot be constructed. Recorded metadata and aborting.")
163
+
164
+ # 2) Link clinical and genetic data
165
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_data, normalized_gene_data)
166
+
167
+ # 3) Missing value handling
168
+ linked_data = handle_missing_values(linked_data, trait)
169
+
170
+ # 4) Bias assessment (and removal of biased demographics)
171
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
172
+
173
+ # 5) Final validation and metadata saving
174
+ is_usable = validate_and_save_cohort_info(
175
+ is_final=True,
176
+ cohort=cohort,
177
+ info_path=json_path,
178
+ is_gene_available=True,
179
+ is_trait_available=True,
180
+ is_biased=is_trait_biased,
181
+ df=unbiased_linked_data,
182
+ note="INFO: Linked dataset processed with standard QC."
183
+ )
184
+
185
+ # 6) Save linked data if usable
186
+ if is_usable:
187
+ unbiased_linked_data.to_csv(out_data_file)
188
+ else:
189
+ # No human subject-level trait data (cell line experiment); skip linking and final validation.
190
+ print("No clinical trait data available (cell-line experiment). Skipping linking/QC; saving gene data only.")
191
+ _ = validate_and_save_cohort_info(
192
+ is_final=False,
193
+ cohort=cohort,
194
+ info_path=json_path,
195
+ is_gene_available=True,
196
+ is_trait_available=False
197
+ )
output/preprocess/Testicular_Cancer/code/TCGA.py ADDED
@@ -0,0 +1,250 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Testicular_Cancer"
6
+
7
+ # Input paths
8
+ tcga_root_dir = "../DATA/TCGA"
9
+
10
+ # Output paths
11
+ out_data_file = "./output/z6/preprocess/Testicular_Cancer/TCGA.csv"
12
+ out_gene_data_file = "./output/z6/preprocess/Testicular_Cancer/gene_data/TCGA.csv"
13
+ out_clinical_data_file = "./output/z6/preprocess/Testicular_Cancer/clinical_data/TCGA.csv"
14
+ json_path = "./output/z6/preprocess/Testicular_Cancer/cohort_info.json"
15
+
16
+
17
+ # Step 1: Initial Data Loading
18
+ import os
19
+ import pandas as pd
20
+
21
+ # Step 1: Select the most relevant TCGA cohort directory for the trait
22
+ subdirs = [d for d in os.listdir(tcga_root_dir) if os.path.isdir(os.path.join(tcga_root_dir, d))]
23
+ priority_keywords = [
24
+ 'testicular',
25
+ '(tgct',
26
+ 'tgct',
27
+ 'testis',
28
+ ]
29
+
30
+ selected_dir = None
31
+ lname_map = {d: d.lower() for d in subdirs}
32
+ for kw in priority_keywords:
33
+ matches = [d for d, ld in lname_map.items() if kw in ld]
34
+ if matches:
35
+ # Choose the most specific (longest name) to bias towards explicit matches
36
+ selected_dir = sorted(matches, key=len, reverse=True)[0]
37
+ break
38
+
39
+ if selected_dir is None:
40
+ # No suitable directory found; record and stop
41
+ _ = validate_and_save_cohort_info(
42
+ is_final=False,
43
+ cohort="TCGA",
44
+ info_path=json_path,
45
+ is_gene_available=False,
46
+ is_trait_available=False
47
+ )
48
+ print("No suitable TCGA cohort directory found for the trait. Skipping.")
49
+ clinical_df = pd.DataFrame()
50
+ genetic_df = pd.DataFrame()
51
+ else:
52
+ cohort_dir = os.path.join(tcga_root_dir, selected_dir)
53
+
54
+ # Step 2: Identify clinical and genetic file paths
55
+ clinical_file_path, genetic_file_path = tcga_get_relevant_filepaths(cohort_dir)
56
+
57
+ # Step 3: Load both files as DataFrames
58
+ def read_tsv(path):
59
+ compression = 'gzip' if path.endswith('.gz') else None
60
+ return pd.read_csv(path, sep='\t', index_col=0, low_memory=False, compression=compression)
61
+
62
+ clinical_df = read_tsv(clinical_file_path)
63
+ genetic_df = read_tsv(genetic_file_path)
64
+
65
+ # Step 4: Print column names of the clinical data
66
+ print(clinical_df.columns.tolist())
67
+
68
+ # Step 2: Find Candidate Demographic Features
69
+ import os
70
+ import re
71
+ import pandas as pd
72
+
73
+ # Given column list from the previous step
74
+ all_columns = ['_INTEGRATION', '_PATIENT', '_cohort', '_primary_disease', '_primary_site', 'age_at_initial_pathologic_diagnosis', 'bcr_followup_barcode', 'bcr_patient_barcode', 'bcr_sample_barcode', 'bilateral_diagnosis_timing_type', 'clinical_M', 'clinical_N', 'clinical_T', 'clinical_stage', 'days_to_bilateral_tumor_dx', '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', 'days_to_post_orchi_serum_test', 'days_to_pre_orchi_serum_test', 'eastern_cancer_oncology_group', 'family_history_other_cancer', 'family_history_testicular_cancer', 'family_member_relationship_type', 'first_treatment_success', 'form_completion_date', 'gender', 'histological_percentage', 'histological_type', 'history_fertility', 'history_hypospadias', 'history_of_neoadjuvant_treatment', 'history_of_undescended_testis', 'icd_10', 'icd_o_3_histology', 'icd_o_3_site', 'igcccg_stage', 'informed_consent_verified', 'init_pathology_dx_method_other', 'initial_pathologic_diagnosis_method', 'initial_weight', 'intratubular_germ_cell_neoplasm', 'is_ffpe', 'karnofsky_performance_score', 'laterality', 'level_of_non_descent', 'lost_follow_up', 'lymphovascular_invasion_present', 'molecular_test_result', 'new_neoplasm_event_occurrence_anatomic_site', 'new_neoplasm_event_type', 'new_neoplasm_occurrence_anatomic_site_text', 'new_tumor_event_after_initial_treatment', 'oct_embedded', 'other_dx', 'pathologic_M', 'pathologic_N', 'pathologic_T', 'pathologic_stage', 'pathology_report_file_name', 'patient_death_reason', 'patient_id', 'person_neoplasm_cancer_status', 'post_orchi_afp', 'post_orchi_hcg', 'post_orchi_ldh', 'post_orchi_lh', 'post_orchi_lymph_node_dissection', 'post_orchi_testosterone', 'postoperative_rx_tx', 'postoperative_tx', 'pre_orchi_afp', 'pre_orchi_hcg', 'pre_orchi_ldh', 'pre_orchi_lh', 'pre_orchi_testosterone', 'primary_therapy_outcome_success', 'radiation_therapy', 'relation_testicular_cancer', 'relative_family_cancer_hx_text', 'sample_type', 'sample_type_id', 'serum_markers', 'source_of_patient_death_reason', 'synchronous_tumor_histology_pct', 'synchronous_tumor_histology_type', 'system_version', 'testis_tumor_macroextent', 'testis_tumor_macroextent_other', 'testis_tumor_microextent', 'tissue_prospective_collection_indicator', 'tissue_retrospective_collection_indicator', 'tissue_source_site', 'tumor_tissue_site', 'undescended_testis_corrected', 'undescended_testis_corrected_age', 'undescended_testis_method_left', 'undescended_testis_method_right', 'vial_number', 'vital_status', 'year_of_initial_pathologic_diagnosis', '_GENOMIC_ID_TCGA_TGCT_PDMRNAseqCNV', '_GENOMIC_ID_TCGA_TGCT_exp_HiSeqV2_exon', '_GENOMIC_ID_TCGA_TGCT_mutation_ucsc_maf_gene', '_GENOMIC_ID_TCGA_TGCT_exp_HiSeqV2', '_GENOMIC_ID_TCGA_TGCT_exp_HiSeqV2_PANCAN', '_GENOMIC_ID_TCGA_TGCT_hMethyl450', '_GENOMIC_ID_TCGA_TGCT_gistic2', '_GENOMIC_ID_data/public/TCGA/TGCT/miRNA_HiSeq_gene', '_GENOMIC_ID_TCGA_TGCT_gistic2thd', '_GENOMIC_ID_TCGA_TGCT_mutation_bcm_gene', '_GENOMIC_ID_TCGA_TGCT_miRNA_HiSeq', '_GENOMIC_ID_TCGA_TGCT_mutation_broad_gene', '_GENOMIC_ID_TCGA_TGCT_PDMRNAseq', '_GENOMIC_ID_TCGA_TGCT_RPPA', '_GENOMIC_ID_TCGA_TGCT_exp_HiSeqV2_percentile', '_GENOMIC_ID_TCGA_TGCT_mutation_bcgsc_gene']
75
+
76
+ # Identify candidate age columns
77
+ def is_age_col(col: str) -> bool:
78
+ c = col.lower()
79
+ if re.search(r'(^|_)age($|_)', c):
80
+ return True
81
+ if 'age_at' in c:
82
+ return True
83
+ # Common proxy for age in TCGA clinical: days_to_birth
84
+ if c == 'days_to_birth':
85
+ return True
86
+ return False
87
+
88
+ candidate_age_cols = [c for c in all_columns if is_age_col(c)]
89
+
90
+ # Identify candidate gender columns
91
+ def is_gender_col(col: str) -> bool:
92
+ c = col.lower()
93
+ if re.search(r'(^|_)gender($|_)', c):
94
+ return True
95
+ if re.search(r'(^|_)sex($|_)', c):
96
+ return True
97
+ return False
98
+
99
+ candidate_gender_cols = [c for c in all_columns if is_gender_col(c)]
100
+
101
+ print(f"candidate_age_cols = {candidate_age_cols}")
102
+ print(f"candidate_gender_cols = {candidate_gender_cols}")
103
+
104
+ # Try to load clinical data and preview candidate columns
105
+ clinical_df = None
106
+ try:
107
+ # Find cohort directory for TGCT within tcga_root_dir
108
+ cohort_dir = None
109
+ for d in os.listdir(tcga_root_dir):
110
+ full = os.path.join(tcga_root_dir, d)
111
+ if os.path.isdir(full):
112
+ name = d.lower()
113
+ if name == 'tgct' or 'tgct' in name or 'testicular' in name:
114
+ cohort_dir = full
115
+ break
116
+ if cohort_dir:
117
+ clinical_fp, _ = tcga_get_relevant_filepaths(cohort_dir)
118
+ clinical_df = pd.read_csv(clinical_fp, sep='\t', index_col=0, dtype=str)
119
+ except Exception as e:
120
+ clinical_df = None
121
+
122
+ if clinical_df is not None:
123
+ age_cols_present = [c for c in candidate_age_cols if c in clinical_df.columns]
124
+ gender_cols_present = [c for c in candidate_gender_cols if c in clinical_df.columns]
125
+ if age_cols_present:
126
+ age_preview = preview_df(clinical_df[age_cols_present])
127
+ print(age_preview)
128
+ if gender_cols_present:
129
+ gender_preview = preview_df(clinical_df[gender_cols_present])
130
+ print(gender_preview)
131
+
132
+ # Step 3: Select Demographic Features
133
+ # Select age and gender columns from candidate lists based on data quality and interpretability
134
+ try:
135
+ age_candidates = candidate_age_cols
136
+ except NameError:
137
+ age_candidates = []
138
+
139
+ try:
140
+ gender_candidates = candidate_gender_cols
141
+ except NameError:
142
+ gender_candidates = []
143
+
144
+ # Preference order for age: direct age in years > derived (days_to_birth) > others
145
+ age_col = None
146
+ if 'age_at_initial_pathologic_diagnosis' in age_candidates:
147
+ age_col = 'age_at_initial_pathologic_diagnosis'
148
+ elif 'days_to_birth' in age_candidates:
149
+ age_col = 'days_to_birth'
150
+ elif len(age_candidates) > 0:
151
+ age_col = age_candidates[0]
152
+
153
+ # Preference for gender: 'gender' if available
154
+ gender_col = 'gender' if 'gender' in gender_candidates else (gender_candidates[0] if len(gender_candidates) > 0 else None)
155
+
156
+ # Print selected columns
157
+ print(f"Selected age_col: {age_col}")
158
+ print(f"Selected gender_col: {gender_col}")
159
+
160
+ # Attempt to print first-5 preview values if preview dictionaries exist
161
+ def _print_preview(col_name: str, preview_dict_varnames):
162
+ values = None
163
+ for varname in preview_dict_varnames:
164
+ if varname in globals():
165
+ v = globals()[varname]
166
+ if isinstance(v, dict) and col_name in v:
167
+ values = v[col_name]
168
+ break
169
+ if values is not None:
170
+ print(f"{col_name} sample values (first 5): {values}")
171
+
172
+ # Common potential variable names used in previous steps for previews
173
+ age_preview_varnames = [
174
+ 'age_preview_dict', 'age_candidate_values', 'age_candidates_preview',
175
+ 'age_values_dict', 'age_candidates_dict'
176
+ ]
177
+ gender_preview_varnames = [
178
+ 'gender_preview_dict', 'gender_candidate_values', 'gender_candidates_preview',
179
+ 'gender_values_dict', 'gender_candidates_dict'
180
+ ]
181
+
182
+ if age_col is not None:
183
+ _print_preview(age_col, age_preview_varnames)
184
+ if gender_col is not None:
185
+ _print_preview(gender_col, gender_preview_varnames)
186
+
187
+ # Step 4: Feature Engineering and Validation
188
+ import os
189
+ import re
190
+ import pandas as pd
191
+
192
+ # 1) Extract and standardize clinical features (trait, Age, Gender)
193
+ age_in_cols = (age_col is not None) and (age_col in clinical_df.columns)
194
+ gender_in_cols = (gender_col is not None) and (gender_col in clinical_df.columns)
195
+ selected_clinical_df = tcga_select_clinical_features(
196
+ clinical_df,
197
+ trait=trait,
198
+ age_col=age_col if age_in_cols else None,
199
+ gender_col=gender_col if gender_in_cols else None
200
+ )
201
+
202
+ # 2) Normalize gene symbols in gene expression data and save
203
+ gene_df = genetic_df.copy()
204
+
205
+ # Auto-detect orientation so that gene_df index are gene symbols and columns are samples
206
+ barcode_re = re.compile(r'^TCGA-[A-Z0-9]{2}-[A-Z0-9]{4}')
207
+ sample_n_idx = min(len(gene_df.index), 100)
208
+ sample_n_cols = min(len(gene_df.columns), 100)
209
+ idx_barcodes = sum(1 for v in list(gene_df.index)[:sample_n_idx] if barcode_re.match(str(v)))
210
+ col_barcodes = sum(1 for v in list(gene_df.columns)[:sample_n_cols] if barcode_re.match(str(v)))
211
+ # If index looks like barcodes, transpose to make genes as index
212
+ if idx_barcodes > col_barcodes:
213
+ gene_df = gene_df.T
214
+
215
+ # Ensure numeric matrix
216
+ gene_df = gene_df.apply(pd.to_numeric, errors='coerce')
217
+
218
+ # Normalize gene symbols (removes unrecognized, aggregates synonyms)
219
+ gene_df_norm = normalize_gene_symbols_in_index(gene_df)
220
+
221
+ # Save normalized gene expression matrix
222
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
223
+ gene_df_norm.to_csv(out_gene_data_file)
224
+
225
+ # 3) Link clinical and genetic data on sample IDs
226
+ linked_data = pd.concat([selected_clinical_df, gene_df_norm.T], axis=1, join='inner')
227
+
228
+ # 4) Handle missing values
229
+ processed_df = handle_missing_values(linked_data, trait_col=trait)
230
+
231
+ # 5) Determine bias and remove biased demographic features
232
+ is_biased, processed_df = judge_and_remove_biased_features(processed_df, trait=trait)
233
+
234
+ # 6) Final validation and save cohort info
235
+ note = "INFO: Gene symbols normalized via NCBI synonyms; gene matrix orientation auto-detected; samples linked by intersection."
236
+ is_usable = validate_and_save_cohort_info(
237
+ is_final=True,
238
+ cohort="TCGA",
239
+ info_path=json_path,
240
+ is_gene_available=True,
241
+ is_trait_available=True,
242
+ is_biased=is_biased,
243
+ df=processed_df,
244
+ note=note
245
+ )
246
+
247
+ # 7) Save linked data if usable
248
+ if is_usable:
249
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
250
+ processed_df.to_csv(out_data_file)
output/preprocess/Testicular_Cancer/cohort_info.json CHANGED
@@ -1,32 +1 @@
1
- {
2
- "GSE62523": {
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
- "GSE42647": {
13
- "is_usable": false,
14
- "is_gene_available": true,
15
- "is_trait_available": true,
16
- "is_available": true,
17
- "is_biased": true,
18
- "has_age": false,
19
- "has_gender": false,
20
- "sample_size": 12
21
- },
22
- "TCGA": {
23
- "is_usable": false,
24
- "is_gene_available": true,
25
- "is_trait_available": true,
26
- "is_available": true,
27
- "is_biased": true,
28
- "has_age": true,
29
- "has_gender": false,
30
- "sample_size": 156
31
- }
32
- }
 
1
+ {"GSE62523": {"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}, "GSE42647": {"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": true, "is_trait_available": true, "is_available": true, "is_biased": true, "has_age": true, "has_gender": false, "sample_size": 156, "note": "INFO: Gene symbols normalized via NCBI synonyms; gene matrix orientation auto-detected; samples linked by intersection."}}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
output/preprocess/Thymoma/clinical_data/GSE131027.csv CHANGED
@@ -1,2 +1,2 @@
1
  ,GSM3759992,GSM3759993,GSM3759994,GSM3759995,GSM3759996,GSM3759997,GSM3759998,GSM3759999,GSM3760000,GSM3760001,GSM3760002,GSM3760003,GSM3760004,GSM3760005,GSM3760006,GSM3760007,GSM3760008,GSM3760009,GSM3760010,GSM3760011,GSM3760012,GSM3760013,GSM3760014,GSM3760015,GSM3760016,GSM3760017,GSM3760018,GSM3760019,GSM3760020,GSM3760021,GSM3760022,GSM3760023,GSM3760024,GSM3760025,GSM3760026,GSM3760027,GSM3760028,GSM3760029,GSM3760030,GSM3760031,GSM3760032,GSM3760033,GSM3760034,GSM3760035,GSM3760036,GSM3760037,GSM3760038,GSM3760039,GSM3760040,GSM3760041,GSM3760042,GSM3760043,GSM3760044,GSM3760045,GSM3760046,GSM3760047,GSM3760048,GSM3760049,GSM3760050,GSM3760051,GSM3760052,GSM3760053,GSM3760054,GSM3760055,GSM3760056,GSM3760057,GSM3760058,GSM3760059,GSM3760060,GSM3760061,GSM3760062,GSM3760063,GSM3760064,GSM3760065,GSM3760066,GSM3760067,GSM3760068,GSM3760069,GSM3760070,GSM3760071,GSM3760072,GSM3760073,GSM3760074,GSM3760075,GSM3760076,GSM3760077,GSM3760078,GSM3760079,GSM3760080,GSM3760081,GSM3760082,GSM3760083
2
- Thymoma,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0
 
1
  ,GSM3759992,GSM3759993,GSM3759994,GSM3759995,GSM3759996,GSM3759997,GSM3759998,GSM3759999,GSM3760000,GSM3760001,GSM3760002,GSM3760003,GSM3760004,GSM3760005,GSM3760006,GSM3760007,GSM3760008,GSM3760009,GSM3760010,GSM3760011,GSM3760012,GSM3760013,GSM3760014,GSM3760015,GSM3760016,GSM3760017,GSM3760018,GSM3760019,GSM3760020,GSM3760021,GSM3760022,GSM3760023,GSM3760024,GSM3760025,GSM3760026,GSM3760027,GSM3760028,GSM3760029,GSM3760030,GSM3760031,GSM3760032,GSM3760033,GSM3760034,GSM3760035,GSM3760036,GSM3760037,GSM3760038,GSM3760039,GSM3760040,GSM3760041,GSM3760042,GSM3760043,GSM3760044,GSM3760045,GSM3760046,GSM3760047,GSM3760048,GSM3760049,GSM3760050,GSM3760051,GSM3760052,GSM3760053,GSM3760054,GSM3760055,GSM3760056,GSM3760057,GSM3760058,GSM3760059,GSM3760060,GSM3760061,GSM3760062,GSM3760063,GSM3760064,GSM3760065,GSM3760066,GSM3760067,GSM3760068,GSM3760069,GSM3760070,GSM3760071,GSM3760072,GSM3760073,GSM3760074,GSM3760075,GSM3760076,GSM3760077,GSM3760078,GSM3760079,GSM3760080,GSM3760081,GSM3760082,GSM3760083
2
+ Thymoma,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0
output/preprocess/Thymoma/clinical_data/TCGA.csv ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ sampleID,Thymoma,Age,Gender
2
+ TCGA-3G-AB0O-01,1,47.98904859685147,1
3
+ TCGA-3G-AB0Q-01,1,66.9678302532512,1
4
+ TCGA-3G-AB0T-01,1,45.79876796714579,1
5
+ TCGA-3G-AB14-01,1,51.28815879534565,1
6
+ TCGA-3G-AB19-01,1,76.18617385352498,0
7
+ TCGA-3Q-A9WF-01,1,71.50444900752909,1
8
+ TCGA-3S-A8YW-01,1,63.115674195756334,1
9
+ TCGA-3S-AAYX-01,1,55.715263518138265,0
10
+ TCGA-3T-AA9L-01,1,31.786447638603697,0
11
+ TCGA-4V-A9QI-01,1,68.94182067077344,1
12
+ TCGA-4V-A9QJ-01,1,64.3668720054757,1
13
+ TCGA-4V-A9QL-01,1,58.08624229979466,0
14
+ TCGA-4V-A9QM-01,1,39.90691307323751,1
15
+ TCGA-4V-A9QN-01,1,40.5886379192334,0
16
+ TCGA-4V-A9QQ-01,1,65.41820670773443,0
17
+ TCGA-4V-A9QR-01,1,51.26078028747433,0
18
+ TCGA-4V-A9QS-01,1,53.23203285420944,0
19
+ TCGA-4V-A9QT-01,1,79.26351813826146,0
20
+ TCGA-4V-A9QU-01,1,76.3750855578371,0
21
+ TCGA-4V-A9QW-01,1,62.3709787816564,1
22
+ TCGA-4V-A9QX-01,1,77.34428473648187,0
23
+ TCGA-4X-A9F9-01,1,57.95482546201232,0
24
+ TCGA-4X-A9FA-01,1,52.106776180698155,1
25
+ TCGA-4X-A9FB-01,1,44.284736481861735,1
26
+ TCGA-4X-A9FC-01,1,50.42573579739904,0
27
+ TCGA-4X-A9FD-01,1,43.71800136892539,0
28
+ TCGA-5G-A9ZZ-01,1,52.33949349760438,0
29
+ TCGA-5K-AAAP-01,1,54.59000684462697,1
30
+ TCGA-5U-AB0D-01,1,71.6413415468857,0
31
+ TCGA-5U-AB0E-01,1,62.19301848049281,1
32
+ TCGA-5U-AB0F-01,1,58.893908281998634,0
33
+ TCGA-5V-A9RR-01,1,67.53730321697468,1
34
+ TCGA-X7-A8D6-01,1,48.65434633812457,0
35
+ TCGA-X7-A8D6-11,0,48.65434633812457,0
36
+ TCGA-X7-A8D7-01,1,46.98425735797399,0
37
+ TCGA-X7-A8D7-11,0,46.98425735797399,0
38
+ TCGA-X7-A8D8-01,1,53.22655715263518,1
39
+ TCGA-X7-A8D9-01,1,,0
40
+ TCGA-X7-A8DB-01,1,71.27994524298425,0
41
+ TCGA-X7-A8DC-01,1,68.62696783025325,1
42
+ TCGA-X7-A8DD-01,1,54.677618069815196,0
43
+ TCGA-X7-A8DE-01,1,35.474332648870636,0
44
+ TCGA-X7-A8DF-01,1,40.53114305270363,1
45
+ TCGA-X7-A8DG-01,1,47.95893223819302,1
46
+ TCGA-X7-A8DI-01,1,57.73032169746749,0
47
+ TCGA-X7-A8DJ-01,1,68.56125941136209,1
48
+ TCGA-X7-A8M0-01,1,61.86447638603696,0
49
+ TCGA-X7-A8M1-01,1,51.54277891854894,1
50
+ TCGA-X7-A8M3-01,1,64.93634496919918,0
51
+ TCGA-X7-A8M4-01,1,41.25941136208077,1
52
+ TCGA-X7-A8M5-01,1,65.80698151950719,0
53
+ TCGA-X7-A8M6-01,1,43.11841204654346,1
54
+ TCGA-X7-A8M7-01,1,26.872005475701574,1
55
+ TCGA-X7-A8M8-01,1,45.83436002737851,1
56
+ TCGA-XH-A853-01,1,67.23066392881589,1
57
+ TCGA-XM-A8R8-01,1,67.09924709103353,0
58
+ TCGA-XM-A8R9-01,1,71.66598220396989,0
59
+ TCGA-XM-A8RB-01,1,68.66529774127311,0
60
+ TCGA-XM-A8RC-01,1,67.51540041067761,1
61
+ TCGA-XM-A8RD-01,1,69.54688569472964,0
62
+ TCGA-XM-A8RE-01,1,54.49144421629021,0
63
+ TCGA-XM-A8RF-01,1,84.58042436687201,0
64
+ TCGA-XM-A8RG-01,1,67.90417522245038,1
65
+ TCGA-XM-A8RH-01,1,60.04380561259411,0
66
+ TCGA-XM-A8RI-01,1,77.33333333333333,1
67
+ TCGA-XM-A8RL-01,1,44.85694729637235,1
68
+ TCGA-XM-AAZ1-01,1,42.116358658453116,1
69
+ TCGA-XM-AAZ2-01,1,73.54140999315537,1
70
+ TCGA-XM-AAZ3-01,1,64.65982203969884,1
71
+ TCGA-XU-A92O-01,1,63.4798083504449,1
72
+ TCGA-XU-A92Q-01,1,50.050650239561946,1
73
+ TCGA-XU-A92R-01,1,76.58042436687201,0
74
+ TCGA-XU-A92T-01,1,81.07597535934292,0
75
+ TCGA-XU-A92U-01,1,67.04175222450377,1
76
+ TCGA-XU-A92V-01,1,72.95277207392198,0
77
+ TCGA-XU-A92W-01,1,61.74948665297741,1
78
+ TCGA-XU-A92X-01,1,17.99315537303217,1
79
+ TCGA-XU-A92Y-01,1,71.24161533196441,0
80
+ TCGA-XU-A92Z-01,1,76.9801505817933,1
81
+ TCGA-XU-A930-01,1,43.19507186858316,1
82
+ TCGA-XU-A931-01,1,61.4154688569473,0
83
+ TCGA-XU-A932-01,1,37.28405201916495,1
84
+ TCGA-XU-A933-01,1,52.77481177275838,0
85
+ TCGA-XU-A936-01,1,65.5003422313484,0
86
+ TCGA-XU-AAXV-01,1,45.399041752224505,0
87
+ TCGA-XU-AAXW-01,1,39.44695414099932,0
88
+ TCGA-XU-AAXX-01,1,44.53114305270363,0
89
+ TCGA-XU-AAXY-01,1,43.13757700205339,1
90
+ TCGA-XU-AAXZ-01,1,63.85763175906913,1
91
+ TCGA-XU-AAY0-01,1,61.998631074606436,0
92
+ TCGA-XU-AAY1-01,1,51.408624229979466,0
93
+ TCGA-YT-A95D-01,1,50.275154004106774,0
94
+ TCGA-YT-A95E-01,1,52.49007529089665,1
95
+ TCGA-YT-A95F-01,1,55.75085557837098,0
96
+ TCGA-YT-A95G-01,1,61.713894592744694,0
97
+ TCGA-YT-A95H-01,1,69.4757015742642,1
98
+ TCGA-ZB-A961-01,1,69.59342915811088,1
99
+ TCGA-ZB-A962-01,1,64.23271731690623,1
100
+ TCGA-ZB-A963-01,1,46.5160848733744,1
101
+ TCGA-ZB-A964-01,1,70.80355920602327,1
102
+ TCGA-ZB-A965-01,1,75.61122518822724,0
103
+ TCGA-ZB-A966-01,1,78.36002737850787,0
104
+ TCGA-ZB-A969-01,1,72.43805612594113,0
105
+ TCGA-ZB-A96A-01,1,53.18001368925393,1
106
+ TCGA-ZB-A96B-01,1,51.723477070499655,1
107
+ TCGA-ZB-A96C-01,1,77.26762491444217,0
108
+ TCGA-ZB-A96D-01,1,52.76933607118412,0
109
+ TCGA-ZB-A96E-01,1,60.48459958932238,1
110
+ TCGA-ZB-A96F-01,1,39.27173169062286,1
111
+ TCGA-ZB-A96G-01,1,59.13210130047912,1
112
+ TCGA-ZB-A96H-01,1,73.05407255304586,1
113
+ TCGA-ZB-A96I-01,1,71.75359342915812,0
114
+ TCGA-ZB-A96K-01,1,69.80971937029432,1
115
+ TCGA-ZB-A96L-01,1,70.94866529774127,0
116
+ TCGA-ZB-A96M-01,1,56.46269678302532,0
117
+ TCGA-ZB-A96O-01,1,54.16016427104723,0
118
+ TCGA-ZB-A96P-01,1,73.56605065023956,1
119
+ TCGA-ZB-A96Q-01,1,49.96303901437371,1
120
+ TCGA-ZB-A96R-01,1,38.26694045174538,1
121
+ TCGA-ZB-A96V-01,1,44.47638603696099,1
122
+ TCGA-ZC-AAA7-01,1,63.696098562628336,1
123
+ TCGA-ZC-AAAA-01,1,39.50444900752909,1
124
+ TCGA-ZC-AAAF-01,1,74.19301848049281,0
125
+ TCGA-ZC-AAAH-01,1,52.41889117043121,1
126
+ TCGA-ZL-A9V6-01,1,61.45653661875428,1
127
+ TCGA-ZT-A8OM-01,1,73.71115674195757,0
output/preprocess/Thymoma/code/GSE131027.py ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Thymoma"
6
+ cohort = "GSE131027"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Thymoma"
10
+ in_cohort_dir = "../DATA/GEO/Thymoma/GSE131027"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z6/preprocess/Thymoma/GSE131027.csv"
14
+ out_gene_data_file = "./output/z6/preprocess/Thymoma/gene_data/GSE131027.csv"
15
+ out_clinical_data_file = "./output/z6/preprocess/Thymoma/clinical_data/GSE131027.csv"
16
+ json_path = "./output/z6/preprocess/Thymoma/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ import os
40
+
41
+ # 1) Gene Expression Data Availability
42
+ is_gene_available = True # Based on series design indicating expression features (HRD expression, PARP sensitivity)
43
+
44
+ # 2) Variable Availability and Data Type Conversion
45
+
46
+ # Trait: Thymoma vs others from 'cancer: ...' -> key 1
47
+ trait_row = 1
48
+
49
+ # Age/Gender: not available in provided characteristics
50
+ age_row = None
51
+ gender_row = None
52
+
53
+ def _post_colon_value(x):
54
+ if x is None:
55
+ return None
56
+ s = str(x)
57
+ # take the substring after the last colon to handle fields with multiple colons
58
+ if ":" in s:
59
+ s = s.split(":")[-1]
60
+ return s.strip()
61
+
62
+ def convert_trait(x):
63
+ v = _post_colon_value(x)
64
+ if not v:
65
+ return None
66
+ v_l = v.lower()
67
+ return 1 if v_l == "thymoma" else 0
68
+
69
+ # Age and Gender converters are not needed since rows are not available
70
+ convert_age = None
71
+ convert_gender = None
72
+
73
+ # 3) Save Metadata (initial filtering)
74
+ is_trait_available = trait_row is not None
75
+ _ = validate_and_save_cohort_info(
76
+ is_final=False,
77
+ cohort=cohort,
78
+ info_path=json_path,
79
+ is_gene_available=is_gene_available,
80
+ is_trait_available=is_trait_available
81
+ )
82
+
83
+ # 4) Clinical Feature Extraction (only if clinical data is available)
84
+ if trait_row is not None:
85
+ selected_clinical_df = geo_select_clinical_features(
86
+ clinical_df=clinical_data,
87
+ trait=trait,
88
+ trait_row=trait_row,
89
+ convert_trait=convert_trait,
90
+ age_row=age_row,
91
+ convert_age=convert_age,
92
+ gender_row=gender_row,
93
+ convert_gender=convert_gender
94
+ )
95
+ clinical_preview = preview_df(selected_clinical_df, n=5)
96
+ print(clinical_preview)
97
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
98
+ selected_clinical_df.to_csv(out_clinical_data_file)
99
+
100
+ # Step 3: Gene Data Extraction
101
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
102
+ gene_data = get_genetic_data(matrix_file)
103
+
104
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
105
+ print(gene_data.index[:20])
106
+
107
+ # Step 4: Gene Identifier Review
108
+ print("requires_gene_mapping = True")
109
+
110
+ # Step 5: Gene Annotation
111
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
112
+ gene_annotation = get_gene_annotation(soft_file)
113
+
114
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
115
+ print("Gene annotation preview:")
116
+ print(preview_df(gene_annotation))
117
+
118
+ # Step 6: Gene Identifier Mapping
119
+ # Identify the appropriate columns in the annotation: 'ID' for probes and 'Gene Symbol' for gene symbols
120
+ mapping_df = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='Gene Symbol')
121
+
122
+ # Apply mapping to convert probe-level data to gene-level expression
123
+ gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
124
+
125
+ # Step 7: Data Normalization and Linking
126
+ import os
127
+ import pandas as pd
128
+
129
+ # 1. Normalize the obtained gene data with the 'normalize_gene_symbols_in_index' function from the library.
130
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
131
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
132
+ normalized_gene_data.to_csv(out_gene_data_file)
133
+
134
+ # Make sure the clinical dataframe is available (load from disk if needed)
135
+ try:
136
+ selected_clinical_df
137
+ except NameError:
138
+ selected_clinical_df = pd.read_csv(out_clinical_data_file, index_col=0)
139
+
140
+ # 2. Link the clinical and genetic data with the 'geo_link_clinical_genetic_data' function from the library.
141
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
142
+
143
+ # 3. Handle missing values in the linked data
144
+ linked_data = handle_missing_values(linked_data, trait)
145
+
146
+ # 4. Determine whether the trait and some demographic features are severely biased, and remove biased features.
147
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
148
+
149
+ # Prepare an informative note about class imbalance using original clinical labels
150
+ trait_series = selected_clinical_df.loc[trait].dropna()
151
+ pos = int((trait_series == 1).sum())
152
+ neg = int((trait_series == 0).sum())
153
+ n_total = pos + neg
154
+ note = f"WARNING: Severe class imbalance for '{trait}': {pos} positive vs {neg} negative (N={n_total})."
155
+
156
+ # 5. Conduct quality check and save the cohort information.
157
+ is_usable = validate_and_save_cohort_info(
158
+ is_final=True,
159
+ cohort=cohort,
160
+ info_path=json_path,
161
+ is_gene_available=True,
162
+ is_trait_available=True,
163
+ is_biased=is_trait_biased,
164
+ df=unbiased_linked_data,
165
+ note=note
166
+ )
167
+
168
+ # 6. If the linked data is usable, save it as a CSV file to 'out_data_file'.
169
+ if is_usable:
170
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
171
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Thymoma/code/GSE29695.py ADDED
@@ -0,0 +1,190 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Thymoma"
6
+ cohort = "GSE29695"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Thymoma"
10
+ in_cohort_dir = "../DATA/GEO/Thymoma/GSE29695"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z6/preprocess/Thymoma/GSE29695.csv"
14
+ out_gene_data_file = "./output/z6/preprocess/Thymoma/gene_data/GSE29695.csv"
15
+ out_clinical_data_file = "./output/z6/preprocess/Thymoma/clinical_data/GSE29695.csv"
16
+ json_path = "./output/z6/preprocess/Thymoma/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ # 1. Gene Expression Data Availability
40
+ is_gene_available = True # Whole-genome gene expression on Illumina Human Ref-8 Beadchip per series summary
41
+
42
+ # 2. Variable Availability and Conversion
43
+
44
+ # From the provided Sample Characteristics Dictionary, there is no explicit human age or gender.
45
+ # The "trait" for this project is Thymoma, which is constant across human tumor samples in this series.
46
+ # Therefore, treat trait as not available for association purposes (no variation).
47
+ trait_row = None
48
+ age_row = None
49
+ gender_row = None
50
+
51
+ # Conversion functions (defined for interface completeness; they won't be used since rows are None)
52
+ def _extract_value(cell):
53
+ if cell is None:
54
+ return None
55
+ # Expect "key: value" format; robustly split on the first colon
56
+ parts = str(cell).split(":", 1)
57
+ val = parts[1].strip() if len(parts) > 1 else str(cell).strip()
58
+ # Normalize NA-like tokens
59
+ if val in {"NA", "na", "Na", "N/A", "n/a", "Unknown", "unknown", ""}:
60
+ return None
61
+ return val
62
+
63
+ def convert_trait(cell):
64
+ # Not used; placeholder: map presence of thymoma-related descriptors to 1
65
+ val = _extract_value(cell)
66
+ if val is None:
67
+ return None
68
+ txt = val.lower()
69
+ if "thymoma" in txt or "thymic" in txt or "tumor" in txt:
70
+ return 1
71
+ if "normal" in txt or "control" in txt:
72
+ return 0
73
+ return None
74
+
75
+ def convert_age(cell):
76
+ val = _extract_value(cell)
77
+ if val is None:
78
+ return None
79
+ # Try to parse numeric age from strings like "45", "45 years", etc.
80
+ try:
81
+ # Keep digits and dot
82
+ import re
83
+ m = re.search(r"(\d+\.?\d*)", val)
84
+ return float(m.group(1)) if m else None
85
+ except Exception:
86
+ return None
87
+
88
+ def convert_gender(cell):
89
+ val = _extract_value(cell)
90
+ if val is None:
91
+ return None
92
+ v = val.strip().lower()
93
+ # Normalize common gender representations
94
+ if v in {"female", "f", "woman", "women"}:
95
+ return 0
96
+ if v in {"male", "m", "man", "men"}:
97
+ return 1
98
+ return None
99
+
100
+ # 3. Save Metadata (initial filtering)
101
+ is_trait_available = trait_row is not None
102
+ _ = validate_and_save_cohort_info(
103
+ is_final=False,
104
+ cohort=cohort,
105
+ info_path=json_path,
106
+ is_gene_available=is_gene_available,
107
+ is_trait_available=is_trait_available
108
+ )
109
+
110
+ # 4. Clinical Feature Extraction (skip because trait_row is None)
111
+ # If trait_row were available:
112
+ # selected_clinical = geo_select_clinical_features(
113
+ # clinical_df=clinical_data,
114
+ # trait=trait,
115
+ # trait_row=trait_row,
116
+ # convert_trait=convert_trait,
117
+ # age_row=age_row,
118
+ # convert_age=convert_age,
119
+ # gender_row=gender_row,
120
+ # convert_gender=convert_gender
121
+ # )
122
+ # preview = preview_df(selected_clinical)
123
+ # os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
124
+ # selected_clinical.to_csv(out_clinical_data_file)
125
+
126
+ # Step 3: Gene Data Extraction
127
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
128
+ gene_data = get_genetic_data(matrix_file)
129
+
130
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
131
+ print(gene_data.index[:20])
132
+
133
+ # Step 4: Gene Identifier Review
134
+ print("requires_gene_mapping = True")
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
+ # 1-2. Decide the identifier and gene symbol columns based on the annotation preview
146
+ probe_col = 'ID' # Matches ILMN_* probe IDs seen in gene expression data
147
+ gene_symbol_col = 'Symbol' # Standard human gene symbols
148
+
149
+ # Build the mapping dataframe
150
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=probe_col, gene_col=gene_symbol_col)
151
+
152
+ # 3. Apply the mapping to convert probe-level data to gene-level expression
153
+ gene_data = apply_gene_mapping(gene_data, mapping_df)
154
+
155
+ # Step 7: Data Normalization and Linking
156
+ import os
157
+ import pandas as pd
158
+
159
+ # 1. Normalize gene symbols and save gene data
160
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
161
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
162
+ normalized_gene_data.to_csv(out_gene_data_file)
163
+
164
+ # Since trait data is unavailable (trait_row was None in Step 2), skip linking and downstream steps.
165
+ linked_data = None
166
+ is_trait_available = False
167
+ is_gene_available = True
168
+
169
+ # Prepare a small dummy dataframe to pass final validation without triggering abnormality override
170
+ if normalized_gene_data.shape[1] >= 5:
171
+ dummy_df = normalized_gene_data.iloc[:1, :5].copy()
172
+ else:
173
+ dummy_df = pd.DataFrame([[0, 0, 0, 0, 0]], columns=[f"col{i}" for i in range(5)])
174
+
175
+ is_trait_biased = False # Placeholder; trait is unavailable
176
+
177
+ # 5. Final validation and save cohort info
178
+ note = "INFO: Trait data unavailable in this series; skipped linking, missing value handling, and bias checks."
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,
184
+ is_trait_available=is_trait_available,
185
+ is_biased=is_trait_biased,
186
+ df=dummy_df,
187
+ note=note
188
+ )
189
+
190
+ # 6. Do not save linked data since dataset is not usable (trait unavailable)
output/preprocess/Thymoma/code/GSE42977.py ADDED
@@ -0,0 +1,252 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Thymoma"
6
+ cohort = "GSE42977"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Thymoma"
10
+ in_cohort_dir = "../DATA/GEO/Thymoma/GSE42977"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z6/preprocess/Thymoma/GSE42977.csv"
14
+ out_gene_data_file = "./output/z6/preprocess/Thymoma/gene_data/GSE42977.csv"
15
+ out_clinical_data_file = "./output/z6/preprocess/Thymoma/clinical_data/GSE42977.csv"
16
+ json_path = "./output/z6/preprocess/Thymoma/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ # 1) Determine gene expression availability
40
+ is_gene_available = True # Microarray gene-expression dataset per background info
41
+
42
+ # 2) Determine variable availability
43
+ trait_row = 0 # 'tissue' field contains 'Thymoma' and 'Metastatic Thymoma'
44
+ age_row = None
45
+ gender_row = None
46
+
47
+ # 2.2) Conversion functions
48
+ def _extract_value(x):
49
+ if x is None or (isinstance(x, float) and pd.isna(x)):
50
+ return None
51
+ s = str(x).strip()
52
+ if ":" in s:
53
+ s = s.split(":", 1)[1].strip()
54
+ if s == "" or s.lower() in {"na", "n/a", "nan", "none", "unknown", "null"}:
55
+ return None
56
+ return s
57
+
58
+ def convert_trait(x):
59
+ v = _extract_value(x)
60
+ if v is None:
61
+ return None
62
+ v_lower = v.lower()
63
+ # Positive for any thymoma mention (includes metastatic thymoma)
64
+ if "thymoma" in v_lower:
65
+ return 1
66
+ # All other tissues are considered non-thymoma
67
+ return 0
68
+
69
+ def convert_age(x):
70
+ v = _extract_value(x)
71
+ if v is None:
72
+ return None
73
+ # Extract the first number as age
74
+ import re
75
+ m = re.search(r"[-+]?\d*\.?\d+", v)
76
+ if m:
77
+ try:
78
+ return float(m.group())
79
+ except Exception:
80
+ return None
81
+ return None
82
+
83
+ def convert_gender(x):
84
+ v = _extract_value(x)
85
+ if v is None:
86
+ return None
87
+ v_lower = v.lower()
88
+ if v_lower in {"f", "female", "woman", "women"}:
89
+ return 0
90
+ if v_lower in {"m", "male", "man", "men"}:
91
+ return 1
92
+ return None
93
+
94
+ # 3) Save metadata (initial filtering)
95
+ is_trait_available = trait_row is not None
96
+ _ = validate_and_save_cohort_info(
97
+ is_final=False,
98
+ cohort=cohort,
99
+ info_path=json_path,
100
+ is_gene_available=is_gene_available,
101
+ is_trait_available=is_trait_available
102
+ )
103
+
104
+ # 4) Clinical Feature Extraction (only if clinical data is available)
105
+ if trait_row is not None:
106
+ selected_clinical_df = geo_select_clinical_features(
107
+ clinical_df=clinical_data,
108
+ trait=trait,
109
+ trait_row=trait_row,
110
+ convert_trait=convert_trait,
111
+ age_row=age_row,
112
+ convert_age=convert_age,
113
+ gender_row=gender_row,
114
+ convert_gender=convert_gender
115
+ )
116
+ print(preview_df(selected_clinical_df))
117
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
118
+ selected_clinical_df.to_csv(out_clinical_data_file)
119
+
120
+ # Step 3: Gene Data Extraction
121
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
122
+ gene_data = get_genetic_data(matrix_file)
123
+
124
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
125
+ print(gene_data.index[:20])
126
+
127
+ # Step 4: Gene Identifier Review
128
+ import os
129
+ import re
130
+ import pandas as pd
131
+
132
+ # Try to get gene identifiers from the saved gene data; fall back to provided sample IDs
133
+ gene_ids = []
134
+ try:
135
+ if os.path.exists(out_gene_data_file):
136
+ df_tmp = pd.read_csv(out_gene_data_file, index_col=0)
137
+ gene_ids = df_tmp.index.astype(str).tolist()
138
+ except Exception:
139
+ pass
140
+
141
+ if not gene_ids:
142
+ gene_ids = [
143
+ 'ILMN_10000', 'ILMN_100000', 'ILMN_100007', 'ILMN_100009', 'ILMN_10001',
144
+ 'ILMN_100010', 'ILMN_10002', 'ILMN_100028', 'ILMN_100030', 'ILMN_100031',
145
+ 'ILMN_100034', 'ILMN_100037', 'ILMN_10004', 'ILMN_10005', 'ILMN_100054',
146
+ 'ILMN_100059', 'ILMN_10006', 'ILMN_100075', 'ILMN_100079', 'ILMN_100083'
147
+ ]
148
+
149
+ def needs_mapping(ids):
150
+ # Common non-gene-symbol identifier patterns
151
+ patterns = [
152
+ r'^ILMN_\d+$', # Illumina probe IDs
153
+ r'^ENSG\d+(\.\d+)?$', # Ensembl genes
154
+ r'^\d+_(at|s_at|x_at|a_at)$', # Affymetrix probes
155
+ r'^(NM|NR|XM|XR)_\d+(\.\d+)?$',# RefSeq transcripts
156
+ r'^cg\d{6,}$', # CpG probes
157
+ r'^A_\d+_P\d+$' # Agilent probes
158
+ ]
159
+ comp = [re.compile(p) for p in patterns]
160
+ matches = 0
161
+ for x in ids:
162
+ s = str(x)
163
+ if any(c.match(s) for c in comp):
164
+ matches += 1
165
+ # If majority match known non-symbol patterns, mapping required
166
+ if len(ids) > 0 and (matches / len(ids)) >= 0.5:
167
+ return True
168
+ # Heuristic: underscores are rare in HGNC symbols; many underscores suggest probes/accessions
169
+ underscore_ratio = sum('_' in str(x) for x in ids) / max(len(ids), 1)
170
+ if underscore_ratio >= 0.5:
171
+ return True
172
+ return False
173
+
174
+ requires_gene_mapping = needs_mapping(gene_ids)
175
+ print(f"requires_gene_mapping = {requires_gene_mapping}")
176
+
177
+ # Step 5: Gene Annotation
178
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
179
+ gene_annotation = get_gene_annotation(soft_file)
180
+
181
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
182
+ print("Gene annotation preview:")
183
+ print(preview_df(gene_annotation))
184
+
185
+ # Step 6: Gene Identifier Mapping
186
+ # 1-2) Decide mapping columns and build mapping dataframe
187
+ prob_col = 'ID' # Probe IDs like ILMN_XXXXX
188
+ gene_col = 'Symbol' # Gene symbols
189
+
190
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=prob_col, gene_col=gene_col)
191
+
192
+ # 3) Apply mapping to convert probe-level data to gene-level expression
193
+ gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
194
+
195
+ # Optionally save the mapped gene expression data for later steps
196
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
197
+ gene_data.to_csv(out_gene_data_file)
198
+
199
+ # Step 7: Data Normalization and Linking
200
+ import os
201
+ import pandas as pd
202
+
203
+ # 1) Normalize gene symbols and save
204
+ # Ensure we have gene_data from previous steps; if not, reload from disk
205
+ try:
206
+ gene_data
207
+ except NameError:
208
+ if os.path.exists(out_gene_data_file):
209
+ gene_data = pd.read_csv(out_gene_data_file, index_col=0)
210
+ else:
211
+ raise RuntimeError("Gene data not found in memory or on disk.")
212
+
213
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
214
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
215
+ normalized_gene_data.to_csv(out_gene_data_file)
216
+
217
+ # 2) Link clinical and genetic data
218
+ # Ensure clinical data is available; if not in memory, load from saved file
219
+ try:
220
+ selected_clinical_df
221
+ except NameError:
222
+ if os.path.exists(out_clinical_data_file):
223
+ selected_clinical_df = pd.read_csv(out_clinical_data_file, index_col=0)
224
+ else:
225
+ raise RuntimeError("Clinical data not found in memory or on disk.")
226
+
227
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
228
+
229
+ # 3) Handle missing values
230
+ linked_data = handle_missing_values(linked_data, trait)
231
+
232
+ # 4) Bias checks and removal of biased demographics
233
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
234
+
235
+ # 5) Final validation and metadata saving
236
+ note = ("INFO: Gene IDs mapped from Illumina ILMN probes to HGNC symbols; "
237
+ "trait derived from 'tissue' field where any mention of 'Thymoma' is labeled as case (1).")
238
+ is_usable = validate_and_save_cohort_info(
239
+ is_final=True,
240
+ cohort=cohort,
241
+ info_path=json_path,
242
+ is_gene_available=True,
243
+ is_trait_available=True,
244
+ is_biased=is_trait_biased,
245
+ df=unbiased_linked_data,
246
+ note=note
247
+ )
248
+
249
+ # 6) Save linked data if usable
250
+ if is_usable:
251
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
252
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Thymoma/code/TCGA.py ADDED
@@ -0,0 +1,424 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Thymoma"
6
+
7
+ # Input paths
8
+ tcga_root_dir = "../DATA/TCGA"
9
+
10
+ # Output paths
11
+ out_data_file = "./output/z6/preprocess/Thymoma/TCGA.csv"
12
+ out_gene_data_file = "./output/z6/preprocess/Thymoma/gene_data/TCGA.csv"
13
+ out_clinical_data_file = "./output/z6/preprocess/Thymoma/clinical_data/TCGA.csv"
14
+ json_path = "./output/z6/preprocess/Thymoma/cohort_info.json"
15
+
16
+
17
+ # Step 1: Initial Data Loading
18
+ import os
19
+ import pandas as pd
20
+
21
+ # Step 1: Select the most relevant TCGA cohort directory for the trait
22
+ all_dirs = [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, trait_name: str) -> int:
25
+ nl = name.lower()
26
+ t = trait_name.lower()
27
+ score = 0
28
+ if t in nl:
29
+ score += 10
30
+ # Common code/synonym matches
31
+ if '(thym)' in name:
32
+ score += 5
33
+ if 'thym' in nl:
34
+ score += 2
35
+ return score
36
+
37
+ candidates = [(d, score_dir(d, trait)) for d in all_dirs]
38
+ # Keep only positively scored directories
39
+ candidates = [d for d in candidates if d[1] > 0]
40
+
41
+ selected_dir = None
42
+ if candidates:
43
+ # Choose the directory with the highest score; in ties, choose the first in sorted order
44
+ candidates.sort(key=lambda x: (-x[1], x[0]))
45
+ selected_dir = candidates[0][0]
46
+
47
+ if selected_dir is None:
48
+ # No suitable directory found: record and skip
49
+ validate_and_save_cohort_info(
50
+ is_final=False,
51
+ cohort="TCGA",
52
+ info_path=json_path,
53
+ is_gene_available=False,
54
+ is_trait_available=False
55
+ )
56
+ else:
57
+ # Step 2: Identify clinical and genetic file paths
58
+ cohort_dir_path = os.path.join(tcga_root_dir, selected_dir)
59
+ clinical_path, genetic_path = tcga_get_relevant_filepaths(cohort_dir_path)
60
+
61
+ # Step 3: Load both files into DataFrames
62
+ def read_tsv(path: str) -> pd.DataFrame:
63
+ comp = 'gzip' if path.endswith('.gz') else None
64
+ return pd.read_csv(path, sep='\t', index_col=0, low_memory=False, compression=comp)
65
+
66
+ clinical_df = read_tsv(clinical_path)
67
+ genetic_df = read_tsv(genetic_path)
68
+
69
+ # Step 4: Print column names of the clinical data
70
+ print(list(clinical_df.columns))
71
+
72
+ # Step 2: Find Candidate Demographic Features
73
+ import os
74
+ import re
75
+ import pandas as pd
76
+
77
+ # Given column list from the previous step
78
+ columns = ['_INTEGRATION', '_PATIENT', '_cohort', '_primary_disease', '_primary_site', 'additional_pharmaceutical_therapy', 'additional_radiation_therapy', 'age_at_initial_pathologic_diagnosis', 'bcr_followup_barcode', 'bcr_patient_barcode', 'bcr_sample_barcode', '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', 'form_completion_date', 'gender', 'height', 'histological_type', 'history_myasthenia_gravis', 'history_of_neoadjuvant_treatment', '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', 'masaoka_stage', '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', 'person_neoplasm_cancer_status', 'post_op_ablation_embolization_tx', 'postoperative_rx_tx', 'radiation_therapy', 'sample_type', 'sample_type_id', 'section_myasthenia_gravis', 'tissue_prospective_collection_indicator', 'tissue_retrospective_collection_indicator', 'tissue_source_site', 'tumor_tissue_site', 'vial_number', 'vital_status', 'weight', 'year_of_initial_pathologic_diagnosis', '_GENOMIC_ID_TCGA_THYM_PDMRNAseqCNV', '_GENOMIC_ID_TCGA_THYM_exp_HiSeqV2_exon', '_GENOMIC_ID_TCGA_THYM_mutation_ucsc_maf_gene', '_GENOMIC_ID_TCGA_THYM_exp_HiSeqV2', '_GENOMIC_ID_TCGA_THYM_exp_HiSeqV2_PANCAN', '_GENOMIC_ID_TCGA_THYM_hMethyl450', '_GENOMIC_ID_TCGA_THYM_gistic2', '_GENOMIC_ID_TCGA_THYM_gistic2thd', '_GENOMIC_ID_data/public/TCGA/THYM/miRNA_HiSeq_gene', '_GENOMIC_ID_TCGA_THYM_mutation_bcm_gene', '_GENOMIC_ID_TCGA_THYM_miRNA_HiSeq', '_GENOMIC_ID_TCGA_THYM_mutation_broad_gene', '_GENOMIC_ID_TCGA_THYM_PDMRNAseq', '_GENOMIC_ID_TCGA_THYM_RPPA', '_GENOMIC_ID_TCGA_THYM_exp_HiSeqV2_percentile', '_GENOMIC_ID_TCGA_THYM_mutation_bcgsc_gene']
79
+
80
+ # Identify candidate columns with strict matching to avoid false positives like "stage"
81
+ candidate_age_cols = []
82
+ candidate_gender_cols = []
83
+
84
+ for c in columns:
85
+ cl = c.lower()
86
+ is_age = bool(re.search(r'(^|[^a-z])age([^a-z]|$)', cl)) or ('days_to_birth' in cl) or ('birth' in cl)
87
+ exclude_age = ('stage' in cl) or ('percentage' in cl) or ('percent' in cl) or ('average' in cl)
88
+ if is_age and not exclude_age:
89
+ candidate_age_cols.append(c)
90
+ if ('gender' in cl) or bool(re.search(r'(^|[^a-z])sex([^a-z]|$)', cl)):
91
+ candidate_gender_cols.append(c)
92
+
93
+ print(f"candidate_age_cols = {candidate_age_cols}")
94
+ print(f"candidate_gender_cols = {candidate_gender_cols}")
95
+
96
+ # Load clinical data and preview selected columns if available
97
+ cohort_dir = os.path.join(tcga_root_dir, "THYM")
98
+ if os.path.isdir(cohort_dir):
99
+ try:
100
+ clinical_file_path, _ = tcga_get_relevant_filepaths(cohort_dir)
101
+ clinical_df = pd.read_csv(clinical_file_path, sep='\t', header=0, index_col=0, dtype=str, low_memory=False)
102
+
103
+ age_cols_present = [c for c in candidate_age_cols if c in clinical_df.columns]
104
+ gender_cols_present = [c for c in candidate_gender_cols if c in clinical_df.columns]
105
+
106
+ if age_cols_present:
107
+ print(preview_df(clinical_df[age_cols_present], n=5))
108
+ if gender_cols_present:
109
+ print(preview_df(clinical_df[gender_cols_present], n=5))
110
+ except Exception:
111
+ pass
112
+
113
+ # Step 3: Select Demographic Features
114
+ # Initialize defaults
115
+ age_col = None
116
+ gender_col = None
117
+
118
+ # Helper functions
119
+ def _is_missing(v):
120
+ if v is None:
121
+ return True
122
+ try:
123
+ import math
124
+ if isinstance(v, float) and math.isnan(v):
125
+ return True
126
+ except Exception:
127
+ pass
128
+ s = str(v).strip().lower()
129
+ return s in {"", "na", "nan", "none", "null"}
130
+
131
+ def _find_preview_dict(candidates):
132
+ # Locate a preview dict in globals that contains candidate keys (first-5-values dict from prior step)
133
+ found = []
134
+ for name, obj in globals().items():
135
+ if isinstance(obj, dict) and obj:
136
+ keys = set(obj.keys())
137
+ if any(k in keys for k in candidates):
138
+ found.append(obj)
139
+ if not found:
140
+ return None
141
+ found.sort(key=lambda d: -len(set(d.keys()).intersection(set(candidates))))
142
+ return found[0]
143
+
144
+ def _age_plausible_count(vals, colname):
145
+ # Handle days_to_birth specially by converting to years via abs(days)/365.25
146
+ col_l = (colname or "").lower()
147
+ plausible = 0
148
+ for v in vals:
149
+ if _is_missing(v):
150
+ continue
151
+ if "days_to_birth" in col_l:
152
+ try:
153
+ d = float(v)
154
+ except Exception:
155
+ # try extracting digits
156
+ a = tcga_convert_age(v)
157
+ d = float(a) if a is not None else None
158
+ if d is None:
159
+ continue
160
+ years = abs(d) / 365.25
161
+ if 0 <= years <= 120:
162
+ plausible += 1
163
+ else:
164
+ a = tcga_convert_age(v)
165
+ if a is not None and 0 <= a <= 120:
166
+ plausible += 1
167
+ return plausible
168
+
169
+ def _select_from_preview_dict(preview_dict, candidates, is_gender=False):
170
+ if not isinstance(preview_dict, dict) or not preview_dict:
171
+ return None
172
+ usable_cols = [c for c in candidates if c in preview_dict]
173
+ if not usable_cols:
174
+ return None
175
+
176
+ scored = []
177
+ for col in usable_cols:
178
+ vals = preview_dict.get(col, [])
179
+ non_missing = sum(0 if _is_missing(v) else 1 for v in vals)
180
+ if is_gender:
181
+ valid = sum(1 for v in vals if tcga_convert_gender(v) in (0, 1))
182
+ # Prefer canonical 'gender' on tie
183
+ preference = 0 if col.lower() == "gender" else 1
184
+ scored.append((col, valid, non_missing, preference))
185
+ else:
186
+ plausible = _age_plausible_count(vals, col)
187
+ # Prefer 'age_at_initial_pathologic_diagnosis' then 'days_to_birth'
188
+ pref = 0 if col.lower() == "age_at_initial_pathologic_diagnosis" else (1 if col.lower() == "days_to_birth" else 2)
189
+ scored.append((col, plausible, non_missing, pref))
190
+
191
+ if not scored:
192
+ return None
193
+
194
+ # Sort by: valid/plausible desc, non_missing desc, preference asc
195
+ scored.sort(key=lambda x: (-x[1], -x[2], x[3]))
196
+ best_col = scored[0][0]
197
+ return best_col
198
+
199
+ def _pick_from_dataframe(candidates, is_gender=False):
200
+ import pandas as pd
201
+ dfs = []
202
+ for name, obj in globals().items():
203
+ if isinstance(obj, pd.DataFrame) and any(c in obj.columns for c in candidates):
204
+ dfs.append(obj)
205
+ if not dfs:
206
+ return None, None
207
+ df = sorted(dfs, key=lambda d: -len(d))[0]
208
+
209
+ best_col = None
210
+ best_score = None
211
+ for col in candidates:
212
+ if col not in df.columns:
213
+ continue
214
+ series = df[col]
215
+ try:
216
+ non_missing_ratio = series.notna().mean() if len(series) > 0 else 0.0
217
+ except Exception:
218
+ non_missing_ratio = 0.0
219
+
220
+ if is_gender:
221
+ try:
222
+ valid_ratio = series.apply(lambda v: tcga_convert_gender(v) in (0, 1)).mean() if len(series) > 0 else 0.0
223
+ except Exception:
224
+ valid_ratio = 0.0
225
+ preference = 0 if col.lower() == "gender" else 1
226
+ score = (valid_ratio, non_missing_ratio, -preference)
227
+ else:
228
+ col_l = col.lower()
229
+ plausible_ratio = 0.0
230
+ try:
231
+ if "days_to_birth" in col_l:
232
+ # convert to years
233
+ s = pd.to_numeric(series, errors="coerce")
234
+ years = s.abs() / 365.25
235
+ plausible_ratio = years.between(0, 120).mean()
236
+ else:
237
+ ages = series.apply(tcga_convert_age)
238
+ plausible_ratio = ages.apply(lambda a: (a is not None) and (0 <= a <= 120)).mean()
239
+ except Exception:
240
+ plausible_ratio = 0.0
241
+ pref_rank = 0 if col_l == "age_at_initial_pathologic_diagnosis" else (1 if col_l == "days_to_birth" else 2)
242
+ score = (plausible_ratio, non_missing_ratio, - (2 - pref_rank)) # prefer lower pref_rank
243
+
244
+ if (best_score is None) or (score > best_score):
245
+ best_score = score
246
+ best_col = col
247
+
248
+ return best_col, df
249
+
250
+ # Find the preview dictionaries prepared in the previous step
251
+ age_preview_dict = _find_preview_dict(candidate_age_cols)
252
+ gender_preview_dict = _find_preview_dict(candidate_gender_cols)
253
+
254
+ # Try selection from preview dicts
255
+ if age_preview_dict:
256
+ age_col = _select_from_preview_dict(age_preview_dict, candidate_age_cols, is_gender=False)
257
+
258
+ if gender_preview_dict:
259
+ gender_col = _select_from_preview_dict(gender_preview_dict, candidate_gender_cols, is_gender=True)
260
+
261
+ # If still not determined, try using an available DataFrame
262
+ age_df = None
263
+ gender_df = None
264
+
265
+ if age_col is None and candidate_age_cols:
266
+ age_col, age_df = _pick_from_dataframe(candidate_age_cols, is_gender=False)
267
+
268
+ if gender_col is None and candidate_gender_cols:
269
+ gender_col, gender_df = _pick_from_dataframe(candidate_gender_cols, is_gender=True)
270
+
271
+ # Fallback to canonical defaults if still None
272
+ if age_col is None:
273
+ if "age_at_initial_pathologic_diagnosis" in candidate_age_cols:
274
+ age_col = "age_at_initial_pathologic_diagnosis"
275
+ elif "days_to_birth" in candidate_age_cols:
276
+ age_col = "days_to_birth"
277
+ elif candidate_age_cols:
278
+ age_col = candidate_age_cols[0]
279
+ else:
280
+ age_col = None
281
+
282
+ if gender_col is None:
283
+ if "gender" in candidate_gender_cols:
284
+ gender_col = "gender"
285
+ elif candidate_gender_cols:
286
+ gender_col = candidate_gender_cols[0]
287
+ else:
288
+ gender_col = None
289
+
290
+ # Explicitly print out information for chosen columns using the preview dicts if available, otherwise from DataFrame
291
+ print("Chosen age_col:", age_col)
292
+ if age_col is not None:
293
+ if age_preview_dict and age_col in age_preview_dict:
294
+ print("Age preview values (first 5):", age_preview_dict[age_col])
295
+ elif age_df is not None and age_col in getattr(age_df, "columns", []):
296
+ try:
297
+ print("Age preview values (first 5):", age_df[age_col].head(5).tolist())
298
+ except Exception:
299
+ print("Age preview values (first 5):", None)
300
+ else:
301
+ # Try to find any df containing the chosen column for preview
302
+ try:
303
+ import pandas as pd
304
+ for name, obj in globals().items():
305
+ if isinstance(obj, pd.DataFrame) and age_col in obj.columns:
306
+ print("Age preview values (first 5):", obj[age_col].head(5).tolist())
307
+ break
308
+ else:
309
+ print("Age preview values (first 5):", None)
310
+ except Exception:
311
+ print("Age preview values (first 5):", None)
312
+ else:
313
+ print("Age preview values (first 5):", None)
314
+
315
+ print("Chosen gender_col:", gender_col)
316
+ if gender_col is not None:
317
+ if gender_preview_dict and gender_col in gender_preview_dict:
318
+ print("Gender preview values (first 5):", gender_preview_dict[gender_col])
319
+ elif gender_df is not None and gender_col in getattr(gender_df, "columns", []):
320
+ try:
321
+ print("Gender preview values (first 5):", gender_df[gender_col].head(5).tolist())
322
+ except Exception:
323
+ print("Gender preview values (first 5):", None)
324
+ else:
325
+ # Try to find any df containing the chosen column for preview
326
+ try:
327
+ import pandas as pd
328
+ for name, obj in globals().items():
329
+ if isinstance(obj, pd.DataFrame) and gender_col in obj.columns:
330
+ print("Gender preview values (first 5):", obj[gender_col].head(5).tolist())
331
+ break
332
+ else:
333
+ print("Gender preview values (first 5):", None)
334
+ except Exception:
335
+ print("Gender preview values (first 5):", None)
336
+ else:
337
+ print("Gender preview values (first 5):", None)
338
+
339
+ # Step 4: Feature Engineering and Validation
340
+ import os
341
+ import pandas as pd
342
+
343
+ # 1) Extract and standardize clinical features
344
+ # Use previously selected columns; if not defined, fall back to None
345
+ try:
346
+ age_col
347
+ except NameError:
348
+ age_col = None
349
+ try:
350
+ gender_col
351
+ except NameError:
352
+ gender_col = None
353
+
354
+ selected_clinical = tcga_select_clinical_features(
355
+ clinical_df=clinical_df,
356
+ trait=trait,
357
+ age_col=age_col,
358
+ gender_col=gender_col
359
+ )
360
+
361
+ # If age was taken from days_to_birth, convert to years
362
+ if ("Age" in selected_clinical.columns) and (age_col is not None) and (age_col.lower() == "days_to_birth"):
363
+ s = pd.to_numeric(selected_clinical["Age"], errors="coerce")
364
+ selected_clinical["Age"] = s.abs() / 365.25
365
+
366
+ # Save clinical data for transparency (optional but helpful)
367
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
368
+ selected_clinical.to_csv(out_clinical_data_file)
369
+
370
+ # 2) Normalize gene symbols and save normalized gene expression
371
+ # Ensure numeric gene expression
372
+ genetic_df_numeric = genetic_df.apply(pd.to_numeric, errors='coerce')
373
+ normalized_gene_df = normalize_gene_symbols_in_index(genetic_df_numeric.copy())
374
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
375
+ normalized_gene_df.to_csv(out_gene_data_file)
376
+
377
+ # 3) Link clinical and genetic data on sample IDs
378
+ gene_expr_T = normalized_gene_df.T # samples as rows, genes as columns
379
+ linked_data = selected_clinical.join(gene_expr_T, how='inner')
380
+
381
+ # 4) Handle missing values systematically
382
+ processed_df = handle_missing_values(linked_data.copy(), trait_col=trait)
383
+
384
+ # 5) Determine bias and remove biased demographic features if needed
385
+ trait_biased, processed_df = judge_and_remove_biased_features(processed_df, trait=trait)
386
+
387
+ # 6) Final validation and save cohort info
388
+ # Force native Python bools to avoid JSON serialization issues
389
+ is_gene_available = bool((normalized_gene_df.shape[0] > 0) and (normalized_gene_df.shape[1] > 0))
390
+ is_trait_available = bool((trait in linked_data.columns) and bool(linked_data[trait].notna().any()))
391
+ trait_biased_py = bool(trait_biased)
392
+
393
+ note = "INFO: Age derived from days_to_birth and converted to years when available."
394
+ is_usable = False
395
+ try:
396
+ is_usable = validate_and_save_cohort_info(
397
+ is_final=True,
398
+ cohort="TCGA",
399
+ info_path=json_path,
400
+ is_gene_available=is_gene_available,
401
+ is_trait_available=is_trait_available,
402
+ is_biased=trait_biased_py,
403
+ df=processed_df,
404
+ note=note
405
+ )
406
+ except TypeError:
407
+ # Retry once with a sanitized DataFrame to ensure standard metadata types
408
+ processed_df_safe = processed_df.copy()
409
+ processed_df_safe.columns = processed_df_safe.columns.map(str)
410
+ is_usable = validate_and_save_cohort_info(
411
+ is_final=True,
412
+ cohort="TCGA",
413
+ info_path=json_path,
414
+ is_gene_available=bool(is_gene_available),
415
+ is_trait_available=bool(is_trait_available),
416
+ is_biased=bool(trait_biased_py),
417
+ df=processed_df_safe,
418
+ note=note
419
+ )
420
+
421
+ # 7) Save usable linked data
422
+ if is_usable:
423
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
424
+ processed_df.to_csv(out_data_file)
output/preprocess/Thymoma/cohort_info.json CHANGED
@@ -1,42 +1 @@
1
- {
2
- "GSE42977": {
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": 117
11
- },
12
- "GSE29695": {
13
- "is_usable": false,
14
- "is_gene_available": true,
15
- "is_trait_available": true,
16
- "is_available": true,
17
- "is_biased": true,
18
- "has_age": false,
19
- "has_gender": false,
20
- "sample_size": 41
21
- },
22
- "GSE131027": {
23
- "is_usable": false,
24
- "is_gene_available": true,
25
- "is_trait_available": true,
26
- "is_available": true,
27
- "is_biased": true,
28
- "has_age": false,
29
- "has_gender": false,
30
- "sample_size": 92
31
- },
32
- "TCGA": {
33
- "is_usable": false,
34
- "is_gene_available": true,
35
- "is_trait_available": true,
36
- "is_available": true,
37
- "is_biased": true,
38
- "has_age": true,
39
- "has_gender": true,
40
- "sample_size": 122
41
- }
42
- }
 
1
+ {"GSE42977": {"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": 117, "note": "INFO: Gene IDs mapped from Illumina ILMN probes to HGNC symbols; trait derived from 'tissue' field where any mention of 'Thymoma' is labeled as case (1)."}, "GSE29695": {"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 unavailable in this series; skipped linking, missing value handling, and bias checks."}, "GSE131027": {"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": 92, "note": "WARNING: Severe class imbalance for 'Thymoma': 1 positive vs 91 negative (N=92)."}, "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": 122, "note": "INFO: Age derived from days_to_birth and converted to years when available."}}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
output/preprocess/Thyroid_Cancer/GSE138198.csv ADDED
The diff for this file is too large to render. See raw diff
 
output/preprocess/Thyroid_Cancer/GSE58689.csv CHANGED
The diff for this file is too large to render. See raw diff
 
output/preprocess/Thyroid_Cancer/clinical_data/GSE104006.csv ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ ,GSM2787513,GSM2787514,GSM2787515,GSM2787516,GSM2787517,GSM2787518,GSM2787519,GSM2787520,GSM2787521,GSM2787522,GSM2787523,GSM2787524,GSM2787525,GSM2787526,GSM2787527,GSM2787528,GSM2787529,GSM2787530,GSM2787531,GSM2787532,GSM2787533,GSM2787534,GSM2787535,GSM2787536,GSM2787537,GSM2787538,GSM2787539,GSM2787540,GSM2787541,GSM2787542,GSM2787543,GSM2787544,GSM2787545,GSM2787546
2
+ Thyroid_Cancer,1.0,1.0,1.0,1.0,1.0,1.0,1.0,0.0,1.0,1.0,1.0,0.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,0.0,1.0,1.0,0.0,1.0,1.0,1.0,1.0,1.0,1.0,0.0,0.0,1.0,1.0
3
+ Age,74.0,74.0,72.0,74.0,38.0,50.0,41.0,51.0,73.0,52.0,48.0,59.0,58.0,39.0,37.0,33.0,36.0,70.0,26.0,46.0,57.0,44.0,35.0,42.0,47.0,61.0,38.0,35.0,35.0,38.0,49.0,56.0,52.0,51.0
4
+ Gender,1.0,1.0,0.0,0.0,0.0,0.0,1.0,0.0,1.0,0.0,0.0,1.0,1.0,0.0,0.0,0.0,1.0,0.0,0.0,1.0,0.0,0.0,1.0,1.0,0.0,0.0,0.0,1.0,0.0,0.0,1.0,1.0,0.0,0.0
output/preprocess/Thyroid_Cancer/clinical_data/GSE107754.csv CHANGED
@@ -1,3 +1,3 @@
1
  ,GSM2878070,GSM2878071,GSM2878072,GSM2878073,GSM2878074,GSM2878075,GSM2878076,GSM2878077,GSM2878078,GSM2878079,GSM2878080,GSM2878081,GSM2878082,GSM2891194,GSM2891195,GSM2891196,GSM2891197,GSM2891198,GSM2891199,GSM2891200,GSM2891201,GSM2891202,GSM2891203,GSM2891204,GSM2891205,GSM2891206,GSM2891207,GSM2891208,GSM2891209,GSM2891210,GSM2891211,GSM2891212,GSM2891213,GSM2891214,GSM2891215,GSM2891216,GSM2891217,GSM2891218,GSM2891219,GSM2891220,GSM2891221,GSM2891222,GSM2891223,GSM2891224,GSM2891225,GSM2891226,GSM2891227,GSM2891228,GSM2891229,GSM2891230,GSM2891231,GSM2891232,GSM2891233,GSM2891234,GSM2891235,GSM2891236,GSM2891237,GSM2891238,GSM2891239,GSM2891240,GSM2891241,GSM2891242,GSM2891243,GSM2891244,GSM2891245,GSM2891246,GSM2891247,GSM2891248,GSM2891249,GSM2891250,GSM2891251,GSM2891252,GSM2891253,GSM2891254,GSM2891255,GSM2891256,GSM2891257,GSM2891258,GSM2891259,GSM2891260,GSM2891261,GSM2891262,GSM2891263,GSM2891264
2
- Thyroid_Cancer,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0
3
  Gender,1.0,0.0,1.0,1.0,0.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,0.0,0.0,1.0,0.0,0.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,1.0,0.0,1.0,0.0,0.0,1.0,0.0,1.0,0.0,1.0,1.0,0.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,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,0.0,1.0,0.0,1.0,1.0,1.0
 
1
  ,GSM2878070,GSM2878071,GSM2878072,GSM2878073,GSM2878074,GSM2878075,GSM2878076,GSM2878077,GSM2878078,GSM2878079,GSM2878080,GSM2878081,GSM2878082,GSM2891194,GSM2891195,GSM2891196,GSM2891197,GSM2891198,GSM2891199,GSM2891200,GSM2891201,GSM2891202,GSM2891203,GSM2891204,GSM2891205,GSM2891206,GSM2891207,GSM2891208,GSM2891209,GSM2891210,GSM2891211,GSM2891212,GSM2891213,GSM2891214,GSM2891215,GSM2891216,GSM2891217,GSM2891218,GSM2891219,GSM2891220,GSM2891221,GSM2891222,GSM2891223,GSM2891224,GSM2891225,GSM2891226,GSM2891227,GSM2891228,GSM2891229,GSM2891230,GSM2891231,GSM2891232,GSM2891233,GSM2891234,GSM2891235,GSM2891236,GSM2891237,GSM2891238,GSM2891239,GSM2891240,GSM2891241,GSM2891242,GSM2891243,GSM2891244,GSM2891245,GSM2891246,GSM2891247,GSM2891248,GSM2891249,GSM2891250,GSM2891251,GSM2891252,GSM2891253,GSM2891254,GSM2891255,GSM2891256,GSM2891257,GSM2891258,GSM2891259,GSM2891260,GSM2891261,GSM2891262,GSM2891263,GSM2891264
2
+ Thyroid_Cancer,,,,,,,,,,,,,,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0
3
  Gender,1.0,0.0,1.0,1.0,0.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,0.0,0.0,1.0,0.0,0.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,1.0,0.0,1.0,0.0,0.0,1.0,0.0,1.0,0.0,1.0,1.0,0.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,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,0.0,1.0,0.0,1.0,1.0,1.0
output/preprocess/Thyroid_Cancer/clinical_data/GSE138198.csv CHANGED
@@ -1,3 +1,3 @@
1
  ,GSM4101749,GSM4101750,GSM4101751,GSM4101752,GSM4101753,GSM4101754,GSM4101755,GSM4101756,GSM4101757,GSM4101758,GSM4101759,GSM4101760,GSM4101761,GSM4101762,GSM4101763,GSM4101764,GSM4101765,GSM4101766,GSM4101767,GSM4101768,GSM4101769,GSM4101770,GSM4101771,GSM4101772,GSM4101773,GSM4101774,GSM4101775,GSM4101776,GSM4101777,GSM4101778,GSM4101779,GSM4101780,GSM4101781,GSM4101782,GSM4101783,GSM4101784
2
- Thyroid_Cancer,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,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
3
  Gender,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,0.0,1.0,0.0,0.0,1.0,0.0,0.0,0.0,1.0,0.0,0.0,0.0,1.0,1.0,0.0,0.0,0.0,1.0,0.0,0.0,,,
 
1
  ,GSM4101749,GSM4101750,GSM4101751,GSM4101752,GSM4101753,GSM4101754,GSM4101755,GSM4101756,GSM4101757,GSM4101758,GSM4101759,GSM4101760,GSM4101761,GSM4101762,GSM4101763,GSM4101764,GSM4101765,GSM4101766,GSM4101767,GSM4101768,GSM4101769,GSM4101770,GSM4101771,GSM4101772,GSM4101773,GSM4101774,GSM4101775,GSM4101776,GSM4101777,GSM4101778,GSM4101779,GSM4101780,GSM4101781,GSM4101782,GSM4101783,GSM4101784
2
+ Thyroid_Cancer,,,,,,,,,,,,,,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,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
3
  Gender,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,0.0,1.0,0.0,0.0,1.0,0.0,0.0,0.0,1.0,0.0,0.0,0.0,1.0,1.0,0.0,0.0,0.0,1.0,0.0,0.0,,,
output/preprocess/Thyroid_Cancer/clinical_data/GSE151179.csv CHANGED
@@ -1,3 +1,2 @@
1
- ,GSM4567912,GSM4567913,GSM4567914,GSM4567915,GSM4567916,GSM4567917,GSM4567918,GSM4567919,GSM4567920,GSM4567921,GSM4567922,GSM4567923,GSM4567924,GSM4567925,GSM4567926,GSM4567927,GSM4567928,GSM4567929,GSM4567930,GSM4567931,GSM4567932,GSM4567933,GSM4567934,GSM4567935,GSM4567936,GSM4567937,GSM4567938,GSM4567939,GSM4567940,GSM4567941,GSM4567942,GSM4567943,GSM4567944,GSM4567945,GSM4567946,GSM4567947,GSM4567948,GSM4567949,GSM4567950,GSM4567951,GSM4567952,GSM4567953,GSM4567954,GSM4567955,GSM4567956,GSM4567957,GSM4567958,GSM4567959,GSM4567960,GSM4567961,GSM4567962,GSM4567963
2
- Thyroid_Cancer,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0
3
- Gender,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
 
1
+ GSM4567912,GSM4567913,GSM4567914,GSM4567915,GSM4567916,GSM4567917,GSM4567918,GSM4567919,GSM4567920,GSM4567921,GSM4567922,GSM4567923,GSM4567924,GSM4567925,GSM4567926,GSM4567927,GSM4567928,GSM4567929,GSM4567930,GSM4567931,GSM4567932,GSM4567933,GSM4567934,GSM4567935,GSM4567936,GSM4567937,GSM4567938,GSM4567939,GSM4567940,GSM4567941,GSM4567942,GSM4567943,GSM4567944,GSM4567945,GSM4567946,GSM4567947,GSM4567948,GSM4567949,GSM4567950,GSM4567951,GSM4567952,GSM4567953,GSM4567954,GSM4567955,GSM4567956,GSM4567957,GSM4567958,GSM4567959,GSM4567960,GSM4567961,GSM4567962,GSM4567963
2
+ 1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,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
 
output/preprocess/Thyroid_Cancer/clinical_data/GSE151181.csv CHANGED
@@ -1,2 +1,2 @@
1
- GSM4567912,GSM4567913,GSM4567914,GSM4567915,GSM4567916,GSM4567917,GSM4567918,GSM4567919,GSM4567920,GSM4567921,GSM4567922,GSM4567923,GSM4567924,GSM4567925,GSM4567926,GSM4567927,GSM4567928,GSM4567929,GSM4567930,GSM4567931,GSM4567932,GSM4567933,GSM4567934,GSM4567935,GSM4567936,GSM4567937,GSM4567938,GSM4567939,GSM4567940,GSM4567941,GSM4567942,GSM4567943,GSM4567944,GSM4567945,GSM4567946,GSM4567947,GSM4567948,GSM4567949,GSM4567950,GSM4567951,GSM4567952,GSM4567953,GSM4567954,GSM4567955,GSM4567956,GSM4567957,GSM4567958,GSM4567959,GSM4567960,GSM4567961,GSM4567962,GSM4567963
2
- 0.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,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
+ ,GSM4567912,GSM4567913,GSM4567914,GSM4567915,GSM4567916,GSM4567917,GSM4567918,GSM4567919,GSM4567920,GSM4567921,GSM4567922,GSM4567923,GSM4567924,GSM4567925,GSM4567926,GSM4567927,GSM4567928,GSM4567929,GSM4567930,GSM4567931,GSM4567932,GSM4567933,GSM4567934,GSM4567935,GSM4567936,GSM4567937,GSM4567938,GSM4567939,GSM4567940,GSM4567941,GSM4567942,GSM4567943,GSM4567944,GSM4567945,GSM4567946,GSM4567947,GSM4567948,GSM4567949,GSM4567950,GSM4567951,GSM4567952,GSM4567953,GSM4567954,GSM4567955,GSM4567956,GSM4567957,GSM4567958,GSM4567959,GSM4567960,GSM4567961,GSM4567962,GSM4567963
2
+ Thyroid_Cancer,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,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
output/preprocess/Thyroid_Cancer/clinical_data/GSE58689.csv CHANGED
@@ -1,3 +1,4 @@
1
  ,GSM1413225,GSM1413226,GSM1413227,GSM1413228,GSM1413229,GSM1413230,GSM1413231,GSM1413232,GSM1413233,GSM1413234,GSM1413235,GSM1413236,GSM1413237,GSM1413238,GSM1413239,GSM1413240,GSM1413241,GSM1413242,GSM1413243,GSM1413244,GSM1413245,GSM1413246,GSM1413247,GSM1413248,GSM1413249,GSM1413250,GSM1413251,GSM1413252,GSM1413253,GSM1413254,GSM1413255,GSM1413256,GSM1413257,GSM1413258,GSM1413259,GSM1413260,GSM1413261,GSM1413262,GSM1413263,GSM1413264,GSM1413265,GSM1413266,GSM1413267,GSM1413268,GSM1413269
2
  Thyroid_Cancer,0.0,0.0,1.0,0.0,1.0,0.0,1.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,0.0,0.0,1.0,0.0,0.0,1.0,0.0,1.0,0.0,0.0,1.0,0.0,1.0,0.0,1.0,0.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0
3
- Gender,0.0,0.0,,0.0,,0.0,,1.0,0.0,0.0,0.0,,,,1.0,0.0,,0.0,1.0,,0.0,,0.0,0.0,,1.0,,0.0,,0.0,,,,,,,,,,,,,,,
 
 
1
  ,GSM1413225,GSM1413226,GSM1413227,GSM1413228,GSM1413229,GSM1413230,GSM1413231,GSM1413232,GSM1413233,GSM1413234,GSM1413235,GSM1413236,GSM1413237,GSM1413238,GSM1413239,GSM1413240,GSM1413241,GSM1413242,GSM1413243,GSM1413244,GSM1413245,GSM1413246,GSM1413247,GSM1413248,GSM1413249,GSM1413250,GSM1413251,GSM1413252,GSM1413253,GSM1413254,GSM1413255,GSM1413256,GSM1413257,GSM1413258,GSM1413259,GSM1413260,GSM1413261,GSM1413262,GSM1413263,GSM1413264,GSM1413265,GSM1413266,GSM1413267,GSM1413268,GSM1413269
2
  Thyroid_Cancer,0.0,0.0,1.0,0.0,1.0,0.0,1.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,0.0,0.0,1.0,0.0,0.0,1.0,0.0,1.0,0.0,0.0,1.0,0.0,1.0,0.0,1.0,0.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0
3
+ Age,,,47.0,,37.0,,67.0,,,,,26.0,32.0,61.0,,,28.0,,,12.0,,69.0,,,6.0,,24.0,,31.0,,71.0,20.0,66.0,21.0,71.0,44.0,31.0,28.0,44.0,30.0,21.0,19.0,59.0,64.0,23.0
4
+ Gender,,,0.0,,0.0,,1.0,,,,,0.0,0.0,1.0,,,0.0,,,1.0,,0.0,,,0.0,,0.0,,0.0,,0.0,1.0,0.0,0.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0
output/preprocess/Thyroid_Cancer/clinical_data/GSE80022.csv CHANGED
@@ -1,4 +1,2 @@
1
  ,GSM2111207,GSM2111208,GSM2111209,GSM2111210,GSM2111211,GSM2111212,GSM2111213,GSM2111214,GSM2111215,GSM2111216,GSM2111217,GSM2111218,GSM2111219,GSM2111220,GSM2111221,GSM2111222,GSM2111223,GSM2111224,GSM2111225,GSM2111226,GSM2111227,GSM2111228,GSM2111229,GSM2111230,GSM2111231,GSM2111232,GSM2111233,GSM2111234,GSM2111235,GSM2111236,GSM2111237,GSM2111238,GSM2111239,GSM2111240,GSM2111241,GSM2111242,GSM2111243,GSM2111244,GSM2111245,GSM2111246,GSM2111247,GSM2111248,GSM2111249,GSM2111250,GSM2111251,GSM2111252,GSM2111253,GSM2111254,GSM2111255,GSM2111256,GSM2111257,GSM2111258,GSM2111259,GSM2111260,GSM2111261,GSM2111262,GSM2111263,GSM2111264,GSM2111265,GSM2111266,GSM2111267,GSM2111268,GSM2111269,GSM2111270,GSM2111271,GSM2111272,GSM2111273,GSM2111274,GSM2111275,GSM2111276,GSM2111277,GSM2111278,GSM2111279
2
- Thyroid_Cancer,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
3
- Age,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
4
- Gender,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
 
1
  ,GSM2111207,GSM2111208,GSM2111209,GSM2111210,GSM2111211,GSM2111212,GSM2111213,GSM2111214,GSM2111215,GSM2111216,GSM2111217,GSM2111218,GSM2111219,GSM2111220,GSM2111221,GSM2111222,GSM2111223,GSM2111224,GSM2111225,GSM2111226,GSM2111227,GSM2111228,GSM2111229,GSM2111230,GSM2111231,GSM2111232,GSM2111233,GSM2111234,GSM2111235,GSM2111236,GSM2111237,GSM2111238,GSM2111239,GSM2111240,GSM2111241,GSM2111242,GSM2111243,GSM2111244,GSM2111245,GSM2111246,GSM2111247,GSM2111248,GSM2111249,GSM2111250,GSM2111251,GSM2111252,GSM2111253,GSM2111254,GSM2111255,GSM2111256,GSM2111257,GSM2111258,GSM2111259,GSM2111260,GSM2111261,GSM2111262,GSM2111263,GSM2111264,GSM2111265,GSM2111266,GSM2111267,GSM2111268,GSM2111269,GSM2111270,GSM2111271,GSM2111272,GSM2111273,GSM2111274,GSM2111275,GSM2111276,GSM2111277,GSM2111278,GSM2111279
2
+ Thyroid_Cancer,0.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0
 
 
output/preprocess/Thyroid_Cancer/code/GSE104005.py ADDED
@@ -0,0 +1,197 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Thyroid_Cancer"
6
+ cohort = "GSE104005"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Thyroid_Cancer"
10
+ in_cohort_dir = "../DATA/GEO/Thyroid_Cancer/GSE104005"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z6/preprocess/Thyroid_Cancer/GSE104005.csv"
14
+ out_gene_data_file = "./output/z6/preprocess/Thyroid_Cancer/gene_data/GSE104005.csv"
15
+ out_clinical_data_file = "./output/z6/preprocess/Thyroid_Cancer/clinical_data/GSE104005.csv"
16
+ json_path = "./output/z6/preprocess/Thyroid_Cancer/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ import os
40
+ import re
41
+
42
+ # 1) Gene expression availability
43
+ is_gene_available = True # Illumina HumanHT-12 expression beadchip mentioned in background
44
+
45
+ # 2) Variable availability (from provided Sample Characteristics Dictionary)
46
+ trait_row = 0 # 'disease: Thyroid_carcinoma' vs 'disease: Non-neoplastic_thyroid'
47
+ age_row = 2 # 'age: <number>'
48
+ gender_row = 3 # 'Sex: F' / 'Sex: M'
49
+
50
+ # 2.2) Conversion functions
51
+ def _after_colon(value):
52
+ if value is None:
53
+ return None
54
+ if isinstance(value, str):
55
+ parts = value.split(":", 1)
56
+ val = parts[1] if len(parts) > 1 else parts[0]
57
+ return val.strip()
58
+ return str(value).strip()
59
+
60
+ def convert_trait(value):
61
+ v = _after_colon(value)
62
+ if v is None or v == '':
63
+ return None
64
+ norm = v.lower().replace('_', ' ').replace('-', ' ').strip()
65
+ # Controls
66
+ if 'non' in norm and 'neoplastic' in norm:
67
+ return 0
68
+ if norm in {'normal', 'control', 'benign'}:
69
+ return 0
70
+ # Cases
71
+ cancer_keywords = ['carcinoma', 'cancer', 'tumor', 'tumour', 'ptc', 'pdtc', 'atc', 'metastasis', 'metastases']
72
+ if any(k in norm for k in cancer_keywords):
73
+ return 1
74
+ # Fallback: specific exact match
75
+ if norm == 'thyroid carcinoma':
76
+ return 1
77
+ return None
78
+
79
+ def convert_age(value):
80
+ v = _after_colon(value)
81
+ if v is None or v == '':
82
+ return None
83
+ v_low = v.lower()
84
+ if v_low in {'na', 'n/a', 'unknown', 'null'}:
85
+ return None
86
+ match = re.search(r'(\d+(?:\.\d+)?)', v_low)
87
+ if not match:
88
+ return None
89
+ num = float(match.group(1))
90
+ # Return int if whole number to keep data neat
91
+ return int(num) if num.is_integer() else num
92
+
93
+ def convert_gender(value):
94
+ v = _after_colon(value)
95
+ if v is None or v == '':
96
+ return None
97
+ norm = v.strip().lower()
98
+ if norm in {'f', 'female', 'woman', 'girl'}:
99
+ return 0
100
+ if norm in {'m', 'male', 'man', 'boy'}:
101
+ return 1
102
+ return None
103
+
104
+ # 3) Save metadata with initial filtering
105
+ is_trait_available = trait_row is not None
106
+ _ = validate_and_save_cohort_info(
107
+ is_final=False,
108
+ cohort=cohort,
109
+ info_path=json_path,
110
+ is_gene_available=is_gene_available,
111
+ is_trait_available=is_trait_available
112
+ )
113
+
114
+ # 4) Clinical feature extraction (only if trait data available)
115
+ if trait_row is not None:
116
+ selected_clinical_df = geo_select_clinical_features(
117
+ clinical_df=clinical_data,
118
+ trait=trait,
119
+ trait_row=trait_row,
120
+ convert_trait=convert_trait,
121
+ age_row=age_row,
122
+ convert_age=convert_age,
123
+ gender_row=gender_row,
124
+ convert_gender=convert_gender
125
+ )
126
+ clinical_preview = preview_df(selected_clinical_df)
127
+ print("Clinical data preview:", clinical_preview)
128
+
129
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
130
+ selected_clinical_df.to_csv(out_clinical_data_file)
131
+
132
+ # Step 3: Gene Data Extraction
133
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
134
+ gene_data = get_genetic_data(matrix_file)
135
+
136
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
137
+ print(gene_data.index[:20])
138
+
139
+ # Step 4: Gene Identifier Review
140
+ print("requires_gene_mapping = True")
141
+
142
+ # Step 5: Gene Annotation
143
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
144
+ gene_annotation = get_gene_annotation(soft_file)
145
+
146
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
147
+ print("Gene annotation preview:")
148
+ print(preview_df(gene_annotation))
149
+
150
+ # Step 6: Gene Identifier Mapping
151
+ # Decide columns for probe ID and gene symbol based on annotation preview
152
+ probe_col = 'ID' # Matches ILMN_* probe IDs seen in expression data
153
+ symbol_col = 'Symbol' if 'Symbol' in gene_annotation.columns else 'ILMN_Gene'
154
+
155
+ # Build probe-to-gene mapping dataframe
156
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=probe_col, gene_col=symbol_col)
157
+
158
+ # Apply mapping to convert probe-level data to gene-level expression
159
+ gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
160
+
161
+ # Step 7: Data Normalization and Linking
162
+ import os
163
+
164
+ # 1. Normalize gene symbols and save
165
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
166
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
167
+ normalized_gene_data.to_csv(out_gene_data_file)
168
+
169
+ # 2. Link clinical and genetic data
170
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
171
+
172
+ # 3. Handle missing values
173
+ linked_data = handle_missing_values(linked_data, trait)
174
+
175
+ # 4. Bias assessment and removal of biased demographic features
176
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
177
+
178
+ # 5. Final validation and save cohort info using actual availability flags
179
+ is_gene_available_final = (normalized_gene_data.shape[0] > 0) and (normalized_gene_data.shape[1] > 0)
180
+ is_trait_available_final = trait in selected_clinical_df.index
181
+
182
+ note = "INFO: Illumina HumanHT-12 probe data mapped to gene symbols; trait from 'disease' field; miRNA platform present but gene chip used."
183
+ is_usable = validate_and_save_cohort_info(
184
+ is_final=True,
185
+ cohort=cohort,
186
+ info_path=json_path,
187
+ is_gene_available=is_gene_available_final,
188
+ is_trait_available=is_trait_available_final,
189
+ is_biased=is_trait_biased,
190
+ df=unbiased_linked_data,
191
+ note=note
192
+ )
193
+
194
+ # 6. Save linked data if usable
195
+ if is_usable:
196
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
197
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Thyroid_Cancer/code/GSE104006.py ADDED
@@ -0,0 +1,262 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Thyroid_Cancer"
6
+ cohort = "GSE104006"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Thyroid_Cancer"
10
+ in_cohort_dir = "../DATA/GEO/Thyroid_Cancer/GSE104006"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z6/preprocess/Thyroid_Cancer/GSE104006.csv"
14
+ out_gene_data_file = "./output/z6/preprocess/Thyroid_Cancer/gene_data/GSE104006.csv"
15
+ out_clinical_data_file = "./output/z6/preprocess/Thyroid_Cancer/clinical_data/GSE104006.csv"
16
+ json_path = "./output/z6/preprocess/Thyroid_Cancer/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ import os
40
+ import re
41
+ import math
42
+
43
+ # 1) Gene expression availability (SuperSeries includes gene expression profiling, not just miRNA)
44
+ is_gene_available = True
45
+
46
+ # 2) Variable availability based on the provided Sample Characteristics Dictionary
47
+ trait_row = 0 # 'disease: Thyroid_carcinoma' vs 'disease: Non-neoplastic_thyroid'
48
+ age_row = 2 # 'age: <number>'
49
+ gender_row = 3 # 'Sex: F/M'
50
+
51
+ # 2.2 Conversion functions
52
+ def _after_colon(x):
53
+ if x is None:
54
+ return None
55
+ s = str(x).strip()
56
+ parts = s.split(':', 1)
57
+ val = parts[1] if len(parts) > 1 else parts[0]
58
+ return val.strip().strip('"').strip("'")
59
+
60
+ def convert_trait(x):
61
+ v = _after_colon(x)
62
+ if v is None or v == '':
63
+ return None
64
+ vl = v.lower()
65
+ # Explicit mappings
66
+ if vl in {'thyroid_carcinoma'}:
67
+ return 1
68
+ if 'non-neoplastic' in vl or vl in {'non-neoplastic_thyroid', 'normal', 'control'}:
69
+ return 0
70
+ # Heuristic for robustness
71
+ if any(k in vl for k in ['carcinoma', 'cancer', 'tumor', 'malignant']):
72
+ return 1
73
+ if any(k in vl for k in ['benign', 'adjacent normal', 'healthy']):
74
+ return 0
75
+ return None
76
+
77
+ def convert_age(x):
78
+ v = _after_colon(x)
79
+ if v is None or v == '':
80
+ return None
81
+ # Extract first number
82
+ m = re.search(r'[-+]?\d+(\.\d+)?', v)
83
+ if not m:
84
+ return None
85
+ try:
86
+ age = float(m.group())
87
+ if 0 <= age <= 120:
88
+ return age
89
+ return None
90
+ except Exception:
91
+ return None
92
+
93
+ def convert_gender(x):
94
+ v = _after_colon(x)
95
+ if v is None or v == '':
96
+ return None
97
+ vl = v.lower()
98
+ if vl in {'f', 'female', 'women', 'woman'}:
99
+ return 0
100
+ if vl in {'m', 'male', 'men', 'man'}:
101
+ return 1
102
+ return None
103
+
104
+ # 3) Save metadata with initial filtering
105
+ is_trait_available = trait_row is not None
106
+ _ = validate_and_save_cohort_info(
107
+ is_final=False,
108
+ cohort=cohort,
109
+ info_path=json_path,
110
+ is_gene_available=is_gene_available,
111
+ is_trait_available=is_trait_available
112
+ )
113
+
114
+ # 4) Clinical Feature Extraction (only if clinical data available)
115
+ if trait_row is not None:
116
+ selected_clinical_df = geo_select_clinical_features(
117
+ clinical_df=clinical_data,
118
+ trait=trait,
119
+ trait_row=trait_row,
120
+ convert_trait=convert_trait,
121
+ age_row=age_row,
122
+ convert_age=convert_age,
123
+ gender_row=gender_row,
124
+ convert_gender=convert_gender
125
+ )
126
+ print(preview_df(selected_clinical_df))
127
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
128
+ selected_clinical_df.to_csv(out_clinical_data_file)
129
+
130
+ # Step 3: Gene Data Extraction
131
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
132
+ gene_data = get_genetic_data(matrix_file)
133
+
134
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
135
+ print(gene_data.index[:20])
136
+
137
+ # Step 4: Gene Identifier Review
138
+ # Identifiers like 'hsa-let-7a-5p' are miRNA IDs (miRBase style), not HGNC gene symbols; thus mapping would be required.
139
+ requires_gene_mapping = True
140
+ print(f"requires_gene_mapping = {requires_gene_mapping}")
141
+
142
+ # Step 5: Gene Annotation
143
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
144
+ gene_annotation = get_gene_annotation(soft_file)
145
+
146
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
147
+ print("Gene annotation preview:")
148
+ print(preview_df(gene_annotation))
149
+
150
+ # Step 6: Gene Identifier Mapping
151
+ # Robust mapping with platform consistency checks. Do not keep unmapped miRNA data as gene_data.
152
+
153
+ import re
154
+
155
+ # Preserve original expression data
156
+ expr_df = gene_data.copy()
157
+ expr_ids = pd.Index(expr_df.index.astype(str))
158
+
159
+ # Heuristics: detect miRNA-like identifiers in expression data
160
+ mirna_like = expr_ids.str.contains(r'(^hsa-)|(^miR)|(^mir-)|(-3p$)|(-5p$)', case=False, regex=True)
161
+ mirna_fraction = mirna_like.mean()
162
+
163
+ # Quick peek of annotation ID-like columns
164
+ candidate_id_cols = [c for c in gene_annotation.columns if c.lower() in {'id', 'name', 'probe_id', 'probeid', 'transcript'}]
165
+ if not candidate_id_cols:
166
+ candidate_id_cols = list(gene_annotation.columns)
167
+
168
+ # Compute overlaps and show a few intersecting IDs to validate
169
+ overlap_stats = {}
170
+ overlap_examples = {}
171
+ expr_id_set = set(expr_ids)
172
+ for col in candidate_id_cols:
173
+ try:
174
+ ann_vals = gene_annotation[col].dropna().astype(str).str.strip()
175
+ ann_set = set(ann_vals)
176
+ inter = expr_id_set.intersection(ann_set)
177
+ overlap_stats[col] = len(inter)
178
+ if inter:
179
+ overlap_examples[col] = list(sorted(list(inter))[:5])
180
+ except Exception:
181
+ continue
182
+
183
+ # Select the best ID column
184
+ best_id_col = None
185
+ best_overlap = -1
186
+ for col, n in overlap_stats.items():
187
+ if n > best_overlap:
188
+ best_overlap = n
189
+ best_id_col = col
190
+
191
+ total_ids = len(expr_ids)
192
+ print(f"Detected miRNA-like identifiers in expression matrix: {mirna_fraction:.2%} of rows")
193
+ print(f"Annotation-ID overlap by column (top 10): {dict(list(sorted(overlap_stats.items(), key=lambda x: -x[1]))[:10])}")
194
+ if best_id_col is not None and best_overlap > 0:
195
+ print(f"Sample intersecting IDs for column '{best_id_col}': {overlap_examples.get(best_id_col, [])}")
196
+ print(f"Selected ID column: {best_id_col!r} with {best_overlap} overlapping IDs out of {total_ids}")
197
+
198
+ # Choose a gene symbol column with common names preference
199
+ preferred_symbol_cols = [
200
+ 'Symbol', 'Gene Symbol', 'Gene_Symbol', 'Gene symbol', 'Gene', 'GENE_SYMBOL',
201
+ 'ILMN_Gene', 'HGNC_symbol', 'HGNC', 'miRNA_ID', 'miRNA', 'MIRNA_SYMBOL', 'Transcript'
202
+ ]
203
+ gene_col = next((c for c in preferred_symbol_cols if c in gene_annotation.columns), None)
204
+ if gene_col is None:
205
+ # Fallback to any column that is not the ID column
206
+ candidates = [c for c in gene_annotation.columns if c != best_id_col]
207
+ gene_col = candidates[0] if candidates else gene_annotation.columns[0]
208
+ print(f"Selected gene symbol column: {gene_col!r}")
209
+
210
+ # Platform consistency and mapping decision:
211
+ platform_mismatch = False
212
+ # If expression looks like miRNA while annotation IDs look like ILMN_* (mRNA), declare mismatch
213
+ ann_id_sample = gene_annotation[best_id_col].dropna().astype(str).str.strip() if best_id_col is not None else pd.Series([], dtype=str)
214
+ ann_looks_ilmn = ann_id_sample.str.startswith('ILMN_').mean() > 0.1 if len(ann_id_sample) > 0 else False
215
+
216
+ if mirna_fraction > 0.5 and ann_looks_ilmn:
217
+ platform_mismatch = True
218
+
219
+ # If there is effectively no overlap, also treat as mismatch
220
+ minimal_overlap = best_overlap <= max(5, int(0.001 * total_ids))
221
+
222
+ if platform_mismatch or minimal_overlap or best_id_col is None:
223
+ print("ERROR: Platform mismatch or insufficient overlap between expression IDs and annotation IDs detected.")
224
+ print("The matrix file appears to be miRNA/small RNA (e.g., 'hsa-let-7*'), while the SOFT annotation corresponds to an Illumina mRNA array (e.g., 'ILMN_*').")
225
+ print("Mapping to human gene symbols cannot be performed with these files. Marking gene data as unavailable for this cohort.")
226
+ # Do not keep miRNA-level data as gene_data; set to empty to fail downstream QC gracefully.
227
+ gene_data = pd.DataFrame()
228
+ try:
229
+ # Update initial metadata to reflect unavailability of gene-level data
230
+ _ = validate_and_save_cohort_info(
231
+ is_final=False,
232
+ cohort=cohort,
233
+ info_path=json_path,
234
+ is_gene_available=False,
235
+ is_trait_available=(True if 'trait_row' in globals() and trait_row is not None else False)
236
+ )
237
+ except Exception as e:
238
+ print(f"Metadata update warning (non-fatal): {e}")
239
+ else:
240
+ # Build mapping and apply it
241
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=best_id_col, gene_col=gene_col)
242
+ gene_data_mapped = apply_gene_mapping(expression_df=expr_df, mapping_df=mapping_df)
243
+
244
+ # Validate mapped result
245
+ if gene_data_mapped is None or gene_data_mapped.empty:
246
+ print("ERROR: Mapping produced an empty gene-level dataframe. Not preserving original miRNA/probe-level data.")
247
+ gene_data = pd.DataFrame()
248
+ try:
249
+ _ = validate_and_save_cohort_info(
250
+ is_final=False,
251
+ cohort=cohort,
252
+ info_path=json_path,
253
+ is_gene_available=False,
254
+ is_trait_available=(True if 'trait_row' in globals() and trait_row is not None else False)
255
+ )
256
+ except Exception as e:
257
+ print(f"Metadata update warning (non-fatal): {e}")
258
+ else:
259
+ gene_data = gene_data_mapped
260
+ print(f"Mapping succeeded. Gene-level dataframe shape: {gene_data.shape}")
261
+ # Show a few gene symbols
262
+ print(f"Example mapped genes: {list(gene_data.index[:10])}")
output/preprocess/Thyroid_Cancer/code/GSE107754.py ADDED
@@ -0,0 +1,200 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Thyroid_Cancer"
6
+ cohort = "GSE107754"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Thyroid_Cancer"
10
+ in_cohort_dir = "../DATA/GEO/Thyroid_Cancer/GSE107754"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z6/preprocess/Thyroid_Cancer/GSE107754.csv"
14
+ out_gene_data_file = "./output/z6/preprocess/Thyroid_Cancer/gene_data/GSE107754.csv"
15
+ out_clinical_data_file = "./output/z6/preprocess/Thyroid_Cancer/clinical_data/GSE107754.csv"
16
+ json_path = "./output/z6/preprocess/Thyroid_Cancer/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ import os
40
+ import pandas as pd
41
+
42
+ # 1) Gene expression availability
43
+ is_gene_available = True # Whole human genome gene expression microarrays per series description.
44
+
45
+ # 2) Variable availability and converters
46
+
47
+ # Trait: Thyroid_Cancer can be inferred from "tissue: Thyroid cancer" under key 2
48
+ trait_row = 2
49
+
50
+ # Age: not available in the provided characteristics
51
+ age_row = None
52
+
53
+ # Gender: available under key 0
54
+ gender_row = 0
55
+
56
+ def convert_trait(x):
57
+ if x is None:
58
+ return None
59
+ s = str(x).strip()
60
+ if s == "":
61
+ return None
62
+ parts = s.split(":", 1)
63
+ if len(parts) == 2:
64
+ header = parts[0].strip().lower()
65
+ value = parts[1].strip().lower()
66
+ # Only use records that specify tissue for trait inference
67
+ if "tissue" in header:
68
+ if "thyroid" in value:
69
+ return 1
70
+ # Any other specified tissue (non-thyroid) -> control (0)
71
+ # We assume all entries are cancers/tumors per dataset description.
72
+ return 0
73
+ else:
74
+ # Irrelevant headers like dataset, biopsy location, suvmean35, etc.
75
+ return None
76
+ else:
77
+ # Fallback: no colon present, attempt heuristic
78
+ s_low = s.lower()
79
+ if "thyroid" in s_low:
80
+ return 1
81
+ return None
82
+
83
+ def convert_age(x):
84
+ # Age not available
85
+ return None
86
+
87
+ def convert_gender(x):
88
+ if x is None:
89
+ return None
90
+ s = str(x).strip()
91
+ if s == "":
92
+ return None
93
+ parts = s.split(":", 1)
94
+ val = parts[1].strip().lower() if len(parts) == 2 else s.lower()
95
+ if val in ["female", "f", "woman", "women"]:
96
+ return 0
97
+ if val in ["male", "m", "man", "men"]:
98
+ return 1
99
+ return None
100
+
101
+ # 3) Save metadata using initial filtering
102
+ is_trait_available = trait_row is not None
103
+ _ = validate_and_save_cohort_info(
104
+ is_final=False,
105
+ cohort=cohort,
106
+ info_path=json_path,
107
+ is_gene_available=is_gene_available,
108
+ is_trait_available=is_trait_available
109
+ )
110
+
111
+ # 4) Clinical feature extraction (only if trait_row is not None)
112
+ if trait_row is not None:
113
+ selected_clinical_df = geo_select_clinical_features(
114
+ clinical_df=clinical_data,
115
+ trait=trait,
116
+ trait_row=trait_row,
117
+ convert_trait=convert_trait,
118
+ age_row=age_row,
119
+ convert_age=convert_age,
120
+ gender_row=gender_row,
121
+ convert_gender=convert_gender
122
+ )
123
+ preview = preview_df(selected_clinical_df)
124
+ print("Clinical features preview:", preview)
125
+
126
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
127
+ 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
+ # Identify columns for probe IDs and gene symbols in the annotation
149
+ probe_col = 'ID'
150
+ gene_symbol_col = 'GENE_SYMBOL'
151
+
152
+ # Build mapping dataframe from annotation
153
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=probe_col, gene_col=gene_symbol_col)
154
+
155
+ # Apply mapping to convert probe-level data to gene-level expression
156
+ gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
157
+
158
+ # Step 7: Data Normalization and Linking
159
+ import os
160
+ import pandas as pd
161
+
162
+ # 1. Normalize gene symbols and save normalized gene data
163
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
164
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
165
+ normalized_gene_data.to_csv(out_gene_data_file)
166
+
167
+ # Ensure clinical data is available in this scope; load from disk if necessary
168
+ try:
169
+ selected_clinical_df
170
+ except NameError:
171
+ selected_clinical_df = pd.read_csv(out_clinical_data_file, index_col=0)
172
+
173
+ # 2. Link clinical and genetic data
174
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
175
+
176
+ # 3. Handle missing values
177
+ linked_data = handle_missing_values(linked_data, trait)
178
+
179
+ # 4. Bias check and removal of biased demographic features
180
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
181
+
182
+ # 5. Final quality validation and save cohort metadata
183
+ is_gene_available = (normalized_gene_data.shape[0] > 0) and (normalized_gene_data.shape[1] > 0)
184
+ is_trait_available = trait in linked_data.columns
185
+ note = "INFO: Trait inferred from tissue; mixed metastatic tumor cohort; no age feature; gender included."
186
+ is_usable = validate_and_save_cohort_info(
187
+ is_final=True,
188
+ cohort=cohort,
189
+ info_path=json_path,
190
+ is_gene_available=is_gene_available,
191
+ is_trait_available=is_trait_available,
192
+ is_biased=is_trait_biased,
193
+ df=unbiased_linked_data,
194
+ note=note
195
+ )
196
+
197
+ # 6. Save linked data if usable
198
+ if is_usable:
199
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
200
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Thyroid_Cancer/code/GSE138198.py ADDED
@@ -0,0 +1,207 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Thyroid_Cancer"
6
+ cohort = "GSE138198"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Thyroid_Cancer"
10
+ in_cohort_dir = "../DATA/GEO/Thyroid_Cancer/GSE138198"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z6/preprocess/Thyroid_Cancer/GSE138198.csv"
14
+ out_gene_data_file = "./output/z6/preprocess/Thyroid_Cancer/gene_data/GSE138198.csv"
15
+ out_clinical_data_file = "./output/z6/preprocess/Thyroid_Cancer/clinical_data/GSE138198.csv"
16
+ json_path = "./output/z6/preprocess/Thyroid_Cancer/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ import os
40
+ import pandas as pd
41
+ import re
42
+
43
+ # 1) Gene expression data availability
44
+ is_gene_available = True # Affymetrix Human Gene 1.0 ST arrays -> gene expression
45
+
46
+ # 2) Variable availability
47
+ trait_row = 1 # sample type
48
+ age_row = None # not available in the characteristics
49
+ gender_row = 0 # gender
50
+
51
+ is_trait_available = trait_row is not None
52
+
53
+ # 2.2) Converters
54
+ def _extract_value(x):
55
+ if x is None:
56
+ return ""
57
+ s = str(x)
58
+ if ":" in s:
59
+ s = s.split(":", 1)[1]
60
+ return s.strip()
61
+
62
+ def convert_trait(x):
63
+ v = _extract_value(x).lower()
64
+ # Exclude descriptive line listing all categories
65
+ if ('and three normal' in v) or ("hashimoto's thyroiditis" in v and 'normal thyroid' in v):
66
+ return None
67
+ # Cancer present (catch-all for any PTC mention)
68
+ if ('ptc' in v) or ('mptc' in v):
69
+ return 1
70
+ # Non-cancer categories
71
+ if ('normal thyroid' in v) or re.search(r'\btn\b', v):
72
+ return 0
73
+ if ('hashimoto' in v) or re.search(r'\bht\b', v):
74
+ return 0
75
+ return None
76
+
77
+ def convert_age(x):
78
+ return None # age not available in this dataset
79
+
80
+ def convert_gender(x):
81
+ v = _extract_value(x).lower()
82
+ if v in {'f', 'female'}:
83
+ return 0
84
+ if v in {'m', 'male'}:
85
+ return 1
86
+ if 'not available' in v or v == '':
87
+ return None
88
+ return None
89
+
90
+ # 3) Save metadata (initial filtering)
91
+ _ = validate_and_save_cohort_info(
92
+ is_final=False,
93
+ cohort=cohort,
94
+ info_path=json_path,
95
+ is_gene_available=is_gene_available,
96
+ is_trait_available=is_trait_available
97
+ )
98
+
99
+ # 4) Clinical feature extraction and save
100
+ if trait_row is not None:
101
+ selected_clinical_df = geo_select_clinical_features(
102
+ clinical_df=clinical_data,
103
+ trait=trait,
104
+ trait_row=trait_row,
105
+ convert_trait=convert_trait,
106
+ age_row=age_row,
107
+ convert_age=convert_age,
108
+ gender_row=gender_row,
109
+ convert_gender=convert_gender
110
+ )
111
+ print("Selected clinical shape:", selected_clinical_df.shape)
112
+ preview = preview_df(selected_clinical_df, n=5)
113
+ print(preview)
114
+ # Save clinical features
115
+ clinical_dir = os.path.dirname(out_clinical_data_file)
116
+ os.makedirs(clinical_dir, exist_ok=True)
117
+ selected_clinical_df.to_csv(out_clinical_data_file)
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
+ # Based on the provided identifiers (e.g., '7892501'), these are probe/transcript IDs (e.g., Affymetrix),
128
+ # not human gene symbols. Hence mapping to gene symbols is required.
129
+ print("requires_gene_mapping = True")
130
+
131
+ # Step 5: Gene Annotation
132
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
133
+ gene_annotation = get_gene_annotation(soft_file)
134
+
135
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
136
+ print("Gene annotation preview:")
137
+ print(preview_df(gene_annotation))
138
+
139
+ # Step 6: Gene Identifier Mapping
140
+ # Decide the appropriate columns for mapping:
141
+ # - Probe/ID column in gene_annotation matches the expression IDs: 'ID'
142
+ # - Gene symbol information is embedded in the 'gene_assignment' column
143
+ probe_col = 'ID'
144
+ gene_symbol_col = 'gene_assignment'
145
+
146
+ # 2. Build the mapping dataframe (ID -> Gene)
147
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=probe_col, gene_col=gene_symbol_col)
148
+
149
+ # 3. Apply the mapping to convert probe-level data to gene-level expression
150
+ gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
151
+
152
+ # Step 7: Data Normalization and Linking
153
+ import os
154
+
155
+ # 1. Normalize gene symbols and save gene expression data
156
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
157
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
158
+ normalized_gene_data.to_csv(out_gene_data_file)
159
+
160
+ # 2. Link clinical and genetic data
161
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
162
+
163
+ # 3. Handle missing values
164
+ linked_data = handle_missing_values(linked_data, trait)
165
+
166
+ # 4. Bias assessment and removal of biased demographic features
167
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
168
+
169
+ # Ensure native Python bools for JSON serialization
170
+ is_trait_biased = bool(is_trait_biased)
171
+ is_gene_available = bool((normalized_gene_data.shape[0] > 0) and (normalized_gene_data.shape[1] > 0))
172
+ is_trait_available = bool((trait in linked_data.columns) and bool(linked_data[trait].notna().any()))
173
+
174
+ # 5. Final validation and save cohort info
175
+ note = ("INFO: Affymetrix Human Gene 1.0 ST platform; age not available; gender partially missing; "
176
+ "probe-to-gene mapping via SOFT gene_assignment with equal-split aggregation.")
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,
184
+ is_trait_available=is_trait_available,
185
+ is_biased=is_trait_biased,
186
+ df=unbiased_linked_data,
187
+ note=note
188
+ )
189
+ except TypeError:
190
+ # If serialization fails due to non-native bool types in an existing file, recreate and retry once.
191
+ if os.path.exists(json_path):
192
+ os.remove(json_path)
193
+ is_usable = validate_and_save_cohort_info(
194
+ is_final=True,
195
+ cohort=cohort,
196
+ info_path=json_path,
197
+ is_gene_available=is_gene_available,
198
+ is_trait_available=is_trait_available,
199
+ is_biased=is_trait_biased,
200
+ df=unbiased_linked_data,
201
+ note=note
202
+ )
203
+
204
+ # 6. Save linked data if usable
205
+ if is_usable:
206
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
207
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Thyroid_Cancer/code/GSE151179.py ADDED
@@ -0,0 +1,316 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Thyroid_Cancer"
6
+ cohort = "GSE151179"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Thyroid_Cancer"
10
+ in_cohort_dir = "../DATA/GEO/Thyroid_Cancer/GSE151179"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z6/preprocess/Thyroid_Cancer/GSE151179.csv"
14
+ out_gene_data_file = "./output/z6/preprocess/Thyroid_Cancer/gene_data/GSE151179.csv"
15
+ out_clinical_data_file = "./output/z6/preprocess/Thyroid_Cancer/clinical_data/GSE151179.csv"
16
+ json_path = "./output/z6/preprocess/Thyroid_Cancer/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ # Step 1: Determine gene expression availability
40
+ is_gene_available = True # Gene expression profiling by Thermo Fisher Human Clariom S Assay is described
41
+
42
+ # Step 2: Variable availability and converters
43
+
44
+ # Identify rows in the sample characteristics dictionary
45
+ trait_row = 1 # 'tissue type' differentiates tumor/metastasis vs non-neoplastic thyroid
46
+ age_row = None # No age info in the sample characteristics dictionary
47
+ gender_row = None # No gender info in the sample characteristics dictionary
48
+
49
+ def _extract_value(x):
50
+ if x is None:
51
+ return None
52
+ if isinstance(x, str):
53
+ parts = x.split(":", 1)
54
+ val = parts[1] if len(parts) > 1 else parts[0]
55
+ val = val.strip()
56
+ return val if val != "" else None
57
+ return x
58
+
59
+ def convert_trait(x):
60
+ v = _extract_value(x)
61
+ if v is None:
62
+ return None
63
+ v_low = v.lower()
64
+ # Map non-neoplastic thyroid to 0; any tumor/metastasis to 1
65
+ if "non-neoplastic" in v_low:
66
+ return 0
67
+ if ("tumor" in v_low) or ("metastasis" in v_low):
68
+ return 1
69
+ # Conservative fallback
70
+ return None
71
+
72
+ def convert_age(x):
73
+ v = _extract_value(x)
74
+ if v is None:
75
+ return None
76
+ # Extract first numeric token as age
77
+ import re
78
+ m = re.search(r"(\d+(\.\d+)?)", str(v))
79
+ if not m:
80
+ return None
81
+ age = float(m.group(1))
82
+ if age <= 0 or age > 120:
83
+ return None
84
+ return age
85
+
86
+ def convert_gender(x):
87
+ v = _extract_value(x)
88
+ if v is None:
89
+ return None
90
+ v_low = str(v).strip().lower()
91
+ if v_low in {"female", "f", "woman", "women"}:
92
+ return 0
93
+ if v_low in {"male", "m", "man", "men"}:
94
+ return 1
95
+ return None
96
+
97
+ # Step 3: Save metadata (initial filtering)
98
+ is_trait_available = trait_row is not None
99
+ _ = validate_and_save_cohort_info(
100
+ is_final=False,
101
+ cohort=cohort,
102
+ info_path=json_path,
103
+ is_gene_available=is_gene_available,
104
+ is_trait_available=is_trait_available
105
+ )
106
+
107
+ # Step 4: Clinical feature extraction (only if trait data is available)
108
+ if trait_row is not None:
109
+ selected_clinical_df = geo_select_clinical_features(
110
+ clinical_df=clinical_data,
111
+ trait=trait,
112
+ trait_row=trait_row,
113
+ convert_trait=convert_trait,
114
+ age_row=age_row,
115
+ convert_age=convert_age,
116
+ gender_row=gender_row,
117
+ convert_gender=convert_gender
118
+ )
119
+ # Preview and save
120
+ preview = preview_df(selected_clinical_df)
121
+ print("Preview of selected clinical features:", preview)
122
+
123
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
124
+ selected_clinical_df.to_csv(out_clinical_data_file, index=False)
125
+
126
+ # Step 3: Gene Data Extraction
127
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
128
+ gene_data = get_genetic_data(matrix_file)
129
+
130
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
131
+ print(gene_data.index[:20])
132
+
133
+ # Step 4: Gene Identifier Review
134
+ requires_gene_mapping = True
135
+ print(f"requires_gene_mapping = {requires_gene_mapping}")
136
+
137
+ # Step 5: Gene Annotation
138
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
139
+ gene_annotation = get_gene_annotation(soft_file)
140
+
141
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
142
+ print("Gene annotation preview:")
143
+ print(preview_df(gene_annotation))
144
+
145
+ # Step 6: Gene Identifier Mapping
146
+ # Improved mapping from probe/transcript IDs to clean human gene symbols
147
+
148
+ import re
149
+ import json
150
+
151
+ # Expression IDs from the series matrix
152
+ expr_ids = set(gene_data.index.astype(str))
153
+
154
+ # 1) Identify the annotation column that matches expression IDs
155
+ preferred_id_cols = [
156
+ 'transcript_cluster_id', 'Transcript_Cluster_ID', 'transcript_cluster', 'cluster_id',
157
+ 'Probe Set ID', 'PROBE_SET_ID', 'probeset_id', 'probeset', 'PROBESET_ID', 'probe_id', 'ProbeID',
158
+ 'ID'
159
+ ]
160
+ available_cols = list(gene_annotation.columns)
161
+
162
+ seen = set()
163
+ id_candidates = []
164
+ for c in preferred_id_cols + list(available_cols):
165
+ if c in available_cols and c not in seen:
166
+ id_candidates.append(c)
167
+ seen.add(c)
168
+
169
+ def compute_overlap(series, expr_ids):
170
+ try:
171
+ vals = series.astype(str)
172
+ except Exception:
173
+ return 0
174
+ return int(vals.isin(expr_ids).sum())
175
+
176
+ overlap_counts = {c: compute_overlap(gene_annotation[c], expr_ids) for c in id_candidates}
177
+ id_col = max(overlap_counts, key=overlap_counts.get)
178
+ max_overlap = overlap_counts[id_col]
179
+
180
+ total_expr_ids = len(expr_ids)
181
+ min_required = max(50, int(0.005 * total_expr_ids)) # a bit looser than before but still meaningful
182
+
183
+ if max_overlap < min_required:
184
+ print("Diagnostics: Overlap of annotation columns with expression IDs (top 20):")
185
+ for c, v in sorted(overlap_counts.items(), key=lambda x: x[1], reverse=True)[:20]:
186
+ print(f" {c}: {v}")
187
+ print(f"Chosen id_col: {id_col} with overlap {max_overlap} out of {total_expr_ids} expression IDs.")
188
+ raise ValueError(
189
+ "Failed to find a suitable annotation ID column that matches the expression IDs."
190
+ )
191
+
192
+ # 2) Choose a column containing gene symbols/descriptions
193
+ # Prefer richer annotation text that includes canonical symbols in parentheses
194
+ if 'SPOT_ID.1' in available_cols:
195
+ gene_col = 'SPOT_ID.1'
196
+ elif 'SPOT_ID' in available_cols:
197
+ gene_col = 'SPOT_ID'
198
+ else:
199
+ # fallback to any column with 'gene' in name, else the second column
200
+ candidates = [c for c in available_cols if re.search(r'gene|symbol|assign|annot', str(c), re.I)]
201
+ gene_col = candidates[0] if candidates else (available_cols[1] if len(available_cols) > 1 else available_cols[0])
202
+
203
+ # 3) Parse clean canonical symbols from the chosen annotation column, filtering by synonym dictionary
204
+ with open("./metadata/gene_synonym.json", "r") as f:
205
+ synonym_dict = json.load(f)
206
+ valid_symbols = set(synonym_dict.keys()) # keys are uppercased synonyms
207
+
208
+ gene_like_pattern = re.compile(r'^(?:[A-Z][A-Z0-9-]{1,9}|C\d+ORF\d+)$')
209
+
210
+ def parse_symbols(text: str):
211
+ if not isinstance(text, str) or not text:
212
+ return []
213
+ tokens = []
214
+
215
+ # Extract tokens that appear inside parentheses, which often hold canonical symbols
216
+ # Limit inner content length to avoid capturing long descriptive phrases
217
+ paren_contents = re.findall(r'\(([^)]{1,50})\)', text)
218
+
219
+ for content in paren_contents:
220
+ # Split on common delimiters
221
+ parts = re.split(r'[;/,\s]+', content)
222
+ for p in parts:
223
+ pu = p.strip().upper()
224
+ if gene_like_pattern.match(pu) and pu in valid_symbols:
225
+ tokens.append(synonym_dict.get(pu, pu))
226
+
227
+ # Fallback: if none found from parentheses, use a conservative global scan then filter strictly
228
+ if not tokens:
229
+ from_candidates = extract_human_gene_symbols(text)
230
+ for c in from_candidates:
231
+ cu = c.strip().upper()
232
+ if gene_like_pattern.match(cu) and cu in valid_symbols:
233
+ tokens.append(synonym_dict.get(cu, cu))
234
+
235
+ # Deduplicate while preserving order
236
+ seen_tok = set()
237
+ cleaned = []
238
+ for t in tokens:
239
+ tu = t.strip().upper()
240
+ if tu and tu not in seen_tok:
241
+ cleaned.append(tu)
242
+ seen_tok.add(tu)
243
+ return cleaned
244
+
245
+ # Build mapping: keep only rows with ID overlapping expression IDs and with at least one valid symbol
246
+ ann_sub = gene_annotation[[id_col, gene_col]].dropna()
247
+ ann_sub[id_col] = ann_sub[id_col].astype(str).str.strip()
248
+ ann_sub = ann_sub[ann_sub[id_col].isin(expr_ids)].copy()
249
+
250
+ parsed = ann_sub[gene_col].apply(parse_symbols)
251
+ has_symbols_mask = parsed.apply(lambda lst: len(lst) > 0)
252
+ ann_sub = ann_sub[has_symbols_mask].copy()
253
+ parsed = parsed[has_symbols_mask]
254
+
255
+ # Join parsed symbols into a space-separated string so that apply_gene_mapping will re-extract them cleanly
256
+ ann_sub['Gene'] = parsed.apply(lambda lst: ' '.join(lst))
257
+ ann_sub = ann_sub.rename(columns={id_col: 'ID'})
258
+
259
+ # Sanity check coverage
260
+ mapping_overlap = ann_sub['ID'].astype(str).isin(gene_data.index.astype(str)).sum()
261
+ if mapping_overlap < min_required:
262
+ print(f"Diagnostics: mapping size={len(ann_sub)}, overlap with expression IDs={mapping_overlap}")
263
+ print(f"Selected id_col={id_col}, gene_col={gene_col}")
264
+ print("Example annotation IDs (first 10):", list(ann_sub['ID'].astype(str).head(10)))
265
+ print("Example expression IDs (first 10):", list(pd.Index(gene_data.index.astype(str)).unique()[:10]))
266
+ raise ValueError("Insufficient overlap between mapping IDs and expression IDs; aborting to avoid empty/erroneous gene data.")
267
+
268
+ # 4) Apply mapping to obtain gene-level data
269
+ mapping_df = ann_sub[['ID', 'Gene']]
270
+ gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
271
+
272
+ # 5) Quick validation: print top gene symbols to verify plausibility
273
+ print(f"Gene-level data shape: {gene_data.shape}")
274
+ print("First 20 gene symbols:", list(gene_data.index[:20]))
275
+
276
+ # Step 7: Data Normalization and Linking
277
+ import os
278
+ import pandas as pd
279
+
280
+ # 1. Normalize gene symbols and save gene expression data
281
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
282
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
283
+ normalized_gene_data.to_csv(out_gene_data_file)
284
+
285
+ # 2. Reload clinical data from disk and set the correct index
286
+ clinical_mat = pd.read_csv(out_clinical_data_file)
287
+ clinical_df = clinical_mat.copy()
288
+ clinical_df.index = [trait] # single row with the trait as the feature name
289
+
290
+ # Link clinical and genetic data
291
+ linked_data = geo_link_clinical_genetic_data(clinical_df, normalized_gene_data)
292
+
293
+ # 3. Handle missing values
294
+ linked_data = handle_missing_values(linked_data, trait)
295
+
296
+ # 4. Judge bias and remove biased demographic features (if any)
297
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
298
+
299
+ # 5. Final validation and save cohort metadata
300
+ note = ("INFO: Age and Gender unavailable in sample characteristics; trait derived from 'tissue type'. "
301
+ "Thermo Fisher Human Clariom S platform used; probe-to-gene mapping and symbol normalization applied.")
302
+ is_usable = validate_and_save_cohort_info(
303
+ is_final=True,
304
+ cohort=cohort,
305
+ info_path=json_path,
306
+ is_gene_available=True,
307
+ is_trait_available=True,
308
+ is_biased=is_trait_biased,
309
+ df=unbiased_linked_data,
310
+ note=note
311
+ )
312
+
313
+ # 6. Save linked data if usable
314
+ if is_usable:
315
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
316
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Thyroid_Cancer/code/GSE151181.py ADDED
@@ -0,0 +1,251 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Thyroid_Cancer"
6
+ cohort = "GSE151181"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Thyroid_Cancer"
10
+ in_cohort_dir = "../DATA/GEO/Thyroid_Cancer/GSE151181"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z6/preprocess/Thyroid_Cancer/GSE151181.csv"
14
+ out_gene_data_file = "./output/z6/preprocess/Thyroid_Cancer/gene_data/GSE151181.csv"
15
+ out_clinical_data_file = "./output/z6/preprocess/Thyroid_Cancer/clinical_data/GSE151181.csv"
16
+ json_path = "./output/z6/preprocess/Thyroid_Cancer/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ import os
40
+ import re
41
+ import pandas as pd
42
+
43
+ # 1) Gene expression data availability (not pure miRNA or methylation)
44
+ # Series title indicates both gene and miRNA expression; presence of CIBERSORT purity also suggests mRNA data.
45
+ is_gene_available = True
46
+
47
+ # 2) Variable availability and conversion
48
+ # Trait: Thyroid_Cancer (cancer vs non-neoplastic control)
49
+ trait_row = 1 # 'tissue type' distinguishes non-neoplastic thyroid vs tumor/metastasis
50
+ age_row = None
51
+ gender_row = None
52
+
53
+ def _extract_value(x):
54
+ if pd.isna(x):
55
+ return None
56
+ s = str(x)
57
+ # Extract substring after the first colon if present
58
+ parts = s.split(':', 1)
59
+ val = parts[1] if len(parts) > 1 else parts[0]
60
+ val = val.strip()
61
+ return val if val != '' else None
62
+
63
+ def convert_trait(x):
64
+ v = _extract_value(x)
65
+ if v is None:
66
+ return None
67
+ vl = v.lower()
68
+ # Map non-cancer controls to 0
69
+ non_cancer_terms = [
70
+ 'non-neoplastic thyroid', 'normal', 'adjacent normal', 'benign', 'normal thyroid'
71
+ ]
72
+ if vl in non_cancer_terms:
73
+ return 0
74
+ if vl in {'na', 'n/a', 'unknown', 'not available'}:
75
+ return None
76
+ # Any tumor/metastasis considered cancer = 1
77
+ cancer_indicators = ['tumor', 'metastasis', 'carcinoma', 'ptc', 'primary']
78
+ if any(term in vl for term in cancer_indicators):
79
+ return 1
80
+ return None
81
+
82
+ def convert_age(x):
83
+ v = _extract_value(x)
84
+ if v is None:
85
+ return None
86
+ # find a number (integer or float)
87
+ m = re.search(r'(\d+(?:\.\d+)?)', v)
88
+ if not m:
89
+ return None
90
+ try:
91
+ age_val = float(m.group(1))
92
+ except Exception:
93
+ return None
94
+ if 0 < age_val < 120:
95
+ return age_val
96
+ return None
97
+
98
+ def convert_gender(x):
99
+ v = _extract_value(x)
100
+ if v is None:
101
+ return None
102
+ vl = v.strip().lower()
103
+ if vl in {'female', 'f'}:
104
+ return 0
105
+ if vl in {'male', 'm'}:
106
+ return 1
107
+ return None
108
+
109
+ # 3) Save metadata (initial filtering)
110
+ is_trait_available = trait_row is not None
111
+ _ = validate_and_save_cohort_info(
112
+ is_final=False,
113
+ cohort=cohort,
114
+ info_path=json_path,
115
+ is_gene_available=is_gene_available,
116
+ is_trait_available=is_trait_available
117
+ )
118
+
119
+ # 4) Clinical feature extraction
120
+ if trait_row is not None:
121
+ selected_clinical_df = geo_select_clinical_features(
122
+ clinical_df=clinical_data,
123
+ trait=trait,
124
+ trait_row=trait_row,
125
+ convert_trait=convert_trait
126
+ )
127
+ preview = preview_df(selected_clinical_df, n=5)
128
+ print(preview)
129
+
130
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
131
+ selected_clinical_df.to_csv(out_clinical_data_file)
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
+ # Based on observed gene identifiers from the previous step
142
+ observed_ids = ['23064070', '23064071', '23064072', '23064073', '23064074',
143
+ '23064075', '23064076', '23064077', '23064078', '23064079',
144
+ '23064080', '23064081', '23064083', '23064084', '23064085',
145
+ '23064086', '23064087', '23064088', '23064089', '23064090']
146
+
147
+ # If identifiers are purely numeric probe IDs, they need mapping to human gene symbols.
148
+ requires_gene_mapping = all(x.isdigit() for x in observed_ids)
149
+
150
+ print(f"requires_gene_mapping = {requires_gene_mapping}")
151
+
152
+ # Step 5: Gene Annotation
153
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
154
+ gene_annotation = get_gene_annotation(soft_file)
155
+
156
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
157
+ print("Gene annotation preview:")
158
+ print(preview_df(gene_annotation))
159
+
160
+ # Step 6: Gene Identifier Mapping
161
+ import re
162
+ import pandas as pd
163
+
164
+ # 1) Decide which annotation column matches the expression identifiers and which holds gene symbols
165
+ expr_ids = set(gene_data.index.astype(str))
166
+
167
+ # Identify the best matching ID column in annotation (direct match or via extracting digits)
168
+ best_match = {'col': None, 'method': None, 'matches': 0, 'series': None}
169
+ for col in gene_annotation.columns:
170
+ ser = gene_annotation[col].astype(str).str.strip()
171
+
172
+ # Direct match
173
+ direct_matches = ser.isin(expr_ids).sum()
174
+ if direct_matches > best_match['matches']:
175
+ best_match = {'col': col, 'method': 'direct', 'matches': direct_matches, 'series': ser}
176
+
177
+ # Match after extracting a long digit token (e.g., from "ILMN_23064070" -> "23064070")
178
+ ser_digits = ser.str.extract(r'(\d{5,})', expand=False)
179
+ if ser_digits is not None:
180
+ digit_matches = ser_digits.isin(expr_ids).sum()
181
+ if digit_matches > best_match['matches']:
182
+ best_match = {'col': col, 'method': 'digits', 'matches': digit_matches, 'series': ser_digits}
183
+
184
+ if best_match['matches'] == 0 or best_match['col'] is None:
185
+ raise ValueError("Failed to find an annotation column that matches expression probe IDs.")
186
+
187
+ id_col = best_match['col']
188
+ id_series = best_match['series'] # already processed per best method (either original or digits extracted)
189
+
190
+ # Identify the best gene symbol column
191
+ candidate_symbol_cols = [c for c in gene_annotation.columns if ('SYMBOL' in c.upper()) or ('GENE' in c.upper() and 'NAME' not in c.upper())]
192
+ if not candidate_symbol_cols:
193
+ # Fallback to any column that might contain symbols
194
+ candidate_symbol_cols = list(gene_annotation.columns)
195
+
196
+ def score_symbol_column(series: pd.Series) -> int:
197
+ def has_symbol(x):
198
+ syms = extract_human_gene_symbols(x)
199
+ return 1 if len(syms) > 0 else 0
200
+ return series.astype(str).apply(has_symbol).sum()
201
+
202
+ symbol_scores = {c: score_symbol_column(gene_annotation[c]) for c in candidate_symbol_cols}
203
+ gene_symbol_col = max(symbol_scores, key=symbol_scores.get)
204
+
205
+ # 2) Build mapping dataframe from the chosen columns
206
+ mapping_df = pd.DataFrame({
207
+ 'ID': id_series.astype(str).str.strip(),
208
+ 'Gene': gene_annotation[gene_symbol_col].astype(str)
209
+ })
210
+
211
+ # Clean mapping
212
+ mapping_df = mapping_df.dropna(subset=['ID', 'Gene'])
213
+ mapping_df = mapping_df[mapping_df['ID'].isin(expr_ids)]
214
+
215
+ # 3) Apply mapping to convert probe-level to gene-level data
216
+ gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
217
+
218
+ # Step 7: Data Normalization and Linking
219
+ import os
220
+
221
+ # 1. Normalize gene symbols and save
222
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
223
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
224
+ normalized_gene_data.to_csv(out_gene_data_file)
225
+
226
+ # 2. Link the clinical and genetic data (use the correct clinical variable name)
227
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
228
+
229
+ # 3. Handle missing values in the linked data
230
+ linked_data = handle_missing_values(linked_data, trait)
231
+
232
+ # 4. Determine whether the trait and demographic features are severely biased, and remove biased features
233
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
234
+
235
+ # 5. Final quality validation and save cohort information
236
+ note = "INFO: Trait derived from 'tissue type' (non-neoplastic thyroid = 0, tumor/metastasis = 1)."
237
+ is_usable = validate_and_save_cohort_info(
238
+ is_final=True,
239
+ cohort=cohort,
240
+ info_path=json_path,
241
+ is_gene_available=True,
242
+ is_trait_available=True,
243
+ is_biased=is_trait_biased,
244
+ df=unbiased_linked_data,
245
+ note=note
246
+ )
247
+
248
+ # 6. Save the linked data if usable
249
+ if is_usable:
250
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
251
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Thyroid_Cancer/code/GSE58689.py ADDED
@@ -0,0 +1,187 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Thyroid_Cancer"
6
+ cohort = "GSE58689"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Thyroid_Cancer"
10
+ in_cohort_dir = "../DATA/GEO/Thyroid_Cancer/GSE58689"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z6/preprocess/Thyroid_Cancer/GSE58689.csv"
14
+ out_gene_data_file = "./output/z6/preprocess/Thyroid_Cancer/gene_data/GSE58689.csv"
15
+ out_clinical_data_file = "./output/z6/preprocess/Thyroid_Cancer/clinical_data/GSE58689.csv"
16
+ json_path = "./output/z6/preprocess/Thyroid_Cancer/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ import os
40
+ import re
41
+
42
+ # 1) Gene expression data availability
43
+ is_gene_available = True # Based on series title indicating gene expression signature
44
+
45
+ # 2) Variable availability and converters
46
+
47
+ # Selected rows from the Sample Characteristics Dictionary
48
+ trait_row = 0 # 'type of thyroid tissue: papillary thyroid carcinoma' vs 'normal thyroid'
49
+ age_row = 3 # Exclusively age values listed
50
+ gender_row = 2 # Contains 'Sex: female/male' among other entries; we'll parse only Sex and ignore others
51
+
52
+ def _after_colon(val: str) -> str:
53
+ if val is None:
54
+ return ''
55
+ parts = str(val).split(':', 1)
56
+ return parts[1].strip() if len(parts) > 1 else str(val).strip()
57
+
58
+ def convert_trait(x):
59
+ v = _after_colon(x).lower()
60
+ # Map thyroid tissue type to binary cancer status
61
+ if 'papillary' in v and 'carcinoma' in v:
62
+ return 1
63
+ if 'normal' in v:
64
+ return 0
65
+ # Heuristic for common abbreviations
66
+ if v in {'ptc', 'papillary thyroid carcinoma (ptc)'}:
67
+ return 1
68
+ return None
69
+
70
+ def convert_age(x):
71
+ v = _after_colon(x)
72
+ # Extract the first number (integer or float)
73
+ m = re.search(r'[-+]?\d+\.?\d*', v)
74
+ if m:
75
+ try:
76
+ age_val = float(m.group())
77
+ # Basic sanity check for human age
78
+ if 0 <= age_val <= 120:
79
+ return age_val
80
+ except:
81
+ return None
82
+ return None
83
+
84
+ def convert_gender(x):
85
+ s = str(x).lower()
86
+ # Prefer extraction after colon if present
87
+ v = _after_colon(s)
88
+ if 'female' in v:
89
+ return 0
90
+ if 'male' in v:
91
+ return 1
92
+ # If not in the value portion, try the whole string as a fallback
93
+ if 'female' in s:
94
+ return 0
95
+ if 'male' in s:
96
+ return 1
97
+ return None
98
+
99
+ # 3) Save metadata (initial filtering)
100
+ is_trait_available = trait_row is not None
101
+ _ = validate_and_save_cohort_info(
102
+ is_final=False,
103
+ cohort=cohort,
104
+ info_path=json_path,
105
+ is_gene_available=is_gene_available,
106
+ is_trait_available=is_trait_available
107
+ )
108
+
109
+ # 4) Clinical Feature Extraction
110
+ if trait_row is not None:
111
+ selected_clinical_df = geo_select_clinical_features(
112
+ clinical_df=clinical_data,
113
+ trait=trait,
114
+ trait_row=trait_row,
115
+ convert_trait=convert_trait,
116
+ age_row=age_row,
117
+ convert_age=convert_age,
118
+ gender_row=gender_row,
119
+ convert_gender=convert_gender
120
+ )
121
+ preview = preview_df(selected_clinical_df)
122
+ print(preview)
123
+
124
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
125
+ selected_clinical_df.to_csv(out_clinical_data_file)
126
+
127
+ # Step 3: Gene Data Extraction
128
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
129
+ gene_data = get_genetic_data(matrix_file)
130
+
131
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
132
+ print(gene_data.index[:20])
133
+
134
+ # Step 4: Gene Identifier Review
135
+ # Affymetrix probe set IDs (e.g., "1007_s_at", "1053_at") are not human gene symbols and require mapping.
136
+ requires_gene_mapping = True
137
+ print(f"requires_gene_mapping = {requires_gene_mapping}")
138
+
139
+ # Step 5: Gene Annotation
140
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
141
+ gene_annotation = get_gene_annotation(soft_file)
142
+
143
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
144
+ print("Gene annotation preview:")
145
+ print(preview_df(gene_annotation))
146
+
147
+ # Step 6: Gene Identifier Mapping
148
+ # Map Affymetrix probe set IDs ('ID') to human gene symbols ('Gene Symbol') and convert to gene-level matrix
149
+ mapping_df = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='Gene Symbol')
150
+ gene_data = apply_gene_mapping(gene_data, mapping_df)
151
+
152
+ # Step 7: Data Normalization and Linking
153
+ import os
154
+
155
+ # 1. Normalize gene symbols and save gene expression data
156
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
157
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
158
+ normalized_gene_data.to_csv(out_gene_data_file)
159
+
160
+ # 2. Link clinical and genetic data
161
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
162
+
163
+ # 3. Handle missing values
164
+ linked_data = handle_missing_values(linked_data, trait)
165
+
166
+ # 4. Evaluate 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
+ is_gene_available = bool((normalized_gene_data.shape[0] > 0) and (normalized_gene_data.shape[1] > 0))
171
+
172
+ has_trait_col = trait in unbiased_linked_data.columns
173
+ has_trait_vals = bool(unbiased_linked_data[trait].notna().any()) if has_trait_col else False
174
+ is_trait_available = bool(has_trait_col and has_trait_vals)
175
+
176
+ note = (
177
+ "INFO: Affymetrix probe IDs mapped via 'Gene Symbol' from platform SOFT; "
178
+ "many samples lack explicit age/gender; missing values handled per protocol."
179
+ )
180
+ is_usable = validate_and_save_cohort_info(
181
+ True, cohort, json_path, is_gene_available, is_trait_available, is_trait_biased, unbiased_linked_data, note
182
+ )
183
+
184
+ # 6. Save linked dataset if usable
185
+ if is_usable:
186
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
187
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Thyroid_Cancer/code/GSE76039.py ADDED
@@ -0,0 +1,182 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Thyroid_Cancer"
6
+ cohort = "GSE76039"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Thyroid_Cancer"
10
+ in_cohort_dir = "../DATA/GEO/Thyroid_Cancer/GSE76039"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z6/preprocess/Thyroid_Cancer/GSE76039.csv"
14
+ out_gene_data_file = "./output/z6/preprocess/Thyroid_Cancer/gene_data/GSE76039.csv"
15
+ out_clinical_data_file = "./output/z6/preprocess/Thyroid_Cancer/clinical_data/GSE76039.csv"
16
+ json_path = "./output/z6/preprocess/Thyroid_Cancer/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ # Step 1: Determine gene expression data availability based on background info
40
+ is_gene_available = True # Affymetrix U133 Plus 2.0 array indicates mRNA expression data
41
+
42
+ # Step 2: Determine variable availability from the provided Sample Characteristics Dictionary
43
+ # Sample Characteristics Dictionary:
44
+ # {0: ['gender: female', 'gender: male'],
45
+ # 1: ['tissue: Thyroid'],
46
+ # 2: ['tumor type: Primary', 'tumor type: Recurrent tumor in neck',
47
+ # 'tumor type: Recurrent/persistent metastasic tumor to lymph node',
48
+ # 'tumor type: Metastasis', 'tumor type: Recurrent tumor', 'tumor type: Primary (residual)']}
49
+
50
+ # Trait is "Thyroid_Cancer". All samples are tumor specimens; no controls. Trait is effectively constant -> not available.
51
+ trait_row = None
52
+
53
+ # Age is not found in the dictionary -> not available.
54
+ age_row = None
55
+
56
+ # Gender is available at key 0.
57
+ gender_row = 0
58
+
59
+ # Step 2.2: Define conversion functions
60
+ import re
61
+ from typing import Optional
62
+
63
+ def _after_colon(value: str) -> str:
64
+ if value is None:
65
+ return ""
66
+ parts = str(value).split(":", 1)
67
+ return parts[1].strip() if len(parts) == 2 else str(value).strip()
68
+
69
+ def convert_trait(x) -> Optional[int]:
70
+ # Not used because trait_row is None. For robustness, map any tumor-related entry to 1.
71
+ v = _after_colon(x).lower()
72
+ if v in ("", "na", "n/a", "unknown", "none"):
73
+ return None
74
+ # If any indication of tumor/tissue thyroid, mark as 1 for Thyroid_Cancer context.
75
+ keywords = ["tumor", "thyroid", "pdtc", "atc", "anaplastic", "poorly-differentiated", "metastasis", "primary"]
76
+ if any(k in v for k in keywords):
77
+ return 1
78
+ return None
79
+
80
+ def convert_age(x) -> Optional[float]:
81
+ # Not used because age_row is None. Robust parser for potential age strings.
82
+ v = _after_colon(x).lower()
83
+ if v in ("", "na", "n/a", "unknown", "none"):
84
+ return None
85
+ # Extract first number (integer or float)
86
+ m = re.search(r"(\d+(\.\d+)?)", v)
87
+ if not m:
88
+ return None
89
+ try:
90
+ return float(m.group(1))
91
+ except Exception:
92
+ return None
93
+
94
+ def convert_gender(x) -> Optional[int]:
95
+ v = _after_colon(x).lower()
96
+ if v in ("", "na", "n/a", "unknown", "none"):
97
+ return None
98
+ if "female" in v or v == "f":
99
+ return 0
100
+ if "male" in v or v == "m":
101
+ return 1
102
+ return None
103
+
104
+ # Step 3: Save metadata with initial filtering
105
+ is_trait_available = trait_row is not None
106
+ _ = validate_and_save_cohort_info(
107
+ is_final=False,
108
+ cohort=cohort,
109
+ info_path=json_path,
110
+ is_gene_available=is_gene_available,
111
+ is_trait_available=is_trait_available
112
+ )
113
+
114
+ # Step 4: Clinical feature extraction (skip because trait_row is None)
115
+ # If trait_row were available, we would extract and save clinical features as below:
116
+ if trait_row is not None:
117
+ selected_clin_df = geo_select_clinical_features(
118
+ clinical_df=clinical_data,
119
+ trait=trait,
120
+ trait_row=trait_row,
121
+ convert_trait=convert_trait,
122
+ age_row=age_row,
123
+ convert_age=convert_age,
124
+ gender_row=gender_row,
125
+ convert_gender=convert_gender
126
+ )
127
+ _ = preview_df(selected_clin_df)
128
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
129
+ selected_clin_df.to_csv(out_clinical_data_file)
130
+
131
+ # Step 3: Gene Data Extraction
132
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
133
+ gene_data = get_genetic_data(matrix_file)
134
+
135
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
136
+ print(gene_data.index[:20])
137
+
138
+ # Step 4: Gene Identifier Review
139
+ # Based on the observed identifiers (e.g., '1007_s_at', '1053_at'), these are Affymetrix probe set IDs, not human gene symbols.
140
+ print("requires_gene_mapping = True")
141
+
142
+ # Step 5: Gene Annotation
143
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
144
+ gene_annotation = get_gene_annotation(soft_file)
145
+
146
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
147
+ print("Gene annotation preview:")
148
+ print(preview_df(gene_annotation))
149
+
150
+ # Step 6: Gene Identifier Mapping
151
+ # Determine appropriate columns for mapping based on annotation preview:
152
+ # - Probe identifiers: 'ID' (e.g., '1007_s_at', matching matrix row IDs)
153
+ # - Gene symbols: 'Gene Symbol'
154
+ probe_col = 'ID'
155
+ gene_symbol_col = 'Gene Symbol'
156
+
157
+ # Build mapping dataframe (ID -> Gene)
158
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=probe_col, gene_col=gene_symbol_col)
159
+
160
+ # Apply mapping to convert probe-level expression to gene-level expression
161
+ gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
162
+
163
+ # Step 7: Data Normalization and Linking
164
+ import os
165
+
166
+ # 1. Normalize gene symbols and save gene expression data
167
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
168
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
169
+ normalized_gene_data.to_csv(out_gene_data_file)
170
+
171
+ # 2. Since trait data is unavailable (from Step 2: trait_row is None), skip linking and downstream steps
172
+ linked_data = None
173
+
174
+ # 5. Record metadata (initial filtering) to reflect unavailable trait data and available gene data
175
+ # Do not attempt final validation without clinical/trait data.
176
+ _ = validate_and_save_cohort_info(
177
+ is_final=False,
178
+ cohort=cohort,
179
+ info_path=json_path,
180
+ is_gene_available=True,
181
+ is_trait_available=False
182
+ )
output/preprocess/Thyroid_Cancer/code/GSE80022.py ADDED
@@ -0,0 +1,190 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Thyroid_Cancer"
6
+ cohort = "GSE80022"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Thyroid_Cancer"
10
+ in_cohort_dir = "../DATA/GEO/Thyroid_Cancer/GSE80022"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z6/preprocess/Thyroid_Cancer/GSE80022.csv"
14
+ out_gene_data_file = "./output/z6/preprocess/Thyroid_Cancer/gene_data/GSE80022.csv"
15
+ out_clinical_data_file = "./output/z6/preprocess/Thyroid_Cancer/clinical_data/GSE80022.csv"
16
+ json_path = "./output/z6/preprocess/Thyroid_Cancer/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ import os
40
+ import math
41
+ import pandas as pd
42
+
43
+ # 1) Gene expression availability (Transcriptomic profiling of xenografts => gene expression data present)
44
+ is_gene_available = True
45
+
46
+ # 2) Variable availability and conversion functions
47
+
48
+ # Trait: Thyroid_Cancer can be inferred from xenograft tissue (GOT2 = medullary thyroid carcinoma; GOT1 = small intestine NET)
49
+ trait_row = 1 # 'xenograft tissue: GOT1' / 'xenograft tissue: GOT2'
50
+
51
+ # No human age/gender in xenograft mouse model metadata
52
+ age_row = None
53
+ gender_row = None
54
+
55
+ def _extract_value(x):
56
+ if x is None or (isinstance(x, float) and math.isnan(x)):
57
+ return None
58
+ s = str(x)
59
+ parts = s.split(":", 1)
60
+ v = parts[1] if len(parts) == 2 else parts[0]
61
+ return v.strip()
62
+
63
+ def convert_trait(x):
64
+ v = _extract_value(x)
65
+ if v is None:
66
+ return None
67
+ vl = v.lower()
68
+ # Map medullary thyroid carcinoma model (GOT2) to 1, GOT1 (small intestine NET) to 0
69
+ if "got2" in vl or "medullary" in vl or "thyroid" in vl:
70
+ return 1
71
+ if "got1" in vl or "small intestine" in vl or "neuroendocrine" in vl or "net" in vl:
72
+ return 0
73
+ return None
74
+
75
+ def convert_age(x):
76
+ v = _extract_value(x)
77
+ if v is None:
78
+ return None
79
+ # Try to parse numeric age if present; otherwise return None
80
+ try:
81
+ # Remove common units if any
82
+ vv = "".join(ch for ch in v if (ch.isdigit() or ch in ".-"))
83
+ return float(vv) if vv not in ("", "-", ".", "-.") else None
84
+ except Exception:
85
+ return None
86
+
87
+ def convert_gender(x):
88
+ v = _extract_value(x)
89
+ if v is None:
90
+ return None
91
+ vl = v.strip().lower()
92
+ if vl in ["male", "m", "man"]:
93
+ return 1
94
+ if vl in ["female", "f", "woman"]:
95
+ return 0
96
+ return None
97
+
98
+ # 3) Save metadata (initial filtering)
99
+ is_trait_available = trait_row is not None
100
+ _ = validate_and_save_cohort_info(
101
+ is_final=False,
102
+ cohort=cohort,
103
+ info_path=json_path,
104
+ is_gene_available=is_gene_available,
105
+ is_trait_available=is_trait_available
106
+ )
107
+
108
+ # 4) Clinical feature extraction and save
109
+ if trait_row is not None:
110
+ selected_clinical_df = geo_select_clinical_features(
111
+ clinical_df=clinical_data,
112
+ trait=trait,
113
+ trait_row=trait_row,
114
+ convert_trait=convert_trait,
115
+ age_row=age_row,
116
+ convert_age=convert_age,
117
+ gender_row=gender_row,
118
+ convert_gender=convert_gender
119
+ )
120
+ preview = preview_df(selected_clinical_df)
121
+ print(preview)
122
+
123
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
124
+ selected_clinical_df.to_csv(out_clinical_data_file)
125
+
126
+ # Step 3: Gene Data Extraction
127
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
128
+ gene_data = get_genetic_data(matrix_file)
129
+
130
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
131
+ print(gene_data.index[:20])
132
+
133
+ # Step 4: Gene Identifier Review
134
+ print("requires_gene_mapping = True")
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 identifier and gene symbol columns based on annotation preview:
146
+ # - Probe IDs match 'ILMN_...' in the 'ID' column.
147
+ # - Gene symbols are in the 'Symbol' column.
148
+
149
+ # 1-2) Build mapping dataframe
150
+ mapping_df = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='Symbol')
151
+
152
+ # 3) Apply mapping to convert probe-level data to gene-level data
153
+ expression_df = gene_data # preserve the original probe-level data
154
+ gene_data = apply_gene_mapping(expression_df, mapping_df)
155
+
156
+ # Step 7: Data Normalization and Linking
157
+ import os
158
+
159
+ # 1. Normalize gene symbols and save
160
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
161
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
162
+ normalized_gene_data.to_csv(out_gene_data_file)
163
+
164
+ # 2. Link clinical and genetic data
165
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
166
+
167
+ # 3. Handle missing values
168
+ linked_data = handle_missing_values(linked_data, trait)
169
+
170
+ # 4. Assess bias and remove biased demographic features
171
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
172
+
173
+ # 5. Final validation and save cohort info
174
+ note = ("INFO: Xenograft mouse model (GOT1 small intestine NET vs GOT2 medullary thyroid carcinoma); "
175
+ "mouse hosts (Balb/c nude), no human age/gender covariates available.")
176
+ is_usable = validate_and_save_cohort_info(
177
+ is_final=True,
178
+ cohort=cohort,
179
+ info_path=json_path,
180
+ is_gene_available=True,
181
+ is_trait_available=True,
182
+ is_biased=is_trait_biased,
183
+ df=unbiased_linked_data,
184
+ note=note
185
+ )
186
+
187
+ # 6. Save linked data if usable
188
+ if is_usable:
189
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
190
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Thyroid_Cancer/code/GSE82208.py ADDED
@@ -0,0 +1,226 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Thyroid_Cancer"
6
+ cohort = "GSE82208"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Thyroid_Cancer"
10
+ in_cohort_dir = "../DATA/GEO/Thyroid_Cancer/GSE82208"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z6/preprocess/Thyroid_Cancer/GSE82208.csv"
14
+ out_gene_data_file = "./output/z6/preprocess/Thyroid_Cancer/gene_data/GSE82208.csv"
15
+ out_clinical_data_file = "./output/z6/preprocess/Thyroid_Cancer/clinical_data/GSE82208.csv"
16
+ json_path = "./output/z6/preprocess/Thyroid_Cancer/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ import os
40
+ import pandas as pd
41
+
42
+ # 1. Gene expression data availability
43
+ is_gene_available = True # mRNA gene expression profiling per series description
44
+
45
+ # 2. Variable availability (rows from Sample Characteristics Dictionary)
46
+ trait_row = 2 # 'class: FTC' vs 'class: FTA'
47
+ age_row = 1 # 'age (years): ...'
48
+ gender_row = 0 # 'Sex: Female/Male/-'
49
+
50
+ # 2.2 Conversion functions
51
+ def _after_colon(val):
52
+ if val is None:
53
+ return None
54
+ s = str(val)
55
+ if ':' in s:
56
+ s = s.split(':', 1)[1]
57
+ return s.strip()
58
+
59
+ def convert_trait(val):
60
+ v = _after_colon(val)
61
+ if v is None or v == '' or v == '-' or v.lower() == 'unknown':
62
+ return None
63
+ v_low = v.lower()
64
+ if 'ftc' in v_low:
65
+ return 1 # cancer
66
+ if 'fta' in v_low:
67
+ return 0 # benign
68
+ return None
69
+
70
+ def convert_age(val):
71
+ v = _after_colon(val)
72
+ if v is None:
73
+ return None
74
+ v = v.strip()
75
+ if v in ['', '-', 'na', 'n/a', 'null', 'none']:
76
+ return None
77
+ try:
78
+ return float(v)
79
+ except Exception:
80
+ # Try to extract leading number if present
81
+ num = ''.join(ch for ch in v if (ch.isdigit() or ch == '.' or ch == '-'))
82
+ try:
83
+ return float(num) if num not in ['', '-', '.', '--'] else None
84
+ except Exception:
85
+ return None
86
+
87
+ def convert_gender(val):
88
+ v = _after_colon(val)
89
+ if v is None:
90
+ return None
91
+ v_low = v.strip().lower()
92
+ if v_low in ['female', 'f']:
93
+ return 0
94
+ if v_low in ['male', 'm']:
95
+ return 1
96
+ return None
97
+
98
+ # 3. Save metadata (initial filtering)
99
+ is_trait_available = trait_row is not None
100
+ _ = validate_and_save_cohort_info(
101
+ is_final=False,
102
+ cohort=cohort,
103
+ info_path=json_path,
104
+ is_gene_available=is_gene_available,
105
+ is_trait_available=is_trait_available
106
+ )
107
+
108
+ # 4. Clinical feature extraction (only if clinical data is available)
109
+ if trait_row is not None:
110
+ selected_clinical_df = geo_select_clinical_features(
111
+ clinical_df=clinical_data,
112
+ trait=trait,
113
+ trait_row=trait_row,
114
+ convert_trait=convert_trait,
115
+ age_row=age_row,
116
+ convert_age=convert_age,
117
+ gender_row=gender_row,
118
+ convert_gender=convert_gender
119
+ )
120
+ preview = preview_df(selected_clinical_df, n=5)
121
+ print(preview)
122
+
123
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
124
+ selected_clinical_df.to_csv(out_clinical_data_file, index=True)
125
+
126
+ # Step 3: Gene Data Extraction
127
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
128
+ gene_data = get_genetic_data(matrix_file)
129
+
130
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
131
+ print(gene_data.index[:20])
132
+
133
+ # Step 4: Gene Identifier Review
134
+ # Affymetrix probe set IDs (e.g., 1007_s_at) are not human gene symbols and require mapping.
135
+ requires_gene_mapping = True
136
+ print(f"requires_gene_mapping = {requires_gene_mapping}")
137
+
138
+ # Step 5: Gene Annotation
139
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
140
+ gene_annotation = get_gene_annotation(soft_file)
141
+
142
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
143
+ print("Gene annotation preview:")
144
+ print(preview_df(gene_annotation))
145
+
146
+ # Step 6: Gene Identifier Mapping
147
+ # Determine the appropriate columns for mapping: probe IDs ('ID') to gene symbols ('Gene Symbol')
148
+ mapping_df = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='Gene Symbol')
149
+
150
+ # Apply mapping to convert probe-level data to gene-level expression
151
+ gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
152
+
153
+ # Step 7: Data Normalization and Linking
154
+ import os
155
+
156
+ # 1. Normalize gene symbols and save
157
+ used_fallback = False
158
+ try:
159
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
160
+ except Exception as e:
161
+ # Fallback if synonym file is missing or normalization fails
162
+ used_fallback = True
163
+ normalized_gene_data = gene_data.copy()
164
+ normalized_gene_data.index = normalized_gene_data.index.str.upper()
165
+ normalized_gene_data = normalized_gene_data[normalized_gene_data.index.notnull()]
166
+ normalized_gene_data = normalized_gene_data.groupby(normalized_gene_data.index).mean()
167
+
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
+ try:
173
+ selected_clinical_df # noqa: F401
174
+ except NameError:
175
+ # Load from disk if not present in current context
176
+ selected_clinical_df = pd.read_csv(out_clinical_data_file, index_col=0)
177
+
178
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
179
+
180
+ # Record pre-missing and shape stats for notes
181
+ pre_n_samples, pre_n_cols = linked_data.shape
182
+ covariate_cols = [trait, 'Age', 'Gender']
183
+ pre_gene_cols = [c for c in linked_data.columns if c not in covariate_cols]
184
+ pre_n_genes = len(pre_gene_cols)
185
+ pre_missing_age = int(linked_data['Age'].isna().sum()) if 'Age' in linked_data.columns else None
186
+ pre_missing_gender = int(linked_data['Gender'].isna().sum()) if 'Gender' in linked_data.columns else None
187
+
188
+ # 3. Handle missing values
189
+ linked_data = handle_missing_values(linked_data, trait)
190
+
191
+ # 4. Bias checks and remove biased covariates
192
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
193
+
194
+ # Prepare note
195
+ post_n_samples, post_n_cols = unbiased_linked_data.shape
196
+ post_gene_cols = [c for c in unbiased_linked_data.columns if c not in [trait, 'Age', 'Gender']]
197
+ post_n_genes = len(post_gene_cols)
198
+ note_parts = []
199
+ if used_fallback:
200
+ note_parts.append("WARNING: Fallback normalization used (gene synonym map unavailable).")
201
+ else:
202
+ note_parts.append("INFO: Gene symbols normalized using NCBI synonym map.")
203
+ note_parts.append(f"INFO: Samples before/after missing-value handling: {pre_n_samples}/{post_n_samples}.")
204
+ note_parts.append(f"INFO: Gene features before/after filtering: {pre_n_genes}/{post_n_genes}.")
205
+ if pre_missing_age is not None:
206
+ note_parts.append(f"INFO: Missing Age before handling: {pre_missing_age}.")
207
+ if pre_missing_gender is not None:
208
+ note_parts.append(f"INFO: Missing Gender before handling: {pre_missing_gender}.")
209
+ note = " ".join(note_parts)
210
+
211
+ # 5. Final quality validation and cohort info saving
212
+ is_usable = validate_and_save_cohort_info(
213
+ is_final=True,
214
+ cohort=cohort,
215
+ info_path=json_path,
216
+ is_gene_available=True,
217
+ is_trait_available=True,
218
+ is_biased=is_trait_biased,
219
+ df=unbiased_linked_data,
220
+ note=note
221
+ )
222
+
223
+ # 6. Save linked data if usable
224
+ if is_usable:
225
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
226
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Thyroid_Cancer/code/TCGA.py ADDED
@@ -0,0 +1,310 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Thyroid_Cancer"
6
+
7
+ # Input paths
8
+ tcga_root_dir = "../DATA/TCGA"
9
+
10
+ # Output paths
11
+ out_data_file = "./output/z6/preprocess/Thyroid_Cancer/TCGA.csv"
12
+ out_gene_data_file = "./output/z6/preprocess/Thyroid_Cancer/gene_data/TCGA.csv"
13
+ out_clinical_data_file = "./output/z6/preprocess/Thyroid_Cancer/clinical_data/TCGA.csv"
14
+ json_path = "./output/z6/preprocess/Thyroid_Cancer/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 Thyroid Cancer
22
+ subdirs = [d for d in os.listdir(tcga_root_dir) if os.path.isdir(os.path.join(tcga_root_dir, d))]
23
+ selected_dirname = None
24
+ for pat in ['Thyroid_Cancer', '(THCA)', 'Thyroid', 'THCA']:
25
+ matches = [d for d in subdirs if pat.lower() in d.lower()]
26
+ if matches:
27
+ # Choose the most specific (shortest match name as proxy)
28
+ selected_dirname = sorted(matches, key=lambda x: len(x))[0]
29
+ break
30
+
31
+ if selected_dirname is None:
32
+ # No suitable directory found: record and stop further processing in this run
33
+ validate_and_save_cohort_info(
34
+ is_final=False,
35
+ cohort="TCGA",
36
+ info_path=json_path,
37
+ is_gene_available=False,
38
+ is_trait_available=False
39
+ )
40
+ else:
41
+ cohort_dir = os.path.join(tcga_root_dir, selected_dirname)
42
+
43
+ # Step 2: Identify clinical and genetic file paths
44
+ clinical_file_path, genetic_file_path = tcga_get_relevant_filepaths(cohort_dir)
45
+
46
+ # Step 3: Load both files
47
+ clinical_df = pd.read_csv(clinical_file_path, sep='\t', index_col=0, low_memory=False)
48
+ genetic_df = pd.read_csv(genetic_file_path, sep='\t', index_col=0, low_memory=False)
49
+
50
+ # Step 4: Print clinical column names
51
+ print(clinical_df.columns.tolist())
52
+
53
+ # Step 2: Find Candidate Demographic Features
54
+ import os
55
+ import re
56
+ import pandas as pd
57
+
58
+ # Columns obtained from the previous step
59
+ columns_from_prev_step = ['_INTEGRATION', '_PATIENT', '_cohort', '_primary_disease', '_primary_site', 'additional_pharmaceutical_therapy', 'additional_radiation_therapy', 'additional_surgery_locoregional_procedure', 'age_at_initial_pathologic_diagnosis', 'bcr_followup_barcode', 'bcr_patient_barcode', 'bcr_sample_barcode', 'braf_gene_genotyping_outcome_lab_results_text', '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_new_tumor_event_additional_surgery_procedure', 'days_to_new_tumor_event_after_initial_treatment', 'extrathyroid_carcinoma_present_extension_status', 'first_degree_relative_history_thyrd_glnd_crcnm_dgnss_rltnshp_typ', 'followup_case_report_form_submission_reason', 'form_completion_date', 'gender', 'genotype_analysis_performed_indicator', 'genotyping_results_gene_mutation_not_reported_reason', 'histologic_disease_progression_present_indicator', 'histologic_disease_progression_present_type', 'histological_type', 'histological_type_other', 'history_of_neoadjuvant_treatment', 'i_131_first_administered_dose', 'i_131_subsequent_administered_dose', 'i_131_total_administered_dose', 'i_131_total_administered_preparation_technique', 'icd_10', 'icd_o_3_histology', 'icd_o_3_site', 'informed_consent_verified', 'initial_weight', 'is_ffpe', 'lost_follow_up', 'lymph_node_examined_count', 'lymph_node_preoperative_assessment_diagnostic_imaging_type', 'lymph_node_preoperative_scan_indicator', 'metastatic_neoplasm_confirmed_diagnosis_method_name', 'metastatic_neoplasm_confirmed_diagnosis_method_text', 'metastatic_site', 'neoplasm_depth', '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_additional_surgery_procedure', 'new_tumor_event_after_initial_treatment', 'number_of_lymphnodes_positive_by_he', 'oct_embedded', 'other_dx', 'other_genotyping_outcome_lab_results_text', 'other_metastatic_site', 'pathologic_M', 'pathologic_N', 'pathologic_T', 'pathologic_stage', 'pathologic_stage', 'pathology_report_file_name', 'patient_id', 'patient_personal_medical_history_thyroid_gland_disorder_name', 'patient_personal_medical_history_thyroid_other_specify_text', 'person_lifetime_risk_radiation_exposure_indicator', 'person_neoplasm_cancer_status', 'post_surgical_procedure_assessment_thyroid_gland_carcinoma_stats', 'postoperative_rx_tx', 'primary_lymph_node_presentation_assessment', 'primary_neoplasm_focus_type', 'primary_thyroid_gland_neoplasm_location_anatomic_site', 'radiation_therapy', 'radiation_therapy_administered_dose_text', 'radiation_therapy_administered_preparation_technique_text', 'radiosensitizing_agent_administered_indicator', 'ras_family_gene_genotyping_outcome_lab_results_text', 'residual_tumor', 'ret_ptc_rearrangement_genotyping_outcome_lab_results_text', 'sample_type', 'sample_type_id', 'system_version', 'targeted_molecular_therapy', 'therapeutic_procedure_new_neoplasm_required_additional_thrpy_typ', 'thyroid_gland_carcinoma_involvement_regional_lymph_node_type', 'tissue_prospective_collection_indicator', 'tissue_retrospective_collection_indicator', 'tissue_source_site', 'tumor_tissue_site', 'vial_number', 'vital_status', 'year_of_initial_pathologic_diagnosis', '_GENOMIC_ID_TCGA_THCA_exp_HiSeqV2_percentile', '_GENOMIC_ID_TCGA_THCA_hMethyl450', '_GENOMIC_ID_TCGA_THCA_mutation_bcm_gene', '_GENOMIC_ID_TCGA_THCA_RPPA', '_GENOMIC_ID_TCGA_THCA_exp_HiSeqV2', '_GENOMIC_ID_TCGA_THCA_gistic2', '_GENOMIC_ID_TCGA_THCA_PDMRNAseqCNV', '_GENOMIC_ID_TCGA_THCA_mutation_bcgsc_gene', '_GENOMIC_ID_TCGA_THCA_mutation', '_GENOMIC_ID_TCGA_THCA_PDMRNAseq', '_GENOMIC_ID_TCGA_THCA_mutation_broad_gene', '_GENOMIC_ID_TCGA_THCA_exp_HiSeqV2_exon', '_GENOMIC_ID_TCGA_THCA_miRNA_HiSeq', '_GENOMIC_ID_TCGA_THCA_exp_HiSeqV2_PANCAN', '_GENOMIC_ID_data/public/TCGA/THCA/miRNA_HiSeq_gene', '_GENOMIC_ID_TCGA_THCA_gistic2thd']
60
+
61
+ # Map lowercase to original for robust matching and original-case output
62
+ lower_to_orig = {c.lower(): c for c in columns_from_prev_step}
63
+
64
+ # Identify candidate age columns with stricter rules to avoid false positives (e.g., "stage", "agent")
65
+ age_pattern = re.compile(r'(^|_)age($|_)', flags=re.I)
66
+ candidate_age_cols = []
67
+
68
+ for c in columns_from_prev_step:
69
+ cl = c.lower()
70
+ if age_pattern.search(cl):
71
+ candidate_age_cols.append(c)
72
+
73
+ # Explicitly include known TCGA age-related aliases if present
74
+ age_aliases = ['age_at_initial_pathologic_diagnosis', 'days_to_birth']
75
+ for alias in age_aliases:
76
+ if alias in lower_to_orig and lower_to_orig[alias] not in candidate_age_cols:
77
+ candidate_age_cols.append(lower_to_orig[alias])
78
+
79
+ # Identify candidate gender columns
80
+ candidate_gender_cols = [c for c in columns_from_prev_step if ('gender' in c.lower() or 'sex' in c.lower())]
81
+
82
+ # Print required lists in strict format
83
+ print(f"candidate_age_cols = {candidate_age_cols}")
84
+ print(f"candidate_gender_cols = {candidate_gender_cols}")
85
+
86
+ # Helper to locate cohort directory
87
+ def _find_cohort_dir(root_dir: str, keyword: str = 'THCA') -> str:
88
+ for entry in sorted(os.listdir(root_dir)):
89
+ full = os.path.join(root_dir, entry)
90
+ if os.path.isdir(full) and keyword.lower() in entry.lower():
91
+ return full
92
+ for r, dnames, _ in os.walk(root_dir):
93
+ for d in dnames:
94
+ if keyword.lower() in d.lower():
95
+ return os.path.join(r, d)
96
+ return ""
97
+
98
+ # Robust reader for clinical matrix
99
+ def _read_matrix_any(path: str) -> pd.DataFrame:
100
+ for sep in ['\t', ',', '|']:
101
+ try:
102
+ df = pd.read_csv(path, sep=sep, header=0, index_col=0, dtype=str)
103
+ if isinstance(df, pd.DataFrame) and df.shape[1] > 0:
104
+ return df
105
+ except Exception:
106
+ continue
107
+ try:
108
+ return pd.read_table(path, header=0, index_col=0, dtype=str)
109
+ except Exception:
110
+ return None
111
+
112
+ # Load clinical data and preview candidate columns (dropping entirely empty columns from preview)
113
+ clinical_df = None
114
+ try:
115
+ cohort_dir = _find_cohort_dir(tcga_root_dir, keyword='THCA')
116
+ if cohort_dir:
117
+ clinical_fp, _ = tcga_get_relevant_filepaths(cohort_dir)
118
+ clinical_df = _read_matrix_any(clinical_fp)
119
+ except Exception:
120
+ clinical_df = None
121
+
122
+ if clinical_df is not None:
123
+ if candidate_age_cols:
124
+ age_cols_present = [c for c in candidate_age_cols if c in clinical_df.columns]
125
+ if age_cols_present:
126
+ age_df = clinical_df[age_cols_present]
127
+ age_df = age_df.loc[:, age_df.notna().any(axis=0)]
128
+ if age_df.shape[1] > 0:
129
+ age_preview = preview_df(age_df, n=5)
130
+ print(age_preview)
131
+ if candidate_gender_cols:
132
+ gender_cols_present = [c for c in candidate_gender_cols if c in clinical_df.columns]
133
+ if gender_cols_present:
134
+ gender_df = clinical_df[gender_cols_present]
135
+ gender_df = gender_df.loc[:, gender_df.notna().any(axis=0)]
136
+ if gender_df.shape[1] > 0:
137
+ gender_preview = preview_df(gender_df, n=5)
138
+ print(gender_preview)
139
+
140
+ # Step 3: Select Demographic Features
141
+ # Heuristic selection of demographic columns based on candidate previews and simple validity checks
142
+
143
+ # Helper to locate the preview dictionaries created in previous steps, if available
144
+ def _find_preview_dict(candidate_cols):
145
+ preview = None
146
+ for name, val in globals().items():
147
+ if isinstance(val, dict) and val:
148
+ # Ensure all keys are within the candidate columns and values are lists (first 5 samples)
149
+ if all(k in candidate_cols for k in val.keys()) and all(isinstance(v, list) for v in val.values()):
150
+ # Prefer the smallest dict that matches (more likely the preview)
151
+ if preview is None or len(val) < len(preview):
152
+ preview = val
153
+ return preview
154
+
155
+ # Initialize defaults
156
+ age_col = None
157
+ gender_col = None
158
+
159
+ # Safeguards in case candidate lists are missing
160
+ _candidate_age_cols = candidate_age_cols if 'candidate_age_cols' in globals() else []
161
+ _candidate_gender_cols = candidate_gender_cols if 'candidate_gender_cols' in globals() else []
162
+
163
+ # Try to retrieve preview dictionaries from previous step
164
+ age_preview_dict = _find_preview_dict(_candidate_age_cols) if _candidate_age_cols else None
165
+ gender_preview_dict = _find_preview_dict(_candidate_gender_cols) if _candidate_gender_cols else None
166
+
167
+ # Select age column
168
+ if _candidate_age_cols:
169
+ if age_preview_dict:
170
+ best_col = None
171
+ best_score = -1
172
+ for col, vals in age_preview_dict.items():
173
+ # Convert preview values using the provided helper
174
+ converted = [tcga_convert_age(v) for v in vals]
175
+ # Plausibility: count values that look like realistic ages
176
+ plausible = [v for v in converted if v is not None and 0 < v < 120]
177
+ score = len(plausible)
178
+ # Prefer explicitly age-like name in tie
179
+ if score > best_score or (score == best_score and best_col and 'age' in col.lower() and 'age' not in best_col.lower()):
180
+ best_col = col
181
+ best_score = score
182
+ age_col = best_col if best_col is not None and best_score > 0 else None
183
+ else:
184
+ # Fallback by common TCGA naming
185
+ for preferred in ['age_at_initial_pathologic_diagnosis', 'age', 'age_at_diagnosis']:
186
+ if preferred in _candidate_age_cols:
187
+ age_col = preferred
188
+ break
189
+
190
+ # If we can assess missingness on the full clinical_df, ensure no large proportion missing
191
+ if age_col and 'clinical_df' in globals() and age_col in getattr(clinical_df, 'columns', []):
192
+ miss_rate = clinical_df[age_col].isna().mean()
193
+ if miss_rate > 0.5:
194
+ age_col = None
195
+
196
+ # Select gender column
197
+ if _candidate_gender_cols:
198
+ if gender_preview_dict:
199
+ best_col = None
200
+ best_score = -1
201
+ for col, vals in gender_preview_dict.items():
202
+ converted = [tcga_convert_gender(v) for v in vals]
203
+ valid = [v for v in converted if v in (0, 1)]
204
+ score = len(valid)
205
+ if score > best_score:
206
+ best_col = col
207
+ best_score = score
208
+ gender_col = best_col if best_col is not None and best_score > 0 else None
209
+ else:
210
+ # Fallback by common TCGA naming
211
+ for preferred in ['gender', 'sex']:
212
+ if preferred in _candidate_gender_cols:
213
+ gender_col = preferred
214
+ break
215
+
216
+ # Missingness check for gender if possible
217
+ if gender_col and 'clinical_df' in globals() and gender_col in getattr(clinical_df, 'columns', []):
218
+ miss_rate = clinical_df[gender_col].isna().mean()
219
+ if miss_rate > 0.5:
220
+ gender_col = None
221
+
222
+ # Explicitly print chosen columns and preview values if available
223
+ print("Chosen age_col:", age_col)
224
+ if age_col:
225
+ if 'clinical_df' in globals() and age_col in getattr(clinical_df, 'columns', []):
226
+ print("First 5 values of age_col:", [str(x) for x in clinical_df[age_col].head(5).tolist()])
227
+ elif age_preview_dict and age_col in age_preview_dict:
228
+ print("Preview values of age_col:", age_preview_dict[age_col])
229
+ else:
230
+ print("No preview available for age_col.")
231
+
232
+ print("Chosen gender_col:", gender_col)
233
+ if gender_col:
234
+ if 'clinical_df' in globals() and gender_col in getattr(clinical_df, 'columns', []):
235
+ print("First 5 values of gender_col:", [str(x) for x in clinical_df[gender_col].head(5).tolist()])
236
+ elif gender_preview_dict and gender_col in gender_preview_dict:
237
+ print("Preview values of gender_col:", gender_preview_dict[gender_col])
238
+ else:
239
+ print("No preview available for gender_col.")
240
+
241
+ # Step 4: Feature Engineering and Validation
242
+ import os
243
+ import pandas as pd
244
+ import numpy as np
245
+
246
+ # 1) Extract and standardize clinical features (trait, Age, Gender)
247
+ selected_clinical_df = tcga_select_clinical_features(
248
+ clinical_df=clinical_df,
249
+ trait=trait,
250
+ age_col=age_col,
251
+ gender_col=gender_col
252
+ )
253
+
254
+ # 2) Normalize gene symbols and save normalized gene expression
255
+ # Ensure numeric dtype for gene expression
256
+ gene_expr_df = genetic_df.apply(pd.to_numeric, errors='coerce')
257
+
258
+ # Normalize symbols (drop unrecognized, aggregate synonyms)
259
+ gene_expr_df = normalize_gene_symbols_in_index(gene_expr_df)
260
+
261
+ # Save normalized gene expression (genes x samples)
262
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
263
+ gene_expr_df.to_csv(out_gene_data_file)
264
+
265
+ # 3) Link clinical and genetic data on sample IDs
266
+ common_samples = selected_clinical_df.index.intersection(gene_expr_df.columns)
267
+ clinical_sub = selected_clinical_df.loc[common_samples]
268
+ gene_sub = gene_expr_df[common_samples].T # samples x genes
269
+
270
+ linked_data = pd.concat([clinical_sub, gene_sub], axis=1)
271
+
272
+ # 4) Handle missing values systematically
273
+ processed_df = handle_missing_values(linked_data, trait_col=trait)
274
+
275
+ # 5) Determine bias and remove biased demographic features (trait bias used for usability)
276
+ is_biased_flag, processed_df = judge_and_remove_biased_features(processed_df, trait)
277
+
278
+ # 6) Final validation and save cohort info
279
+ covariate_cols = [trait, 'Age', 'Gender']
280
+ gene_cols_processed = [c for c in processed_df.columns if c not in covariate_cols]
281
+ # Force pure Python bools to avoid JSON serialization issues
282
+ is_gene_available = bool(len(gene_cols_processed) > 0)
283
+ is_trait_available = bool((trait in processed_df.columns) and bool(processed_df[trait].notna().any()))
284
+ is_biased_flag = bool(is_biased_flag)
285
+
286
+ # Prepare notes
287
+ label_counts = processed_df[trait].value_counts().to_dict() if trait in processed_df.columns else {}
288
+ n_tumor = int(label_counts.get(1, 0))
289
+ n_normal = int(label_counts.get(0, 0))
290
+ note = (
291
+ f"INFO: Linked samples={len(processed_df)}; genes={len(gene_cols_processed)}; "
292
+ f"Tumor={n_tumor}; Normal={n_normal}; "
293
+ f"Age_included={bool('Age' in processed_df.columns)}; Gender_included={bool('Gender' in processed_df.columns)}"
294
+ )
295
+
296
+ is_usable = validate_and_save_cohort_info(
297
+ is_final=True,
298
+ cohort="TCGA",
299
+ info_path=json_path,
300
+ is_gene_available=is_gene_available,
301
+ is_trait_available=is_trait_available,
302
+ is_biased=is_biased_flag,
303
+ df=processed_df,
304
+ note=note
305
+ )
306
+
307
+ # 7) Save linked data only if usable
308
+ if is_usable:
309
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
310
+ processed_df.to_csv(out_data_file)
output/preprocess/Thyroid_Cancer/cohort_info.json CHANGED
@@ -1,102 +1 @@
1
- {
2
- "GSE82208": {
3
- "is_usable": true,
4
- "is_gene_available": true,
5
- "is_trait_available": true,
6
- "is_available": true,
7
- "is_biased": false,
8
- "has_age": true,
9
- "has_gender": true,
10
- "sample_size": 52
11
- },
12
- "GSE80022": {
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
- "GSE76039": {
23
- "is_usable": true,
24
- "is_gene_available": true,
25
- "is_trait_available": true,
26
- "is_available": true,
27
- "is_biased": false,
28
- "has_age": false,
29
- "has_gender": true,
30
- "sample_size": 37
31
- },
32
- "GSE58689": {
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": 45
41
- },
42
- "GSE151181": {
43
- "is_usable": false,
44
- "is_gene_available": false,
45
- "is_trait_available": true,
46
- "is_available": false,
47
- "is_biased": null,
48
- "has_age": null,
49
- "has_gender": null,
50
- "sample_size": null
51
- },
52
- "GSE151179": {
53
- "is_usable": false,
54
- "is_gene_available": true,
55
- "is_trait_available": true,
56
- "is_available": true,
57
- "is_biased": true,
58
- "has_age": false,
59
- "has_gender": false,
60
- "sample_size": 13
61
- },
62
- "GSE138198": {
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
- "GSE107754": {
73
- "is_usable": false,
74
- "is_gene_available": true,
75
- "is_trait_available": true,
76
- "is_available": true,
77
- "is_biased": true,
78
- "has_age": false,
79
- "has_gender": true,
80
- "sample_size": 84
81
- },
82
- "GSE104005": {
83
- "is_usable": true,
84
- "is_gene_available": true,
85
- "is_trait_available": true,
86
- "is_available": true,
87
- "is_biased": false,
88
- "has_age": true,
89
- "has_gender": true,
90
- "sample_size": 34
91
- },
92
- "TCGA": {
93
- "is_usable": true,
94
- "is_gene_available": true,
95
- "is_trait_available": true,
96
- "is_available": true,
97
- "is_biased": false,
98
- "has_age": true,
99
- "has_gender": true,
100
- "sample_size": 572
101
- }
102
- }
 
1
+ {"GSE82208": {"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": 52, "note": "INFO: Gene symbols normalized using NCBI synonym map. INFO: Samples before/after missing-value handling: 52/52. INFO: Gene features before/after filtering: 19845/19845. INFO: Missing Age before handling: 2. INFO: Missing Gender before handling: 2."}, "GSE80022": {"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": 73, "note": "INFO: Xenograft mouse model (GOT1 small intestine NET vs GOT2 medullary thyroid carcinoma); mouse hosts (Balb/c nude), no human age/gender covariates available."}, "GSE76039": {"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}, "GSE58689": {"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": 45, "note": "INFO: Affymetrix probe IDs mapped via 'Gene Symbol' from platform SOFT; many samples lack explicit age/gender; missing values handled per protocol."}, "GSE151181": {"is_usable": false, "is_gene_available": false, "is_trait_available": false, "is_available": false, "is_biased": null, "has_age": null, "has_gender": null, "sample_size": null, "note": "INFO: Trait derived from 'tissue type' (non-neoplastic thyroid = 0, tumor/metastasis = 1)."}, "GSE151179": {"is_usable": true, "is_gene_available": true, "is_trait_available": true, "is_available": true, "is_biased": false, "has_age": false, "has_gender": false, "sample_size": 52, "note": "INFO: Age and Gender unavailable in sample characteristics; trait derived from 'tissue type'. Thermo Fisher Human Clariom S platform used; probe-to-gene mapping and symbol normalization applied."}, "GSE138198": {"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": 23, "note": "INFO: Affymetrix Human Gene 1.0 ST platform; age not available; gender partially missing; probe-to-gene mapping via SOFT gene_assignment with equal-split aggregation."}, "GSE107754": {"is_usable": false, "is_gene_available": true, "is_trait_available": true, "is_available": true, "is_biased": true, "has_age": false, "has_gender": true, "sample_size": 71, "note": "INFO: Trait inferred from tissue; mixed metastatic tumor cohort; no age feature; gender included."}, "GSE104006": {"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": null}, "GSE104005": {"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": 34, "note": "INFO: Illumina HumanHT-12 probe data mapped to gene symbols; trait from 'disease' field; miRNA platform present but gene chip used."}, "TCGA": {"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": 572, "note": "INFO: Linked samples=572; genes=19848; Tumor=513; Normal=59; Age_included=True; Gender_included=True"}}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
output/preprocess/Thyroid_Cancer/gene_data/GSE151181.csv ADDED
@@ -0,0 +1 @@
 
 
1
+ Gene,GSM4567912,GSM4567913,GSM4567914,GSM4567915,GSM4567916,GSM4567917,GSM4567918,GSM4567919,GSM4567920,GSM4567921,GSM4567922,GSM4567923,GSM4567924,GSM4567925,GSM4567926,GSM4567927,GSM4567928,GSM4567929,GSM4567930,GSM4567931,GSM4567932,GSM4567933,GSM4567934,GSM4567935,GSM4567936,GSM4567937,GSM4567938,GSM4567939,GSM4567940,GSM4567941,GSM4567942,GSM4567943,GSM4567944,GSM4567945,GSM4567946,GSM4567947,GSM4567948,GSM4567949,GSM4567950,GSM4567951,GSM4567952,GSM4567953,GSM4567954,GSM4567955,GSM4567956,GSM4567957,GSM4567958,GSM4567959,GSM4567960,GSM4567961,GSM4567962,GSM4567963
output/preprocess/Type_1_Diabetes/clinical_data/GSE123086.csv ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ ,GSM3494884,GSM3494885,GSM3494886,GSM3494887,GSM3494888,GSM3494889,GSM3494890,GSM3494891,GSM3494892,GSM3494893,GSM3494894,GSM3494895,GSM3494896,GSM3494897,GSM3494898,GSM3494899,GSM3494900,GSM3494901,GSM3494902,GSM3494903,GSM3494904,GSM3494905,GSM3494906,GSM3494907,GSM3494908,GSM3494909,GSM3494910,GSM3494911,GSM3494912,GSM3494913,GSM3494914,GSM3494915,GSM3494916,GSM3494917,GSM3494918,GSM3494919,GSM3494920,GSM3494921,GSM3494922,GSM3494923,GSM3494924,GSM3494925,GSM3494926,GSM3494927,GSM3494928,GSM3494929,GSM3494930,GSM3494931,GSM3494932,GSM3494933,GSM3494934,GSM3494935,GSM3494936,GSM3494937,GSM3494938,GSM3494939,GSM3494940,GSM3494941,GSM3494942,GSM3494943,GSM3494944,GSM3494945,GSM3494946,GSM3494947,GSM3494948,GSM3494949,GSM3494950,GSM3494951,GSM3494952,GSM3494953,GSM3494954,GSM3494955,GSM3494956,GSM3494957,GSM3494958,GSM3494959,GSM3494960,GSM3494961,GSM3494962,GSM3494963,GSM3494964,GSM3494965,GSM3494966,GSM3494967,GSM3494968,GSM3494969,GSM3494970,GSM3494971,GSM3494972,GSM3494973,GSM3494974,GSM3494975,GSM3494976,GSM3494977,GSM3494978,GSM3494979,GSM3494980,GSM3494981,GSM3494982,GSM3494983,GSM3494984,GSM3494985,GSM3494986,GSM3494987,GSM3494988,GSM3494989,GSM3494990,GSM3494991,GSM3494992,GSM3494993,GSM3494994,GSM3494995,GSM3494996,GSM3494997,GSM3494998,GSM3494999,GSM3495000,GSM3495001,GSM3495002,GSM3495003,GSM3495004,GSM3495005,GSM3495006,GSM3495007,GSM3495008,GSM3495009,GSM3495010,GSM3495011,GSM3495012,GSM3495013,GSM3495014,GSM3495015,GSM3495016,GSM3495017,GSM3495018,GSM3495019,GSM3495020,GSM3495021,GSM3495022,GSM3495023,GSM3495024,GSM3495025,GSM3495026,GSM3495027,GSM3495028,GSM3495029,GSM3495030,GSM3495031,GSM3495032,GSM3495033,GSM3495034,GSM3495035,GSM3495036,GSM3495037,GSM3495038,GSM3495039,GSM3495040,GSM3495041,GSM3495042,GSM3495043,GSM3495044,GSM3495045,GSM3495046,GSM3495047,GSM3495048,GSM3495049
2
+ Type_1_Diabetes,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,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,,,,,,,,,,,,,,,,
3
+ Age,56.0,,20.0,51.0,37.0,61.0,,31.0,56.0,41.0,61.0,,80.0,53.0,61.0,73.0,60.0,76.0,77.0,74.0,69.0,77.0,81.0,70.0,82.0,69.0,82.0,67.0,67.0,78.0,67.0,74.0,,51.0,72.0,66.0,80.0,36.0,67.0,31.0,31.0,45.0,56.0,65.0,53.0,48.0,50.0,76.0,,24.0,42.0,76.0,22.0,,23.0,34.0,43.0,47.0,24.0,55.0,48.0,58.0,30.0,28.0,41.0,63.0,55.0,55.0,67.0,47.0,46.0,49.0,23.0,68.0,39.0,24.0,36.0,58.0,38.0,27.0,67.0,61.0,69.0,63.0,60.0,17.0,10.0,9.0,13.0,10.0,13.0,15.0,12.0,13.0,81.0,94.0,51.0,40.0,,97.0,23.0,93.0,58.0,28.0,54.0,15.0,8.0,11.0,12.0,8.0,14.0,8.0,10.0,14.0,13.0,40.0,52.0,42.0,29.0,43.0,41.0,54.0,42.0,49.0,45.0,56.0,64.0,71.0,48.0,20.0,53.0,32.0,26.0,28.0,47.0,24.0,48.0,,19.0,41.0,38.0,,15.0,12.0,13.0,,11.0,,16.0,11.0,,35.0,26.0,39.0,46.0,42.0,20.0,69.0,69.0,47.0,47.0,56.0,54.0,53.0,50.0,22.0
4
+ Gender,1.0,,0.0,0.0,1.0,1.0,,1.0,0.0,0.0,0.0,,1.0,1.0,1.0,1.0,1.0,1.0,0.0,0.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,,1.0,1.0,1.0,0.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,,0.0,0.0,1.0,1.0,,0.0,1.0,1.0,1.0,0.0,1.0,1.0,1.0,0.0,1.0,0.0,1.0,0.0,0.0,1.0,0.0,0.0,1.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,0.0,1.0,0.0,1.0,0.0,1.0,0.0,1.0,1.0,1.0,0.0,0.0,1.0,1.0,,1.0,1.0,0.0,1.0,0.0,1.0,1.0,1.0,1.0,1.0,0.0,1.0,0.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,0.0,1.0,0.0,0.0,0.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,,0.0,0.0,0.0,,0.0,1.0,0.0,,1.0,,1.0,1.0,,0.0,0.0,0.0,0.0,0.0,1.0,1.0,0.0,1.0,1.0,0.0,0.0,0.0,0.0,1.0
output/preprocess/Type_1_Diabetes/clinical_data/GSE123088.csv CHANGED
@@ -1,2 +1,4 @@
1
  ,GSM3494884,GSM3494885,GSM3494886,GSM3494887,GSM3494888,GSM3494889,GSM3494890,GSM3494891,GSM3494892,GSM3494893,GSM3494894,GSM3494895,GSM3494896,GSM3494897,GSM3494898,GSM3494899,GSM3494900,GSM3494901,GSM3494902,GSM3494903,GSM3494904,GSM3494905,GSM3494906,GSM3494907,GSM3494908,GSM3494909,GSM3494910,GSM3494911,GSM3494912,GSM3494913,GSM3494914,GSM3494915,GSM3494916,GSM3494917,GSM3494918,GSM3494919,GSM3494920,GSM3494921,GSM3494922,GSM3494923,GSM3494924,GSM3494925,GSM3494926,GSM3494927,GSM3494928,GSM3494929,GSM3494930,GSM3494931,GSM3494932,GSM3494933,GSM3494934,GSM3494935,GSM3494936,GSM3494937,GSM3494938,GSM3494939,GSM3494940,GSM3494941,GSM3494942,GSM3494943,GSM3494944,GSM3494945,GSM3494946,GSM3494947,GSM3494948,GSM3494949,GSM3494950,GSM3494951,GSM3494952,GSM3494953,GSM3494954,GSM3494955,GSM3494956,GSM3494957,GSM3494958,GSM3494959,GSM3494960,GSM3494961,GSM3494962,GSM3494963,GSM3494964,GSM3494965,GSM3494966,GSM3494967,GSM3494968,GSM3494969,GSM3494970,GSM3494971,GSM3494972,GSM3494973,GSM3494974,GSM3494975,GSM3494976,GSM3494977,GSM3494978,GSM3494979,GSM3494980,GSM3494981,GSM3494982,GSM3494983,GSM3494984,GSM3494985,GSM3494986,GSM3494987,GSM3494988,GSM3494989,GSM3494990,GSM3494991,GSM3494992,GSM3494993,GSM3494994,GSM3494995,GSM3494996,GSM3494997,GSM3494998,GSM3494999,GSM3495000,GSM3495001,GSM3495002,GSM3495003,GSM3495004,GSM3495005,GSM3495006,GSM3495007,GSM3495008,GSM3495009,GSM3495010,GSM3495011,GSM3495012,GSM3495013,GSM3495014,GSM3495015,GSM3495016,GSM3495017,GSM3495018,GSM3495019,GSM3495020,GSM3495021,GSM3495022,GSM3495023,GSM3495024,GSM3495025,GSM3495026,GSM3495027,GSM3495028,GSM3495029,GSM3495030,GSM3495031,GSM3495032,GSM3495033,GSM3495034,GSM3495035,GSM3495036,GSM3495037,GSM3495038,GSM3495039,GSM3495040,GSM3495041,GSM3495042,GSM3495043,GSM3495044,GSM3495045,GSM3495046,GSM3495047,GSM3495048,GSM3495049,GSM3495050,GSM3495051,GSM3495052,GSM3495053,GSM3495054,GSM3495055,GSM3495056,GSM3495057,GSM3495058,GSM3495059,GSM3495060,GSM3495061,GSM3495062,GSM3495063,GSM3495064,GSM3495065,GSM3495066,GSM3495067,GSM3495068,GSM3495069,GSM3495070,GSM3495071,GSM3495072,GSM3495073,GSM3495074,GSM3495075,GSM3495076,GSM3495077,GSM3495078,GSM3495079,GSM3495080,GSM3495081,GSM3495082,GSM3495083,GSM3495084,GSM3495085,GSM3495086,GSM3495087
2
- Type_1_Diabetes,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
 
 
 
1
  ,GSM3494884,GSM3494885,GSM3494886,GSM3494887,GSM3494888,GSM3494889,GSM3494890,GSM3494891,GSM3494892,GSM3494893,GSM3494894,GSM3494895,GSM3494896,GSM3494897,GSM3494898,GSM3494899,GSM3494900,GSM3494901,GSM3494902,GSM3494903,GSM3494904,GSM3494905,GSM3494906,GSM3494907,GSM3494908,GSM3494909,GSM3494910,GSM3494911,GSM3494912,GSM3494913,GSM3494914,GSM3494915,GSM3494916,GSM3494917,GSM3494918,GSM3494919,GSM3494920,GSM3494921,GSM3494922,GSM3494923,GSM3494924,GSM3494925,GSM3494926,GSM3494927,GSM3494928,GSM3494929,GSM3494930,GSM3494931,GSM3494932,GSM3494933,GSM3494934,GSM3494935,GSM3494936,GSM3494937,GSM3494938,GSM3494939,GSM3494940,GSM3494941,GSM3494942,GSM3494943,GSM3494944,GSM3494945,GSM3494946,GSM3494947,GSM3494948,GSM3494949,GSM3494950,GSM3494951,GSM3494952,GSM3494953,GSM3494954,GSM3494955,GSM3494956,GSM3494957,GSM3494958,GSM3494959,GSM3494960,GSM3494961,GSM3494962,GSM3494963,GSM3494964,GSM3494965,GSM3494966,GSM3494967,GSM3494968,GSM3494969,GSM3494970,GSM3494971,GSM3494972,GSM3494973,GSM3494974,GSM3494975,GSM3494976,GSM3494977,GSM3494978,GSM3494979,GSM3494980,GSM3494981,GSM3494982,GSM3494983,GSM3494984,GSM3494985,GSM3494986,GSM3494987,GSM3494988,GSM3494989,GSM3494990,GSM3494991,GSM3494992,GSM3494993,GSM3494994,GSM3494995,GSM3494996,GSM3494997,GSM3494998,GSM3494999,GSM3495000,GSM3495001,GSM3495002,GSM3495003,GSM3495004,GSM3495005,GSM3495006,GSM3495007,GSM3495008,GSM3495009,GSM3495010,GSM3495011,GSM3495012,GSM3495013,GSM3495014,GSM3495015,GSM3495016,GSM3495017,GSM3495018,GSM3495019,GSM3495020,GSM3495021,GSM3495022,GSM3495023,GSM3495024,GSM3495025,GSM3495026,GSM3495027,GSM3495028,GSM3495029,GSM3495030,GSM3495031,GSM3495032,GSM3495033,GSM3495034,GSM3495035,GSM3495036,GSM3495037,GSM3495038,GSM3495039,GSM3495040,GSM3495041,GSM3495042,GSM3495043,GSM3495044,GSM3495045,GSM3495046,GSM3495047,GSM3495048,GSM3495049,GSM3495050,GSM3495051,GSM3495052,GSM3495053,GSM3495054,GSM3495055,GSM3495056,GSM3495057,GSM3495058,GSM3495059,GSM3495060,GSM3495061,GSM3495062,GSM3495063,GSM3495064,GSM3495065,GSM3495066,GSM3495067,GSM3495068,GSM3495069,GSM3495070,GSM3495071,GSM3495072,GSM3495073,GSM3495074,GSM3495075,GSM3495076,GSM3495077,GSM3495078,GSM3495079,GSM3495080,GSM3495081,GSM3495082,GSM3495083,GSM3495084,GSM3495085,GSM3495086,GSM3495087
2
+ Type_1_Diabetes,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,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,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0
3
+ Age,56.0,,20.0,51.0,37.0,61.0,,31.0,56.0,41.0,61.0,,80.0,53.0,61.0,73.0,60.0,76.0,77.0,74.0,69.0,77.0,81.0,70.0,82.0,69.0,82.0,67.0,67.0,78.0,67.0,74.0,,51.0,72.0,66.0,80.0,36.0,67.0,31.0,31.0,45.0,56.0,65.0,53.0,48.0,50.0,76.0,,24.0,42.0,76.0,22.0,,23.0,34.0,43.0,47.0,24.0,55.0,48.0,58.0,30.0,28.0,41.0,63.0,55.0,55.0,67.0,47.0,46.0,49.0,23.0,68.0,39.0,24.0,36.0,58.0,38.0,27.0,67.0,61.0,69.0,63.0,60.0,17.0,10.0,9.0,13.0,10.0,13.0,15.0,12.0,13.0,81.0,94.0,51.0,40.0,,97.0,23.0,93.0,58.0,28.0,54.0,15.0,8.0,11.0,12.0,8.0,14.0,8.0,10.0,14.0,13.0,40.0,52.0,42.0,29.0,43.0,41.0,54.0,42.0,49.0,45.0,56.0,64.0,71.0,48.0,20.0,53.0,32.0,26.0,28.0,47.0,24.0,48.0,,19.0,41.0,38.0,,15.0,12.0,13.0,,11.0,,16.0,11.0,,35.0,26.0,39.0,46.0,42.0,20.0,69.0,69.0,47.0,47.0,56.0,54.0,53.0,50.0,22.0,62.0,74.0,57.0,47.0,70.0,50.0,52.0,43.0,57.0,53.0,70.0,41.0,61.0,39.0,58.0,55.0,63.0,60.0,43.0,68.0,67.0,50.0,67.0,51.0,59.0,44.0,35.0,83.0,78.0,88.0,41.0,60.0,72.0,53.0,73.0,56.0,38.0,53.0
4
+ Gender,1.0,,0.0,0.0,1.0,1.0,,1.0,0.0,0.0,0.0,,1.0,1.0,1.0,1.0,1.0,1.0,0.0,0.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,,1.0,1.0,1.0,0.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,,0.0,0.0,1.0,1.0,,0.0,1.0,1.0,1.0,0.0,1.0,1.0,1.0,0.0,1.0,0.0,1.0,0.0,0.0,1.0,0.0,0.0,1.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,0.0,1.0,0.0,1.0,0.0,1.0,0.0,1.0,1.0,1.0,0.0,0.0,1.0,1.0,,1.0,1.0,0.0,1.0,0.0,1.0,1.0,1.0,1.0,1.0,0.0,1.0,0.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,0.0,1.0,0.0,0.0,0.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,,0.0,0.0,0.0,,0.0,1.0,0.0,,1.0,,1.0,1.0,,0.0,0.0,0.0,0.0,0.0,1.0,1.0,0.0,1.0,1.0,0.0,0.0,0.0,0.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0
output/preprocess/Type_1_Diabetes/clinical_data/GSE156035.csv CHANGED
@@ -1,3 +1,3 @@
1
- GSM4720871,GSM4720872,GSM4720873,GSM4720874,GSM4720875,GSM4720876,GSM4720877,GSM4720878,GSM4720879,GSM4720880,GSM4720881,GSM4720882,GSM4720883,GSM4720884,GSM4720885,GSM4720886,GSM4720887,GSM4720888,GSM4720889,GSM4720890,GSM4720891,GSM4720892,GSM4720893,GSM4720894,GSM4720895,GSM4720896,GSM4720897,GSM4720898,GSM4720899,GSM4720900,GSM4720901,GSM4720902,GSM4720903,GSM4720904,GSM4720905,GSM4720906,GSM4720907,GSM4720908,GSM4720909,GSM4720910
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,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0
3
- 0.0,0.0,1.0,0.0,1.0,0.0,1.0,1.0,0.0,0.0,1.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,1.0,0.0,1.0,1.0
 
1
+ ,GSM4720871,GSM4720872,GSM4720873,GSM4720874,GSM4720875,GSM4720876,GSM4720877,GSM4720878,GSM4720879,GSM4720880,GSM4720881,GSM4720882,GSM4720883,GSM4720884,GSM4720885,GSM4720886,GSM4720887,GSM4720888,GSM4720889,GSM4720890,GSM4720891,GSM4720892,GSM4720893,GSM4720894,GSM4720895,GSM4720896,GSM4720897,GSM4720898,GSM4720899,GSM4720900,GSM4720901,GSM4720902,GSM4720903,GSM4720904,GSM4720905,GSM4720906,GSM4720907,GSM4720908,GSM4720909,GSM4720910
2
+ Type_1_Diabetes,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,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
3
+ Gender,0.0,0.0,1.0,0.0,1.0,0.0,1.0,1.0,0.0,0.0,1.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,1.0,0.0,1.0,1.0
output/preprocess/Type_1_Diabetes/clinical_data/GSE182870.csv CHANGED
The diff for this file is too large to render. See raw diff
 
output/preprocess/Type_1_Diabetes/clinical_data/GSE193273.csv CHANGED
@@ -1,2 +1,2 @@
1
- ,0,1
2
- Type_1_Diabetes,0.0,1.0
 
1
+ ,GSM5781088,GSM5781089,GSM5781090,GSM5781091,GSM5781092,GSM5781093,GSM5781095,GSM5781096,GSM5781097,GSM5781098,GSM5781099,GSM5781100,GSM5781101,GSM5781102,GSM5781104,GSM5781105,GSM5781106,GSM5781107,GSM5781108,GSM5781109,GSM5781110,GSM5781111,GSM5781113,GSM5781114,GSM5781115,GSM5781116,GSM5781117,GSM5781118,GSM5781119,GSM5781120,GSM5781121,GSM5781123,GSM5781124,GSM5781125,GSM5781126,GSM5781127,GSM5781128,GSM5781129,GSM5781131,GSM5781132
2
+ Type_1_Diabetes,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,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
output/preprocess/Type_1_Diabetes/code/GSE123086.py ADDED
@@ -0,0 +1,322 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Type_1_Diabetes"
6
+ cohort = "GSE123086"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Type_1_Diabetes"
10
+ in_cohort_dir = "../DATA/GEO/Type_1_Diabetes/GSE123086"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z6/preprocess/Type_1_Diabetes/GSE123086.csv"
14
+ out_gene_data_file = "./output/z6/preprocess/Type_1_Diabetes/gene_data/GSE123086.csv"
15
+ out_clinical_data_file = "./output/z6/preprocess/Type_1_Diabetes/clinical_data/GSE123086.csv"
16
+ json_path = "./output/z6/preprocess/Type_1_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 os
40
+ import re
41
+ import pandas as pd
42
+
43
+ # 1) Gene expression data availability
44
+ is_gene_available = True # Agilent one-color gene expression microarray per Series_overall_design
45
+
46
+ # 2) Variable availability and converters based on Sample Characteristics Dictionary
47
+ trait_row = 1 # 'primary diagnosis: ...' includes TYPE_1_DIABETES and HEALTHY_CONTROL
48
+ age_row = 3 # contains many 'age: ...' entries (more coverage than row 4)
49
+ gender_row = 2 # contains 'Sex: Female'/'Sex: Male' entries
50
+
51
+ def _split_header_value(x: str):
52
+ if x is None:
53
+ return None, None
54
+ parts = str(x).split(":", 1)
55
+ if len(parts) == 2:
56
+ header = parts[0].strip().lower()
57
+ value = parts[1].strip()
58
+ return header, value
59
+ # If no colon, treat entire string as value with unknown header
60
+ return None, str(x).strip()
61
+
62
+ def convert_trait(x):
63
+ header, val = _split_header_value(x)
64
+ if val is None:
65
+ return None
66
+ # Only use 'primary diagnosis' field for trait conversion
67
+ if header not in {"primary diagnosis", "primary_diagnosis", "primarydiagnosis"}:
68
+ return None
69
+ v = val.upper().replace("-", "_").replace(" ", "_")
70
+ # Map T1D cases to 1
71
+ if ("TYPE_1_DIABETES" in v) or ("TYPE_I_DIABETES" in v):
72
+ return 1
73
+ # Map healthy controls to 0
74
+ if ("HEALTHY" in v) or ("CONTROL" in v) or ("HEALTHY_CONTROL" in v):
75
+ return 0
76
+ # Other diseases -> not applicable for this trait
77
+ return None
78
+
79
+ def convert_age(x):
80
+ header, val = _split_header_value(x)
81
+ if val is None:
82
+ return None
83
+ if header != "age":
84
+ return None
85
+ # Extract first numeric token
86
+ m = re.search(r"[-+]?\d+(\.\d+)?", val)
87
+ if not m:
88
+ return None
89
+ try:
90
+ age = float(m.group())
91
+ except Exception:
92
+ return None
93
+ if 0 <= age <= 120:
94
+ return age
95
+ return None
96
+
97
+ def convert_gender(x):
98
+ header, val = _split_header_value(x)
99
+ if val is None:
100
+ return None
101
+ if header not in {"sex", "gender"}:
102
+ return None
103
+ v = val.strip().lower()
104
+ if v in {"male", "m"}:
105
+ return 1
106
+ if v in {"female", "f"}:
107
+ return 0
108
+ return None
109
+
110
+ # 3) Initial filtering and save metadata
111
+ is_trait_available = trait_row is not None
112
+ _ = validate_and_save_cohort_info(
113
+ is_final=False,
114
+ cohort=cohort,
115
+ info_path=json_path,
116
+ is_gene_available=is_gene_available,
117
+ is_trait_available=is_trait_available
118
+ )
119
+
120
+ # 4) Clinical feature extraction, preview, and save
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)
133
+ print(preview)
134
+
135
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
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
+ # Based on the observed identifiers (numeric IDs like '1','2','3',...), these are not human gene symbols.
147
+ requires_gene_mapping = True
148
+ print(f"requires_gene_mapping = {requires_gene_mapping}")
149
+
150
+ # Step 5: Gene Annotation
151
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
152
+ gene_annotation = get_gene_annotation(soft_file)
153
+
154
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
155
+ print("Gene annotation preview:")
156
+ print(preview_df(gene_annotation))
157
+
158
+ # Step 6: Gene Identifier Mapping
159
+ import re
160
+ import pandas as pd
161
+
162
+ # Inspect available columns to choose ID and symbol columns robustly
163
+ ann_cols = list(gene_annotation.columns)
164
+
165
+ # 1) Decide identifier and gene symbol columns
166
+ expr_ids = set(gene_data.index.astype(str))
167
+
168
+ # Choose probe/ID column: prefer 'ID' if present, otherwise choose max overlap
169
+ if 'ID' in gene_annotation.columns:
170
+ id_col = 'ID'
171
+ else:
172
+ overlap_scores = {}
173
+ for col in ann_cols:
174
+ vals = gene_annotation[col].astype(str)
175
+ overlap_scores[col] = (vals.head(2000).isin(expr_ids)).mean()
176
+ id_col = max(overlap_scores, key=overlap_scores.get)
177
+
178
+ # Try to find a gene symbol-like column using flexible matching
179
+ symbol_candidates = [
180
+ 'GENE_SYMBOL', 'GENE SYMBOL', 'GENE_SYMBOLS', 'GENE SYMBOLS',
181
+ 'GENE_SYMBOL_CH1', 'GENE SYMBOL CH1', 'SYMBOL', 'GENE', 'GENE_NAME', 'GENE NAME',
182
+ 'GENE_TITLE', 'GENE TITLE', 'HGNC_SYMBOL', 'HGNC SYMBOL', 'GENES'
183
+ ]
184
+ def normalize_colname(c):
185
+ return re.sub(r'[^A-Z0-9]', '', str(c).upper())
186
+ normalized_map = {normalize_colname(c): c for c in ann_cols}
187
+ symbol_col = None
188
+ for cand in symbol_candidates:
189
+ norm_cand = normalize_colname(cand)
190
+ if norm_cand in normalized_map:
191
+ symbol_col = normalized_map[norm_cand]
192
+ break
193
+
194
+ print(f"[INFO] Using ID column: {id_col}")
195
+ print(f"[INFO] Gene symbol column: {symbol_col if symbol_col is not None else 'None (will fallback to ENTREZ_GENE_ID)'}")
196
+
197
+ # 2) Build mapping dataframe and 3) Apply mapping to convert to gene-level data
198
+ if symbol_col is not None:
199
+ # Use provided helper for mapping extraction; apply_gene_mapping will parse symbols sensibly
200
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=id_col, gene_col=symbol_col)
201
+ gene_data = apply_gene_mapping(gene_data, mapping_df)
202
+ else:
203
+ # Fallback: use ENTREZ_GENE_ID as gene identifier (do not blindly split; only split on clear multi-maps)
204
+ if 'ENTREZ_GENE_ID' not in gene_annotation.columns:
205
+ # If even ENTREZ is not available, map 1:1 to probe IDs to avoid explosion
206
+ print("[WARNING] ENTREZ_GENE_ID not found. Keeping probe-level data (no mapping applied).")
207
+ # Keep gene_data as is (probe-level). This is a conservative fallback.
208
+ else:
209
+ temp_map = gene_annotation.loc[:, [id_col, 'ENTREZ_GENE_ID']].copy()
210
+ temp_map.columns = ['ID', 'GeneRaw']
211
+ temp_map = temp_map.dropna()
212
+ temp_map['ID'] = temp_map['ID'].astype(str).str.strip()
213
+ temp_map['GeneRaw'] = temp_map['GeneRaw'].astype(str).str.strip()
214
+
215
+ # Keep only IDs present in expression data
216
+ temp_map = temp_map[temp_map['ID'].isin(gene_data.index)]
217
+
218
+ # Split only if clear multi-mapping separators exist; keep only numeric Entrez tokens
219
+ sep_pattern = re.compile(r'///|[,;|]')
220
+ def to_gene_list(s: str):
221
+ if pd.isna(s):
222
+ return []
223
+ s = str(s).strip()
224
+ if not s:
225
+ return []
226
+ if sep_pattern.search(s):
227
+ parts = re.split(r'\s*(?:///|[,;|])\s*', s)
228
+ else:
229
+ parts = [s]
230
+ # Keep only strictly numeric Entrez IDs and remove zeros or empty tokens
231
+ parts = [p for p in parts if re.fullmatch(r'\d+', p) and p != '0']
232
+ # Deduplicate while preserving order
233
+ return list(dict.fromkeys(parts))
234
+
235
+ temp_map['GeneList'] = temp_map['GeneRaw'].map(to_gene_list)
236
+ # Drop mappings with no valid Entrez ID
237
+ temp_map = temp_map[temp_map['GeneList'].map(len) > 0].copy()
238
+
239
+ # Compute number of genes per probe
240
+ temp_map['num_genes'] = temp_map['GeneList'].map(len)
241
+
242
+ # Explode to one row per probe-gene pair and deduplicate
243
+ mapping_df = temp_map[['ID', 'GeneList', 'num_genes']].explode('GeneList')
244
+ mapping_df = mapping_df.rename(columns={'GeneList': 'Gene'})
245
+ mapping_df = mapping_df.drop_duplicates(subset=['ID', 'Gene'])
246
+
247
+ # Join with expression and distribute equally
248
+ mapping_df = mapping_df.set_index('ID')
249
+ merged = mapping_df.join(gene_data, how='inner')
250
+ expr_cols = [c for c in merged.columns if c not in ['Gene', 'num_genes']]
251
+
252
+ # Safety: avoid division by zero
253
+ merged['num_genes'] = merged['num_genes'].replace(0, 1)
254
+ merged[expr_cols] = merged[expr_cols].div(merged['num_genes'], axis=0)
255
+
256
+ # Aggregate to gene (Entrez) level
257
+ gene_data = merged.groupby('Gene')[expr_cols].sum()
258
+
259
+ # Sanity checks
260
+ print(f"[INFO] Gene-level data shape: {gene_data.shape}")
261
+ if isinstance(gene_data.index, pd.Index):
262
+ print(f"[INFO] Unique gene identifiers: {gene_data.index.nunique()}")
263
+
264
+ # Step 7: Data Normalization and Linking
265
+ import os
266
+ import pandas as pd
267
+
268
+ # 1. Normalize gene symbols if appropriate; otherwise keep Entrez-level data and leave a note.
269
+ note = ""
270
+ # Detect if index looks like Entrez IDs (all numeric)
271
+ idx_as_str = pd.Index(gene_data.index.astype(str))
272
+ is_entrez_index = idx_as_str.str.fullmatch(r'\d+').all()
273
+
274
+ if is_entrez_index:
275
+ # Skip normalization due to lack of gene symbols in annotation; keep Entrez-level data
276
+ normalized_gene_data = gene_data
277
+ note = "WARNING: Skipped gene-symbol normalization because gene index consists of Entrez IDs and no gene symbol annotations were available."
278
+ else:
279
+ # Attempt normalization; if it collapses too much, fall back to original
280
+ temp_normalized = normalize_gene_symbols_in_index(gene_data.copy())
281
+ if temp_normalized.shape[0] == 0:
282
+ normalized_gene_data = gene_data
283
+ note = "WARNING: Gene-symbol normalization produced an empty matrix; reverted to original gene data."
284
+ else:
285
+ normalized_gene_data = temp_normalized
286
+ note = "INFO: Gene symbols normalized using synonym mapping."
287
+
288
+ # Save gene (possibly normalized) data
289
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
290
+ normalized_gene_data.to_csv(out_gene_data_file)
291
+
292
+ # 2. Link the clinical and genetic data
293
+ # Fix variable name to use the existing clinical dataframe from Step 2
294
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
295
+
296
+ # 3. Handle missing values
297
+ linked_data = handle_missing_values(linked_data, trait)
298
+
299
+ # 4. Determine bias and remove biased demographics
300
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
301
+
302
+ # 5. Final validation and save cohort info
303
+ # Determine availability flags based on data presence
304
+ is_gene_available_flag = (normalized_gene_data.shape[0] > 0 and normalized_gene_data.shape[1] > 0)
305
+ # Trait data was extracted earlier; let final validation handle abnormalities if any
306
+ is_trait_available_flag = True
307
+
308
+ is_usable = validate_and_save_cohort_info(
309
+ is_final=True,
310
+ cohort=cohort,
311
+ info_path=json_path,
312
+ is_gene_available=is_gene_available_flag,
313
+ is_trait_available=is_trait_available_flag,
314
+ is_biased=is_trait_biased,
315
+ df=unbiased_linked_data,
316
+ note=note
317
+ )
318
+
319
+ # 6. Save linked data only if usable
320
+ if is_usable:
321
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
322
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Type_1_Diabetes/code/GSE123088.py ADDED
@@ -0,0 +1,303 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Type_1_Diabetes"
6
+ cohort = "GSE123088"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Type_1_Diabetes"
10
+ in_cohort_dir = "../DATA/GEO/Type_1_Diabetes/GSE123088"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z6/preprocess/Type_1_Diabetes/GSE123088.csv"
14
+ out_gene_data_file = "./output/z6/preprocess/Type_1_Diabetes/gene_data/GSE123088.csv"
15
+ out_clinical_data_file = "./output/z6/preprocess/Type_1_Diabetes/clinical_data/GSE123088.csv"
16
+ json_path = "./output/z6/preprocess/Type_1_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 os
40
+ import re
41
+
42
+ # 1. Gene Expression Data Availability
43
+ is_gene_available = True # Based on series context indicating single-cell gene expression (not miRNA/methylation)
44
+
45
+ # 2. Variable Availability and Data Type Conversion
46
+
47
+ # Identify rows where variables are recorded
48
+ trait_row = 1 # 'primary diagnosis: ...'
49
+ age_row = 3 # 'age: ...' (most ages appear here)
50
+ gender_row = 2 # 'Sex: Female/Male'
51
+
52
+ # Conversion functions
53
+ def convert_trait(x):
54
+ if x is None:
55
+ return None
56
+ s = str(x).strip()
57
+ parts = s.split(":", 1)
58
+ header = parts[0].strip().lower()
59
+ value = parts[1].strip() if len(parts) > 1 else s.strip()
60
+ v = value.lower()
61
+
62
+ if 'primary' in header and 'diagnosis' in header:
63
+ # Map presence of Type 1 Diabetes to 1, others (including controls and other diseases) to 0
64
+ v_std = re.sub(r'[^a-z0-9]+', '_', v)
65
+ if ('diab' in v and ('type_1' in v_std or 'type1' in v_std or 't1d' in v_std)):
66
+ return 1
67
+ else:
68
+ return 0
69
+ return None
70
+
71
+ def convert_age(x):
72
+ if x is None:
73
+ return None
74
+ s = str(x).strip()
75
+ parts = s.split(":", 1)
76
+ header = parts[0].strip().lower()
77
+ value = parts[1].strip() if len(parts) > 1 else s.strip()
78
+ if 'age' in header:
79
+ m = re.search(r'[-+]?\d*\.?\d+', value)
80
+ if m:
81
+ try:
82
+ val = float(m.group())
83
+ return val
84
+ except:
85
+ return None
86
+ return None
87
+
88
+ def convert_gender(x):
89
+ if x is None:
90
+ return None
91
+ s = str(x).strip()
92
+ parts = s.split(":", 1)
93
+ header = parts[0].strip().lower()
94
+ value = parts[1].strip() if len(parts) > 1 else s.strip()
95
+ if ('sex' in header) or ('gender' in header):
96
+ v = value.lower()
97
+ if 'female' in v:
98
+ return 0
99
+ if 'male' in v:
100
+ return 1
101
+ return None
102
+ return None
103
+
104
+ # 3. Save Metadata (initial filtering)
105
+ is_trait_available = trait_row is not None
106
+ _ = validate_and_save_cohort_info(
107
+ is_final=False,
108
+ cohort=cohort,
109
+ info_path=json_path,
110
+ is_gene_available=is_gene_available,
111
+ is_trait_available=is_trait_available
112
+ )
113
+
114
+ # 4. Clinical Feature Extraction (only if trait is available)
115
+ if trait_row is not None:
116
+ selected_clinical_df = geo_select_clinical_features(
117
+ clinical_df=clinical_data,
118
+ trait=trait,
119
+ trait_row=trait_row,
120
+ convert_trait=convert_trait,
121
+ age_row=age_row,
122
+ convert_age=convert_age,
123
+ gender_row=gender_row,
124
+ convert_gender=convert_gender
125
+ )
126
+ preview = preview_df(selected_clinical_df)
127
+ print(preview)
128
+
129
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
130
+ selected_clinical_df.to_csv(out_clinical_data_file)
131
+
132
+ # Step 3: Gene Data Extraction
133
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
134
+ gene_data = get_genetic_data(matrix_file)
135
+
136
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
137
+ print(gene_data.index[:20])
138
+
139
+ # Step 4: Gene Identifier Review
140
+ requires_gene_mapping = True
141
+ print(f"requires_gene_mapping = {requires_gene_mapping}")
142
+
143
+ # Step 5: Gene Annotation
144
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
145
+ gene_annotation = get_gene_annotation(soft_file)
146
+
147
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
148
+ print("Gene annotation preview:")
149
+ print(preview_df(gene_annotation))
150
+
151
+ # Step 6: Gene Identifier Mapping
152
+ import re
153
+ import pandas as pd
154
+
155
+ # Recreate probe-level expression to avoid contamination from prior attempts
156
+ expr_df = get_genetic_data(matrix_file)
157
+
158
+ # Try to find a gene symbol column in the annotation
159
+ symbol_col = None
160
+ colnames = list(gene_annotation.columns)
161
+
162
+ # Common symbol-like names
163
+ preferred_names = [
164
+ 'Gene Symbol', 'GENE_SYMBOL', 'SYMBOL', 'Gene symbol', 'Symbol', 'gene_symbol', 'gene symbol'
165
+ ]
166
+
167
+ # First pass: exact-ish matches by name
168
+ for name in preferred_names:
169
+ if name in colnames:
170
+ symbol_col = name
171
+ break
172
+
173
+ # Second pass: regex match on column names if not found
174
+ if symbol_col is None:
175
+ for c in colnames:
176
+ if re.search(r'\b(gene\s*symbol|symbol)\b', str(c), flags=re.I):
177
+ symbol_col = c
178
+ break
179
+
180
+ # Validate candidate symbol column by content (must yield plausible human gene symbols)
181
+ def looks_like_symbol_col(series: pd.Series, sample_n: int = 200) -> bool:
182
+ # sample a subset to avoid heavy computation
183
+ sample_vals = series.astype(str).head(sample_n)
184
+ count_symbolish = 0
185
+ for v in sample_vals:
186
+ syms = extract_human_gene_symbols(v)
187
+ if len(syms) > 0:
188
+ count_symbolish += 1
189
+ # Heuristic: at least 10% rows produce plausible symbols
190
+ return (count_symbolish / max(1, len(sample_vals))) >= 0.1
191
+
192
+ if symbol_col is not None and not looks_like_symbol_col(gene_annotation[symbol_col]):
193
+ symbol_col = None
194
+
195
+ if symbol_col is not None:
196
+ # Use library helpers to map to gene symbols and aggregate
197
+ mapping_df = get_gene_mapping(annotation=gene_annotation, prob_col='ID', gene_col=symbol_col)
198
+ mapping_df = mapping_df[mapping_df['ID'].isin(expr_df.index)]
199
+ print(f"Using symbol column: {symbol_col}. Candidate mappings: {len(mapping_df)}")
200
+
201
+ gene_data = apply_gene_mapping(expression_df=expr_df, mapping_df=mapping_df)
202
+
203
+ # Sanity checks
204
+ n_genes = gene_data.shape[0]
205
+ if n_genes <= 0 or n_genes > 70000:
206
+ raise ValueError(f"Unreasonable number of genes after symbol mapping: {n_genes}")
207
+ print(f"Gene-level matrix (symbol) shape: {gene_data.shape}")
208
+ print(f"First 5 gene symbols: {list(gene_data.index[:5])}")
209
+
210
+ else:
211
+ # Fallback: robust Entrez ID mapping
212
+ if 'ENTREZ_GENE_ID' not in gene_annotation.columns:
213
+ raise ValueError("No gene symbol column found and ENTREZ_GENE_ID column is missing; cannot build mapping.")
214
+
215
+ mapping_df = gene_annotation.loc[:, ['ID', 'ENTREZ_GENE_ID']].dropna().copy()
216
+ mapping_df['ID'] = mapping_df['ID'].astype(str).str.strip()
217
+ mapping_df = mapping_df[mapping_df['ID'].isin(expr_df.index)]
218
+
219
+ # Restrictive split: GEO uses "///" for multi-mapping; also accept semicolon/comma
220
+ def split_entrez_ids(x: str):
221
+ if not isinstance(x, str):
222
+ return []
223
+ parts = re.split(r'\s*///\s*|[;,]+', x)
224
+ parts = [p.strip() for p in parts if p and p.upper() not in {'NA', 'NAN', '---'}]
225
+ # Keep strictly numeric (Entrez IDs)
226
+ parts = [p for p in parts if re.fullmatch(r'\d+', p) is not None]
227
+ return parts
228
+
229
+ mapping_df['Gene'] = mapping_df['ENTREZ_GENE_ID'].astype(str).apply(split_entrez_ids)
230
+ mapping_df['num_genes'] = mapping_df['Gene'].apply(len)
231
+ mapping_df = mapping_df[mapping_df['num_genes'] > 0]
232
+ mapping_df = mapping_df.explode('Gene').dropna(subset=['Gene'])
233
+
234
+ # Make Gene labels explicit and non-numeric to avoid collision/contamination
235
+ mapping_df['Gene'] = mapping_df['Gene'].astype(str).map(lambda x: f"ENTREZ:{x}")
236
+
237
+ # Join and aggregate
238
+ mapping_df = mapping_df.set_index('ID')
239
+ merged = mapping_df.join(expr_df, how='inner')
240
+
241
+ expr_cols = [c for c in merged.columns if c not in ['ENTREZ_GENE_ID', 'Gene', 'num_genes']]
242
+ merged[expr_cols] = merged[expr_cols].div(merged['num_genes'].replace(0, 1), axis=0)
243
+
244
+ gene_data = merged.groupby('Gene', sort=False)[expr_cols].sum()
245
+
246
+ # Sanity checks
247
+ n_genes = gene_data.shape[0]
248
+ if n_genes <= 0 or n_genes > 70000:
249
+ raise ValueError(f"Unreasonable number of genes after Entrez mapping: {n_genes}")
250
+ # Ensure IDs look like "ENTREZ:####"
251
+ bad_ids = [g for g in gene_data.index[:1000] if re.fullmatch(r'ENTREZ:\d+', g) is None]
252
+ if len(bad_ids) > 0:
253
+ raise ValueError(f"Unexpected gene IDs detected (showing up to 5): {bad_ids[:5]}")
254
+
255
+ print(f"Gene-level matrix (Entrez) shape: {gene_data.shape}")
256
+ print(f"First 5 gene IDs: {list(gene_data.index[:5])}")
257
+
258
+ # Step 7: Data Normalization and Linking
259
+ import os
260
+ import re
261
+
262
+ # 1. Normalize gene symbols if applicable; skip if IDs are Entrez
263
+ entrez_pattern = re.compile(r'^ENTREZ:\d+$')
264
+ all_entrez = all(entrez_pattern.fullmatch(idx) is not None for idx in gene_data.index)
265
+
266
+ note = ""
267
+ if all_entrez:
268
+ # Skip normalization because we have Entrez-style IDs, not gene symbols
269
+ normalized_gene_data = gene_data.copy()
270
+ note = "INFO: Gene normalization skipped because gene IDs are Entrez (ENTREZ:####)."
271
+ else:
272
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
273
+ note = "INFO: Gene symbols normalized using NCBI synonym mapping."
274
+
275
+ # Ensure output directory exists and save gene data
276
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
277
+ normalized_gene_data.to_csv(out_gene_data_file)
278
+
279
+ # 2. Link the clinical and genetic data
280
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
281
+
282
+ # 3. Handle missing values in the linked data
283
+ linked_data = handle_missing_values(linked_data, trait)
284
+
285
+ # 4. Determine whether the trait and demographic features are severely biased, and remove biased features
286
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
287
+
288
+ # 5. Final quality validation and save cohort information
289
+ is_usable = validate_and_save_cohort_info(
290
+ is_final=True,
291
+ cohort=cohort,
292
+ info_path=json_path,
293
+ is_gene_available=True,
294
+ is_trait_available=True,
295
+ is_biased=is_trait_biased,
296
+ df=unbiased_linked_data,
297
+ note=note
298
+ )
299
+
300
+ # 6. Save linked data only if usable
301
+ if is_usable:
302
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
303
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Type_1_Diabetes/code/GSE131528.py ADDED
@@ -0,0 +1,204 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Type_1_Diabetes"
6
+ cohort = "GSE131528"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Type_1_Diabetes"
10
+ in_cohort_dir = "../DATA/GEO/Type_1_Diabetes/GSE131528"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z6/preprocess/Type_1_Diabetes/GSE131528.csv"
14
+ out_gene_data_file = "./output/z6/preprocess/Type_1_Diabetes/gene_data/GSE131528.csv"
15
+ out_clinical_data_file = "./output/z6/preprocess/Type_1_Diabetes/clinical_data/GSE131528.csv"
16
+ json_path = "./output/z6/preprocess/Type_1_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
+ # Determine data availability based on provided background and characteristics
40
+
41
+ # 1) Gene expression availability: Title suggests immune signature profiling; likely gene expression (not miRNA-only or methylation)
42
+ is_gene_available = True
43
+
44
+ # 2) Variable availability and conversion functions
45
+
46
+ # Trait (Type_1_Diabetes): Only T1D/new onset T1D observed, no healthy/control in the sample characteristics.
47
+ # Treat as not available for our binary case-control analysis.
48
+ trait_row = None # constant "case-only" cohort is not useful for association with the trait
49
+
50
+ # Age: Available in key 3 (age at enrollment / age at blood draw)
51
+ age_row = 3
52
+
53
+ # Gender: Available in key 5 (sex: female/male)
54
+ gender_row = 5
55
+
56
+ # Conversion utilities
57
+ def _after_colon(value):
58
+ if value is None:
59
+ return None
60
+ s = str(value)
61
+ if ':' in s:
62
+ s = s.split(':', 1)[1]
63
+ return s.strip()
64
+
65
+ def convert_trait(value):
66
+ v = _after_colon(value)
67
+ if v is None:
68
+ return None
69
+ vl = v.lower()
70
+ # Positive (T1D) indicators
71
+ positive = ['t1d', 'type 1 diabetes', 'type i diabetes', 'new onset t1d', 'diabetic']
72
+ if any(tok in vl for tok in positive):
73
+ return 1
74
+ # Negative (control/healthy) indicators
75
+ negative = ['control', 'healthy', 'non-diabetic', 'no diabetes', 'normoglycemic', 'normoglycaemic']
76
+ if any(tok in vl for tok in negative):
77
+ return 0
78
+ return None
79
+
80
+ def convert_age(value):
81
+ v = _after_colon(value)
82
+ if v is None:
83
+ return None
84
+ vl = v.lower()
85
+ # Only attempt to parse when the field is about age; otherwise return None
86
+ if 'age' not in vl:
87
+ # Some entries in the same row may be race or other descriptors
88
+ # If the part after colon is numeric already (rare), still try to parse
89
+ pass
90
+ # Handle NA-like values
91
+ if v.strip().lower() in ['na', 'n/a', '', 'nan']:
92
+ return None
93
+ # Extract numeric token (age values look like plain numbers)
94
+ try:
95
+ return float(v)
96
+ except Exception:
97
+ # Try to extract leading/trailing numeric substrings
98
+ import re
99
+ m = re.search(r'[-+]?\d*\.?\d+', v)
100
+ if m:
101
+ try:
102
+ return float(m.group(0))
103
+ except Exception:
104
+ return None
105
+ return None
106
+
107
+ def convert_gender(value):
108
+ v = _after_colon(value)
109
+ if v is None:
110
+ return None
111
+ vl = v.lower()
112
+ # Accept various representations
113
+ if vl in ['f', 'female']:
114
+ return 0
115
+ if vl in ['m', 'male']:
116
+ return 1
117
+ # Some entries in the same row are unrelated (e.g., AUC); return None
118
+ return None
119
+
120
+ # 3) Save metadata (initial filtering)
121
+ is_trait_available = trait_row is not None
122
+ _ = validate_and_save_cohort_info(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
+ # 4) Clinical feature extraction: skip because trait_row is None (trait not available for this dataset)
129
+ # If in future trait_row becomes available, the following template can be used:
130
+ # selected_clinical_df = geo_select_clinical_features(clinical_data, trait, trait_row,
131
+ # convert_trait,
132
+ # age_row=age_row,
133
+ # convert_age=convert_age,
134
+ # gender_row=gender_row,
135
+ # convert_gender=convert_gender)
136
+ # preview = preview_df(selected_clinical_df)
137
+ # os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
138
+ # selected_clinical_df.to_csv(out_clinical_data_file)
139
+
140
+ # Step 3: Gene Data Extraction
141
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
142
+ gene_data = get_genetic_data(matrix_file)
143
+
144
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
145
+ print(gene_data.index[:20])
146
+
147
+ # Step 4: Gene Identifier Review
148
+ requires_gene_mapping = True
149
+ print(f"requires_gene_mapping = {requires_gene_mapping}")
150
+
151
+ # Step 5: Gene Annotation
152
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
153
+ gene_annotation = get_gene_annotation(soft_file)
154
+
155
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
156
+ print("Gene annotation preview:")
157
+ print(preview_df(gene_annotation))
158
+
159
+ # Step 6: Gene Identifier Mapping
160
+ # 1-2. Decide columns and build mapping dataframe
161
+ probe_col = 'ID' # matches probe identifiers in gene_data index
162
+ gene_symbol_col = 'Gene Symbol' # contains gene symbols
163
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=probe_col, gene_col=gene_symbol_col)
164
+
165
+ # 3. Apply mapping to convert probe-level data to gene-level expression
166
+ gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
167
+
168
+ # Step 7: Data Normalization and Linking
169
+ import os
170
+
171
+ # 1. Normalize gene symbols and save gene-level data
172
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
173
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
174
+ normalized_gene_data.to_csv(out_gene_data_file)
175
+
176
+ # 2-6. Proceed only if clinical features were extracted earlier; otherwise skip linking and final validation
177
+ if 'selected_clinical_data' in globals() and selected_clinical_data is not None:
178
+ # 2. Link clinical and genetic data
179
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_data, normalized_gene_data)
180
+
181
+ # 3. Handle missing values
182
+ linked_data = handle_missing_values(linked_data, trait)
183
+
184
+ # 4. Bias checks
185
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
186
+
187
+ # 5. Final validation and cohort info
188
+ is_usable = validate_and_save_cohort_info(
189
+ True, cohort, json_path, True, True, is_trait_biased, unbiased_linked_data
190
+ )
191
+
192
+ # 6. Save linked data if usable
193
+ if is_usable:
194
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
195
+ unbiased_linked_data.to_csv(out_data_file)
196
+ else:
197
+ # Trait not available; record initial metadata (if not already done) and skip linking
198
+ _ = validate_and_save_cohort_info(
199
+ is_final=False,
200
+ cohort=cohort,
201
+ info_path=json_path,
202
+ is_gene_available=True,
203
+ is_trait_available=False
204
+ )
output/preprocess/Type_1_Diabetes/code/GSE156035.py ADDED
@@ -0,0 +1,197 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Type_1_Diabetes"
6
+ cohort = "GSE156035"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Type_1_Diabetes"
10
+ in_cohort_dir = "../DATA/GEO/Type_1_Diabetes/GSE156035"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z6/preprocess/Type_1_Diabetes/GSE156035.csv"
14
+ out_gene_data_file = "./output/z6/preprocess/Type_1_Diabetes/gene_data/GSE156035.csv"
15
+ out_clinical_data_file = "./output/z6/preprocess/Type_1_Diabetes/clinical_data/GSE156035.csv"
16
+ json_path = "./output/z6/preprocess/Type_1_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 os
40
+
41
+ # Step 1: Determine data availability
42
+ is_gene_available = True # Global gene expression profiling in PBMC (not miRNA/methylation)
43
+
44
+ # Step 2: Identify rows for variables based on Sample Characteristics Dictionary
45
+ trait_row = 2 # 'diagnosis: Healthy control' vs 'diagnosis: Type 1 diabetes'
46
+ age_row = None # Not available in provided characteristics
47
+ gender_row = 0 # 'gender: Female/Male'
48
+
49
+ # Step 2.2: Define conversion functions
50
+ def _after_colon(value):
51
+ if value is None:
52
+ return None
53
+ parts = str(value).split(":", 1)
54
+ v = parts[-1].strip() if len(parts) > 1 else str(value).strip()
55
+ return v
56
+
57
+ def convert_trait(x):
58
+ v = _after_colon(x)
59
+ if v is None or v == '':
60
+ return None
61
+ vl = v.lower()
62
+ # Map T1D cases to 1, controls to 0
63
+ if any(k in vl for k in ["type 1 diabetes", "t1d", "type1", "type i diabetes", "recent-onset type 1"]):
64
+ return 1
65
+ if any(k in vl for k in ["healthy control", "control", "healthy", "non-diabetic", "islet autoantibody-negative healthy controls"]):
66
+ return 0
67
+ # Fallback heuristics
68
+ if any(k in vl for k in ["case", "patient", "diabetes"]):
69
+ return 1
70
+ if "control" in vl:
71
+ return 0
72
+ return None
73
+
74
+ def convert_age(x):
75
+ v = _after_colon(x)
76
+ if v is None or v == '':
77
+ return None
78
+ vl = v.lower().replace("years", "").replace("year", "").replace("yrs", "").replace("yr", "").strip()
79
+ # Remove common non-numeric characters
80
+ vl = ''.join(ch for ch in vl if (ch.isdigit() or ch == '.' or ch == '-'))
81
+ try:
82
+ return float(vl)
83
+ except:
84
+ return None
85
+
86
+ def convert_gender(x):
87
+ v = _after_colon(x)
88
+ if v is None or v == '':
89
+ return None
90
+ vl = v.strip().lower()
91
+ if vl in ["female", "f", "woman", "women"]:
92
+ return 0
93
+ if vl in ["male", "m", "man", "men"]:
94
+ return 1
95
+ return None
96
+
97
+ # Step 3: Initial filtering and save metadata
98
+ is_trait_available = trait_row is not None
99
+ _ = validate_and_save_cohort_info(
100
+ is_final=False,
101
+ cohort=cohort,
102
+ info_path=json_path,
103
+ is_gene_available=is_gene_available,
104
+ is_trait_available=is_trait_available
105
+ )
106
+
107
+ # Step 4: Clinical feature extraction (only if trait is available)
108
+ if trait_row is not None:
109
+ selected_clinical_df = geo_select_clinical_features(
110
+ clinical_df=clinical_data,
111
+ trait=trait,
112
+ trait_row=trait_row,
113
+ convert_trait=convert_trait,
114
+ age_row=age_row,
115
+ convert_age=convert_age if age_row is not None else None,
116
+ gender_row=gender_row,
117
+ convert_gender=convert_gender
118
+ )
119
+ preview = preview_df(selected_clinical_df, n=5)
120
+ print(preview)
121
+ # Save clinical data
122
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
123
+ selected_clinical_df.to_csv(out_clinical_data_file)
124
+
125
+ # Step 3: Gene Data Extraction
126
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
127
+ gene_data = get_genetic_data(matrix_file)
128
+
129
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
130
+ print(gene_data.index[:20])
131
+
132
+ # Step 4: Gene Identifier Review
133
+ print("requires_gene_mapping = True")
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
+ # Identify the appropriate columns in the annotation:
145
+ # - Probe/row identifiers in expression data match the 'ID' column in annotation
146
+ # - Gene symbols are in the 'GENE_SYMBOL' column
147
+ probe_col = 'ID'
148
+ gene_col = 'GENE_SYMBOL'
149
+
150
+ # Build mapping dataframe
151
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=probe_col, gene_col=gene_col)
152
+
153
+ # Apply mapping to convert probe-level data to gene-level data
154
+ gene_data = apply_gene_mapping(gene_data, mapping_df)
155
+
156
+ # Step 7: Data Normalization and Linking
157
+ import os
158
+
159
+ # 1. Normalize gene symbols and save normalized gene data
160
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
161
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
162
+ normalized_gene_data.to_csv(out_gene_data_file)
163
+
164
+ # 2. Link the clinical and genetic data
165
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
166
+
167
+ # 3. Handle missing values in the linked data
168
+ linked_data = handle_missing_values(linked_data, trait)
169
+
170
+ # 4. Determine bias and remove biased demographic features
171
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
172
+
173
+ # Ensure pure Python bools for JSON serialization
174
+ is_gene_available = bool((normalized_gene_data.shape[0] > 0) and (normalized_gene_data.shape[1] > 0))
175
+ is_trait_available = bool((trait in linked_data.columns) and bool(linked_data[trait].notna().any()))
176
+ is_trait_biased = bool(is_trait_biased)
177
+
178
+ note = ("INFO: PBMC expression microarray; probes mapped via GENE_SYMBOL; "
179
+ "no Age feature in clinical annotations; Gender inferred; "
180
+ "standard GEO pipeline with missingness filtering and imputation.")
181
+
182
+ # 5. Final validation and save cohort info
183
+ is_usable = validate_and_save_cohort_info(
184
+ is_final=True,
185
+ cohort=cohort,
186
+ info_path=json_path,
187
+ is_gene_available=is_gene_available,
188
+ is_trait_available=is_trait_available,
189
+ is_biased=is_trait_biased,
190
+ df=unbiased_linked_data,
191
+ note=note
192
+ )
193
+
194
+ # 6. Save linked data if usable
195
+ if is_usable:
196
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
197
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Type_1_Diabetes/code/GSE162622.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Type_1_Diabetes"
6
+ cohort = "GSE162622"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Type_1_Diabetes"
10
+ in_cohort_dir = "../DATA/GEO/Type_1_Diabetes/GSE162622"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z6/preprocess/Type_1_Diabetes/GSE162622.csv"
14
+ out_gene_data_file = "./output/z6/preprocess/Type_1_Diabetes/gene_data/GSE162622.csv"
15
+ out_clinical_data_file = "./output/z6/preprocess/Type_1_Diabetes/clinical_data/GSE162622.csv"
16
+ json_path = "./output/z6/preprocess/Type_1_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
+ # 1) Gene expression availability
40
+ is_gene_available = True # Gene expression profiling was performed on UPN119 cells
41
+
42
+ # 2) Variable availability in sample characteristics
43
+ # Sample Characteristics Dictionary shows only a constant 'cell line' field, no human trait/age/gender.
44
+ trait_row = None
45
+ age_row = None
46
+ gender_row = None
47
+
48
+ # 2.2) Conversion functions
49
+ def _after_colon(x):
50
+ if x is None:
51
+ return None
52
+ if isinstance(x, str):
53
+ parts = x.split(":", 1)
54
+ x = parts[1] if len(parts) > 1 else parts[0]
55
+ return str(x).strip() if x is not None else None
56
+
57
+ def convert_trait(x):
58
+ # No trait information is available for T1D status in this dataset; return None.
59
+ _ = _after_colon(x)
60
+ return None
61
+
62
+ def convert_age(x):
63
+ v = _after_colon(x)
64
+ if v is None or v == "" or v.lower() in {"na", "n/a", "unknown"}:
65
+ return None
66
+ # Attempt to extract a number (e.g., "35", "35 years")
67
+ try:
68
+ return float(''.join(ch for ch in v if (ch.isdigit() or ch == '.' )))
69
+ except Exception:
70
+ return None
71
+
72
+ def convert_gender(x):
73
+ v = _after_colon(x)
74
+ if not v:
75
+ return None
76
+ vlow = v.lower()
77
+ if vlow in {"female", "f", "woman", "girl"}:
78
+ return 0
79
+ if vlow in {"male", "m", "man", "boy"}:
80
+ return 1
81
+ return None
82
+
83
+ # 3) Save initial metadata
84
+ is_trait_available = trait_row is not None
85
+ _ = validate_and_save_cohort_info(
86
+ is_final=False,
87
+ cohort=cohort,
88
+ info_path=json_path,
89
+ is_gene_available=is_gene_available,
90
+ is_trait_available=is_trait_available
91
+ )
92
+
93
+ # 4) Clinical feature extraction (skip because trait_row is None)
94
+ # If in future a trait_row is identified, uncomment the following block:
95
+ # if trait_row is not None:
96
+ # selected_clinical_df = geo_select_clinical_features(
97
+ # clinical_df=clinical_data,
98
+ # trait=trait,
99
+ # trait_row=trait_row,
100
+ # convert_trait=convert_trait,
101
+ # age_row=age_row,
102
+ # convert_age=convert_age,
103
+ # gender_row=gender_row,
104
+ # convert_gender=convert_gender
105
+ # )
106
+ # preview = preview_df(selected_clinical_df)
107
+ # os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
108
+ # selected_clinical_df.to_csv(out_clinical_data_file)
output/preprocess/Type_1_Diabetes/code/GSE182870.py ADDED
@@ -0,0 +1,211 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Type_1_Diabetes"
6
+ cohort = "GSE182870"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Type_1_Diabetes"
10
+ in_cohort_dir = "../DATA/GEO/Type_1_Diabetes/GSE182870"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z6/preprocess/Type_1_Diabetes/GSE182870.csv"
14
+ out_gene_data_file = "./output/z6/preprocess/Type_1_Diabetes/gene_data/GSE182870.csv"
15
+ out_clinical_data_file = "./output/z6/preprocess/Type_1_Diabetes/clinical_data/GSE182870.csv"
16
+ json_path = "./output/z6/preprocess/Type_1_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 os
40
+ import re
41
+ import math
42
+
43
+ # 1) Gene expression data availability (scRNA-seq study)
44
+ is_gene_available = True
45
+
46
+ # 2) Variable availability based on Sample Characteristics Dictionary
47
+ trait_row = 1 # 'study group: new onset T1D', 'study group: T1D', 'study group: HC'
48
+ age_row = 3 # 'age: <number>'
49
+ gender_row = 4 # 'Sex: male/female'
50
+
51
+ # 2.2) Conversion functions
52
+ def _after_colon(x):
53
+ if x is None:
54
+ return None
55
+ try:
56
+ parts = str(x).split(":", 1)
57
+ return parts[1].strip() if len(parts) > 1 else str(x).strip()
58
+ except Exception:
59
+ return None
60
+
61
+ def convert_trait(x):
62
+ v = _after_colon(x)
63
+ if v is None:
64
+ return None
65
+ v_low = v.lower()
66
+ # Map controls
67
+ if any(k in v_low for k in ["hc", "healthy", "control", "ctrl"]):
68
+ return 0
69
+ # Map T1D (including new-onset or established)
70
+ if any(k in v_low for k in ["t1d", "type 1", "type i", "new onset", "new-onset", "established"]):
71
+ return 1
72
+ return None
73
+
74
+ def convert_age(x):
75
+ v = _after_colon(x)
76
+ if v is None:
77
+ return None
78
+ m = re.search(r"[-+]?\d*\.?\d+", v)
79
+ if not m:
80
+ return None
81
+ try:
82
+ val = float(m.group())
83
+ if abs(val - round(val)) < 1e-6:
84
+ return int(round(val))
85
+ return val
86
+ except Exception:
87
+ return None
88
+
89
+ def convert_gender(x):
90
+ v = _after_colon(x)
91
+ if v is None:
92
+ return None
93
+ v_low = v.lower()
94
+ if v_low in ["female", "f"]:
95
+ return 0
96
+ if v_low in ["male", "m"]:
97
+ return 1
98
+ return None
99
+
100
+ # 3) Save metadata (initial filtering)
101
+ is_trait_available = trait_row is not None
102
+ _ = validate_and_save_cohort_info(
103
+ is_final=False,
104
+ cohort=cohort,
105
+ info_path=json_path,
106
+ is_gene_available=is_gene_available,
107
+ is_trait_available=is_trait_available
108
+ )
109
+
110
+ # 4) Clinical feature extraction (only if trait data available)
111
+ if trait_row is not None:
112
+ selected_clinical_df = geo_select_clinical_features(
113
+ clinical_df=clinical_data,
114
+ trait=trait,
115
+ trait_row=trait_row,
116
+ convert_trait=convert_trait,
117
+ age_row=age_row,
118
+ convert_age=convert_age,
119
+ gender_row=gender_row,
120
+ convert_gender=convert_gender
121
+ )
122
+ preview = preview_df(selected_clinical_df)
123
+ print("Preview of selected clinical features:", preview)
124
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
125
+ selected_clinical_df.to_csv(out_clinical_data_file, index=True)
126
+
127
+ # Step 3: Gene Data Extraction
128
+ # Step 3: Gene Data Extraction with diagnostics and scRNA-seq fallback
129
+
130
+ # 1) Try extracting gene expression from the GEO series matrix file
131
+ gene_data = get_genetic_data(matrix_file)
132
+
133
+ # Diagnostics
134
+ print("Primary extraction (series matrix) gene_data shape:", gene_data.shape)
135
+
136
+ # If empty, attempt fallback for scRNA-seq supplementary (10x) files
137
+ if gene_data.shape[0] == 0:
138
+ print("Warning: No expression rows found in the series matrix. Searching for 10x files (matrix.mtx, features/genes.tsv, barcodes.tsv)...")
139
+ import os
140
+
141
+ # Find candidate 10x triplets within the cohort directory
142
+ tenx_dirs = {}
143
+ for root, dirs, files in os.walk(in_cohort_dir):
144
+ files_lower = {f.lower(): f for f in files}
145
+ has_mtx = 'matrix.mtx' in files_lower or 'matrix.mtx.gz' in files_lower
146
+ has_features = any(k in files_lower for k in ['features.tsv', 'features.tsv.gz', 'genes.tsv', 'genes.tsv.gz'])
147
+ has_barcodes = 'barcodes.tsv' in files_lower or 'barcodes.tsv.gz' in files_lower
148
+ if has_mtx and has_features and has_barcodes:
149
+ def pick_one(names):
150
+ for n in names:
151
+ if n in files_lower:
152
+ return os.path.join(root, files_lower[n])
153
+ return None
154
+
155
+ mtx_path = pick_one(['matrix.mtx', 'matrix.mtx.gz'])
156
+ features_path = pick_one(['features.tsv', 'features.tsv.gz', 'genes.tsv', 'genes.tsv.gz'])
157
+ barcodes_path = pick_one(['barcodes.tsv', 'barcodes.tsv.gz'])
158
+ tenx_dirs[root] = (mtx_path, features_path, barcodes_path)
159
+
160
+ if len(tenx_dirs) == 0:
161
+ print("No 10x triplet found. Gene expression may only be available as external supplementary files not downloaded.")
162
+ else:
163
+ # Use the first discovered 10x directory
164
+ mtx_path, features_path, barcodes_path = list(tenx_dirs.values())[0]
165
+ print("Found 10x files:")
166
+ print(" matrix:", mtx_path)
167
+ print(" features/genes:", features_path)
168
+ print(" barcodes:", barcodes_path)
169
+
170
+ try:
171
+ import pandas as pd
172
+ from scipy.io import mmread
173
+
174
+ # Read features and barcodes
175
+ features_df = pd.read_csv(features_path, sep='\t', header=None, compression='infer')
176
+ barcodes_df = pd.read_csv(barcodes_path, sep='\t', header=None, compression='infer')
177
+
178
+ # Determine gene names column (10x v3 features.tsv has: feature_id, gene_name, feature_type)
179
+ if features_df.shape[1] >= 2:
180
+ gene_names = features_df.iloc[:, 1].astype(str).tolist()
181
+ else:
182
+ gene_names = features_df.iloc[:, 0].astype(str).tolist()
183
+
184
+ barcodes = barcodes_df.iloc[:, 0].astype(str).tolist()
185
+
186
+ # Read sparse matrix
187
+ M = mmread(mtx_path)
188
+
189
+ # Ensure orientation matches (rows: genes/features; cols: barcodes/cells)
190
+ if (M.shape[0] == len(gene_names) and M.shape[1] == len(barcodes)):
191
+ pass
192
+ elif (M.shape[1] == len(gene_names) and M.shape[0] == len(barcodes)):
193
+ M = M.T
194
+ else:
195
+ print(f"Shape mismatch after reading mtx: {M.shape}, genes: {len(gene_names)}, barcodes: {len(barcodes)}")
196
+ M = None
197
+
198
+ if M is not None:
199
+ # Build a sparse DataFrame to avoid densification
200
+ gene_data = pd.DataFrame.sparse.from_spmatrix(M, index=gene_names, columns=barcodes)
201
+ print("10x extraction gene_data shape:", gene_data.shape)
202
+ except ImportError as e:
203
+ print("SciPy is required to read matrix.mtx but is not available. Skipping 10x fallback.")
204
+ except Exception as e:
205
+ print("An error occurred while reading 10x files:", e)
206
+
207
+ # 2) Print the first 20 row IDs (gene or probe identifiers)
208
+ try:
209
+ print("First 20 row IDs:", list(gene_data.index[:20]))
210
+ except Exception as e:
211
+ print("Unable to print row IDs. gene_data may be undefined or malformed:", e)
output/preprocess/Type_1_Diabetes/code/GSE193273.py ADDED
@@ -0,0 +1,193 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Type_1_Diabetes"
6
+ cohort = "GSE193273"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Type_1_Diabetes"
10
+ in_cohort_dir = "../DATA/GEO/Type_1_Diabetes/GSE193273"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z6/preprocess/Type_1_Diabetes/GSE193273.csv"
14
+ out_gene_data_file = "./output/z6/preprocess/Type_1_Diabetes/gene_data/GSE193273.csv"
15
+ out_clinical_data_file = "./output/z6/preprocess/Type_1_Diabetes/clinical_data/GSE193273.csv"
16
+ json_path = "./output/z6/preprocess/Type_1_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
+ # Determine data availability
40
+ is_gene_available = True # Whole genome expression on PBMC (not miRNA-only or methylation)
41
+ trait_row = 1 # 'diagnosis' field
42
+ age_row = None
43
+ gender_row = None
44
+
45
+ # Conversion functions
46
+ def _after_colon(x):
47
+ if x is None:
48
+ return None
49
+ s = str(x)
50
+ parts = s.split(":", 1)
51
+ return parts[1].strip() if len(parts) > 1 else s.strip()
52
+
53
+ def convert_trait(x):
54
+ val = _after_colon(x)
55
+ if val is None:
56
+ return None
57
+ v = val.lower()
58
+ # Map controls to 0
59
+ if "control" in v:
60
+ return 0
61
+ # Map T1D cases to 1
62
+ if ("t1d" in v) or ("type 1" in v) or ("type i" in v) or ("type-1" in v) or ("diabetes" in v):
63
+ return 1
64
+ return None
65
+
66
+ def convert_age(x):
67
+ val = _after_colon(x)
68
+ if val is None:
69
+ return None
70
+ # Extract the first numeric token as age (years)
71
+ import re
72
+ m = re.search(r"[-+]?\d*\.?\d+", val)
73
+ if m:
74
+ try:
75
+ return float(m.group())
76
+ except Exception:
77
+ return None
78
+ return None
79
+
80
+ def convert_gender(x):
81
+ val = _after_colon(x)
82
+ if val is None:
83
+ return None
84
+ v = val.lower()
85
+ if v in {"female", "f", "woman", "women"}:
86
+ return 0
87
+ if v in {"male", "m", "man", "men"}:
88
+ return 1
89
+ return None
90
+
91
+ # Initial metadata recording
92
+ is_trait_available = trait_row is not None
93
+ _ = validate_and_save_cohort_info(
94
+ is_final=False,
95
+ cohort=cohort,
96
+ info_path=json_path,
97
+ is_gene_available=is_gene_available,
98
+ is_trait_available=is_trait_available
99
+ )
100
+
101
+ # Clinical feature extraction and saving
102
+ if trait_row is not None:
103
+ selected_clinical_df = geo_select_clinical_features(
104
+ clinical_df=clinical_data,
105
+ trait=trait,
106
+ trait_row=trait_row,
107
+ convert_trait=convert_trait,
108
+ age_row=age_row,
109
+ convert_age=convert_age,
110
+ gender_row=gender_row,
111
+ convert_gender=convert_gender
112
+ )
113
+ preview = preview_df(selected_clinical_df)
114
+ print(preview)
115
+
116
+ import os
117
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
118
+ selected_clinical_df.to_csv(out_clinical_data_file)
119
+
120
+ # Step 3: Gene Data Extraction
121
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
122
+ gene_data = get_genetic_data(matrix_file)
123
+
124
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
125
+ print(gene_data.index[:20])
126
+
127
+ # Step 4: Gene Identifier Review
128
+ # The observed identifiers are numeric strings like '4', '5', ... '23', which are not human gene symbols.
129
+ requires_gene_mapping = True
130
+ print(f"requires_gene_mapping = {requires_gene_mapping}")
131
+
132
+ # Step 5: Gene Annotation
133
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
134
+ gene_annotation = get_gene_annotation(soft_file)
135
+
136
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
137
+ print("Gene annotation preview:")
138
+ print(preview_df(gene_annotation))
139
+
140
+ # Step 6: Gene Identifier Mapping
141
+ # Identify the appropriate columns in the annotation
142
+ probe_id_col = 'ID' # Matches the numeric feature IDs seen in the matrix (e.g., '4', '5', ...)
143
+ gene_symbol_col = 'GENE_SYMBOL'
144
+
145
+ # Ensure probe-level expression data is available
146
+ try:
147
+ gene_data
148
+ except NameError:
149
+ gene_data = get_genetic_data(matrix_file)
150
+
151
+ # Build mapping and apply it to convert probe-level data to gene-level data
152
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=probe_id_col, gene_col=gene_symbol_col)
153
+ gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
154
+
155
+ # Step 7: Data Normalization and Linking
156
+ import os
157
+
158
+ # 1. Normalize gene symbols and save
159
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
160
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
161
+ normalized_gene_data.to_csv(out_gene_data_file)
162
+
163
+ # 2. Link clinical and genetic data
164
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
165
+
166
+ # 3. Handle missing values
167
+ linked_data = handle_missing_values(linked_data, trait)
168
+
169
+ # 4. Bias check and remove biased demographic features
170
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
171
+ is_trait_biased = bool(is_trait_biased)
172
+
173
+ # Dynamically infer availability flags for final validation (cast to built-in bool)
174
+ is_gene_available = bool((normalized_gene_data.shape[0] > 0) and (normalized_gene_data.shape[1] > 0))
175
+ is_trait_available = bool((trait in selected_clinical_df.index) and selected_clinical_df.loc[trait].notna().any())
176
+
177
+ # 5. Final validation and save cohort info
178
+ note = "INFO: Only diagnosis (trait) available; Age/Gender not provided in series characteristics."
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,
184
+ is_trait_available=is_trait_available,
185
+ is_biased=is_trait_biased,
186
+ df=unbiased_linked_data,
187
+ note=note
188
+ )
189
+
190
+ # 6. Save linked data if usable
191
+ if is_usable:
192
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
193
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Type_1_Diabetes/code/GSE232310.py ADDED
@@ -0,0 +1,155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Type_1_Diabetes"
6
+ cohort = "GSE232310"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Type_1_Diabetes"
10
+ in_cohort_dir = "../DATA/GEO/Type_1_Diabetes/GSE232310"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z6/preprocess/Type_1_Diabetes/GSE232310.csv"
14
+ out_gene_data_file = "./output/z6/preprocess/Type_1_Diabetes/gene_data/GSE232310.csv"
15
+ out_clinical_data_file = "./output/z6/preprocess/Type_1_Diabetes/clinical_data/GSE232310.csv"
16
+ json_path = "./output/z6/preprocess/Type_1_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 os
40
+
41
+ # 1) Gene expression data availability
42
+ is_gene_available = True # RNA extracted from monocytes -> gene expression data likely available
43
+
44
+ # 2) Variable availability and conversion functions
45
+ trait_row = 1
46
+ age_row = None
47
+ gender_row = None
48
+
49
+ def convert_trait(x):
50
+ if x is None:
51
+ return None
52
+ # Extract value after colon
53
+ try:
54
+ val = str(x).split(":", 1)[1].strip().lower()
55
+ except Exception:
56
+ val = str(x).strip().lower()
57
+ # Map to binary: ROT1D = 1 (case), others (HRS, LRS, uHC) = 0 (controls)
58
+ if "rot1d" in val or "recent on" in val: # capture 'recent onset' variants
59
+ return 1
60
+ if any(k in val for k in ["uhc", "hrs", "lrs", "healthy", "sibling", "control"]):
61
+ return 0
62
+ return None
63
+
64
+ convert_age = None
65
+ convert_gender = None
66
+
67
+ # 3) Save metadata (initial filtering)
68
+ is_trait_available = trait_row is not None
69
+ _ = validate_and_save_cohort_info(
70
+ is_final=False,
71
+ cohort=cohort,
72
+ info_path=json_path,
73
+ is_gene_available=is_gene_available,
74
+ is_trait_available=is_trait_available
75
+ )
76
+
77
+ # 4) Clinical feature extraction (only if clinical data is available)
78
+ if trait_row is not None:
79
+ selected_clinical_df = geo_select_clinical_features(
80
+ clinical_df=clinical_data,
81
+ trait=trait,
82
+ trait_row=trait_row,
83
+ convert_trait=convert_trait,
84
+ age_row=age_row,
85
+ convert_age=convert_age,
86
+ gender_row=gender_row,
87
+ convert_gender=convert_gender
88
+ )
89
+ print(preview_df(selected_clinical_df))
90
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
91
+ selected_clinical_df.to_csv(out_clinical_data_file)
92
+
93
+ # Step 3: Gene Data Extraction
94
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
95
+ gene_data = get_genetic_data(matrix_file)
96
+
97
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
98
+ print(gene_data.index[:20])
99
+
100
+ # Step 4: Gene Identifier Review
101
+ requires_gene_mapping = True
102
+ print(f"requires_gene_mapping = {requires_gene_mapping}")
103
+
104
+ # Step 5: Gene Annotation
105
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
106
+ gene_annotation = get_gene_annotation(soft_file)
107
+
108
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
109
+ print("Gene annotation preview:")
110
+ print(preview_df(gene_annotation))
111
+
112
+ # Step 6: Gene Identifier Mapping
113
+ # Determine appropriate columns for probe IDs and gene symbols based on preview:
114
+ # Probe identifier column: 'ID' (e.g., '1007_s_at')
115
+ # Gene symbol column: 'Gene Symbol' (e.g., 'DDR1 /// MIR4640')
116
+
117
+ # 1-2) Build mapping dataframe from annotation
118
+ mapping_df = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='Gene Symbol')
119
+
120
+ # 3) Apply mapping to convert probe-level data to gene-level expression
121
+ gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
122
+
123
+ # Step 7: Data Normalization and Linking
124
+ import os
125
+
126
+ # 1. Normalize gene symbols and save
127
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
128
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
129
+ normalized_gene_data.to_csv(out_gene_data_file)
130
+
131
+ # 2. Link clinical and genetic data
132
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
133
+
134
+ # 3. Handle missing values
135
+ linked_data = handle_missing_values(linked_data, trait)
136
+
137
+ # 4. Assess bias and remove biased demographic features
138
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
139
+
140
+ # 5. Final validation and save cohort info
141
+ is_usable = validate_and_save_cohort_info(
142
+ is_final=True,
143
+ cohort=cohort,
144
+ info_path=json_path,
145
+ is_gene_available=True,
146
+ is_trait_available=True,
147
+ is_biased=is_trait_biased,
148
+ df=unbiased_linked_data,
149
+ note=''
150
+ )
151
+
152
+ # 6. Save linked data if usable
153
+ if is_usable:
154
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
155
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Type_1_Diabetes/code/GSE71799.py ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Type_1_Diabetes"
6
+ cohort = "GSE71799"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Type_1_Diabetes"
10
+ in_cohort_dir = "../DATA/GEO/Type_1_Diabetes/GSE71799"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z6/preprocess/Type_1_Diabetes/GSE71799.csv"
14
+ out_gene_data_file = "./output/z6/preprocess/Type_1_Diabetes/gene_data/GSE71799.csv"
15
+ out_clinical_data_file = "./output/z6/preprocess/Type_1_Diabetes/clinical_data/GSE71799.csv"
16
+ json_path = "./output/z6/preprocess/Type_1_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
+ # Step 1: Assess data availability based on provided background and sample characteristics
40
+ is_gene_available = True # Gene expression profiling was performed (not miRNA/methylation)
41
+ trait_row = None # No Type 1 Diabetes status recorded; cohort compares CF vs healthy controls
42
+ age_row = None # No age information available
43
+ gender_row = None # No gender information available
44
+
45
+ # Step 2: Define conversion functions
46
+ def _after_colon(x):
47
+ if x is None:
48
+ return None
49
+ s = str(x)
50
+ parts = s.split(":", 1)
51
+ val = parts[1] if len(parts) == 2 else parts[0]
52
+ return val.strip().strip('"').strip("'")
53
+
54
+ def convert_trait(x):
55
+ # Binary: 1 = Type 1 Diabetes, 0 = non-T1D
56
+ v = _after_colon(x)
57
+ if v is None or v == "":
58
+ return None
59
+ v_lower = v.lower()
60
+ t1d_pos = [
61
+ "type 1 diabetes", "t1d", "t1dm", "recent-onset t1d", "recent onset t1d",
62
+ "recent-onset type 1 diabetes", "recent onset type 1 diabetes", "ro t1d",
63
+ "type i diabetes", "diabetic", "type 1 dm"
64
+ ]
65
+ t1d_neg = [
66
+ "control", "healthy", "hc", "uhc", "unrelated healthy control", "non-diabetic",
67
+ "no diabetes", "cystic fibrosis", "cf"
68
+ ]
69
+ if any(k in v_lower for k in t1d_pos):
70
+ return 1
71
+ if any(k in v_lower for k in t1d_neg):
72
+ return 0
73
+ return None
74
+
75
+ def convert_age(x):
76
+ # Continuous: years
77
+ v = _after_colon(x)
78
+ if v is None or v == "":
79
+ return None
80
+ s = v.lower()
81
+ # Extract first float-like number
82
+ import re
83
+ m = re.search(r"[-+]?\d*\.?\d+", s)
84
+ if not m:
85
+ return None
86
+ num = float(m.group())
87
+ if "month" in s:
88
+ return num / 12.0
89
+ if "week" in s:
90
+ return num / 52.0
91
+ if "day" in s:
92
+ return num / 365.0
93
+ # default assume years
94
+ return num
95
+
96
+ def convert_gender(x):
97
+ # Binary: female -> 0, male -> 1
98
+ v = _after_colon(x)
99
+ if v is None or v == "":
100
+ return None
101
+ s = v.strip().lower()
102
+ if s in {"female", "f", "woman", "girl"}:
103
+ return 0
104
+ if s in {"male", "m", "man", "boy"}:
105
+ return 1
106
+ return None
107
+
108
+ # Step 3: Initial filtering and save metadata
109
+ is_trait_available = trait_row is not None
110
+ _ = validate_and_save_cohort_info(
111
+ is_final=False,
112
+ cohort=cohort,
113
+ info_path=json_path,
114
+ is_gene_available=is_gene_available,
115
+ is_trait_available=is_trait_available
116
+ )
117
+
118
+ # Step 4: Clinical feature extraction (skipped because trait_row is None)
119
+ # If in another scenario trait_row is not None, the following block would run:
120
+ if trait_row is not None:
121
+ selected_clinical = geo_select_clinical_features(
122
+ clinical_df=clinical_data,
123
+ trait=trait,
124
+ trait_row=trait_row,
125
+ convert_trait=convert_trait,
126
+ age_row=age_row,
127
+ convert_age=convert_age,
128
+ gender_row=gender_row,
129
+ convert_gender=convert_gender
130
+ )
131
+ preview = preview_df(selected_clinical, n=5)
132
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
133
+ selected_clinical.to_csv(out_clinical_data_file, index=True)
output/preprocess/Type_1_Diabetes/code/GSE75062.py ADDED
@@ -0,0 +1,158 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Type_1_Diabetes"
6
+ cohort = "GSE75062"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Type_1_Diabetes"
10
+ in_cohort_dir = "../DATA/GEO/Type_1_Diabetes/GSE75062"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z6/preprocess/Type_1_Diabetes/GSE75062.csv"
14
+ out_gene_data_file = "./output/z6/preprocess/Type_1_Diabetes/gene_data/GSE75062.csv"
15
+ out_clinical_data_file = "./output/z6/preprocess/Type_1_Diabetes/clinical_data/GSE75062.csv"
16
+ json_path = "./output/z6/preprocess/Type_1_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
+
41
+ # 1) Gene expression data availability (based on series description: microarray gene expression of human islets)
42
+ is_gene_available = True
43
+
44
+ # 2) Variable availability (from Sample Characteristics Dictionary)
45
+ # Keys present:
46
+ # 0 -> 'diabetes reversal status: Yes/No' (mouse outcome, not human T1D status)
47
+ # 1 -> 'tissue: pancreas' (constant)
48
+ # 2 -> 'cell type: islet cells' (constant)
49
+ trait_row = None # No human Type 1 Diabetes status available
50
+ age_row = None # No age information available
51
+ gender_row = None # No gender information available
52
+
53
+ # 2.2) Converters
54
+ def _after_colon(x: str) -> str:
55
+ if x is None:
56
+ return ""
57
+ parts = str(x).split(':', 1)
58
+ return parts[1].strip() if len(parts) > 1 else str(x).strip()
59
+
60
+ def convert_trait(x):
61
+ # Binary: 1 = Type 1 Diabetes, 0 = Not Type 1 Diabetes
62
+ v = _after_colon(x).lower()
63
+ if not v:
64
+ return None
65
+ # Positive indicators for T1D
66
+ if any(k in v for k in ["type 1 diabetes", "type i diabetes", "t1d", "t1dm"]):
67
+ return 1
68
+ # Negative indicators (explicitly not T1D)
69
+ if any(k in v for k in ["non-diabetic", "nondiabetic", "control", "healthy", "normoglycemic", "no diabetes", "type 2 diabetes", "t2d", "t2dm"]):
70
+ return 0
71
+ # If the field is about "diabetes reversal status", it's not human T1D; avoid misclassification
72
+ if "reversal" in x.lower():
73
+ return None
74
+ return None
75
+
76
+ def convert_age(x):
77
+ v = _after_colon(x)
78
+ if not v:
79
+ return None
80
+ # Extract first numeric value (years)
81
+ m = re.search(r"[-+]?\d*\.?\d+", v)
82
+ if not m:
83
+ return None
84
+ try:
85
+ age = float(m.group())
86
+ if 0 < age < 120:
87
+ return age
88
+ except Exception:
89
+ pass
90
+ return None
91
+
92
+ def convert_gender(x):
93
+ v = _after_colon(x).lower()
94
+ if not v:
95
+ return None
96
+ if v in ["female", "f", "woman", "women", "girl"]:
97
+ return 0
98
+ if v in ["male", "m", "man", "men", "boy"]:
99
+ return 1
100
+ return None
101
+
102
+ # 3) Save metadata (initial filtering)
103
+ is_trait_available = trait_row is not None
104
+ _ = validate_and_save_cohort_info(
105
+ is_final=False,
106
+ cohort=cohort,
107
+ info_path=json_path,
108
+ is_gene_available=is_gene_available,
109
+ is_trait_available=is_trait_available
110
+ )
111
+
112
+ # 4) Clinical feature extraction (skip because trait_row is None)
113
+ if trait_row is not None:
114
+ selected = geo_select_clinical_features(
115
+ clinical_df=clinical_data,
116
+ trait=trait,
117
+ trait_row=trait_row,
118
+ convert_trait=convert_trait,
119
+ age_row=age_row,
120
+ convert_age=convert_age,
121
+ gender_row=gender_row,
122
+ convert_gender=convert_gender
123
+ )
124
+ preview = preview_df(selected, n=5)
125
+ selected.to_csv(out_clinical_data_file, index=True)
126
+
127
+ # Step 3: Gene Data Extraction
128
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
129
+ gene_data = get_genetic_data(matrix_file)
130
+
131
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
132
+ print(gene_data.index[:20])
133
+
134
+ # Step 4: Gene Identifier Review
135
+ requires_gene_mapping = True
136
+ print(f"requires_gene_mapping = {requires_gene_mapping}")
137
+
138
+ # Step 5: Gene Annotation
139
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
140
+ gene_annotation = get_gene_annotation(soft_file)
141
+
142
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
143
+ print("Gene annotation preview:")
144
+ print(preview_df(gene_annotation))
145
+
146
+ # Step 6: Gene Identifier Mapping
147
+ # Identify the appropriate columns for probe IDs and gene symbols based on the annotation preview:
148
+ # Probe identifiers: 'ID'
149
+ # Gene symbols: 'Gene Symbol'
150
+
151
+ # Preserve the original probe-level data
152
+ probe_data = gene_data
153
+
154
+ # 2. Get mapping dataframe
155
+ mapping_df = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='Gene Symbol')
156
+
157
+ # 3. Apply mapping to convert probe-level data to gene-level expression
158
+ gene_data = apply_gene_mapping(probe_data, mapping_df)
output/preprocess/Type_1_Diabetes/code/TCGA.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Type_1_Diabetes"
6
+
7
+ # Input paths
8
+ tcga_root_dir = "../DATA/TCGA"
9
+
10
+ # Output paths
11
+ out_data_file = "./output/z6/preprocess/Type_1_Diabetes/TCGA.csv"
12
+ out_gene_data_file = "./output/z6/preprocess/Type_1_Diabetes/gene_data/TCGA.csv"
13
+ out_clinical_data_file = "./output/z6/preprocess/Type_1_Diabetes/clinical_data/TCGA.csv"
14
+ json_path = "./output/z6/preprocess/Type_1_Diabetes/cohort_info.json"
15
+
16
+
17
+ # Step 1: Initial Data Loading
18
+ import os
19
+ import pandas as pd
20
+
21
+ # Given TCGA subdirectories (from the task)
22
+ tcga_subdirs = [
23
+ 'TCGA_lower_grade_glioma_and_glioblastoma_(GBMLGG)', 'TCGA_Uterine_Carcinosarcoma_(UCS)',
24
+ 'TCGA_Thyroid_Cancer_(THCA)', 'TCGA_Thymoma_(THYM)', 'TCGA_Testicular_Cancer_(TGCT)',
25
+ 'TCGA_Stomach_Cancer_(STAD)', 'TCGA_Sarcoma_(SARC)', 'TCGA_Rectal_Cancer_(READ)',
26
+ 'TCGA_Prostate_Cancer_(PRAD)', 'TCGA_Pheochromocytoma_Paraganglioma_(PCPG)',
27
+ 'TCGA_Pancreatic_Cancer_(PAAD)', 'TCGA_Ovarian_Cancer_(OV)', 'TCGA_Ocular_melanomas_(UVM)',
28
+ 'TCGA_Mesothelioma_(MESO)', 'TCGA_Melanoma_(SKCM)', 'TCGA_Lung_Squamous_Cell_Carcinoma_(LUSC)',
29
+ 'TCGA_Lung_Cancer_(LUNG)', 'TCGA_Lung_Adenocarcinoma_(LUAD)', 'TCGA_Lower_Grade_Glioma_(LGG)',
30
+ 'TCGA_Liver_Cancer_(LIHC)', 'TCGA_Large_Bcell_Lymphoma_(DLBC)', 'TCGA_Kidney_Papillary_Cell_Carcinoma_(KIRP)',
31
+ 'TCGA_Kidney_Clear_Cell_Carcinoma_(KIRC)', 'TCGA_Kidney_Chromophobe_(KICH)',
32
+ 'TCGA_Head_and_Neck_Cancer_(HNSC)', 'TCGA_Glioblastoma_(GBM)', 'TCGA_Esophageal_Cancer_(ESCA)',
33
+ 'TCGA_Endometrioid_Cancer_(UCEC)', 'TCGA_Colon_and_Rectal_Cancer_(COADREAD)',
34
+ 'TCGA_Colon_Cancer_(COAD)', 'TCGA_Cervical_Cancer_(CESC)', 'TCGA_Breast_Cancer_(BRCA)',
35
+ 'TCGA_Bladder_Cancer_(BLCA)', 'TCGA_Bile_Duct_Cancer_(CHOL)', 'TCGA_Adrenocortical_Cancer_(ACC)',
36
+ 'TCGA_Acute_Myeloid_Leukemia_(LAML)'
37
+ ]
38
+
39
+ # Try to find a cohort related to Type 1 Diabetes (unlikely in TCGA, which is cancer-focused)
40
+ synonyms = {
41
+ "type_1_diabetes", "type 1 diabetes", "t1d", "insulin-dependent", "insulin dependent", "juvenile diabetes",
42
+ "diabetes"
43
+ }
44
+ selected_dir = None
45
+ for d in tcga_subdirs:
46
+ name = d.lower()
47
+ if any(term in name for term in synonyms):
48
+ selected_dir = d
49
+ break
50
+
51
+ clinical_df = None
52
+ genetic_df = None
53
+ clinical_file_path = None
54
+ genetic_file_path = None
55
+ skip_tcga_processing = False
56
+
57
+ if selected_dir is None:
58
+ print("No suitable TCGA cohort matching the trait 'Type_1_Diabetes' was found. Skipping TCGA for this trait.")
59
+ # Record metadata: no suitable cohort, thus no gene/trait available for this trait in TCGA
60
+ _ = validate_and_save_cohort_info(
61
+ is_final=False,
62
+ cohort="TCGA",
63
+ info_path=json_path,
64
+ is_gene_available=False,
65
+ is_trait_available=False
66
+ )
67
+ skip_tcga_processing = True
68
+ else:
69
+ # Identify key file paths within the selected cohort directory
70
+ cohort_dir = os.path.join(tcga_root_dir, selected_dir)
71
+ clinical_file_path, genetic_file_path = tcga_get_relevant_filepaths(cohort_dir)
72
+
73
+ # Load the clinical and genetic data
74
+ clinical_df = pd.read_csv(clinical_file_path, sep='\t', index_col=0, low_memory=False)
75
+ genetic_df = pd.read_csv(genetic_file_path, sep='\t', index_col=0, low_memory=False)
76
+
77
+ # Print clinical column names
78
+ print(list(clinical_df.columns))
output/preprocess/Type_1_Diabetes/cohort_info.json CHANGED
@@ -1,112 +1 @@
1
- {
2
- "GSE156035": {
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": true,
10
- "sample_size": 40
11
- },
12
- "GSE75062": {
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": 59
21
- },
22
- "GSE71799": {
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
- "GSE232310": {
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": 62
41
- },
42
- "GSE193273": {
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": 2
51
- },
52
- "GSE182870": {
53
- "is_usable": false,
54
- "is_gene_available": false,
55
- "is_trait_available": true,
56
- "is_available": false,
57
- "is_biased": null,
58
- "has_age": null,
59
- "has_gender": null,
60
- "sample_size": null
61
- },
62
- "GSE162622": {
63
- "is_usable": false,
64
- "is_gene_available": true,
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
- "GSE131528": {
73
- "is_usable": false,
74
- "is_gene_available": true,
75
- "is_trait_available": true,
76
- "is_available": true,
77
- "is_biased": true,
78
- "has_age": true,
79
- "has_gender": false,
80
- "sample_size": 55
81
- },
82
- "GSE123088": {
83
- "is_usable": false,
84
- "is_gene_available": false,
85
- "is_trait_available": false,
86
- "is_available": false,
87
- "is_biased": null,
88
- "has_age": null,
89
- "has_gender": null,
90
- "sample_size": null
91
- },
92
- "GSE123086": {
93
- "is_usable": false,
94
- "is_gene_available": false,
95
- "is_trait_available": false,
96
- "is_available": false,
97
- "is_biased": null,
98
- "has_age": null,
99
- "has_gender": null,
100
- "sample_size": null
101
- },
102
- "TCGA": {
103
- "is_usable": false,
104
- "is_gene_available": false,
105
- "is_trait_available": false,
106
- "is_available": false,
107
- "is_biased": null,
108
- "has_age": null,
109
- "has_gender": null,
110
- "sample_size": null
111
- }
112
- }
 
1
+ {"GSE75062": {"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}, "GSE71799": {"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}, "GSE232310": {"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": 62, "note": ""}, "GSE193273": {"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": 40, "note": "INFO: Only diagnosis (trait) available; Age/Gender not provided in series characteristics."}, "GSE162622": {"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}, "GSE156035": {"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": 40, "note": "INFO: PBMC expression microarray; probes mapped via GENE_SYMBOL; no Age feature in clinical annotations; Gender inferred; standard GEO pipeline with missingness filtering and imputation."}, "GSE131528": {"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}, "GSE123088": {"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": 204, "note": "INFO: Gene normalization skipped because gene IDs are Entrez (ENTREZ:####)."}, "GSE123086": {"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": 47, "note": "WARNING: Skipped gene-symbol normalization because gene index consists of Entrez IDs and no gene symbol annotations were available."}, "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}}