Liu-Hy commited on
Commit
72233eb
·
verified ·
1 Parent(s): d0debab

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. .gitattributes +3 -0
  2. output/preprocess/Acute_Myeloid_Leukemia/code/GSE121291.py +128 -0
  3. output/preprocess/Acute_Myeloid_Leukemia/code/GSE121431.py +120 -0
  4. output/preprocess/Acute_Myeloid_Leukemia/code/GSE161532.py +314 -0
  5. output/preprocess/Acute_Myeloid_Leukemia/code/GSE222124.py +213 -0
  6. output/preprocess/Acute_Myeloid_Leukemia/code/GSE222169.py +129 -0
  7. output/preprocess/Acute_Myeloid_Leukemia/code/GSE222616.py +113 -0
  8. output/preprocess/Acute_Myeloid_Leukemia/code/GSE235070.py +130 -0
  9. output/preprocess/Acute_Myeloid_Leukemia/code/GSE249638.py +284 -0
  10. output/preprocess/Acute_Myeloid_Leukemia/code/GSE98578.py +107 -0
  11. output/preprocess/Acute_Myeloid_Leukemia/code/GSE99612.py +208 -0
  12. output/preprocess/Acute_Myeloid_Leukemia/code/TCGA.py +267 -0
  13. output/preprocess/Acute_Myeloid_Leukemia/cohort_info.json +1 -112
  14. output/preprocess/Adrenocortical_Cancer/clinical_data/GSE68950.csv +1 -1
  15. output/preprocess/Adrenocortical_Cancer/code/GSE108088.py +122 -0
  16. output/preprocess/Adrenocortical_Cancer/code/GSE143383.py +123 -0
  17. output/preprocess/Adrenocortical_Cancer/code/GSE19776.py +125 -0
  18. output/preprocess/Adrenocortical_Cancer/code/GSE49278.py +119 -0
  19. output/preprocess/Adrenocortical_Cancer/code/GSE67766.py +213 -0
  20. output/preprocess/Adrenocortical_Cancer/code/GSE68606.py +125 -0
  21. output/preprocess/Adrenocortical_Cancer/code/GSE68950.py +160 -0
  22. output/preprocess/Adrenocortical_Cancer/code/GSE75415.py +201 -0
  23. output/preprocess/Adrenocortical_Cancer/code/GSE76019.py +128 -0
  24. output/preprocess/Adrenocortical_Cancer/code/GSE90713.py +177 -0
  25. output/preprocess/Adrenocortical_Cancer/code/TCGA.py +348 -0
  26. output/preprocess/Adrenocortical_Cancer/cohort_info.json +1 -112
  27. output/preprocess/Age-Related_Macular_Degeneration/clinical_data/GSE29801.csv +4 -0
  28. output/preprocess/Age-Related_Macular_Degeneration/code/GSE29801.py +192 -0
  29. output/preprocess/Age-Related_Macular_Degeneration/code/GSE38662.py +143 -0
  30. output/preprocess/Age-Related_Macular_Degeneration/code/GSE43176.py +190 -0
  31. output/preprocess/Age-Related_Macular_Degeneration/code/GSE45485.py +375 -0
  32. output/preprocess/Age-Related_Macular_Degeneration/code/GSE62224.py +462 -0
  33. output/preprocess/Age-Related_Macular_Degeneration/code/GSE67899.py +177 -0
  34. output/preprocess/Age-Related_Macular_Degeneration/code/TCGA.py +65 -0
  35. output/preprocess/Age-Related_Macular_Degeneration/cohort_info.json +1 -22
  36. output/preprocess/Age-Related_Macular_Degeneration/gene_data/GSE62224.csv +0 -0
  37. output/preprocess/Age-Related_Macular_Degeneration/gene_data/GSE67899.csv +0 -0
  38. output/preprocess/Alcohol_Flush_Reaction/code/GSE133228.py +156 -0
  39. output/preprocess/Alcohol_Flush_Reaction/code/TCGA.py +64 -0
  40. output/preprocess/Alcohol_Flush_Reaction/cohort_info.json +1 -0
  41. output/preprocess/Allergies/GSE270312.csv +0 -0
  42. output/preprocess/Allergies/clinical_data/GSE185658.csv +1 -1
  43. output/preprocess/Allergies/clinical_data/GSE270312.csv +3 -0
  44. output/preprocess/Allergies/code/GSE169149.py +157 -0
  45. output/preprocess/Allergies/code/GSE182740.py +187 -0
  46. output/preprocess/Allergies/code/GSE184382.py +97 -0
  47. output/preprocess/Allergies/code/GSE185658.py +201 -0
  48. output/preprocess/Allergies/code/GSE192454.py +213 -0
  49. output/preprocess/Allergies/code/GSE203196.py +287 -0
  50. output/preprocess/Allergies/code/GSE203409.py +201 -0
.gitattributes CHANGED
@@ -2200,3 +2200,6 @@ output/preprocess/Parkinsons_Disease/GSE101534.csv filter=lfs diff=lfs merge=lfs
2200
  output/preprocess/Bladder_Cancer/GSE138118.csv filter=lfs diff=lfs merge=lfs -text
2201
  output/preprocess/Liver_Cancer/gene_data/GSE218438.csv filter=lfs diff=lfs merge=lfs -text
2202
  output/preprocess/Parkinsons_Disease/gene_data/GSE101534.csv filter=lfs diff=lfs merge=lfs -text
 
 
 
 
2200
  output/preprocess/Bladder_Cancer/GSE138118.csv filter=lfs diff=lfs merge=lfs -text
2201
  output/preprocess/Liver_Cancer/gene_data/GSE218438.csv filter=lfs diff=lfs merge=lfs -text
2202
  output/preprocess/Parkinsons_Disease/gene_data/GSE101534.csv filter=lfs diff=lfs merge=lfs -text
2203
+ output/preprocess/Chronic_kidney_disease/GSE66494.csv filter=lfs diff=lfs merge=lfs -text
2204
+ output/preprocess/Chronic_kidney_disease/gene_data/GSE180393.csv filter=lfs diff=lfs merge=lfs -text
2205
+ output/preprocess/Bipolar_disorder/GSE62191.csv filter=lfs diff=lfs merge=lfs -text
output/preprocess/Acute_Myeloid_Leukemia/code/GSE121291.py ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Acute_Myeloid_Leukemia"
6
+ cohort = "GSE121291"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Acute_Myeloid_Leukemia"
10
+ in_cohort_dir = "../DATA/GEO/Acute_Myeloid_Leukemia/GSE121291"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z1/preprocess/Acute_Myeloid_Leukemia/GSE121291.csv"
14
+ out_gene_data_file = "./output/z1/preprocess/Acute_Myeloid_Leukemia/gene_data/GSE121291.csv"
15
+ out_clinical_data_file = "./output/z1/preprocess/Acute_Myeloid_Leukemia/clinical_data/GSE121291.csv"
16
+ json_path = "./output/z1/preprocess/Acute_Myeloid_Leukemia/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 (microarray mRNA -> gene expression data present)
43
+ is_gene_available = True
44
+
45
+ # 2) Variable availability
46
+ # Based on the sample characteristics, all samples are AML THP-1 cell line with varying agents/time.
47
+ # Trait (Acute_Myeloid_Leukemia) is constant; age and gender are not provided for the cell line context.
48
+ trait_row = None
49
+ age_row = None
50
+ gender_row = None
51
+
52
+ # 2.2) Conversion functions
53
+ def _extract_after_colon(x):
54
+ if x is None:
55
+ return None
56
+ s = str(x)
57
+ parts = s.split(":", 1)
58
+ val = parts[1] if len(parts) == 2 else parts[0]
59
+ return val.strip()
60
+
61
+ def convert_trait(x):
62
+ v = _extract_after_colon(x)
63
+ if not v:
64
+ return None
65
+ v_low = v.lower()
66
+ # Map AML to 1, healthy/normal/control to 0 where applicable
67
+ if "acute myeloid leukemia" in v_low or "aml" in v_low:
68
+ return 1
69
+ if any(k in v_low for k in ["healthy", "normal", "control", "non-aml", "no disease", "disease free"]):
70
+ return 0
71
+ # If clearly other leukemia types, map to disease=1 as well
72
+ if any(k in v_low for k in ["leukemia", "cancer", "tumor", "malignant"]):
73
+ return 1
74
+ return None
75
+
76
+ def convert_age(x):
77
+ v = _extract_after_colon(x)
78
+ if not v:
79
+ return None
80
+ # Extract first number as age in years if plausible
81
+ m = re.search(r"(\d+(\.\d+)*)", v)
82
+ if not m:
83
+ return None
84
+ try:
85
+ age = float(m.group(1))
86
+ except Exception:
87
+ return None
88
+ # Keep plausible human ages
89
+ if 0 < age < 120:
90
+ return age
91
+ return None
92
+
93
+ def convert_gender(x):
94
+ v = _extract_after_colon(x)
95
+ if not v:
96
+ return None
97
+ v_low = v.lower()
98
+ if v_low in ["female", "f", "woman", "women"]:
99
+ return 0
100
+ if v_low in ["male", "m", "man", "men"]:
101
+ return 1
102
+ return None
103
+
104
+ # 3) Initial filtering and save metadata
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 (skip because trait_row is None)
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_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)
output/preprocess/Acute_Myeloid_Leukemia/code/GSE121431.py ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Acute_Myeloid_Leukemia"
6
+ cohort = "GSE121431"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Acute_Myeloid_Leukemia"
10
+ in_cohort_dir = "../DATA/GEO/Acute_Myeloid_Leukemia/GSE121431"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z1/preprocess/Acute_Myeloid_Leukemia/GSE121431.csv"
14
+ out_gene_data_file = "./output/z1/preprocess/Acute_Myeloid_Leukemia/gene_data/GSE121431.csv"
15
+ out_clinical_data_file = "./output/z1/preprocess/Acute_Myeloid_Leukemia/clinical_data/GSE121431.csv"
16
+ json_path = "./output/z1/preprocess/Acute_Myeloid_Leukemia/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 sample characteristics:
40
+ # - This is a cell-line perturbation study (THP-1), not human subjects.
41
+ # - 'disease state' is uniformly Acute Myeloid Leukemia (constant), so trait is not usable for association.
42
+ # - Age and gender are not provided for cell lines.
43
+
44
+ is_gene_available = True # Likely gene expression data (mRNA) in GEO series; not miRNA/methylation-only.
45
+ trait_row = None # Trait is constant (all AML) and from cell line model; not usable.
46
+ age_row = None # No age for cell lines.
47
+ gender_row = None # No gender for cell lines.
48
+
49
+ def _after_colon(x):
50
+ if x is None:
51
+ return None
52
+ s = str(x)
53
+ parts = s.split(":", 1)
54
+ val = parts[1] if len(parts) == 2 else parts[0]
55
+ val = val.strip()
56
+ return val if val != "" else None
57
+
58
+ def convert_trait(x):
59
+ # Not used because trait_row is None; kept for interface completeness.
60
+ v = _after_colon(x)
61
+ if v is None:
62
+ return None
63
+ v_low = v.lower()
64
+ # Map AML presence to 1 if ever used; otherwise None for unknown/other.
65
+ if v_low in {"acute myeloid leukemia", "aml"}:
66
+ return 1
67
+ return None
68
+
69
+ def convert_age(x):
70
+ # Not used; provided for interface completeness.
71
+ v = _after_colon(x)
72
+ if v is None:
73
+ return None
74
+ # Extract first numeric token as age
75
+ import re
76
+ m = re.search(r"[-+]?\d*\.?\d+", v)
77
+ if not m:
78
+ return None
79
+ try:
80
+ return float(m.group(0))
81
+ except Exception:
82
+ return None
83
+
84
+ def convert_gender(x):
85
+ # Not used; provided for interface completeness.
86
+ v = _after_colon(x)
87
+ if v is None:
88
+ return None
89
+ v_low = v.strip().lower()
90
+ if v_low in {"female", "f", "woman", "women"}:
91
+ return 0
92
+ if v_low in {"male", "m", "man", "men"}:
93
+ return 1
94
+ return None
95
+
96
+ # Initial filtering and save metadata
97
+ is_trait_available = trait_row is not None
98
+ _ = validate_and_save_cohort_info(
99
+ is_final=False,
100
+ cohort=cohort,
101
+ info_path=json_path,
102
+ is_gene_available=is_gene_available,
103
+ is_trait_available=is_trait_available
104
+ )
105
+
106
+ # Clinical feature extraction: skipped because trait_row is None
107
+ if trait_row is not None:
108
+ selected_clinical_df = geo_select_clinical_features(
109
+ clinical_df=clinical_data,
110
+ trait=trait,
111
+ trait_row=trait_row,
112
+ convert_trait=convert_trait,
113
+ age_row=age_row,
114
+ convert_age=convert_age,
115
+ gender_row=gender_row,
116
+ convert_gender=convert_gender
117
+ )
118
+ clinical_preview = preview_df(selected_clinical_df)
119
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
120
+ selected_clinical_df.to_csv(out_clinical_data_file)
output/preprocess/Acute_Myeloid_Leukemia/code/GSE161532.py ADDED
@@ -0,0 +1,314 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Acute_Myeloid_Leukemia"
6
+ cohort = "GSE161532"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Acute_Myeloid_Leukemia"
10
+ in_cohort_dir = "../DATA/GEO/Acute_Myeloid_Leukemia/GSE161532"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z1/preprocess/Acute_Myeloid_Leukemia/GSE161532.csv"
14
+ out_gene_data_file = "./output/z1/preprocess/Acute_Myeloid_Leukemia/gene_data/GSE161532.csv"
15
+ out_clinical_data_file = "./output/z1/preprocess/Acute_Myeloid_Leukemia/clinical_data/GSE161532.csv"
16
+ json_path = "./output/z1/preprocess/Acute_Myeloid_Leukemia/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ import re
40
+ import pandas as pd
41
+
42
+ # 1) Gene expression data availability
43
+ is_gene_available = True # Affymetrix Human Transcriptome Array 2.0 indicates mRNA expression data.
44
+
45
+ # 2) Variable availability
46
+ # Trait (Acute Myeloid Leukemia) is constant across all samples -> not available for association as a varying trait
47
+ trait_row = None
48
+
49
+ # Age and Gender are available
50
+ age_row = 1
51
+ gender_row = 2
52
+
53
+ # 2.2) Data type conversion functions
54
+ def _extract_value_after_colon(x):
55
+ if x is None:
56
+ return None
57
+ s = str(x)
58
+ parts = s.split(":", 1)
59
+ return parts[1].strip() if len(parts) == 2 else s.strip()
60
+
61
+ def convert_trait(x):
62
+ # Binary: 1 = AML, 0 = non-AML; return None if unknown
63
+ val = _extract_value_after_colon(x)
64
+ if val is None:
65
+ return None
66
+ v = val.strip().lower()
67
+ if v in {"", "na", "n/a", "not available", "unknown"}:
68
+ return None
69
+ # Positive indicators
70
+ if "aml" in v or "acute myeloid leukemia" in v:
71
+ return 1
72
+ # Negative indicators
73
+ negatives = ["control", "healthy", "normal", "non-aml", "no aml", "donor", "non leukemia", "non-leukemia", "remission"]
74
+ if any(neg in v for neg in negatives):
75
+ return 0
76
+ return None
77
+
78
+ def convert_age(x):
79
+ # Continuous age in years; return None if not parseable
80
+ val = _extract_value_after_colon(x)
81
+ if val is None:
82
+ return None
83
+ v = val.strip().lower()
84
+ if v in {"", "na", "n/a", "not available", "unknown"}:
85
+ return None
86
+ m = re.search(r"[-+]?\d*\.?\d+", v)
87
+ if not m:
88
+ return None
89
+ try:
90
+ age = float(m.group())
91
+ if 0 <= age <= 120:
92
+ return age
93
+ return None
94
+ except Exception:
95
+ return None
96
+
97
+ def convert_gender(x):
98
+ # Binary: female=0, male=1
99
+ val = _extract_value_after_colon(x)
100
+ if val is None:
101
+ return None
102
+ v = val.strip().lower()
103
+ if v in {"", "na", "n/a", "not available", "unknown"}:
104
+ return None
105
+ if v in {"female", "f", "woman", "women"}:
106
+ return 0
107
+ if v in {"male", "m", "man", "men"}:
108
+ return 1
109
+ return None
110
+
111
+ # 3) Save metadata (initial filtering)
112
+ is_trait_available = trait_row is not None
113
+ _ = validate_and_save_cohort_info(
114
+ is_final=False,
115
+ cohort=cohort,
116
+ info_path=json_path,
117
+ is_gene_available=is_gene_available,
118
+ is_trait_available=is_trait_available
119
+ )
120
+
121
+ # 4) Clinical feature extraction (skip because trait_row is None)
122
+ if trait_row is not None:
123
+ selected_clinical_df = geo_select_clinical_features(
124
+ clinical_df=clinical_data,
125
+ trait=trait,
126
+ trait_row=trait_row,
127
+ convert_trait=convert_trait,
128
+ age_row=age_row,
129
+ convert_age=convert_age,
130
+ gender_row=gender_row,
131
+ convert_gender=convert_gender
132
+ )
133
+ clinical_preview = preview_df(selected_clinical_df)
134
+ # Save clinical features
135
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
136
+ selected_clinical_df.to_csv(out_clinical_data_file, index=True)
137
+
138
+ # Step 3: Gene Data Extraction
139
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
140
+ gene_data = get_genetic_data(matrix_file)
141
+
142
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
143
+ print(gene_data.index[:20])
144
+
145
+ # Step 4: Gene Identifier Review
146
+ requires_gene_mapping = True
147
+ print(f"requires_gene_mapping = {requires_gene_mapping}")
148
+
149
+ # Step 5: Gene Annotation
150
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
151
+ gene_annotation = get_gene_annotation(soft_file)
152
+
153
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
154
+ print("Gene annotation preview:")
155
+ print(preview_df(gene_annotation))
156
+
157
+ # Step 6: Gene Identifier Mapping
158
+ import re
159
+
160
+ # Keep original expression matrix for diagnostics
161
+ expr_df = gene_data
162
+ expr_ids = set(expr_df.index.astype(str).str.strip())
163
+
164
+ # Heuristic for expression ID format typically seen on Affymetrix ST arrays
165
+ expr_id_regex = re.compile(r'^\d+_(?:st|at|s_at|x_at)$', re.IGNORECASE)
166
+
167
+ def tokens_from_string(s: str):
168
+ # Extract alphanumeric tokens commonly used in GEO/SOFT fields
169
+ return re.findall(r'[A-Za-z0-9_.-]+', str(s))
170
+
171
+ # 1) Find the annotation column with real overlap to expression IDs
172
+ col_overlaps = {}
173
+ for col in gene_annotation.columns:
174
+ series = gene_annotation[col].dropna().astype(str)
175
+ hits = set()
176
+ for v in series:
177
+ for t in tokens_from_string(v):
178
+ if t in expr_ids:
179
+ hits.add(t)
180
+ col_overlaps[col] = len(hits)
181
+
182
+ # Select best ID column based on exact overlap with expression IDs
183
+ best_id_col, best_overlap = max(col_overlaps.items(), key=lambda kv: kv[1])
184
+
185
+ if best_overlap == 0:
186
+ # No usable overlap found; print diagnostics and stop early to avoid silent empty mapping
187
+ print("No overlap between expression IDs and any annotation column.")
188
+ print("Top columns by regex-like token matches (diagnostics):")
189
+ regex_like_counts = {}
190
+ for col in gene_annotation.columns:
191
+ series = gene_annotation[col].dropna().astype(str)
192
+ cnt = 0
193
+ for v in series:
194
+ for t in tokens_from_string(v):
195
+ if expr_id_regex.match(t):
196
+ cnt += 1
197
+ regex_like_counts[col] = cnt
198
+ for col, cnt in sorted(regex_like_counts.items(), key=lambda kv: kv[1], reverse=True)[:10]:
199
+ print(f" {col}: {cnt} regex-like tokens")
200
+ raise ValueError("Failed to find a probe ID column matching expression IDs (e.g., '2824546_st').")
201
+
202
+ # 2) Choose gene symbol column (prefer rich annotation fields)
203
+ candidate_gene_cols = [c for c in ['gene_assignment', 'mrna_assignment', 'gene_symbol', 'symbol', 'Gene Symbol']
204
+ if c in gene_annotation.columns]
205
+ if candidate_gene_cols:
206
+ def score_gene_col(col, n=500):
207
+ sample_vals = gene_annotation[col].dropna().astype(str).head(n)
208
+ return sum(len(extract_human_gene_symbols(v)) for v in sample_vals)
209
+ scores = {col: score_gene_col(col) for col in candidate_gene_cols}
210
+ best_gene_col = max(scores, key=scores.get)
211
+ else:
212
+ best_gene_col = gene_annotation.columns[-1]
213
+
214
+ print(f"Selected ID column: {best_id_col} with {best_overlap} overlapping IDs.")
215
+ print(f"Selected gene column: {best_gene_col}")
216
+
217
+ # 3) Build mapping and sanitize IDs to ensure they match expression IDs
218
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=best_id_col, gene_col=best_gene_col)
219
+
220
+ def pick_expr_id_token(x):
221
+ toks = tokens_from_string(x)
222
+ # Prefer exact match against expr_ids
223
+ for t in toks:
224
+ if t in expr_ids:
225
+ return t
226
+ # As a fallback, pick the first token that looks like an expression ID
227
+ for t in toks:
228
+ if expr_id_regex.match(t):
229
+ return t
230
+ return None
231
+
232
+ mapping_df['ID'] = mapping_df['ID'].astype(str).map(pick_expr_id_token)
233
+ mapping_df = mapping_df.dropna(subset=['ID'])
234
+ mapping_df['ID'] = mapping_df['ID'].astype(str)
235
+ mapping_df = mapping_df.drop_duplicates(subset=['ID', 'Gene'])
236
+
237
+ mapped_probes = mapping_df['ID'].nunique()
238
+ print(f"Number of mapped probes: {mapped_probes} out of {len(expr_ids)} ({mapped_probes/len(expr_ids):.2%})")
239
+
240
+ if mapped_probes == 0:
241
+ raise ValueError("Mapping resulted in zero mapped probes. Aborting to avoid empty gene matrix.")
242
+
243
+ # Convert to gene-level expression
244
+ gene_data = apply_gene_mapping(expression_df=expr_df, mapping_df=mapping_df)
245
+
246
+ # Sanity check on resulting gene-level data
247
+ if gene_data.shape[0] == 0 or gene_data.shape[1] == 0:
248
+ raise ValueError(f"Gene-level expression matrix is empty after mapping. Shape: {gene_data.shape}")
249
+
250
+ print(f"Gene-level matrix shape: {gene_data.shape}")
251
+
252
+ # Step 7: Data Normalization and Linking
253
+ import os
254
+
255
+ # 1. Normalize gene symbols and save gene data
256
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
257
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
258
+ normalized_gene_data.to_csv(out_gene_data_file)
259
+
260
+ # Determine trait availability from previous steps
261
+ is_trait_available = (trait_row is not None)
262
+
263
+ if is_trait_available:
264
+ # Build clinical features if trait is available
265
+ selected_clinical_data = geo_select_clinical_features(
266
+ clinical_df=clinical_data,
267
+ trait=trait,
268
+ trait_row=trait_row,
269
+ convert_trait=convert_trait,
270
+ age_row=age_row,
271
+ convert_age=convert_age,
272
+ gender_row=gender_row,
273
+ convert_gender=convert_gender
274
+ )
275
+
276
+ # 2. Link clinical and genetic data
277
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_data, normalized_gene_data)
278
+
279
+ # 3. Handle missing values
280
+ linked_data = handle_missing_values(linked_data, trait)
281
+
282
+ # 4. Bias check and remove biased covariates
283
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
284
+
285
+ # 5. Final validation and save cohort info
286
+ is_usable = validate_and_save_cohort_info(
287
+ is_final=True,
288
+ cohort=cohort,
289
+ info_path=json_path,
290
+ is_gene_available=True,
291
+ is_trait_available=True,
292
+ is_biased=is_trait_biased,
293
+ df=unbiased_linked_data,
294
+ note="INFO: Trait and clinical features were available and processed."
295
+ )
296
+
297
+ # 6. Save linked data if usable
298
+ if is_usable:
299
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
300
+ unbiased_linked_data.to_csv(out_data_file)
301
+
302
+ else:
303
+ # Trait is not available (constant across samples), skip linking and downstream steps
304
+ is_usable = validate_and_save_cohort_info(
305
+ is_final=True,
306
+ cohort=cohort,
307
+ info_path=json_path,
308
+ is_gene_available=True,
309
+ is_trait_available=False,
310
+ is_biased=False,
311
+ df=normalized_gene_data.T,
312
+ note="INFO: Trait is constant/unavailable for this cohort; only gene data was processed and saved."
313
+ )
314
+ # Do not save out_data_file since the dataset is not usable for trait association
output/preprocess/Acute_Myeloid_Leukemia/code/GSE222124.py ADDED
@@ -0,0 +1,213 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Acute_Myeloid_Leukemia"
6
+ cohort = "GSE222124"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Acute_Myeloid_Leukemia"
10
+ in_cohort_dir = "../DATA/GEO/Acute_Myeloid_Leukemia/GSE222124"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z1/preprocess/Acute_Myeloid_Leukemia/GSE222124.csv"
14
+ out_gene_data_file = "./output/z1/preprocess/Acute_Myeloid_Leukemia/gene_data/GSE222124.csv"
15
+ out_clinical_data_file = "./output/z1/preprocess/Acute_Myeloid_Leukemia/clinical_data/GSE222124.csv"
16
+ json_path = "./output/z1/preprocess/Acute_Myeloid_Leukemia/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 json
42
+ import pandas as pd
43
+
44
+ # 1) Gene expression data availability (based on series title/summary)
45
+ is_gene_available = True
46
+
47
+ # 2) Variable availability and converters
48
+
49
+ # Based on the sample characteristics:
50
+ # 0: 'cell type: T cell leukemia' | 'cell type: Acute monocytic leukemia monocyte' | 'cell type: Natural killer cell leukemia'
51
+ # Infer AML status from 'cell type' field: Acute monocytic leukemia -> AML (1); others -> non-AML (0)
52
+ trait_row = 0
53
+ age_row = None
54
+ gender_row = None
55
+
56
+ def _extract_value(x: str) -> str:
57
+ if x is None or (isinstance(x, float) and pd.isna(x)):
58
+ return ""
59
+ s = str(x)
60
+ parts = s.split(":", 1)
61
+ v = parts[1] if len(parts) > 1 else parts[0]
62
+ return v.strip()
63
+
64
+ def convert_trait(x):
65
+ v = _extract_value(x).lower()
66
+ if v in ("", "na", "n/a", "unknown", "not available", "none"):
67
+ return None
68
+ # Positive mappings for AML
69
+ aml_patterns = [
70
+ "acute myeloid leukemia",
71
+ "acute myelogenous leukemia",
72
+ "acute myeloid leukaemia",
73
+ "acute monocytic leukemia",
74
+ "aml",
75
+ ]
76
+ if any(p in v for p in aml_patterns):
77
+ return 1
78
+ # Known non-AML leukemias in this dataset
79
+ non_aml_patterns = [
80
+ "t cell leukemia",
81
+ "natural killer cell leukemia",
82
+ ]
83
+ if any(p in v for p in non_aml_patterns):
84
+ return 0
85
+ # Heuristic: if it contains 'leukemia' but no AML hint, classify as non-AML
86
+ if "leukemia" in v:
87
+ return 0
88
+ return None
89
+
90
+ def convert_age(x):
91
+ v = _extract_value(x).lower()
92
+ if v in ("", "na", "n/a", "unknown", "not available", "none"):
93
+ return None
94
+ m = re.search(r"(-?\d+(\.\d+)?)", v)
95
+ if m:
96
+ try:
97
+ return float(m.group(1))
98
+ except Exception:
99
+ return None
100
+ return None
101
+
102
+ def convert_gender(x):
103
+ v = _extract_value(x).strip().lower()
104
+ if v in ("", "na", "n/a", "unknown", "not available", "none"):
105
+ return None
106
+ if v in ("female", "f", "woman", "girl"):
107
+ return 0
108
+ if v in ("male", "m", "man", "boy"):
109
+ return 1
110
+ return None
111
+
112
+ # is_trait_available determined by trait_row presence
113
+ is_trait_available = trait_row is not None
114
+
115
+ # 3) Initial filtering and save metadata
116
+ _ = validate_and_save_cohort_info(
117
+ is_final=False,
118
+ cohort=cohort,
119
+ info_path=json_path,
120
+ is_gene_available=is_gene_available,
121
+ is_trait_available=is_trait_available
122
+ )
123
+
124
+ # 4) Clinical feature extraction (only if clinical data available)
125
+ if trait_row is not None:
126
+ selected_clinical_df = geo_select_clinical_features(
127
+ clinical_df=clinical_data,
128
+ trait=trait,
129
+ trait_row=trait_row,
130
+ convert_trait=convert_trait,
131
+ age_row=age_row,
132
+ convert_age=convert_age,
133
+ gender_row=gender_row,
134
+ convert_gender=convert_gender
135
+ )
136
+ preview = preview_df(selected_clinical_df, n=5)
137
+ print(preview)
138
+
139
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
140
+ selected_clinical_df.to_csv(out_clinical_data_file)
141
+
142
+ # Step 3: Gene Data Extraction
143
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
144
+ gene_data = get_genetic_data(matrix_file)
145
+
146
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
147
+ print(gene_data.index[:20])
148
+
149
+ # Step 4: Gene Identifier Review
150
+ requires_gene_mapping = True
151
+ print(f"requires_gene_mapping = {requires_gene_mapping}")
152
+
153
+ # Step 5: Gene Annotation
154
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
155
+ gene_annotation = get_gene_annotation(soft_file)
156
+
157
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
158
+ print("Gene annotation preview:")
159
+ print(preview_df(gene_annotation))
160
+
161
+ # Step 6: Gene Identifier Mapping
162
+ # Identify the correct columns for probe IDs and gene symbols
163
+ probe_col = 'ID'
164
+ gene_symbol_col = 'Gene Symbol'
165
+
166
+ # Build the mapping dataframe
167
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=probe_col, gene_col=gene_symbol_col)
168
+
169
+ # Apply the mapping to convert probe-level data to gene-level data
170
+ gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
171
+
172
+ # Step 7: Data Normalization and Linking
173
+ import os
174
+ import pandas as pd
175
+
176
+ # 1. Normalize gene symbols and save
177
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
178
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
179
+ normalized_gene_data.to_csv(out_gene_data_file)
180
+
181
+ # 2. Link clinical and genetic data
182
+ # Use the correct clinical dataframe variable; load from disk if not in scope
183
+ try:
184
+ selected_clinical_df
185
+ except NameError:
186
+ selected_clinical_df = pd.read_csv(out_clinical_data_file, index_col=0)
187
+
188
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
189
+
190
+ # 3. Handle missing values
191
+ linked_data = handle_missing_values(linked_data, trait)
192
+
193
+ # 4. Assess bias and remove biased demographic features
194
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
195
+
196
+ # 5. Final validation and save cohort info
197
+ note = ("INFO: Cell-line study (Jurkat/THP1/KHYG-1) treated with glycodelin; trait inferred from cell type; "
198
+ "no age/gender available.")
199
+ is_usable = validate_and_save_cohort_info(
200
+ is_final=True,
201
+ cohort=cohort,
202
+ info_path=json_path,
203
+ is_gene_available=True,
204
+ is_trait_available=True,
205
+ is_biased=is_trait_biased,
206
+ df=unbiased_linked_data,
207
+ note=note
208
+ )
209
+
210
+ # 6. Save linked data if usable
211
+ if is_usable:
212
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
213
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Acute_Myeloid_Leukemia/code/GSE222169.py ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Acute_Myeloid_Leukemia"
6
+ cohort = "GSE222169"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Acute_Myeloid_Leukemia"
10
+ in_cohort_dir = "../DATA/GEO/Acute_Myeloid_Leukemia/GSE222169"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z1/preprocess/Acute_Myeloid_Leukemia/GSE222169.csv"
14
+ out_gene_data_file = "./output/z1/preprocess/Acute_Myeloid_Leukemia/gene_data/GSE222169.csv"
15
+ out_clinical_data_file = "./output/z1/preprocess/Acute_Myeloid_Leukemia/clinical_data/GSE222169.csv"
16
+ json_path = "./output/z1/preprocess/Acute_Myeloid_Leukemia/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ # Step: Dataset Analysis and Clinical Feature Extraction for GSE222169
40
+
41
+ import re
42
+ import pandas as pd
43
+
44
+ # 1) Gene Expression Data Availability
45
+ # Based on GEO series context and characteristics (genotype knockdowns/overexpression; leukemia cell lines/patient AML),
46
+ # this series is likely RNA-seq/gene expression rather than miRNA-only or methylation-only.
47
+ is_gene_available = True
48
+
49
+ # 2) Variable Availability and Data Type Conversion
50
+
51
+ # From the sample characteristics:
52
+ # {0: ['tissue source: patient with AML', 'cell line: MOLM-14', 'cell line: OCI-AML2'],
53
+ # 1: ['cell type: leukemia cell line', 'genotype: shCTL', 'genotype: shOPA1', 'genotype: shMFN2', 'genotype: OE_EMPTY', 'genotype: OE_MFN2'],
54
+ # 2: ['treatment: shCTL_72h', 'treatment: shMFN2_72h']}
55
+ #
56
+ # All entries indicate AML disease context (patient with AML or AML-derived leukemia cell lines),
57
+ # with no healthy/control samples. Thus, trait (AML status) is constant and not suitable for association analysis.
58
+ trait_row = None
59
+ age_row = None # No age information observed
60
+ gender_row = None # No gender information observed
61
+
62
+ def _after_colon(x: str) -> str:
63
+ if x is None:
64
+ return ""
65
+ parts = str(x).split(":", 1)
66
+ return parts[1].strip() if len(parts) == 2 else str(x).strip()
67
+
68
+ def convert_trait(x):
69
+ # Binary mapping for AML status if ever needed: AML/leukemia -> 1; healthy/control/normal -> 0
70
+ val = _after_colon(x).lower()
71
+ if val == "":
72
+ return None
73
+ positives = [
74
+ "acute myeloid leukemia", "aml", "leukemia", "leukemia cell line", "molm-14", "oci-aml2", "patient with aml"
75
+ ]
76
+ negatives = ["healthy", "control", "normal", "non-aml", "no leukemia"]
77
+ if any(p in val for p in positives):
78
+ return 1
79
+ if any(n in val for n in negatives):
80
+ return 0
81
+ return None
82
+
83
+ def convert_age(x):
84
+ # Extract first numeric value as age in years; otherwise None
85
+ val = _after_colon(x)
86
+ m = re.search(r"[-+]?\d*\.?\d+", val)
87
+ if m:
88
+ try:
89
+ return float(m.group())
90
+ except Exception:
91
+ return None
92
+ return None
93
+
94
+ def convert_gender(x):
95
+ # Female -> 0; Male -> 1
96
+ val = _after_colon(x).strip().lower()
97
+ if val in ["female", "f", "woman", "women", "girl"]:
98
+ return 0
99
+ if val in ["male", "m", "man", "men", "boy"]:
100
+ return 1
101
+ return None
102
+
103
+ # 3) Save Metadata (initial filtering)
104
+ is_trait_available = trait_row is not None
105
+ _ = validate_and_save_cohort_info(
106
+ is_final=False,
107
+ cohort=cohort,
108
+ info_path=json_path,
109
+ is_gene_available=is_gene_available,
110
+ is_trait_available=is_trait_available
111
+ )
112
+
113
+ # 4) Clinical Feature Extraction (skip because trait_row is None)
114
+ if (trait_row is not None) and ('clinical_data' in globals()):
115
+ selected_clinical_df = geo_select_clinical_features(
116
+ clinical_df=clinical_data,
117
+ trait=trait,
118
+ trait_row=trait_row,
119
+ convert_trait=convert_trait,
120
+ age_row=age_row,
121
+ convert_age=convert_age,
122
+ gender_row=gender_row,
123
+ convert_gender=convert_gender
124
+ )
125
+ clinical_preview = preview_df(selected_clinical_df)
126
+ print(clinical_preview)
127
+ # Save clinical data
128
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
129
+ selected_clinical_df.to_csv(out_clinical_data_file)
output/preprocess/Acute_Myeloid_Leukemia/code/GSE222616.py ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Acute_Myeloid_Leukemia"
6
+ cohort = "GSE222616"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Acute_Myeloid_Leukemia"
10
+ in_cohort_dir = "../DATA/GEO/Acute_Myeloid_Leukemia/GSE222616"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z1/preprocess/Acute_Myeloid_Leukemia/GSE222616.csv"
14
+ out_gene_data_file = "./output/z1/preprocess/Acute_Myeloid_Leukemia/gene_data/GSE222616.csv"
15
+ out_clinical_data_file = "./output/z1/preprocess/Acute_Myeloid_Leukemia/clinical_data/GSE222616.csv"
16
+ json_path = "./output/z1/preprocess/Acute_Myeloid_Leukemia/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ import re
40
+ import pandas as pd
41
+
42
+ # 1) Gene expression availability based on background (Affymetrix HuGene 1.0 ST arrays => mRNA expression)
43
+ is_gene_available = True
44
+
45
+ # 2) Variable availability assessment from Sample Characteristics:
46
+ # All samples are HL-60 AML cell line with various treatments; no human subject variability in trait/age/gender.
47
+ trait_row = None
48
+ age_row = None
49
+ gender_row = None
50
+
51
+ # 2.2) Converters (defined for interface completeness; not used since corresponding rows are None)
52
+ def _after_colon(x: str) -> str:
53
+ if x is None:
54
+ return ""
55
+ parts = str(x).split(":", 1)
56
+ return parts[1].strip() if len(parts) == 2 else str(x).strip()
57
+
58
+ def convert_trait(x):
59
+ val = _after_colon(x).lower()
60
+ # Map common case/control words; here not applicable, but kept for robustness
61
+ if val in {"aml", "acute myeloid leukemia", "acute myeloid leukaemia"}:
62
+ return 1
63
+ if val in {"control", "healthy", "normal"}:
64
+ return 0
65
+ # Heuristic for treatment/control context if ever encountered
66
+ if "wt" in val or "control" in val or "untreated" in val:
67
+ return 0
68
+ if "atra" in val or "gsk343" in val or "hkmti" in val or "ezh2" in val:
69
+ return 1
70
+ return None
71
+
72
+ def convert_age(x):
73
+ val = _after_colon(x)
74
+ nums = re.findall(r"\d+\.?\d*", val)
75
+ if nums:
76
+ try:
77
+ return float(nums[0])
78
+ except Exception:
79
+ return None
80
+ return None
81
+
82
+ def convert_gender(x):
83
+ val = _after_colon(x).lower()
84
+ if val in {"f", "female", "woman", "women"}:
85
+ return 0
86
+ if val in {"m", "male", "man", "men"}:
87
+ return 1
88
+ return None
89
+
90
+ # 3) Initial filtering and save metadata
91
+ is_trait_available = trait_row is not None
92
+ _ = validate_and_save_cohort_info(
93
+ is_final=False,
94
+ cohort=cohort,
95
+ info_path=json_path,
96
+ is_gene_available=is_gene_available,
97
+ is_trait_available=is_trait_available
98
+ )
99
+
100
+ # 4) Clinical feature extraction (skip because trait_row is None)
101
+ # if trait_row is not None:
102
+ # selected_clinical = geo_select_clinical_features(
103
+ # clinical_df=clinical_data,
104
+ # trait=trait,
105
+ # trait_row=trait_row,
106
+ # convert_trait=convert_trait,
107
+ # age_row=age_row,
108
+ # convert_age=convert_age if age_row is not None else None,
109
+ # gender_row=gender_row,
110
+ # convert_gender=convert_gender if gender_row is not None else None
111
+ # )
112
+ # _ = preview_df(selected_clinical, n=5)
113
+ # selected_clinical.to_csv(out_clinical_data_file)
output/preprocess/Acute_Myeloid_Leukemia/code/GSE235070.py ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Acute_Myeloid_Leukemia"
6
+ cohort = "GSE235070"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Acute_Myeloid_Leukemia"
10
+ in_cohort_dir = "../DATA/GEO/Acute_Myeloid_Leukemia/GSE235070"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z1/preprocess/Acute_Myeloid_Leukemia/GSE235070.csv"
14
+ out_gene_data_file = "./output/z1/preprocess/Acute_Myeloid_Leukemia/gene_data/GSE235070.csv"
15
+ out_clinical_data_file = "./output/z1/preprocess/Acute_Myeloid_Leukemia/clinical_data/GSE235070.csv"
16
+ json_path = "./output/z1/preprocess/Acute_Myeloid_Leukemia/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ import re
40
+ import pandas as pd
41
+ from typing import Optional, Any
42
+
43
+ # 1) Assess gene expression availability (SuperSeries; characteristics suggest constant AML; no clear gene matrix here)
44
+ is_gene_available = False
45
+
46
+ # 2) Variable availability and conversion functions
47
+
48
+ # Based on the provided Sample Characteristics Dictionary:
49
+ # {0: ['disease state: patient with AML']}
50
+ # The trait is constant (all AML), thus not usable. Age and gender are not present.
51
+ trait_row = None
52
+ age_row = None
53
+ gender_row = None
54
+
55
+ def _after_colon(x: Any) -> str:
56
+ if x is None:
57
+ return ""
58
+ s = str(x)
59
+ parts = s.split(":", 1)
60
+ val = parts[1] if len(parts) == 2 else parts[0]
61
+ return val.strip()
62
+
63
+ def convert_trait(x: Any) -> Optional[int]:
64
+ """
65
+ Map AML/Leukemia cases to 1; healthy/normal/control to 0; unknown to None.
66
+ Not used here because trait_row is None, but provided for completeness.
67
+ """
68
+ val = _after_colon(x).lower()
69
+ if not val:
70
+ return None
71
+
72
+ # Positive (case) cues
73
+ positive_cues = [
74
+ "aml", "acute myeloid leukemia", "acute myelogenous leukemia",
75
+ "leukemia", "leukemic", "patient with aml", "case", "tumor", "cancer"
76
+ ]
77
+ # Negative (control) cues
78
+ negative_cues = ["control", "healthy", "normal", "non-cancer", "non cancer", "no cancer", "benign"]
79
+
80
+ if any(k in val for k in positive_cues):
81
+ return 1
82
+ if any(k in val for k in negative_cues):
83
+ return 0
84
+ return None
85
+
86
+ def convert_age(x: Any) -> Optional[float]:
87
+ """
88
+ Extract age in years from free text; return None if not parseable or out of range.
89
+ """
90
+ val = _after_colon(x).lower()
91
+ if not val:
92
+ return None
93
+ # Find a number (integer or decimal)
94
+ m = re.search(r"(\d+(?:\.\d+)?)", val)
95
+ if not m:
96
+ return None
97
+ try:
98
+ age = float(m.group(1))
99
+ except Exception:
100
+ return None
101
+ # Simple plausibility check
102
+ if 0 < age < 120:
103
+ return age
104
+ return None
105
+
106
+ def convert_gender(x: Any) -> Optional[int]:
107
+ """
108
+ Map female->0, male->1; unknown -> None.
109
+ """
110
+ val = _after_colon(x).strip().lower()
111
+ if not val:
112
+ return None
113
+ if val in ["female", "f", "woman", "girl"]:
114
+ return 0
115
+ if val in ["male", "m", "man", "boy"]:
116
+ return 1
117
+ return None
118
+
119
+ # 3) Save metadata (initial filtering)
120
+ is_trait_available = trait_row is not None
121
+ _ = validate_and_save_cohort_info(
122
+ is_final=False,
123
+ cohort=cohort,
124
+ info_path=json_path,
125
+ is_gene_available=is_gene_available,
126
+ is_trait_available=is_trait_available
127
+ )
128
+
129
+ # 4) Clinical Feature Extraction
130
+ # Skipped because trait_row is None (no usable clinical variability available).
output/preprocess/Acute_Myeloid_Leukemia/code/GSE249638.py ADDED
@@ -0,0 +1,284 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Acute_Myeloid_Leukemia"
6
+ cohort = "GSE249638"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Acute_Myeloid_Leukemia"
10
+ in_cohort_dir = "../DATA/GEO/Acute_Myeloid_Leukemia/GSE249638"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z1/preprocess/Acute_Myeloid_Leukemia/GSE249638.csv"
14
+ out_gene_data_file = "./output/z1/preprocess/Acute_Myeloid_Leukemia/gene_data/GSE249638.csv"
15
+ out_clinical_data_file = "./output/z1/preprocess/Acute_Myeloid_Leukemia/clinical_data/GSE249638.csv"
16
+ json_path = "./output/z1/preprocess/Acute_Myeloid_Leukemia/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 # Transcriptomic profiling of CD4+ T cells suggests mRNA expression data
41
+
42
+ # 2. Variable availability and conversion functions
43
+
44
+ # Determine rows from the Sample Characteristics Dictionary
45
+ trait_row = 1
46
+ age_row = None
47
+ gender_row = None
48
+
49
+ # Conversion helpers
50
+ def _extract_value(x):
51
+ if x is None:
52
+ return None
53
+ try:
54
+ s = str(x)
55
+ except Exception:
56
+ return None
57
+ parts = s.split(":", 1)
58
+ v = parts[1] if len(parts) > 1 else parts[0]
59
+ return v.strip()
60
+
61
+ def convert_trait(x):
62
+ v = _extract_value(x)
63
+ if v is None:
64
+ return None
65
+ vl = v.lower()
66
+ # Map AML/case to 1, controls to 0
67
+ if "control" in vl or vl in {"healthy", "normal"}:
68
+ return 0
69
+ if "leukemia" in vl or vl in {"aml", "acute myeloid leukemia"}:
70
+ return 1
71
+ return None
72
+
73
+ def convert_age(x):
74
+ # Not available in this dataset
75
+ return None
76
+
77
+ def convert_gender(x):
78
+ # Not available in this dataset
79
+ return None
80
+
81
+ # 3. Save metadata (initial filtering)
82
+ is_trait_available = trait_row is not None
83
+ _ = validate_and_save_cohort_info(
84
+ is_final=False,
85
+ cohort=cohort,
86
+ info_path=json_path,
87
+ is_gene_available=is_gene_available,
88
+ is_trait_available=is_trait_available
89
+ )
90
+
91
+ # 4. Clinical Feature Extraction (only if clinical data is available)
92
+ if trait_row is not None:
93
+ selected_clinical_df = geo_select_clinical_features(
94
+ clinical_df=clinical_data,
95
+ trait=trait,
96
+ trait_row=trait_row,
97
+ convert_trait=convert_trait,
98
+ age_row=age_row,
99
+ convert_age=convert_age,
100
+ gender_row=gender_row,
101
+ convert_gender=convert_gender
102
+ )
103
+ preview = preview_df(selected_clinical_df)
104
+ print(preview)
105
+
106
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
107
+ selected_clinical_df.to_csv(out_clinical_data_file)
108
+
109
+ # Step 3: Gene Data Extraction
110
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
111
+ gene_data = get_genetic_data(matrix_file)
112
+
113
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
114
+ print(gene_data.index[:20])
115
+
116
+ # Step 4: Gene Identifier Review
117
+ requires_gene_mapping = True
118
+ print(f"requires_gene_mapping = {requires_gene_mapping}")
119
+
120
+ # Step 5: Gene Annotation
121
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
122
+ gene_annotation = get_gene_annotation(soft_file)
123
+
124
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
125
+ print("Gene annotation preview:")
126
+ print(preview_df(gene_annotation))
127
+
128
+ # Step 6: Gene Identifier Mapping
129
+ # Keep original probe-level data
130
+ probe_data = gene_data.copy()
131
+
132
+ expr_ids = set(probe_data.index.astype(str))
133
+
134
+ # Build auxiliary set stripping common Affy suffixes
135
+ def strip_affy_suffix(s: str) -> str:
136
+ return re.sub(r'_(st|at|s_at|x_at|a_at)$', '', s)
137
+
138
+ expr_ids_core = {strip_affy_suffix(x) for x in expr_ids}
139
+
140
+ # 1) Find the best matching identifier column by overlap with expression IDs
141
+ best_id_col = None
142
+ best_overlap = 0
143
+ best_overlap_core = 0
144
+
145
+ for col in gene_annotation.columns:
146
+ try:
147
+ ann_vals = gene_annotation[col].astype(str).str.strip()
148
+ except Exception:
149
+ continue
150
+ ann_set = set(ann_vals)
151
+ overlap = len(expr_ids.intersection(ann_set))
152
+
153
+ # Also try overlap with stripped core IDs (to tolerate suffix differences)
154
+ ann_set_core = {strip_affy_suffix(x) for x in ann_set}
155
+ overlap_core = len(expr_ids_core.intersection(ann_set_core))
156
+
157
+ # Prioritize exact overlap, then core overlap
158
+ if overlap > best_overlap or (overlap == best_overlap and overlap_core > best_overlap_core):
159
+ best_overlap = overlap
160
+ best_overlap_core = overlap_core
161
+ best_id_col = col
162
+
163
+ # Enforce minimum overlap
164
+ if (best_overlap == 0) and (best_overlap_core == 0):
165
+ print("WARNING: No overlapping identifier column found between gene annotation and expression IDs. "
166
+ "Skipping probe-to-gene mapping and keeping probe-level data.")
167
+ else:
168
+ # 2) Choose a gene symbol column
169
+ gene_col = None
170
+ # Prefer columns explicitly indicating symbol(s)
171
+ symbol_like = [c for c in gene_annotation.columns if 'symbol' in c.lower()]
172
+ if symbol_like:
173
+ gene_col = symbol_like[0]
174
+ elif 'gene_assignment' in gene_annotation.columns:
175
+ gene_col = 'gene_assignment'
176
+ else:
177
+ # Fallbacks: any column mentioning 'gene' or 'assignment' that likely contains symbols
178
+ candidates = [c for c in gene_annotation.columns if ('gene' in c.lower() and 'seq' not in c.lower())
179
+ or ('assign' in c.lower())]
180
+ if candidates:
181
+ gene_col = candidates[0]
182
+ elif 'mrna_assignment' in gene_annotation.columns:
183
+ gene_col = 'mrna_assignment'
184
+
185
+ if gene_col is None:
186
+ print("WARNING: Could not identify a gene symbol column in the annotation. "
187
+ "Skipping mapping and keeping probe-level data.")
188
+ else:
189
+ # If the best match came from core overlap only, try to harmonize IDs by stripping suffix in the annotation
190
+ ann_col_series = gene_annotation[best_id_col].astype(str).str.strip()
191
+ if best_overlap == 0 and best_overlap_core > 0:
192
+ # Create a temporary harmonized ID column matching expression IDs' core part
193
+ tmp_id_col = f"__HARMONIZED_ID__"
194
+ gene_annotation[tmp_id_col] = ann_col_series.apply(strip_affy_suffix)
195
+ use_id_col = tmp_id_col
196
+ else:
197
+ use_id_col = best_id_col
198
+
199
+ # 3) Build mapping and apply
200
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=use_id_col, gene_col=gene_col)
201
+
202
+ # Restrict mapping to probes present in expression data (using exact IDs; if harmonized, rebuild a bridge)
203
+ if use_id_col == best_id_col:
204
+ # Direct mapping
205
+ mapped_ids = set(mapping_df['ID'])
206
+ matched = len(mapped_ids.intersection(expr_ids))
207
+ print(f"Mapping using column '{best_id_col}' to '{gene_col}': matched probes = {matched}")
208
+ if matched == 0:
209
+ print("WARNING: Mapping resulted in zero matched probes. Keeping probe-level data.")
210
+ else:
211
+ gene_data_mapped = apply_gene_mapping(expression_df=probe_data, mapping_df=mapping_df)
212
+ if gene_data_mapped.shape[0] > 0:
213
+ gene_data = gene_data_mapped
214
+ else:
215
+ print("WARNING: Gene-level DataFrame is empty after mapping. Keeping probe-level data.")
216
+ else:
217
+ # Harmonized core mapping: need to map core IDs back to full probe IDs present in expression
218
+ # Build a bridge from core -> full IDs (there can be multiple suffix variants; choose those present)
219
+ core_to_full = {}
220
+ for pid in expr_ids:
221
+ core = strip_affy_suffix(pid)
222
+ core_to_full.setdefault(core, set()).add(pid)
223
+
224
+ # Expand mapping_df so that each core ID is replaced by all corresponding full IDs present in probe_data
225
+ expanded_rows = []
226
+ for _, row in mapping_df.iterrows():
227
+ core_id = row['ID']
228
+ if core_id in core_to_full:
229
+ for full_id in core_to_full[core_id]:
230
+ new_row = row.copy()
231
+ new_row['ID'] = full_id
232
+ expanded_rows.append(new_row)
233
+
234
+ if not expanded_rows:
235
+ print("WARNING: Harmonized mapping produced no matches to full probe IDs. Keeping probe-level data.")
236
+ else:
237
+ mapping_df_expanded = pd.DataFrame(expanded_rows)
238
+ matched = mapping_df_expanded['ID'].isin(probe_data.index).sum()
239
+ print(f"Mapping using harmonized IDs from '{best_id_col}' to '{gene_col}': matched probes = {matched}")
240
+ if matched == 0:
241
+ print("WARNING: Mapping resulted in zero matched probes after expansion. Keeping probe-level data.")
242
+ else:
243
+ gene_data_mapped = apply_gene_mapping(expression_df=probe_data, mapping_df=mapping_df_expanded)
244
+ if gene_data_mapped.shape[0] > 0:
245
+ gene_data = gene_data_mapped
246
+ else:
247
+ print("WARNING: Gene-level DataFrame is empty after mapping. Keeping probe-level data.")
248
+
249
+ # Step 7: Data Normalization and Linking
250
+ # 1. Normalize gene symbols and save normalized gene data
251
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
252
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
253
+ normalized_gene_data.to_csv(out_gene_data_file)
254
+
255
+ # 2. Link clinical and genetic data
256
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
257
+
258
+ # 3. Handle missing values
259
+ linked_data = handle_missing_values(linked_data, trait)
260
+
261
+ # 4. Assess bias and remove biased demographic features
262
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
263
+
264
+ # 5. Final validation and save cohort info
265
+ is_gene_available_final = bool((normalized_gene_data.shape[0] > 0) and (normalized_gene_data.shape[1] > 0))
266
+ is_trait_available_final = bool((trait in unbiased_linked_data.columns) and bool(unbiased_linked_data[trait].notna().any()))
267
+ is_trait_biased_bool = bool(is_trait_biased)
268
+ note = "INFO: Only trait available; Age and Gender not provided in sample characteristics."
269
+
270
+ is_usable = validate_and_save_cohort_info(
271
+ is_final=True,
272
+ cohort=cohort,
273
+ info_path=json_path,
274
+ is_gene_available=is_gene_available_final,
275
+ is_trait_available=is_trait_available_final,
276
+ is_biased=is_trait_biased_bool,
277
+ df=unbiased_linked_data,
278
+ note=note
279
+ )
280
+
281
+ # 6. Save linked data if usable
282
+ if is_usable:
283
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
284
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Acute_Myeloid_Leukemia/code/GSE98578.py ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Acute_Myeloid_Leukemia"
6
+ cohort = "GSE98578"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Acute_Myeloid_Leukemia"
10
+ in_cohort_dir = "../DATA/GEO/Acute_Myeloid_Leukemia/GSE98578"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z1/preprocess/Acute_Myeloid_Leukemia/GSE98578.csv"
14
+ out_gene_data_file = "./output/z1/preprocess/Acute_Myeloid_Leukemia/gene_data/GSE98578.csv"
15
+ out_clinical_data_file = "./output/z1/preprocess/Acute_Myeloid_Leukemia/clinical_data/GSE98578.csv"
16
+ json_path = "./output/z1/preprocess/Acute_Myeloid_Leukemia/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
+ # Decision: This series contains microarray gene expression data from AML cell lines (not miRNA/methylation), so genes are available.
40
+ # However, all samples are AML; no healthy controls. Thus, the trait (Acute_Myeloid_Leukemia) is constant and not usable.
41
+ # No age or gender information is present for cell lines.
42
+
43
+ # 1) Gene expression data availability
44
+ is_gene_available = True
45
+
46
+ # 2) Variable availability
47
+ trait_row = None # All are AML; no case/control variation
48
+ age_row = None # Not available for cell lines
49
+ gender_row = None # Not available for cell lines
50
+
51
+ # 2) Converters (defined for completeness; they won't be used since rows are None)
52
+ def _after_colon(val):
53
+ if val is None:
54
+ return None
55
+ s = str(val)
56
+ parts = s.split(":", 1)
57
+ return parts[1].strip() if len(parts) == 2 else s.strip()
58
+
59
+ def convert_trait(x):
60
+ # Not used for this cohort; returning None keeps it safe if accidentally called.
61
+ return None
62
+
63
+ def convert_age(x):
64
+ v = _after_colon(x)
65
+ if v is None:
66
+ return None
67
+ # Try to extract a number if any
68
+ import re
69
+ m = re.search(r"[-+]?\d*\.?\d+", v)
70
+ return float(m.group()) if m else None
71
+
72
+ def convert_gender(x):
73
+ v = _after_colon(x)
74
+ if v is None:
75
+ return None
76
+ v_low = v.strip().lower()
77
+ if v_low in {"female", "f"}:
78
+ return 0
79
+ if v_low in {"male", "m"}:
80
+ return 1
81
+ return None
82
+
83
+ # 3) Save metadata (initial filtering)
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 trait_row were available:
95
+ # selected_df = geo_select_clinical_features(
96
+ # clinical_df=clinical_data,
97
+ # trait=trait,
98
+ # trait_row=trait_row,
99
+ # convert_trait=convert_trait,
100
+ # age_row=age_row,
101
+ # convert_age=convert_age,
102
+ # gender_row=gender_row,
103
+ # convert_gender=convert_gender
104
+ # )
105
+ # preview = preview_df(selected_df)
106
+ # os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
107
+ # selected_df.to_csv(out_clinical_data_file, index=True)
output/preprocess/Acute_Myeloid_Leukemia/code/GSE99612.py ADDED
@@ -0,0 +1,208 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Acute_Myeloid_Leukemia"
6
+ cohort = "GSE99612"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Acute_Myeloid_Leukemia"
10
+ in_cohort_dir = "../DATA/GEO/Acute_Myeloid_Leukemia/GSE99612"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z1/preprocess/Acute_Myeloid_Leukemia/GSE99612.csv"
14
+ out_gene_data_file = "./output/z1/preprocess/Acute_Myeloid_Leukemia/gene_data/GSE99612.csv"
15
+ out_clinical_data_file = "./output/z1/preprocess/Acute_Myeloid_Leukemia/clinical_data/GSE99612.csv"
16
+ json_path = "./output/z1/preprocess/Acute_Myeloid_Leukemia/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ # Step 1: Determine data availability
40
+ is_gene_available = True # Expression profiling in cell lines indicates gene data likely available.
41
+
42
+ # Step 2: Identify variable availability
43
+ # Given this is a cell line experiment (Caco-2 and THP-1) with mixed annotations split across rows
44
+ # and no consistent human-level trait/age/gender per sample, treat these as not available.
45
+ trait_row = None
46
+ age_row = None
47
+ gender_row = None
48
+
49
+ # Step 2.2: Define conversion functions (robust to potential inputs, though not used when rows are None)
50
+ import re
51
+
52
+ def _after_colon(value):
53
+ if value is None:
54
+ return None
55
+ s = str(value)
56
+ parts = s.split(":", 1)
57
+ return parts[1].strip() if len(parts) == 2 else s.strip()
58
+
59
+ def convert_trait(value):
60
+ v = _after_colon(value)
61
+ if v is None:
62
+ return None
63
+ vlow = v.lower()
64
+ # Map AML-related origins/cell line to 1; non-AML colon adenocarcinoma/Caco-2 to 0
65
+ if any(k in vlow for k in ["acute monocytic leukemia", "acute myeloid leukemia", "thp-1"]):
66
+ return 1
67
+ if any(k in vlow for k in ["caco-2", "colon adenocarcinoma"]):
68
+ return 0
69
+ return None
70
+
71
+ def convert_age(value):
72
+ v = _after_colon(value)
73
+ if v is None:
74
+ return None
75
+ vlow = v.lower()
76
+ # Extract numeric years if present
77
+ m = re.search(r'(\d+(\.\d+)?)\s*year', vlow)
78
+ if m:
79
+ try:
80
+ return float(m.group(1))
81
+ except Exception:
82
+ return None
83
+ # If explicit number without 'year' present, fallback
84
+ m2 = re.search(r'\d+(\.\d+)?', vlow)
85
+ if m2:
86
+ try:
87
+ return float(m2.group(0))
88
+ except Exception:
89
+ return None
90
+ return None
91
+
92
+ def convert_gender(value):
93
+ v = _after_colon(value)
94
+ if v is None:
95
+ return None
96
+ vlow = v.lower()
97
+ if "male" in vlow:
98
+ return 1
99
+ if "female" in vlow:
100
+ return 0
101
+ return None
102
+
103
+ # Step 3: Initial filtering and save metadata
104
+ is_trait_available = trait_row is not None
105
+ _ = validate_and_save_cohort_info(
106
+ is_final=False,
107
+ cohort=cohort,
108
+ info_path=json_path,
109
+ is_gene_available=is_gene_available,
110
+ is_trait_available=is_trait_available
111
+ )
112
+
113
+ # Step 4: Clinical feature extraction (skip because trait_row is None)
114
+ if trait_row is not None:
115
+ selected_clinical_df = geo_select_clinical_features(
116
+ clinical_df=clinical_data,
117
+ trait=trait,
118
+ trait_row=trait_row,
119
+ convert_trait=convert_trait,
120
+ age_row=age_row,
121
+ convert_age=convert_age,
122
+ gender_row=gender_row,
123
+ convert_gender=convert_gender
124
+ )
125
+ preview = preview_df(selected_clinical_df)
126
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
127
+ selected_clinical_df.to_csv(out_clinical_data_file)
128
+ preview # for inspection in the execution result
129
+
130
+ # Step 3: Gene Data Extraction
131
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
132
+ gene_data = get_genetic_data(matrix_file)
133
+
134
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
135
+ print(gene_data.index[:20])
136
+
137
+ # Step 4: Gene Identifier Review
138
+ print("requires_gene_mapping = True")
139
+
140
+ # Step 5: Gene Annotation
141
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
142
+ gene_annotation = get_gene_annotation(soft_file)
143
+
144
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
145
+ print("Gene annotation preview:")
146
+ print(preview_df(gene_annotation))
147
+
148
+ # Step 6: Gene Identifier Mapping
149
+ # Identify the appropriate columns for mapping
150
+ probe_col = 'ID' # Matches the probe IDs in the expression data
151
+ gene_symbol_col = 'gene_assignment' # Contains gene symbols within the annotation text
152
+
153
+ # Build the mapping DataFrame
154
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=probe_col, gene_col=gene_symbol_col)
155
+
156
+ # Apply mapping to convert probe-level data to gene-level expression
157
+ gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
158
+
159
+ # Step 7: Data Normalization and Linking
160
+ import os
161
+
162
+ # 1. Normalize gene symbols and save gene expression data
163
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
164
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
165
+ normalized_gene_data.to_csv(out_gene_data_file)
166
+
167
+ # 2-6. Handle two cases depending on clinical trait availability
168
+ trait_data_available = ("selected_clinical_data" in globals())
169
+
170
+ if trait_data_available and selected_clinical_data is not None:
171
+ # 2. Link clinical and genetic data
172
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_data, normalized_gene_data)
173
+
174
+ # 3. Handle missing values
175
+ linked_data = handle_missing_values(linked_data, trait)
176
+
177
+ # 4. Bias checking
178
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
179
+
180
+ # 5. Final validation and metadata save
181
+ is_usable = validate_and_save_cohort_info(
182
+ is_final=True,
183
+ cohort=cohort,
184
+ info_path=json_path,
185
+ is_gene_available=True,
186
+ is_trait_available=True,
187
+ is_biased=is_trait_biased,
188
+ df=unbiased_linked_data,
189
+ note="INFO: Clinical trait extracted; proceeded with full linking and QC."
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
+
197
+ else:
198
+ # Trait not available in this cohort; skip linking and record metadata
199
+ is_usable = validate_and_save_cohort_info(
200
+ is_final=True,
201
+ cohort=cohort,
202
+ info_path=json_path,
203
+ is_gene_available=True,
204
+ is_trait_available=False,
205
+ is_biased=False, # Dummy value since trait not available
206
+ df=normalized_gene_data,
207
+ note="INFO: Trait not available for this cohort (cell line study; no human-level labels). Gene data saved; linking skipped."
208
+ )
output/preprocess/Acute_Myeloid_Leukemia/code/TCGA.py ADDED
@@ -0,0 +1,267 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Acute_Myeloid_Leukemia"
6
+
7
+ # Input paths
8
+ tcga_root_dir = "../DATA/TCGA"
9
+
10
+ # Output paths
11
+ out_data_file = "./output/z1/preprocess/Acute_Myeloid_Leukemia/TCGA.csv"
12
+ out_gene_data_file = "./output/z1/preprocess/Acute_Myeloid_Leukemia/gene_data/TCGA.csv"
13
+ out_clinical_data_file = "./output/z1/preprocess/Acute_Myeloid_Leukemia/clinical_data/TCGA.csv"
14
+ json_path = "./output/z1/preprocess/Acute_Myeloid_Leukemia/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 Acute Myeloid Leukemia
22
+ subdirs = [d for d in os.listdir(tcga_root_dir) if os.path.isdir(os.path.join(tcga_root_dir, d))]
23
+ trait_terms = ["acute_myeloid_leukemia", "acute myeloid leukemia", "laml", "aml"]
24
+
25
+ def score_dir(name: str) -> int:
26
+ lname = name.lower()
27
+ score = 0
28
+ # Strong preference for exact trait name or TCGA code
29
+ if "acute_myeloid_leukemia" in lname:
30
+ score += 10
31
+ if "(laml)" in lname or lname.endswith("_laml)") or lname.startswith("tcga_") and "laml" in lname:
32
+ score += 8
33
+ # General matches
34
+ for t in trait_terms:
35
+ if t in lname:
36
+ score += 1
37
+ return score
38
+
39
+ scored = [(d, score_dir(d)) for d in subdirs]
40
+ scored.sort(key=lambda x: x[1], reverse=True)
41
+ selected_dir = scored[0][0] if scored and scored[0][1] > 0 else None
42
+
43
+ if selected_dir is None:
44
+ # No suitable directory found; record and stop further processing
45
+ validate_and_save_cohort_info(
46
+ is_final=False,
47
+ cohort="TCGA",
48
+ info_path=json_path,
49
+ is_gene_available=False,
50
+ is_trait_available=False
51
+ )
52
+ else:
53
+ cohort_dir = os.path.join(tcga_root_dir, selected_dir)
54
+
55
+ # Step 2: Identify clinical and genetic data file paths
56
+ clinical_file_path, genetic_file_path = tcga_get_relevant_filepaths(cohort_dir)
57
+
58
+ # Step 3: Load both files as DataFrames
59
+ clinical_df = pd.read_csv(clinical_file_path, sep='\t', index_col=0, low_memory=False)
60
+ genetic_df = pd.read_csv(genetic_file_path, sep='\t', index_col=0, low_memory=False)
61
+
62
+ # Step 4: Print clinical column names for further analysis
63
+ print(list(clinical_df.columns))
64
+
65
+ # Step 2: Find Candidate Demographic Features
66
+ # Determine the list of all columns from previous step or fallback options
67
+ try:
68
+ all_columns = list(clinical_df.columns)
69
+ except NameError:
70
+ all_columns = ['FISH_test_component', 'FISH_test_component_percentage_value', '_INTEGRATION', '_PANCAN_CNA_PANCAN_K8', '_PANCAN_Cluster_Cluster_PANCAN', '_PANCAN_DNAMethyl_LAML', '_PANCAN_DNAMethyl_PANCAN', '_PANCAN_UNC_RNAseq_PANCAN_K16', '_PANCAN_miRNA_PANCAN', '_PANCAN_mirna_LAML', '_PANCAN_mutation_PANCAN', '_PATIENT', '_cohort', '_primary_disease', '_primary_site', 'acute_myeloid_leukemia_calgb_cytogenetics_risk_category', 'age_at_initial_pathologic_diagnosis', 'atra_exposure', 'cumulative_agent_total_dose', 'cytogenetic_abnormality', 'cytogenetic_abnormality_other', 'cytogenetic_analysis_performed_ind', 'days_to_birth', 'days_to_death', 'days_to_initial_pathologic_diagnosis', 'days_to_last_followup', 'disease_detection_molecular_analysis_method_type', 'fish_evaluation_performed_ind', 'fluorescence_in_situ_hybrid_cytogenetics_metaphase_ncls_rslt_cnt', 'fluorescence_in_situ_hybridization_abnormal_result_indicator', 'form_completion_date', 'gender', 'history_of_neoadjuvant_treatment', 'hydroxyurea_administration_prior_registration_clinicl_stdy_ndctr', 'hydroxyurea_agent_administered_day_count', 'immunophenotype_cytochemistry_testing_result', 'informed_consent_verified', 'is_ffpe', 'lab_procedure_abnormal_lymphocyte_result_percent_value', 'lab_procedure_blast_cell_outcome_percentage_value', 'lab_procedure_bone_marrow_band_cell_result_percent_value', 'lab_procedure_bone_marrow_basophil_result_percent_value', 'lab_procedure_bone_marrow_blast_cell_outcome_percent_value', 'lab_procedure_bone_marrow_cellularity_outcome_percent_value', 'lab_procedure_bone_marrow_lymphocyte_outcome_percent_value', 'lab_procedure_bone_marrow_metamyelocyte_result_value', 'lab_procedure_bone_marrow_myelocyte_result_percent_value', 'lab_procedure_bone_marrow_neutrophil_result_percent_value', 'lab_procedure_bone_marrow_prolymphocyte_result_percent_value', 'lab_procedure_bone_marrow_promonocyte_count_result_percent_value', 'lab_procedure_bone_marrow_promyelocyte_result_percent_value', 'lab_procedure_hematocrit_outcome_percent_value', 'lab_procedure_hemoglobin_result_specified_value', 'lab_procedure_leukocyte_result_unspecified_value', 'lab_procedure_monocyte_result_percent_value', 'lab_procedure_platelet_result_specified_value', 'leukemia_french_american_british_morphology_code', 'leukemia_specimen_cell_source_type', 'molecular_analysis_abnormal_result_indicator', 'molecular_analysis_abnormality_testing_result', 'molecular_analysis_performed_indicator', 'patient_id', 'person_history_nonmedical_leukemia_causing_agent_type', 'prior_dx', 'prior_hematologic_disorder_diagnosis_indicator', 'sample_type', 'sample_type_id', 'steroid_therapy_administered', 'tissue_source_site', 'total_dose_units', 'tumor_tissue_site', 'vial_number', 'vital_status', 'year_of_initial_pathologic_diagnosis', '_GENOMIC_ID_TCGA_LAML_exp_HiSeqV2_PANCAN', '_GENOMIC_ID_TCGA_LAML_hMethyl27', '_GENOMIC_ID_TCGA_LAML_exp_HiSeqV2', '_GENOMIC_ID_TCGA_LAML_miRNA_GA', '_GENOMIC_ID_data/public/TCGA/LAML/miRNA_GA_gene', '_GENOMIC_ID_TCGA_LAML_exp_HiSeqV2_exon', '_GENOMIC_ID_TCGA_LAML_mutation_wustl_hiseq_gene', '_GENOMIC_ID_TCGA_LAML_exp_GA_exon', '_GENOMIC_ID_TCGA_LAML_gistic2', '_GENOMIC_ID_TCGA_LAML_exp_GA', '_GENOMIC_ID_TCGA_LAML_hMethyl450', '_GENOMIC_ID_TCGA_LAML_mutation', '_GENOMIC_ID_TCGA_LAML_PDMRNAseq', '_GENOMIC_ID_TCGA_LAML_PDMRNAseqCNV', '_GENOMIC_ID_TCGA_LAML_gistic2thd', '_GENOMIC_ID_TCGA_LAML_exp_HiSeqV2_percentile', '_GENOMIC_ID_TCGA_LAML_mutation_wustl_gene']
71
+
72
+ # Identify candidate columns
73
+ candidate_age_cols = []
74
+ candidate_gender_cols = []
75
+
76
+ for col in all_columns:
77
+ name = col.lower()
78
+ tokens = name.split('_')
79
+ # Age candidates: token 'age' or starts with 'age', and known alias 'days_to_birth'
80
+ if ('age' in tokens) or name.startswith('age') or (name == 'days_to_birth'):
81
+ candidate_age_cols.append(col)
82
+ # Gender candidates: token 'gender' or 'sex'
83
+ if ('gender' in tokens) or (name == 'sex'):
84
+ candidate_gender_cols.append(col)
85
+
86
+ print(f"candidate_age_cols = {candidate_age_cols}")
87
+ print(f"candidate_gender_cols = {candidate_gender_cols}")
88
+
89
+ # Extract and preview if clinical_df is available
90
+ if 'clinical_df' in globals():
91
+ age_present = [c for c in candidate_age_cols if c in clinical_df.columns]
92
+ gender_present = [c for c in candidate_gender_cols if c in clinical_df.columns]
93
+
94
+ if age_present:
95
+ print(preview_df(clinical_df[age_present], n=5))
96
+ if gender_present:
97
+ print(preview_df(clinical_df[gender_present], n=5))
98
+
99
+ # Step 3: Select Demographic Features
100
+ # Select columns based on candidate lists and typical TCGA conventions
101
+ age_col = None
102
+ gender_col = None
103
+
104
+ # Prefer age in years if available; otherwise fall back to days_to_birth
105
+ if 'candidate_age_cols' in globals() and isinstance(candidate_age_cols, (list, tuple)):
106
+ if 'age_at_initial_pathologic_diagnosis' in candidate_age_cols:
107
+ age_col = 'age_at_initial_pathologic_diagnosis'
108
+ elif 'age' in candidate_age_cols:
109
+ age_col = 'age'
110
+ elif 'days_to_birth' in candidate_age_cols:
111
+ age_col = 'days_to_birth'
112
+ else:
113
+ # As a fallback, choose the column with the least missingness (if clinical_df is available)
114
+ if 'clinical_df' in globals():
115
+ best_col, best_non_null = None, -1.0
116
+ for c in candidate_age_cols:
117
+ if c in clinical_df.columns:
118
+ non_null_ratio = float(clinical_df[c].notna().mean())
119
+ if non_null_ratio > best_non_null:
120
+ best_col, best_non_null = c, non_null_ratio
121
+ # Require at least some reasonable data availability
122
+ age_col = best_col if best_non_null >= 0.5 else None
123
+
124
+ # Prefer 'gender'; otherwise fall back to 'sex' if present
125
+ if 'candidate_gender_cols' in globals() and isinstance(candidate_gender_cols, (list, tuple)):
126
+ if 'gender' in candidate_gender_cols:
127
+ gender_col = 'gender'
128
+ elif 'sex' in candidate_gender_cols:
129
+ gender_col = 'sex'
130
+ else:
131
+ # Fallback based on least missingness (if clinical_df is available)
132
+ if 'clinical_df' in globals():
133
+ best_col, best_non_null = None, -1.0
134
+ for c in candidate_gender_cols:
135
+ if c in clinical_df.columns:
136
+ non_null_ratio = float(clinical_df[c].notna().mean())
137
+ if non_null_ratio > best_non_null:
138
+ best_col, best_non_null = c, non_null_ratio
139
+ gender_col = best_col if best_non_null >= 0.5 else None
140
+
141
+ # Explicitly print chosen columns
142
+ print(f"Selected age_col: {age_col}")
143
+ print(f"Selected gender_col: {gender_col}")
144
+
145
+ # Additionally, print brief info (first 5 values and missingness) if clinical_df is available
146
+ if 'clinical_df' in globals():
147
+ if age_col is not None and age_col in clinical_df.columns:
148
+ age_vals = clinical_df[age_col].head(5).tolist()
149
+ age_missing_ratio = float(clinical_df[age_col].isna().mean())
150
+ print("age_col preview (first 5):", age_vals)
151
+ print("age_col missing ratio:", age_missing_ratio)
152
+ if gender_col is not None and gender_col in clinical_df.columns:
153
+ gender_vals = clinical_df[gender_col].head(5).tolist()
154
+ gender_missing_ratio = float(clinical_df[gender_col].isna().mean())
155
+ print("gender_col preview (first 5):", gender_vals)
156
+ print("gender_col missing ratio:", gender_missing_ratio)
157
+
158
+ # Step 4: Feature Engineering and Validation
159
+ import os
160
+ import json
161
+
162
+ # 1) Extract and standardize clinical features (trait, Age, Gender)
163
+ selected_clinical_df = tcga_select_clinical_features(
164
+ clinical_df=clinical_df,
165
+ trait=trait,
166
+ age_col=age_col,
167
+ gender_col=gender_col
168
+ )
169
+
170
+ # 2) Normalize gene symbols, drop unrecognized, aggregate duplicates, save normalized gene data
171
+ gene_df = genetic_df.copy()
172
+ gene_df_norm = normalize_gene_symbols_in_index(gene_df)
173
+
174
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
175
+ gene_df_norm.to_csv(out_gene_data_file)
176
+
177
+ # 3) Link clinical and genetic data on sample IDs
178
+ linked_data = pd.concat([selected_clinical_df, gene_df_norm.T], axis=1, join='inner')
179
+
180
+ # 4) Handle missing values systematically
181
+ processed_df = handle_missing_values(linked_data, trait_col=trait)
182
+
183
+ # 5) Determine bias of trait and remove biased demographic features
184
+ is_biased, processed_df = judge_and_remove_biased_features(processed_df, trait=trait)
185
+
186
+ # 6) Final validation and save cohort info
187
+ # Coerce to plain Python types to avoid JSON serialization issues
188
+ is_gene_available = bool((gene_df_norm.shape[0] > 0) and (gene_df_norm.shape[1] > 0))
189
+ is_trait_available = bool(selected_clinical_df[trait].notna().any())
190
+ is_biased_bool = bool(is_biased)
191
+
192
+ # Optional note: summarize class distribution if available
193
+ note = ""
194
+ if trait in processed_df.columns:
195
+ counts = processed_df[trait].value_counts(dropna=True).to_dict()
196
+ note = f"INFO: Trait distribution after preprocessing: {counts}. Cohort: TCGA LAML. "
197
+
198
+ # Try the library function first
199
+ is_usable = None
200
+ try:
201
+ is_usable = validate_and_save_cohort_info(
202
+ is_final=True,
203
+ cohort="TCGA",
204
+ info_path=json_path,
205
+ is_gene_available=is_gene_available,
206
+ is_trait_available=is_trait_available,
207
+ is_biased=is_biased_bool,
208
+ df=processed_df,
209
+ note=note
210
+ )
211
+ except Exception as e:
212
+ # Fallback: mirror the library's final validation logic and write JSON safely
213
+ print(f"validate_and_save_cohort_info failed with error: {e}. Falling back to safe writer.")
214
+
215
+ _is_gene_available = bool(is_gene_available)
216
+ _is_trait_available = bool(is_trait_available)
217
+
218
+ # Detect abnormality in data and override indicators (mirror library logic)
219
+ if (processed_df is None) or (is_biased is None):
220
+ raise ValueError("For final data validation, 'df' and 'is_biased' must be provided.")
221
+ if len(processed_df) <= 0 or len(processed_df.columns) <= 4:
222
+ print(f"Abnormality detected in the cohort: TCGA. Preprocessing failed.")
223
+ _is_gene_available = False
224
+ if len(processed_df) <= 0:
225
+ _is_trait_available = False
226
+
227
+ _is_available = bool(_is_gene_available and _is_trait_available)
228
+ is_usable = bool(_is_available and (is_biased_bool is False))
229
+
230
+ new_record = {
231
+ "is_usable": bool(is_usable),
232
+ "is_gene_available": bool(_is_gene_available),
233
+ "is_trait_available": bool(_is_trait_available),
234
+ "is_available": bool(_is_available),
235
+ "is_biased": (bool(is_biased_bool) if _is_available else None),
236
+ "has_age": (bool("Age" in processed_df.columns) if _is_available else None),
237
+ "has_gender": (bool("Gender" in processed_df.columns) if _is_available else None),
238
+ "sample_size": (int(len(processed_df)) if _is_available else None),
239
+ "note": str(note) if note is not None else None
240
+ }
241
+
242
+ trait_directory = os.path.dirname(json_path)
243
+ os.makedirs(trait_directory, exist_ok=True)
244
+ if not os.path.exists(json_path):
245
+ with open(json_path, 'w') as file:
246
+ json.dump({}, file)
247
+ print(f"A new JSON file was created at: {json_path}")
248
+
249
+ with open(json_path, "r") as file:
250
+ records = json.load(file)
251
+ records["TCGA"] = new_record
252
+
253
+ temp_path = json_path + ".tmp"
254
+ try:
255
+ with open(temp_path, 'w') as file:
256
+ json.dump(records, file, default=str)
257
+ os.replace(temp_path, json_path)
258
+ except Exception as e2:
259
+ print(f"Safe writer also failed: {e2}")
260
+ if os.path.exists(temp_path):
261
+ os.remove(temp_path)
262
+ raise
263
+
264
+ # 7) Save linked data only if usable
265
+ if is_usable:
266
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
267
+ processed_df.to_csv(out_data_file)
output/preprocess/Acute_Myeloid_Leukemia/cohort_info.json CHANGED
@@ -1,112 +1 @@
1
- {
2
- "GSE99612": {
3
- "is_usable": false,
4
- "is_gene_available": false,
5
- "is_trait_available": false,
6
- "is_available": false,
7
- "is_biased": null,
8
- "has_age": null,
9
- "has_gender": null,
10
- "sample_size": null
11
- },
12
- "GSE98578": {
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": 48
21
- },
22
- "GSE249638": {
23
- "is_usable": true,
24
- "is_gene_available": true,
25
- "is_trait_available": true,
26
- "is_available": true,
27
- "is_biased": false,
28
- "has_age": false,
29
- "has_gender": false,
30
- "sample_size": 37
31
- },
32
- "GSE235070": {
33
- "is_usable": false,
34
- "is_gene_available": true,
35
- "is_trait_available": true,
36
- "is_available": true,
37
- "is_biased": true,
38
- "has_age": false,
39
- "has_gender": false,
40
- "sample_size": 32
41
- },
42
- "GSE222616": {
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": 42
51
- },
52
- "GSE222169": {
53
- "is_usable": false,
54
- "is_gene_available": false,
55
- "is_trait_available": false,
56
- "is_available": false,
57
- "is_biased": null,
58
- "has_age": null,
59
- "has_gender": null,
60
- "sample_size": null
61
- },
62
- "GSE222124": {
63
- "is_usable": true,
64
- "is_gene_available": true,
65
- "is_trait_available": true,
66
- "is_available": true,
67
- "is_biased": false,
68
- "has_age": false,
69
- "has_gender": false,
70
- "sample_size": 70
71
- },
72
- "GSE161532": {
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": true,
80
- "sample_size": 61
81
- },
82
- "GSE121431": {
83
- "is_usable": false,
84
- "is_gene_available": true,
85
- "is_trait_available": true,
86
- "is_available": true,
87
- "is_biased": true,
88
- "has_age": false,
89
- "has_gender": false,
90
- "sample_size": 30
91
- },
92
- "GSE121291": {
93
- "is_usable": false,
94
- "is_gene_available": true,
95
- "is_trait_available": true,
96
- "is_available": true,
97
- "is_biased": true,
98
- "has_age": false,
99
- "has_gender": false,
100
- "sample_size": 30
101
- },
102
- "TCGA": {
103
- "is_usable": false,
104
- "is_gene_available": true,
105
- "is_trait_available": true,
106
- "is_available": true,
107
- "is_biased": true,
108
- "has_age": true,
109
- "has_gender": true,
110
- "sample_size": 173
111
- }
112
- }
 
1
+ {"GSE99612": {"is_usable": false, "is_gene_available": true, "is_trait_available": false, "is_available": false, "is_biased": null, "has_age": null, "has_gender": null, "sample_size": null, "note": "INFO: Trait not available for this cohort (cell line study; no human-level labels). Gene data saved; linking skipped."}, "GSE98578": {"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}, "GSE249638": {"is_usable": true, "is_gene_available": true, "is_trait_available": true, "is_available": true, "is_biased": false, "has_age": false, "has_gender": false, "sample_size": 37, "note": "INFO: Only trait available; Age and Gender not provided in sample characteristics."}, "GSE235070": {"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}, "GSE222616": {"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}, "GSE222169": {"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}, "GSE222124": {"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": 70, "note": "INFO: Cell-line study (Jurkat/THP1/KHYG-1) treated with glycodelin; trait inferred from cell type; no age/gender available."}, "GSE161532": {"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 is constant/unavailable for this cohort; only gene data was processed and saved."}, "GSE121431": {"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}, "GSE121291": {"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": true, "sample_size": 173, "note": "INFO: Trait distribution after preprocessing: {1: 173}. Cohort: TCGA LAML. "}}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
output/preprocess/Adrenocortical_Cancer/clinical_data/GSE68950.csv CHANGED
@@ -1,2 +1,2 @@
1
  ,GSM1687570,GSM1687571,GSM1687572,GSM1687573,GSM1687574,GSM1687575,GSM1687576,GSM1687577,GSM1687578,GSM1687579,GSM1687580,GSM1687581,GSM1687582,GSM1687583,GSM1687584,GSM1687585,GSM1687586,GSM1687587,GSM1687588,GSM1687589,GSM1687590,GSM1687591,GSM1687592,GSM1687593,GSM1687594,GSM1687595,GSM1687596,GSM1687597,GSM1687598,GSM1687599,GSM1687600,GSM1687601,GSM1687602,GSM1687603,GSM1687604,GSM1687605,GSM1687606,GSM1687607,GSM1687608,GSM1687609,GSM1687610,GSM1687611,GSM1687612,GSM1687613,GSM1687614,GSM1687615,GSM1687616,GSM1687617,GSM1687618,GSM1687619,GSM1687620,GSM1687621,GSM1687622,GSM1687623,GSM1687624,GSM1687625,GSM1687626,GSM1687627,GSM1687628,GSM1687629,GSM1687630,GSM1687631,GSM1687632,GSM1687633,GSM1687634,GSM1687635,GSM1687636,GSM1687637,GSM1687638,GSM1687639,GSM1687640,GSM1687641,GSM1687642,GSM1687643,GSM1687644,GSM1687645,GSM1687646,GSM1687647,GSM1687648,GSM1687649,GSM1687650,GSM1687651,GSM1687652,GSM1687653,GSM1687654,GSM1687655,GSM1687656,GSM1687657,GSM1687658,GSM1687659,GSM1687660,GSM1687661,GSM1687662,GSM1687663,GSM1687664,GSM1687665,GSM1687666,GSM1687667,GSM1687668,GSM1687669,GSM1687670,GSM1687671,GSM1687672,GSM1687673,GSM1687674,GSM1687675,GSM1687676,GSM1687677,GSM1687678,GSM1687679,GSM1687680,GSM1687681,GSM1687682,GSM1687683,GSM1687684,GSM1687685,GSM1687686,GSM1687687,GSM1687688,GSM1687689,GSM1687690,GSM1687691,GSM1687692,GSM1687693,GSM1687694,GSM1687695,GSM1687696,GSM1687697,GSM1687698,GSM1687699,GSM1687700,GSM1687701,GSM1687702,GSM1687703,GSM1687704,GSM1687705,GSM1687706,GSM1687707,GSM1687708,GSM1687709,GSM1687710,GSM1687711,GSM1687712,GSM1687713,GSM1687714,GSM1687715,GSM1687716,GSM1687717,GSM1687718,GSM1687719,GSM1687720,GSM1687721,GSM1687722,GSM1687723,GSM1687724,GSM1687725,GSM1687726,GSM1687727,GSM1687728,GSM1687729,GSM1687730,GSM1687731,GSM1687732,GSM1687733,GSM1687734,GSM1687735,GSM1687736,GSM1687737,GSM1687738,GSM1687739,GSM1687740,GSM1687741,GSM1687742,GSM1687743,GSM1687744,GSM1687745,GSM1687746,GSM1687747,GSM1687748,GSM1687749,GSM1687750,GSM1687751,GSM1687752,GSM1687753,GSM1687754,GSM1687755,GSM1687756,GSM1687757,GSM1687758,GSM1687759,GSM1687760,GSM1687761,GSM1687762,GSM1687763,GSM1687764,GSM1687765,GSM1687766,GSM1687767,GSM1687768,GSM1687769,GSM1687770,GSM1687771,GSM1687772,GSM1687773,GSM1687774,GSM1687775,GSM1687776,GSM1687777,GSM1687778,GSM1687779,GSM1687780,GSM1687781,GSM1687782,GSM1687783,GSM1687784,GSM1687785,GSM1687786,GSM1687787,GSM1687788,GSM1687789,GSM1687790,GSM1687791,GSM1687792,GSM1687793,GSM1687794,GSM1687795,GSM1687796,GSM1687797,GSM1687798,GSM1687799,GSM1687800,GSM1687801,GSM1687802,GSM1687803,GSM1687804,GSM1687805,GSM1687806,GSM1687807,GSM1687808,GSM1687809,GSM1687810,GSM1687811,GSM1687812,GSM1687813,GSM1687814,GSM1687815,GSM1687816,GSM1687817,GSM1687818,GSM1687819,GSM1687820,GSM1687821,GSM1687822,GSM1687823,GSM1687824,GSM1687825,GSM1687826,GSM1687827,GSM1687828,GSM1687829,GSM1687830,GSM1687831,GSM1687832,GSM1687833,GSM1687834,GSM1687835,GSM1687836,GSM1687837,GSM1687838,GSM1687839,GSM1687840,GSM1687841,GSM1687842,GSM1687843,GSM1687844,GSM1687845,GSM1687846,GSM1687847,GSM1687848,GSM1687849,GSM1687850,GSM1687851,GSM1687852,GSM1687853,GSM1687854,GSM1687855,GSM1687856,GSM1687857,GSM1687858,GSM1687859,GSM1687860,GSM1687861,GSM1687862,GSM1687863,GSM1687864,GSM1687865,GSM1687866,GSM1687867,GSM1687868,GSM1687869,GSM1687870,GSM1687871,GSM1687872,GSM1687873,GSM1687874,GSM1687875,GSM1687876,GSM1687877,GSM1687878,GSM1687879,GSM1687880,GSM1687881,GSM1687882,GSM1687883,GSM1687884,GSM1687885,GSM1687886,GSM1687887,GSM1687888,GSM1687889,GSM1687890,GSM1687891,GSM1687892,GSM1687893,GSM1687894,GSM1687895,GSM1687896,GSM1687897,GSM1687898,GSM1687899,GSM1687900,GSM1687901,GSM1687902,GSM1687903,GSM1687904,GSM1687905,GSM1687906,GSM1687907,GSM1687908,GSM1687909,GSM1687910,GSM1687911,GSM1687912,GSM1687913,GSM1687914,GSM1687915,GSM1687916,GSM1687917,GSM1687918,GSM1687919,GSM1687920,GSM1687921,GSM1687922,GSM1687923,GSM1687924,GSM1687925,GSM1687926,GSM1687927,GSM1687928,GSM1687929,GSM1687930,GSM1687931,GSM1687932,GSM1687933,GSM1687934,GSM1687935,GSM1687936,GSM1687937,GSM1687938,GSM1687939,GSM1687940,GSM1687941,GSM1687942,GSM1687943,GSM1687944,GSM1687945,GSM1687946,GSM1687947,GSM1687948,GSM1687949,GSM1687950,GSM1687951,GSM1687952,GSM1687953,GSM1687954,GSM1687955,GSM1687956,GSM1687957,GSM1687958,GSM1687959,GSM1687960,GSM1687961,GSM1687962,GSM1687963,GSM1687964,GSM1687965,GSM1687966,GSM1687967,GSM1687968,GSM1687969,GSM1687970,GSM1687971,GSM1687972,GSM1687973,GSM1687974,GSM1687975,GSM1687976,GSM1687977,GSM1687978,GSM1687979,GSM1687980,GSM1687981,GSM1687982,GSM1687983,GSM1687984,GSM1687985,GSM1687986,GSM1687987,GSM1687988,GSM1687989,GSM1687990,GSM1687991,GSM1687992,GSM1687993,GSM1687994,GSM1687995,GSM1687996,GSM1687997,GSM1687998,GSM1687999,GSM1688000,GSM1688001,GSM1688002,GSM1688003,GSM1688004,GSM1688005,GSM1688006,GSM1688007,GSM1688008,GSM1688009,GSM1688010,GSM1688011,GSM1688012,GSM1688013,GSM1688014,GSM1688015,GSM1688016,GSM1688017,GSM1688018,GSM1688019,GSM1688020,GSM1688021,GSM1688022,GSM1688023,GSM1688024,GSM1688025,GSM1688026,GSM1688027,GSM1688028,GSM1688029,GSM1688030,GSM1688031,GSM1688032,GSM1688033,GSM1688034,GSM1688035,GSM1688036,GSM1688037,GSM1688038,GSM1688039,GSM1688040,GSM1688041,GSM1688042,GSM1688043,GSM1688044,GSM1688045,GSM1688046,GSM1688047,GSM1688048,GSM1688049,GSM1688050,GSM1688051,GSM1688052,GSM1688053,GSM1688054,GSM1688055,GSM1688056,GSM1688057,GSM1688058,GSM1688059,GSM1688060,GSM1688061,GSM1688062,GSM1688063,GSM1688064,GSM1688065,GSM1688066,GSM1688067,GSM1688068,GSM1688069,GSM1688070,GSM1688071,GSM1688072,GSM1688073,GSM1688074,GSM1688075,GSM1688076,GSM1688077,GSM1688078,GSM1688079,GSM1688080,GSM1688081,GSM1688082,GSM1688083,GSM1688084,GSM1688085,GSM1688086,GSM1688087,GSM1688088,GSM1688089,GSM1688090,GSM1688091,GSM1688092,GSM1688093,GSM1688094,GSM1688095,GSM1688096,GSM1688097,GSM1688098,GSM1688099,GSM1688100,GSM1688101,GSM1688102,GSM1688103,GSM1688104,GSM1688105,GSM1688106,GSM1688107,GSM1688108,GSM1688109,GSM1688110,GSM1688111,GSM1688112,GSM1688113,GSM1688114,GSM1688115,GSM1688116,GSM1688117,GSM1688118,GSM1688119,GSM1688120,GSM1688121,GSM1688122,GSM1688123,GSM1688124,GSM1688125,GSM1688126,GSM1688127,GSM1688128,GSM1688129,GSM1688130,GSM1688131,GSM1688132,GSM1688133,GSM1688134,GSM1688135,GSM1688136,GSM1688137,GSM1688138,GSM1688139,GSM1688140,GSM1688141,GSM1688142,GSM1688143,GSM1688144,GSM1688145,GSM1688146,GSM1688147,GSM1688148,GSM1688149,GSM1688150,GSM1688151,GSM1688152,GSM1688153,GSM1688154,GSM1688155,GSM1688156,GSM1688157,GSM1688158,GSM1688159,GSM1688160,GSM1688161,GSM1688162,GSM1688163,GSM1688164,GSM1688165,GSM1688166,GSM1688167,GSM1688168,GSM1688169,GSM1688170,GSM1688171,GSM1688172,GSM1688173,GSM1688174,GSM1688175,GSM1688176,GSM1688177,GSM1688178,GSM1688179,GSM1688180,GSM1688181,GSM1688182,GSM1688183,GSM1688184,GSM1688185,GSM1688186,GSM1688187,GSM1688188,GSM1688189,GSM1688190,GSM1688191,GSM1688192,GSM1688193,GSM1688194,GSM1688195,GSM1688196,GSM1688197,GSM1688198,GSM1688199,GSM1688200,GSM1688201,GSM1688202,GSM1688203,GSM1688204,GSM1688205,GSM1688206,GSM1688207,GSM1688208,GSM1688209,GSM1688210,GSM1688211,GSM1688212,GSM1688213,GSM1688214,GSM1688215,GSM1688216,GSM1688217,GSM1688218,GSM1688219,GSM1688220,GSM1688221,GSM1688222,GSM1688223,GSM1688224,GSM1688225,GSM1688226,GSM1688227,GSM1688228,GSM1688229,GSM1688230,GSM1688231,GSM1688232,GSM1688233,GSM1688234,GSM1688235,GSM1688236,GSM1688237,GSM1688238,GSM1688239,GSM1688240,GSM1688241,GSM1688242,GSM1688243,GSM1688244,GSM1688245,GSM1688246,GSM1688247,GSM1688248,GSM1688249,GSM1688250,GSM1688251,GSM1688252,GSM1688253,GSM1688254,GSM1688255,GSM1688256,GSM1688257,GSM1688258,GSM1688259,GSM1688260,GSM1688261,GSM1688262,GSM1688263,GSM1688264,GSM1688265,GSM1688266,GSM1688267,GSM1688268,GSM1688269,GSM1688270,GSM1688271,GSM1688272,GSM1688273,GSM1688274,GSM1688275,GSM1688276,GSM1688277,GSM1688278,GSM1688279,GSM1688280,GSM1688281,GSM1688282,GSM1688283,GSM1688284,GSM1688285,GSM1688286,GSM1688287,GSM1688288,GSM1688289,GSM1688290,GSM1688291,GSM1688292,GSM1688293,GSM1688294,GSM1688295,GSM1688296,GSM1688297,GSM1688298,GSM1688299,GSM1688300,GSM1688301,GSM1688302,GSM1688303,GSM1688304,GSM1688305,GSM1688306,GSM1688307,GSM1688308,GSM1688309,GSM1688310,GSM1688311,GSM1688312,GSM1688313,GSM1688314,GSM1688315,GSM1688316,GSM1688317,GSM1688318,GSM1688319,GSM1688320,GSM1688321,GSM1688322,GSM1688323,GSM1688324,GSM1688325,GSM1688326,GSM1688327,GSM1688328,GSM1688329,GSM1688330,GSM1688331,GSM1688332,GSM1688333,GSM1688334,GSM1688335,GSM1688336,GSM1688337,GSM1688338,GSM1688339,GSM1688340,GSM1688341,GSM1688342,GSM1688343,GSM1688344,GSM1688345,GSM1688346,GSM1688347,GSM1688348,GSM1688349,GSM1688350,GSM1688351,GSM1688352,GSM1688353,GSM1688354,GSM1688355,GSM1688356,GSM1688357,GSM1688358,GSM1688359,GSM1688360,GSM1688361,GSM1688362,GSM1688363,GSM1688364,GSM1688365,GSM1688366,GSM1688367
2
- Adrenocortical_Cancer,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
 
1
  ,GSM1687570,GSM1687571,GSM1687572,GSM1687573,GSM1687574,GSM1687575,GSM1687576,GSM1687577,GSM1687578,GSM1687579,GSM1687580,GSM1687581,GSM1687582,GSM1687583,GSM1687584,GSM1687585,GSM1687586,GSM1687587,GSM1687588,GSM1687589,GSM1687590,GSM1687591,GSM1687592,GSM1687593,GSM1687594,GSM1687595,GSM1687596,GSM1687597,GSM1687598,GSM1687599,GSM1687600,GSM1687601,GSM1687602,GSM1687603,GSM1687604,GSM1687605,GSM1687606,GSM1687607,GSM1687608,GSM1687609,GSM1687610,GSM1687611,GSM1687612,GSM1687613,GSM1687614,GSM1687615,GSM1687616,GSM1687617,GSM1687618,GSM1687619,GSM1687620,GSM1687621,GSM1687622,GSM1687623,GSM1687624,GSM1687625,GSM1687626,GSM1687627,GSM1687628,GSM1687629,GSM1687630,GSM1687631,GSM1687632,GSM1687633,GSM1687634,GSM1687635,GSM1687636,GSM1687637,GSM1687638,GSM1687639,GSM1687640,GSM1687641,GSM1687642,GSM1687643,GSM1687644,GSM1687645,GSM1687646,GSM1687647,GSM1687648,GSM1687649,GSM1687650,GSM1687651,GSM1687652,GSM1687653,GSM1687654,GSM1687655,GSM1687656,GSM1687657,GSM1687658,GSM1687659,GSM1687660,GSM1687661,GSM1687662,GSM1687663,GSM1687664,GSM1687665,GSM1687666,GSM1687667,GSM1687668,GSM1687669,GSM1687670,GSM1687671,GSM1687672,GSM1687673,GSM1687674,GSM1687675,GSM1687676,GSM1687677,GSM1687678,GSM1687679,GSM1687680,GSM1687681,GSM1687682,GSM1687683,GSM1687684,GSM1687685,GSM1687686,GSM1687687,GSM1687688,GSM1687689,GSM1687690,GSM1687691,GSM1687692,GSM1687693,GSM1687694,GSM1687695,GSM1687696,GSM1687697,GSM1687698,GSM1687699,GSM1687700,GSM1687701,GSM1687702,GSM1687703,GSM1687704,GSM1687705,GSM1687706,GSM1687707,GSM1687708,GSM1687709,GSM1687710,GSM1687711,GSM1687712,GSM1687713,GSM1687714,GSM1687715,GSM1687716,GSM1687717,GSM1687718,GSM1687719,GSM1687720,GSM1687721,GSM1687722,GSM1687723,GSM1687724,GSM1687725,GSM1687726,GSM1687727,GSM1687728,GSM1687729,GSM1687730,GSM1687731,GSM1687732,GSM1687733,GSM1687734,GSM1687735,GSM1687736,GSM1687737,GSM1687738,GSM1687739,GSM1687740,GSM1687741,GSM1687742,GSM1687743,GSM1687744,GSM1687745,GSM1687746,GSM1687747,GSM1687748,GSM1687749,GSM1687750,GSM1687751,GSM1687752,GSM1687753,GSM1687754,GSM1687755,GSM1687756,GSM1687757,GSM1687758,GSM1687759,GSM1687760,GSM1687761,GSM1687762,GSM1687763,GSM1687764,GSM1687765,GSM1687766,GSM1687767,GSM1687768,GSM1687769,GSM1687770,GSM1687771,GSM1687772,GSM1687773,GSM1687774,GSM1687775,GSM1687776,GSM1687777,GSM1687778,GSM1687779,GSM1687780,GSM1687781,GSM1687782,GSM1687783,GSM1687784,GSM1687785,GSM1687786,GSM1687787,GSM1687788,GSM1687789,GSM1687790,GSM1687791,GSM1687792,GSM1687793,GSM1687794,GSM1687795,GSM1687796,GSM1687797,GSM1687798,GSM1687799,GSM1687800,GSM1687801,GSM1687802,GSM1687803,GSM1687804,GSM1687805,GSM1687806,GSM1687807,GSM1687808,GSM1687809,GSM1687810,GSM1687811,GSM1687812,GSM1687813,GSM1687814,GSM1687815,GSM1687816,GSM1687817,GSM1687818,GSM1687819,GSM1687820,GSM1687821,GSM1687822,GSM1687823,GSM1687824,GSM1687825,GSM1687826,GSM1687827,GSM1687828,GSM1687829,GSM1687830,GSM1687831,GSM1687832,GSM1687833,GSM1687834,GSM1687835,GSM1687836,GSM1687837,GSM1687838,GSM1687839,GSM1687840,GSM1687841,GSM1687842,GSM1687843,GSM1687844,GSM1687845,GSM1687846,GSM1687847,GSM1687848,GSM1687849,GSM1687850,GSM1687851,GSM1687852,GSM1687853,GSM1687854,GSM1687855,GSM1687856,GSM1687857,GSM1687858,GSM1687859,GSM1687860,GSM1687861,GSM1687862,GSM1687863,GSM1687864,GSM1687865,GSM1687866,GSM1687867,GSM1687868,GSM1687869,GSM1687870,GSM1687871,GSM1687872,GSM1687873,GSM1687874,GSM1687875,GSM1687876,GSM1687877,GSM1687878,GSM1687879,GSM1687880,GSM1687881,GSM1687882,GSM1687883,GSM1687884,GSM1687885,GSM1687886,GSM1687887,GSM1687888,GSM1687889,GSM1687890,GSM1687891,GSM1687892,GSM1687893,GSM1687894,GSM1687895,GSM1687896,GSM1687897,GSM1687898,GSM1687899,GSM1687900,GSM1687901,GSM1687902,GSM1687903,GSM1687904,GSM1687905,GSM1687906,GSM1687907,GSM1687908,GSM1687909,GSM1687910,GSM1687911,GSM1687912,GSM1687913,GSM1687914,GSM1687915,GSM1687916,GSM1687917,GSM1687918,GSM1687919,GSM1687920,GSM1687921,GSM1687922,GSM1687923,GSM1687924,GSM1687925,GSM1687926,GSM1687927,GSM1687928,GSM1687929,GSM1687930,GSM1687931,GSM1687932,GSM1687933,GSM1687934,GSM1687935,GSM1687936,GSM1687937,GSM1687938,GSM1687939,GSM1687940,GSM1687941,GSM1687942,GSM1687943,GSM1687944,GSM1687945,GSM1687946,GSM1687947,GSM1687948,GSM1687949,GSM1687950,GSM1687951,GSM1687952,GSM1687953,GSM1687954,GSM1687955,GSM1687956,GSM1687957,GSM1687958,GSM1687959,GSM1687960,GSM1687961,GSM1687962,GSM1687963,GSM1687964,GSM1687965,GSM1687966,GSM1687967,GSM1687968,GSM1687969,GSM1687970,GSM1687971,GSM1687972,GSM1687973,GSM1687974,GSM1687975,GSM1687976,GSM1687977,GSM1687978,GSM1687979,GSM1687980,GSM1687981,GSM1687982,GSM1687983,GSM1687984,GSM1687985,GSM1687986,GSM1687987,GSM1687988,GSM1687989,GSM1687990,GSM1687991,GSM1687992,GSM1687993,GSM1687994,GSM1687995,GSM1687996,GSM1687997,GSM1687998,GSM1687999,GSM1688000,GSM1688001,GSM1688002,GSM1688003,GSM1688004,GSM1688005,GSM1688006,GSM1688007,GSM1688008,GSM1688009,GSM1688010,GSM1688011,GSM1688012,GSM1688013,GSM1688014,GSM1688015,GSM1688016,GSM1688017,GSM1688018,GSM1688019,GSM1688020,GSM1688021,GSM1688022,GSM1688023,GSM1688024,GSM1688025,GSM1688026,GSM1688027,GSM1688028,GSM1688029,GSM1688030,GSM1688031,GSM1688032,GSM1688033,GSM1688034,GSM1688035,GSM1688036,GSM1688037,GSM1688038,GSM1688039,GSM1688040,GSM1688041,GSM1688042,GSM1688043,GSM1688044,GSM1688045,GSM1688046,GSM1688047,GSM1688048,GSM1688049,GSM1688050,GSM1688051,GSM1688052,GSM1688053,GSM1688054,GSM1688055,GSM1688056,GSM1688057,GSM1688058,GSM1688059,GSM1688060,GSM1688061,GSM1688062,GSM1688063,GSM1688064,GSM1688065,GSM1688066,GSM1688067,GSM1688068,GSM1688069,GSM1688070,GSM1688071,GSM1688072,GSM1688073,GSM1688074,GSM1688075,GSM1688076,GSM1688077,GSM1688078,GSM1688079,GSM1688080,GSM1688081,GSM1688082,GSM1688083,GSM1688084,GSM1688085,GSM1688086,GSM1688087,GSM1688088,GSM1688089,GSM1688090,GSM1688091,GSM1688092,GSM1688093,GSM1688094,GSM1688095,GSM1688096,GSM1688097,GSM1688098,GSM1688099,GSM1688100,GSM1688101,GSM1688102,GSM1688103,GSM1688104,GSM1688105,GSM1688106,GSM1688107,GSM1688108,GSM1688109,GSM1688110,GSM1688111,GSM1688112,GSM1688113,GSM1688114,GSM1688115,GSM1688116,GSM1688117,GSM1688118,GSM1688119,GSM1688120,GSM1688121,GSM1688122,GSM1688123,GSM1688124,GSM1688125,GSM1688126,GSM1688127,GSM1688128,GSM1688129,GSM1688130,GSM1688131,GSM1688132,GSM1688133,GSM1688134,GSM1688135,GSM1688136,GSM1688137,GSM1688138,GSM1688139,GSM1688140,GSM1688141,GSM1688142,GSM1688143,GSM1688144,GSM1688145,GSM1688146,GSM1688147,GSM1688148,GSM1688149,GSM1688150,GSM1688151,GSM1688152,GSM1688153,GSM1688154,GSM1688155,GSM1688156,GSM1688157,GSM1688158,GSM1688159,GSM1688160,GSM1688161,GSM1688162,GSM1688163,GSM1688164,GSM1688165,GSM1688166,GSM1688167,GSM1688168,GSM1688169,GSM1688170,GSM1688171,GSM1688172,GSM1688173,GSM1688174,GSM1688175,GSM1688176,GSM1688177,GSM1688178,GSM1688179,GSM1688180,GSM1688181,GSM1688182,GSM1688183,GSM1688184,GSM1688185,GSM1688186,GSM1688187,GSM1688188,GSM1688189,GSM1688190,GSM1688191,GSM1688192,GSM1688193,GSM1688194,GSM1688195,GSM1688196,GSM1688197,GSM1688198,GSM1688199,GSM1688200,GSM1688201,GSM1688202,GSM1688203,GSM1688204,GSM1688205,GSM1688206,GSM1688207,GSM1688208,GSM1688209,GSM1688210,GSM1688211,GSM1688212,GSM1688213,GSM1688214,GSM1688215,GSM1688216,GSM1688217,GSM1688218,GSM1688219,GSM1688220,GSM1688221,GSM1688222,GSM1688223,GSM1688224,GSM1688225,GSM1688226,GSM1688227,GSM1688228,GSM1688229,GSM1688230,GSM1688231,GSM1688232,GSM1688233,GSM1688234,GSM1688235,GSM1688236,GSM1688237,GSM1688238,GSM1688239,GSM1688240,GSM1688241,GSM1688242,GSM1688243,GSM1688244,GSM1688245,GSM1688246,GSM1688247,GSM1688248,GSM1688249,GSM1688250,GSM1688251,GSM1688252,GSM1688253,GSM1688254,GSM1688255,GSM1688256,GSM1688257,GSM1688258,GSM1688259,GSM1688260,GSM1688261,GSM1688262,GSM1688263,GSM1688264,GSM1688265,GSM1688266,GSM1688267,GSM1688268,GSM1688269,GSM1688270,GSM1688271,GSM1688272,GSM1688273,GSM1688274,GSM1688275,GSM1688276,GSM1688277,GSM1688278,GSM1688279,GSM1688280,GSM1688281,GSM1688282,GSM1688283,GSM1688284,GSM1688285,GSM1688286,GSM1688287,GSM1688288,GSM1688289,GSM1688290,GSM1688291,GSM1688292,GSM1688293,GSM1688294,GSM1688295,GSM1688296,GSM1688297,GSM1688298,GSM1688299,GSM1688300,GSM1688301,GSM1688302,GSM1688303,GSM1688304,GSM1688305,GSM1688306,GSM1688307,GSM1688308,GSM1688309,GSM1688310,GSM1688311,GSM1688312,GSM1688313,GSM1688314,GSM1688315,GSM1688316,GSM1688317,GSM1688318,GSM1688319,GSM1688320,GSM1688321,GSM1688322,GSM1688323,GSM1688324,GSM1688325,GSM1688326,GSM1688327,GSM1688328,GSM1688329,GSM1688330,GSM1688331,GSM1688332,GSM1688333,GSM1688334,GSM1688335,GSM1688336,GSM1688337,GSM1688338,GSM1688339,GSM1688340,GSM1688341,GSM1688342,GSM1688343,GSM1688344,GSM1688345,GSM1688346,GSM1688347,GSM1688348,GSM1688349,GSM1688350,GSM1688351,GSM1688352,GSM1688353,GSM1688354,GSM1688355,GSM1688356,GSM1688357,GSM1688358,GSM1688359,GSM1688360,GSM1688361,GSM1688362,GSM1688363,GSM1688364,GSM1688365,GSM1688366,GSM1688367
2
+ Adrenocortical_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,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,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,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,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,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,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/Adrenocortical_Cancer/code/GSE108088.py ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Adrenocortical_Cancer"
6
+ cohort = "GSE108088"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Adrenocortical_Cancer"
10
+ in_cohort_dir = "../DATA/GEO/Adrenocortical_Cancer/GSE108088"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z1/preprocess/Adrenocortical_Cancer/GSE108088.csv"
14
+ out_gene_data_file = "./output/z1/preprocess/Adrenocortical_Cancer/gene_data/GSE108088.csv"
15
+ out_clinical_data_file = "./output/z1/preprocess/Adrenocortical_Cancer/clinical_data/GSE108088.csv"
16
+ json_path = "./output/z1/preprocess/Adrenocortical_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
+ from typing import Optional
40
+
41
+ # Decision summary based on provided background and sample characteristics:
42
+ # - Gene expression data: Likely available (matrix file parsed; comprehensive molecular profiling) -> True
43
+ # - Trait (Adrenocortical_Cancer): Not available in 'condition' list (no adrenocortical carcinoma; would be constant 0) -> None
44
+ # - Age: Not provided in the sample characteristics dictionary -> None
45
+ # - Gender: Not provided in the sample characteristics dictionary -> None
46
+
47
+ is_gene_available = True
48
+ trait_row = None
49
+ age_row = None
50
+ gender_row = None
51
+
52
+ def _after_colon(x: str) -> Optional[str]:
53
+ if x is None:
54
+ return None
55
+ if isinstance(x, str):
56
+ parts = x.split(":", 1)
57
+ val = parts[1] if len(parts) > 1 else parts[0]
58
+ val = val.strip().strip('"').strip()
59
+ return val if val != "" else None
60
+ return None
61
+
62
+ def convert_trait(x):
63
+ # Binary: 1 = Adrenocortical cancer, 0 = others
64
+ val = _after_colon(x)
65
+ if val is None:
66
+ return None
67
+ v = val.lower()
68
+ keywords_pos = [
69
+ "adrenocortical", "adrenocortical carcinoma", "adrenal cortex carcinoma",
70
+ "adrenal cortical carcinoma", "acc"
71
+ ]
72
+ if any(k in v for k in keywords_pos):
73
+ return 1
74
+ # If clearly a different cancer type, map to 0
75
+ return 0
76
+
77
+ def convert_age(x):
78
+ # Continuous: age in years
79
+ val = _after_colon(x)
80
+ if val is None:
81
+ return None
82
+ v = val.lower()
83
+ try:
84
+ import re
85
+ nums = re.findall(r"[-+]?\d*\.?\d+", v)
86
+ if not nums:
87
+ return None
88
+ num = float(nums[0])
89
+ if any(u in v for u in ["month", "mo", "mons"]):
90
+ return num / 12.0
91
+ if any(u in v for u in ["day", "d"]):
92
+ return num / 365.0
93
+ if any(u in v for u in ["week", "wk", "wks"]):
94
+ return num / 52.0
95
+ # default assume years
96
+ return num
97
+ except Exception:
98
+ return None
99
+
100
+ def convert_gender(x):
101
+ # Binary: female -> 0, male -> 1
102
+ val = _after_colon(x)
103
+ if val is None:
104
+ return None
105
+ v = val.strip().lower()
106
+ if v in ["female", "f", "woman", "girl"]:
107
+ return 0
108
+ if v in ["male", "m", "man", "boy"]:
109
+ return 1
110
+ return None
111
+
112
+ # Initial filtering and save metadata
113
+ is_trait_available = trait_row is not None
114
+ validate_and_save_cohort_info(
115
+ is_final=False,
116
+ cohort=cohort,
117
+ info_path=json_path,
118
+ is_gene_available=is_gene_available,
119
+ is_trait_available=is_trait_available
120
+ )
121
+
122
+ # Clinical feature extraction is skipped because trait_row is None (no usable clinical trait data).
output/preprocess/Adrenocortical_Cancer/code/GSE143383.py ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Adrenocortical_Cancer"
6
+ cohort = "GSE143383"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Adrenocortical_Cancer"
10
+ in_cohort_dir = "../DATA/GEO/Adrenocortical_Cancer/GSE143383"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z1/preprocess/Adrenocortical_Cancer/GSE143383.csv"
14
+ out_gene_data_file = "./output/z1/preprocess/Adrenocortical_Cancer/gene_data/GSE143383.csv"
15
+ out_clinical_data_file = "./output/z1/preprocess/Adrenocortical_Cancer/clinical_data/GSE143383.csv"
16
+ json_path = "./output/z1/preprocess/Adrenocortical_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
42
+ is_gene_available = True # Affymetrix PrimeView gene expression profiling (not miRNA/methylation)
43
+
44
+ # 2) Variable availability based on Sample Characteristics Dictionary
45
+ # Provided dictionary indicates only gender info at key 0 with multiple values.
46
+ trait_row = None # ACC tumor-only cohort; trait is constant/not provided explicitly => not available
47
+ age_row = None # No age field present
48
+ gender_row = 0 # gender: F/M/unknown
49
+
50
+ # 2.2) Conversion functions
51
+ def _after_colon(val):
52
+ if val is None:
53
+ return None
54
+ s = str(val)
55
+ parts = s.split(":", 1)
56
+ return parts[1].strip() if len(parts) == 2 else s.strip()
57
+
58
+ def convert_trait(v):
59
+ # Binary: 1 = Adrenocortical_Cancer (ACC/tumor), 0 = control/normal/benign
60
+ x = _after_colon(v)
61
+ if x is None or x == "":
62
+ return None
63
+ xl = x.lower()
64
+ pos_terms = [
65
+ "adrenocortical carcinoma", "acc", "carcinoma", "tumor", "metastatic",
66
+ "adrenocortical cancer"
67
+ ]
68
+ neg_terms = [
69
+ "normal", "control", "benign", "adjacent normal", "healthy", "adenoma",
70
+ "hyperplasia"
71
+ ]
72
+ if any(term in xl for term in pos_terms):
73
+ return 1
74
+ if any(term in xl for term in neg_terms):
75
+ return 0
76
+ return None
77
+
78
+ def convert_age(v):
79
+ # Continuous: extract first numeric age in years
80
+ x = _after_colon(v)
81
+ if x is None or x == "":
82
+ return None
83
+ m = re.search(r"(\d+(\.\d+)?)", x)
84
+ if not m:
85
+ return None
86
+ try:
87
+ age = float(m.group(1))
88
+ if 0 <= age <= 120:
89
+ return age
90
+ except Exception:
91
+ pass
92
+ return None
93
+
94
+ def convert_gender(v):
95
+ # Binary: female=0, male=1, unknown=None
96
+ x = _after_colon(v)
97
+ if x is None or x == "":
98
+ return None
99
+ xl = x.strip().lower()
100
+ if xl in {"f", "female", "woman", "women"}:
101
+ return 0
102
+ if xl in {"m", "male", "man", "men"}:
103
+ return 1
104
+ if xl in {"u", "unk", "unknown", "na", "n/a", "not available"}:
105
+ return None
106
+ # Heuristics
107
+ if "female" in xl:
108
+ return 0
109
+ if "male" in xl:
110
+ return 1
111
+ return None
112
+
113
+ # 3) Save metadata with initial filtering
114
+ is_trait_available = trait_row is not None
115
+ validate_and_save_cohort_info(
116
+ is_final=False,
117
+ cohort=cohort,
118
+ info_path=json_path,
119
+ is_gene_available=is_gene_available,
120
+ is_trait_available=is_trait_available
121
+ )
122
+
123
+ # 4) Clinical feature extraction: skipped because trait_row is None (no usable trait variable)
output/preprocess/Adrenocortical_Cancer/code/GSE19776.py ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Adrenocortical_Cancer"
6
+ cohort = "GSE19776"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Adrenocortical_Cancer"
10
+ in_cohort_dir = "../DATA/GEO/Adrenocortical_Cancer/GSE19776"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z1/preprocess/Adrenocortical_Cancer/GSE19776.csv"
14
+ out_gene_data_file = "./output/z1/preprocess/Adrenocortical_Cancer/gene_data/GSE19776.csv"
15
+ out_clinical_data_file = "./output/z1/preprocess/Adrenocortical_Cancer/clinical_data/GSE19776.csv"
16
+ json_path = "./output/z1/preprocess/Adrenocortical_Cancer/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ # 1. Gene Expression Data Availability
40
+ is_gene_available = True # Series title indicates gene expression profiling
41
+
42
+ # 2. Variable Availability and Data Type Conversion
43
+
44
+ # 2.1 Data Availability
45
+ # Trait (Adrenocortical_Cancer): All samples are adrenocortical carcinoma tissue => constant => not usable
46
+ trait_row = None
47
+
48
+ # Age
49
+ age_row = 5 # 'age: ...'
50
+ # Gender
51
+ gender_row = 4 # 'gender: F/M'
52
+
53
+ # 2.2 Data Type Conversion
54
+
55
+ def _extract_value(cell):
56
+ if cell is None:
57
+ return None
58
+ # Split on the first colon to get value part
59
+ parts = str(cell).split(":", 1)
60
+ val = parts[1] if len(parts) > 1 else parts[0]
61
+ return val.strip()
62
+
63
+ def convert_trait(x):
64
+ # Binary: presence of Adrenocortical Cancer (1) vs not (0). Here it's constant 1 for 'adrenocortical carcinoma'.
65
+ val = _extract_value(x)
66
+ if val is None or val == "" or val.lower() in {"unknown", "na", "n/a"}:
67
+ return None
68
+ v = val.lower()
69
+ if "adrenocortical" in v and "carcinoma" in v:
70
+ return 1
71
+ # If it explicitly states normal/benign or non-cancer tissue, map to 0, else None to avoid mislabeling
72
+ if any(k in v for k in ["normal", "benign", "control", "adjacent normal"]):
73
+ return 0
74
+ return None
75
+
76
+ def convert_age(x):
77
+ # Continuous
78
+ val = _extract_value(x)
79
+ if val is None:
80
+ return None
81
+ v = val.strip()
82
+ if v == "" or v.lower() in {"unknown", "na", "n/a"}:
83
+ return None
84
+ try:
85
+ return float(v)
86
+ except Exception:
87
+ return None
88
+
89
+ def convert_gender(x):
90
+ # Binary: female=0, male=1
91
+ val = _extract_value(x)
92
+ if val is None:
93
+ return None
94
+ v = val.strip().lower()
95
+ if v in {"f", "female", "woman", "women"}:
96
+ return 0
97
+ if v in {"m", "male", "man", "men"}:
98
+ return 1
99
+ return None
100
+
101
+ # 3. Save Metadata (initial filtering)
102
+ is_trait_available = trait_row is not None
103
+ _ = validate_and_save_cohort_info(
104
+ is_final=False,
105
+ cohort=cohort,
106
+ info_path=json_path,
107
+ is_gene_available=is_gene_available,
108
+ is_trait_available=is_trait_available
109
+ )
110
+
111
+ # 4. Clinical Feature Extraction (skip if trait_row is 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_df(selected_clinical_df)
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)
output/preprocess/Adrenocortical_Cancer/code/GSE49278.py ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Adrenocortical_Cancer"
6
+ cohort = "GSE49278"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Adrenocortical_Cancer"
10
+ in_cohort_dir = "../DATA/GEO/Adrenocortical_Cancer/GSE49278"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z1/preprocess/Adrenocortical_Cancer/GSE49278.csv"
14
+ out_gene_data_file = "./output/z1/preprocess/Adrenocortical_Cancer/gene_data/GSE49278.csv"
15
+ out_clinical_data_file = "./output/z1/preprocess/Adrenocortical_Cancer/clinical_data/GSE49278.csv"
16
+ json_path = "./output/z1/preprocess/Adrenocortical_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
42
+ is_gene_available = True # Affymetrix Human Gene 2.0 ST Array indicates gene expression profiling
43
+
44
+ # 2) Variable availability based on provided Sample Characteristics Dictionary
45
+ trait_row = None # 'cell type: Adrenocortical carcinoma' is constant across samples -> not useful
46
+ age_row = 0
47
+ gender_row = 1
48
+
49
+ # 2.2) Data type conversion functions
50
+ def _extract_value(cell):
51
+ if cell is None:
52
+ return None
53
+ s = str(cell)
54
+ if ':' in s:
55
+ s = s.split(':', 1)[1]
56
+ return s.strip()
57
+
58
+ def convert_trait(cell):
59
+ # Generalized mapping for adrenal conditions if present; not used here since trait_row is None.
60
+ val = _extract_value(cell)
61
+ if val is None or val == '':
62
+ return None
63
+ v = val.lower()
64
+ # Cancer vs non-cancer heuristic
65
+ if any(k in v for k in ['adrenocortical carcinoma', 'carcinoma', 'acc', 'cancer', 'malignant']):
66
+ return 1
67
+ if any(k in v for k in ['normal', 'benign', 'adenoma', 'hyperplasia', 'control', 'healthy']):
68
+ return 0
69
+ return None
70
+
71
+ def convert_age(cell):
72
+ val = _extract_value(cell)
73
+ if val is None or val == '':
74
+ return None
75
+ m = re.search(r'[-+]?\d*\.?\d+', val)
76
+ if not m:
77
+ return None
78
+ try:
79
+ age = float(m.group())
80
+ return age
81
+ except Exception:
82
+ return None
83
+
84
+ def convert_gender(cell):
85
+ val = _extract_value(cell)
86
+ if val is None or val == '':
87
+ return None
88
+ v = val.strip().lower()
89
+ if v in ['f', 'female', 'woman', 'women']:
90
+ return 0
91
+ if v in ['m', 'male', 'man', 'men']:
92
+ return 1
93
+ return None
94
+
95
+ # 3) Save metadata (initial filtering)
96
+ is_trait_available = trait_row is not None
97
+ _ = validate_and_save_cohort_info(
98
+ is_final=False,
99
+ cohort=cohort,
100
+ info_path=json_path,
101
+ is_gene_available=is_gene_available,
102
+ is_trait_available=is_trait_available
103
+ )
104
+
105
+ # 4) Clinical feature extraction: skipped because trait_row is None
106
+ # If trait_row were available:
107
+ # selected_clinical_df = geo_select_clinical_features(
108
+ # clinical_df=clinical_data,
109
+ # trait=trait,
110
+ # trait_row=trait_row,
111
+ # convert_trait=convert_trait,
112
+ # age_row=age_row,
113
+ # convert_age=convert_age,
114
+ # gender_row=gender_row,
115
+ # convert_gender=convert_gender
116
+ # )
117
+ # preview = preview_df(selected_clinical_df)
118
+ # os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
119
+ # selected_clinical_df.to_csv(out_clinical_data_file)
output/preprocess/Adrenocortical_Cancer/code/GSE67766.py ADDED
@@ -0,0 +1,213 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Adrenocortical_Cancer"
6
+ cohort = "GSE67766"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Adrenocortical_Cancer"
10
+ in_cohort_dir = "../DATA/GEO/Adrenocortical_Cancer/GSE67766"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z1/preprocess/Adrenocortical_Cancer/GSE67766.csv"
14
+ out_gene_data_file = "./output/z1/preprocess/Adrenocortical_Cancer/gene_data/GSE67766.csv"
15
+ out_clinical_data_file = "./output/z1/preprocess/Adrenocortical_Cancer/clinical_data/GSE67766.csv"
16
+ json_path = "./output/z1/preprocess/Adrenocortical_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 availability based on background info (cell line study likely includes expression profiling)
42
+ is_gene_available = True
43
+
44
+ # 2) Variable availability assessment from sample characteristics:
45
+ # Sample Characteristics showed only: {0: ['cell line: SW-13']}
46
+ # No human clinical variation; trait is constant (all SW-13 adrenocortical carcinoma cell line), age/gender not provided.
47
+ trait_row = None
48
+ age_row = None
49
+ gender_row = None
50
+
51
+ # 2.2) Converters
52
+ def _after_colon(x):
53
+ if x is None:
54
+ return None
55
+ s = str(x)
56
+ return s.split(":", 1)[1].strip() if ":" in s else s.strip()
57
+
58
+ def convert_trait(x):
59
+ v = _after_colon(x)
60
+ if not v:
61
+ return None
62
+ vl = v.lower()
63
+ # Map plausible labels to case/control
64
+ positive_markers = [
65
+ "adrenocortical cancer", "adrenocortical carcinoma",
66
+ "adrenal cortex carcinoma", "adrenal carcinoma", "acc", "sw-13", "sw13"
67
+ ]
68
+ negative_markers = ["normal", "control", "healthy", "adjacent normal", "benign"]
69
+ if any(p in vl for p in positive_markers):
70
+ return 1
71
+ if any(n in vl for n in negative_markers):
72
+ return 0
73
+ return None
74
+
75
+ def convert_age(x):
76
+ v = _after_colon(x)
77
+ if not v:
78
+ return None
79
+ vl = v.lower()
80
+ # Extract number and possible unit
81
+ m = re.search(r'([-+]?\d*\.?\d+)', vl)
82
+ if not m:
83
+ return None
84
+ num = float(m.group(1))
85
+ if "month" in vl:
86
+ return num / 12.0
87
+ # Assume years otherwise
88
+ return num
89
+
90
+ def convert_gender(x):
91
+ v = _after_colon(x)
92
+ if not v:
93
+ return None
94
+ vl = v.strip().lower()
95
+ # Common mappings
96
+ if vl in ["female", "f", "woman", "women"]:
97
+ return 0
98
+ if vl in ["male", "m", "man", "men"]:
99
+ return 1
100
+ # Sometimes embedded like "sex: female" handled by _after_colon
101
+ if "female" in vl:
102
+ return 0
103
+ if "male" in vl:
104
+ return 1
105
+ return None
106
+
107
+ # 3) Initial filtering metadata save
108
+ is_trait_available = trait_row is not None
109
+ _ = validate_and_save_cohort_info(
110
+ is_final=False,
111
+ cohort=cohort,
112
+ info_path=json_path,
113
+ is_gene_available=is_gene_available,
114
+ is_trait_available=is_trait_available
115
+ )
116
+
117
+ # 4) Clinical feature extraction (skip because trait_row is None)
118
+ # If clinical data existed and trait_row was available, we would extract and save features as below:
119
+ # selected = geo_select_clinical_features(
120
+ # clinical_df=clinical_data,
121
+ # trait=trait,
122
+ # trait_row=trait_row,
123
+ # convert_trait=convert_trait,
124
+ # age_row=age_row,
125
+ # convert_age=convert_age,
126
+ # gender_row=gender_row,
127
+ # convert_gender=convert_gender
128
+ # )
129
+ # _ = preview_df(selected)
130
+ # os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
131
+ # selected.to_csv(out_clinical_data_file, index=True)
132
+
133
+ # Step 3: Gene Data Extraction
134
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
135
+ gene_data = get_genetic_data(matrix_file)
136
+
137
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
138
+ print(gene_data.index[:20])
139
+
140
+ # Step 4: Gene Identifier Review
141
+ print("requires_gene_mapping = True")
142
+
143
+ # Step 5: Gene Annotation
144
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
145
+ gene_annotation = get_gene_annotation(soft_file)
146
+
147
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
148
+ print("Gene annotation preview:")
149
+ print(preview_df(gene_annotation))
150
+
151
+ # Step 6: Gene Identifier Mapping
152
+ # 1-2. Determine appropriate columns and create mapping dataframe
153
+ # Probe IDs align with 'ID' and gene symbols are in 'Symbol'
154
+ mapping_df = get_gene_mapping(annotation=gene_annotation, prob_col='ID', gene_col='Symbol')
155
+
156
+ # 3. Apply mapping to convert probe-level to gene-level expression
157
+ gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
158
+
159
+ # Step 7: Data Normalization and Linking
160
+ import os
161
+ import pandas as pd
162
+
163
+ # 1. Normalize gene symbols and save normalized gene data
164
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
165
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
166
+ normalized_gene_data.to_csv(out_gene_data_file)
167
+
168
+ # 2-6. Branch based on clinical trait availability
169
+ if 'trait_row' not in locals() or trait_row is None:
170
+ # No clinical data available; skip linking and final QC
171
+ linked_data = None
172
+ # Record metadata as unusable for linkage analysis
173
+ _ = validate_and_save_cohort_info(
174
+ is_final=False,
175
+ cohort=cohort,
176
+ info_path=json_path,
177
+ is_gene_available=True,
178
+ is_trait_available=False
179
+ )
180
+ else:
181
+ # Clinical data available: proceed with linking and downstream processing
182
+ # Retrieve clinical data if not in memory
183
+ if 'selected_clinical_data' not in locals() or selected_clinical_data is None:
184
+ if os.path.exists(out_clinical_data_file):
185
+ selected_clinical_data = pd.read_csv(out_clinical_data_file, index_col=0)
186
+ else:
187
+ raise RuntimeError("Clinical data not found in memory or on disk, cannot proceed with linking.")
188
+
189
+ # 2. Link clinical and genetic data
190
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_data, normalized_gene_data)
191
+
192
+ # 3. Handle missing values
193
+ linked_data = handle_missing_values(linked_data, trait)
194
+
195
+ # 4. Bias checks and removal of biased demographic features
196
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
197
+
198
+ # 5. Final validation and metadata save
199
+ is_usable = validate_and_save_cohort_info(
200
+ is_final=True,
201
+ cohort=cohort,
202
+ info_path=json_path,
203
+ is_gene_available=True,
204
+ is_trait_available=True,
205
+ is_biased=is_trait_biased,
206
+ df=unbiased_linked_data,
207
+ note="INFO: Proceeded with clinical-genetic linking and QC."
208
+ )
209
+
210
+ # 6. Save linked data only if usable
211
+ if is_usable:
212
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
213
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Adrenocortical_Cancer/code/GSE68606.py ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Adrenocortical_Cancer"
6
+ cohort = "GSE68606"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Adrenocortical_Cancer"
10
+ in_cohort_dir = "../DATA/GEO/Adrenocortical_Cancer/GSE68606"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z1/preprocess/Adrenocortical_Cancer/GSE68606.csv"
14
+ out_gene_data_file = "./output/z1/preprocess/Adrenocortical_Cancer/gene_data/GSE68606.csv"
15
+ out_clinical_data_file = "./output/z1/preprocess/Adrenocortical_Cancer/clinical_data/GSE68606.csv"
16
+ json_path = "./output/z1/preprocess/Adrenocortical_Cancer/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ # 1. Gene expression data availability
40
+ is_gene_available = True # Affymetrix HG-U133A; Assay Type: Gene Expression
41
+
42
+ # 2. Variable availability and conversion functions
43
+
44
+ # From the sample characteristics dictionary:
45
+ # - trait (Adrenocortical_Cancer): Not available (no evidence of carcinoma; only "Adrenal Cortical Adenoma")
46
+ trait_row = None
47
+
48
+ # - Age is available at key 6
49
+ age_row = 6
50
+
51
+ # - Gender is available at key 5
52
+ gender_row = 5
53
+
54
+ def _after_colon(x):
55
+ if x is None:
56
+ return None
57
+ s = str(x)
58
+ parts = s.split(":", 1)
59
+ val = parts[1] if len(parts) > 1 else parts[0]
60
+ return val.strip()
61
+
62
+ def convert_trait(x):
63
+ # Not used since trait_row is None. Provided for completeness if needed later.
64
+ val = _after_colon(x)
65
+ if val is None or val == "" or val == "--":
66
+ return None
67
+ v = val.lower()
68
+ # Positive (1): adrenocortical carcinoma
69
+ if ("adrenocortical" in v or "adrenal cortical" in v or "adrenal cortex" in v) and ("carcinoma" in v or "cancer" in v):
70
+ return 1
71
+ # Explicit negatives (0): adenoma or benign adrenal
72
+ if ("adrenal cortical adenoma" in v) or ("adenoma" in v and ("adrenal" in v or "adrenocortical" in v)):
73
+ return 0
74
+ # If explicitly healthy/control, map to 0
75
+ if any(tok in v for tok in ["normal", "control", "benign"]):
76
+ return 0
77
+ # Otherwise, unknown relative to this trait
78
+ return None
79
+
80
+ def convert_age(x):
81
+ val = _after_colon(x)
82
+ if val is None or val == "" or val in {"--", "na", "n/a", "NA", "unknown"}:
83
+ return None
84
+ try:
85
+ num = float(val)
86
+ # Return integer if it's whole number
87
+ return int(num) if num.is_integer() else num
88
+ except Exception:
89
+ return None
90
+
91
+ def convert_gender(x):
92
+ val = _after_colon(x)
93
+ if val is None or val == "" or val in {"--", "na", "n/a", "NA", "unknown"}:
94
+ return None
95
+ v = val.strip().lower()
96
+ if v in {"male", "m"}:
97
+ return 1
98
+ if v in {"female", "f"}:
99
+ return 0
100
+ return None
101
+
102
+ # 3. Save metadata with initial filtering
103
+ is_trait_available = trait_row is not None
104
+ _ = validate_and_save_cohort_info(
105
+ is_final=False,
106
+ cohort=cohort,
107
+ info_path=json_path,
108
+ is_gene_available=is_gene_available,
109
+ is_trait_available=is_trait_available
110
+ )
111
+
112
+ # 4. Clinical feature extraction (skip because trait_row is None)
113
+ # If trait_row becomes available in future, uncomment the following:
114
+ # selected_clinical_df = geo_select_clinical_features(
115
+ # clinical_df=clinical_data,
116
+ # trait=trait,
117
+ # trait_row=trait_row,
118
+ # convert_trait=convert_trait,
119
+ # age_row=age_row,
120
+ # convert_age=convert_age,
121
+ # gender_row=gender_row,
122
+ # convert_gender=convert_gender
123
+ # )
124
+ # preview = preview_df(selected_clinical_df, n=5)
125
+ # selected_clinical_df.to_csv(out_clinical_data_file)
output/preprocess/Adrenocortical_Cancer/code/GSE68950.py ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Adrenocortical_Cancer"
6
+ cohort = "GSE68950"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Adrenocortical_Cancer"
10
+ in_cohort_dir = "../DATA/GEO/Adrenocortical_Cancer/GSE68950"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z1/preprocess/Adrenocortical_Cancer/GSE68950.csv"
14
+ out_gene_data_file = "./output/z1/preprocess/Adrenocortical_Cancer/gene_data/GSE68950.csv"
15
+ out_clinical_data_file = "./output/z1/preprocess/Adrenocortical_Cancer/clinical_data/GSE68950.csv"
16
+ json_path = "./output/z1/preprocess/Adrenocortical_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) Determine gene expression availability (Affymetrix HT_HG-U133A, gene expression)
44
+ is_gene_available = True
45
+
46
+ # Candidate rows from sample characteristics dictionary
47
+ # 0: cosmic id
48
+ # 1: disease state -> candidate for trait (binary: Adrenocortical Cancer vs others)
49
+ # 2: disease location
50
+ # 3: organism part
51
+ # 4: sample
52
+ # 5: cell line code
53
+ # 6: supplier
54
+ # 7: affy_batch
55
+ # 8: crna plate
56
+
57
+ trait_row = 1
58
+ age_row = None # Cell line compendium; no human subject age
59
+ gender_row = None # Cell line compendium; no human subject gender
60
+
61
+ # Conversion helpers
62
+ def _post_colon(value):
63
+ if value is None:
64
+ return None
65
+ s = str(value)
66
+ if ':' in s:
67
+ s = s.split(':', 1)[1]
68
+ s = s.strip()
69
+ if s == '':
70
+ return None
71
+ return s
72
+
73
+ def convert_trait(v):
74
+ s = _post_colon(v)
75
+ if s is None:
76
+ return None
77
+ t = s.lower()
78
+ if t in {'na', 'n/a', '#n/a', 'unknown'}:
79
+ return None
80
+ # Positive mapping for Adrenocortical_Cancer
81
+ # Capture common phrasings
82
+ if ('adrenocortical' in t and 'carcin' in t) \
83
+ or (('adrenal' in t) and ('cortical' in t) and ('carcin' in t)) \
84
+ or (('adrenal' in t) and ('cortex' in t) and ('carcin' in t)) \
85
+ or ('adrenal cortical carcinoma' in t) \
86
+ or ('adrenocortical carcinoma' in t) \
87
+ or ('adrenal cortex carcinoma' in t):
88
+ return 1
89
+ return 0
90
+
91
+ def convert_age(v):
92
+ s = _post_colon(v)
93
+ if s is None:
94
+ return None
95
+ t = s.lower().replace('years', '').replace('year', '').replace('yrs', '').replace('yr', '').strip()
96
+ try:
97
+ val = float(t)
98
+ if math.isnan(val):
99
+ return None
100
+ return val
101
+ except Exception:
102
+ return None
103
+
104
+ def convert_gender(v):
105
+ s = _post_colon(v)
106
+ if s is None:
107
+ return None
108
+ t = s.strip().lower()
109
+ if t in {'female', 'f', 'woman', 'women', 'girl'}:
110
+ return 0
111
+ if t in {'male', 'm', 'man', 'men', 'boy'}:
112
+ return 1
113
+ return None
114
+
115
+ # 2) Determine if the trait is actually available (non-constant) in this cohort
116
+ is_trait_available = False
117
+ if trait_row is not None:
118
+ # Map the candidate trait row values to 0/1/None and check variability
119
+ try:
120
+ mapped = clinical_data.loc[trait_row].apply(convert_trait)
121
+ unique_vals = set([x for x in mapped if x is not None])
122
+ # Trait must have at least two classes to be usable
123
+ if unique_vals == {0, 1}:
124
+ is_trait_available = True
125
+ else:
126
+ # All 0s (no ACC) or all 1s or only None -> treat as unavailable
127
+ trait_row = None
128
+ except Exception:
129
+ # If anything goes wrong accessing the row, treat as unavailable
130
+ trait_row = None
131
+
132
+ # 3) Save metadata (initial filtering)
133
+ # Note: This is a cancer cell line compendium; age and gender are not provided.
134
+ _ = validate_and_save_cohort_info(
135
+ is_final=False,
136
+ cohort=cohort,
137
+ info_path=json_path,
138
+ is_gene_available=is_gene_available,
139
+ is_trait_available=is_trait_available
140
+ )
141
+
142
+ # 4) Clinical Feature Extraction (only if trait is available and non-constant)
143
+ if trait_row is not None:
144
+ selected_clinical_df = geo_select_clinical_features(
145
+ clinical_df=clinical_data,
146
+ trait=trait,
147
+ trait_row=trait_row,
148
+ convert_trait=convert_trait,
149
+ age_row=age_row,
150
+ convert_age=convert_age,
151
+ gender_row=gender_row,
152
+ convert_gender=convert_gender
153
+ )
154
+ preview = preview_df(selected_clinical_df)
155
+ print("Preview of selected clinical features:", preview)
156
+
157
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
158
+ selected_clinical_df.to_csv(out_clinical_data_file)
159
+ else:
160
+ print("INFO: Trait is not available for association analysis in this cohort (constant or absent). Skipping clinical feature extraction. This is a cell line compendium without age or gender.")
output/preprocess/Adrenocortical_Cancer/code/GSE75415.py ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Adrenocortical_Cancer"
6
+ cohort = "GSE75415"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Adrenocortical_Cancer"
10
+ in_cohort_dir = "../DATA/GEO/Adrenocortical_Cancer/GSE75415"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z1/preprocess/Adrenocortical_Cancer/GSE75415.csv"
14
+ out_gene_data_file = "./output/z1/preprocess/Adrenocortical_Cancer/gene_data/GSE75415.csv"
15
+ out_clinical_data_file = "./output/z1/preprocess/Adrenocortical_Cancer/clinical_data/GSE75415.csv"
16
+ json_path = "./output/z1/preprocess/Adrenocortical_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
+
42
+ # 1) Gene expression data availability
43
+ is_gene_available = True # Microarray-based gene expression profiling per background
44
+
45
+ # 2) Variable availability
46
+ trait_row = 1 # 'histologic type' with carcinoma/adenoma/normal/unknown
47
+ age_row = None # Age not present in the characteristics dictionary
48
+ gender_row = 0 # 'gender' with female/male/unknown
49
+
50
+ # 2.2 Conversion functions
51
+ def _extract_value(x):
52
+ if x is None or (isinstance(x, float) and math.isnan(x)):
53
+ return None
54
+ try:
55
+ s = str(x)
56
+ except Exception:
57
+ return None
58
+ if ':' in s:
59
+ s = s.split(':', 1)[1]
60
+ return s.strip().lower()
61
+
62
+ # Trait (binary): adrenocortical carcinoma=1; normal/adenoma=0; unknown=None
63
+ def convert_trait(x):
64
+ v = _extract_value(x)
65
+ if v is None or v == '' or v == 'unknown':
66
+ return None
67
+ if 'carcinoma' in v:
68
+ return 1
69
+ if 'normal' in v or 'adenoma' in v:
70
+ return 0
71
+ return None
72
+
73
+ # Age (continuous): not available here, but provide a robust parser
74
+ def convert_age(x):
75
+ v = _extract_value(x)
76
+ if v is None or v == '' or v == 'unknown' or v == 'not applicable' or v == 'not available':
77
+ return None
78
+ # Try to extract a number (years). Handles formats like "5", "5 yrs", "5 years", "60 months"
79
+ import re
80
+ m = re.search(r'(\d+(\.\d+)?)', v)
81
+ if not m:
82
+ return None
83
+ num = float(m.group(1))
84
+ # Convert months to years if clearly indicated
85
+ if 'month' in v:
86
+ return num / 12.0
87
+ return num
88
+
89
+ # Gender (binary): female=0; male=1; unknown=None
90
+ def convert_gender(x):
91
+ v = _extract_value(x)
92
+ if v is None or v == '' or v == 'unknown':
93
+ return None
94
+ if v.startswith('fem'):
95
+ return 0
96
+ if v.startswith('mal'):
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 is available)
111
+ if is_trait_available:
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
+ 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)
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
+ # Determine mapping columns based on previous previews:
147
+ # Probe IDs: 'ID'; 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(gene_data, mapping_df)
152
+
153
+ # Step 7: Data Normalization and Linking
154
+ import os
155
+ import pandas as pd
156
+
157
+ # Ensure required input paths are available
158
+ if 'soft_file' not in locals() or 'matrix_file' not in locals():
159
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
160
+
161
+ # Ensure clinical data is available (reload if not in scope)
162
+ if 'selected_clinical_df' not in locals():
163
+ selected_clinical_df = pd.read_csv(out_clinical_data_file, index_col=0)
164
+
165
+ # Reconstruct gene-level expression data deterministically (probe -> gene mapping)
166
+ raw_probe_df = get_genetic_data(matrix_file)
167
+ gene_annotation = get_gene_annotation(soft_file)
168
+ mapping_df = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='Gene Symbol')
169
+ gene_data = apply_gene_mapping(raw_probe_df, mapping_df)
170
+
171
+ # 1. Normalize gene symbols and save gene expression 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. Link clinical and genetic data
177
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
178
+
179
+ # 3. Handle missing values
180
+ linked_data = handle_missing_values(linked_data, trait)
181
+
182
+ # 4. Bias checks (remove biased demographic features if needed)
183
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
184
+
185
+ # 5. Final validation and save cohort info
186
+ note = "INFO: Trait derived from histologic type; Gender available; Age not provided in series characteristics."
187
+ is_usable = validate_and_save_cohort_info(
188
+ is_final=True,
189
+ cohort=cohort,
190
+ info_path=json_path,
191
+ is_gene_available=True,
192
+ is_trait_available=True,
193
+ is_biased=is_trait_biased,
194
+ df=unbiased_linked_data,
195
+ note=note
196
+ )
197
+
198
+ # 6. Save linked data only if usable
199
+ if is_usable:
200
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
201
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Adrenocortical_Cancer/code/GSE76019.py ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Adrenocortical_Cancer"
6
+ cohort = "GSE76019"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Adrenocortical_Cancer"
10
+ in_cohort_dir = "../DATA/GEO/Adrenocortical_Cancer/GSE76019"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z1/preprocess/Adrenocortical_Cancer/GSE76019.csv"
14
+ out_gene_data_file = "./output/z1/preprocess/Adrenocortical_Cancer/gene_data/GSE76019.csv"
15
+ out_clinical_data_file = "./output/z1/preprocess/Adrenocortical_Cancer/clinical_data/GSE76019.csv"
16
+ json_path = "./output/z1/preprocess/Adrenocortical_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
42
+ is_gene_available = True # Background indicates gene expression microarrays were used.
43
+
44
+ # 2. Variable Availability
45
+ # Based on the provided Sample Characteristics Dictionary:
46
+ # 0: histology: ACC (constant)
47
+ # 1: Stage: I/II/III/IV
48
+ # 2: efs.time
49
+ # 3: efs.event
50
+ # No explicit age or gender. Trait (Adrenocortical_Cancer) is constant "ACC" -> not usable.
51
+ trait_row = None
52
+ age_row = None
53
+ gender_row = None
54
+
55
+ # 2.2 Data Type Conversion
56
+
57
+ def _after_colon(value: str) -> str:
58
+ if value is None:
59
+ return ""
60
+ parts = str(value).split(":", 1)
61
+ val = parts[1] if len(parts) > 1 else parts[0]
62
+ return val.strip()
63
+
64
+ def convert_trait(value):
65
+ """
66
+ Binary: 1 = Adrenocortical cancer present, 0 = no cancer/benign/normal.
67
+ Unknown -> None.
68
+ """
69
+ v = _after_colon(value).lower()
70
+ if not v:
71
+ return None
72
+ # Positive indicators
73
+ pos_markers = ["acc", "adrenocortical carcinoma", "adrenocortical cancer", "carcinoma"]
74
+ if any(tok == v or tok in v for tok in pos_markers):
75
+ return 1
76
+ # Negative indicators
77
+ neg_markers = ["normal", "control", "benign", "adenoma", "healthy", "non-cancer", "noncancer"]
78
+ if any(tok in v for tok in neg_markers):
79
+ return 0
80
+ return None
81
+
82
+ def convert_age(value):
83
+ """
84
+ Continuous: age in years (float). Tries to parse numeric; converts months/days to years if indicated.
85
+ Unknown -> None.
86
+ """
87
+ v = _after_colon(value).lower()
88
+ if not v or v in {"na", "nan", "none", "unknown", ""}:
89
+ return None
90
+ # Find first float/integers in the string
91
+ m = re.search(r"[-+]?\d*\.?\d+", v)
92
+ if not m:
93
+ return None
94
+ num = float(m.group())
95
+ # Unit heuristics
96
+ if "month" in v or "mo" in v:
97
+ return num / 12.0
98
+ if "day" in v or "d " in v or v.endswith("d"):
99
+ return num / 365.25
100
+ # Default assume years
101
+ return num
102
+
103
+ def convert_gender(value):
104
+ """
105
+ Binary: female -> 0, male -> 1. Unknown -> None.
106
+ """
107
+ v = _after_colon(value).lower()
108
+ if not v:
109
+ return None
110
+ v = v.strip()
111
+ if v in {"female", "f", "woman", "girl"} or "female" in v:
112
+ return 0
113
+ if v in {"male", "m", "man", "boy"} or "male" in v:
114
+ return 1
115
+ return None
116
+
117
+ # 3. Save Metadata (initial filtering)
118
+ is_trait_available = trait_row is not None
119
+ _ = validate_and_save_cohort_info(
120
+ is_final=False,
121
+ cohort=cohort,
122
+ info_path=json_path,
123
+ is_gene_available=is_gene_available,
124
+ is_trait_available=is_trait_available
125
+ )
126
+
127
+ # 4. Clinical Feature Extraction
128
+ # Skipped because trait_row is None (no usable trait variability).
output/preprocess/Adrenocortical_Cancer/code/GSE90713.py ADDED
@@ -0,0 +1,177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Adrenocortical_Cancer"
6
+ cohort = "GSE90713"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Adrenocortical_Cancer"
10
+ in_cohort_dir = "../DATA/GEO/Adrenocortical_Cancer/GSE90713"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z1/preprocess/Adrenocortical_Cancer/GSE90713.csv"
14
+ out_gene_data_file = "./output/z1/preprocess/Adrenocortical_Cancer/gene_data/GSE90713.csv"
15
+ out_clinical_data_file = "./output/z1/preprocess/Adrenocortical_Cancer/clinical_data/GSE90713.csv"
16
+ json_path = "./output/z1/preprocess/Adrenocortical_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: Gene expression data availability
40
+ is_gene_available = True # Affymetrix microarrays with RNA extraction imply gene expression data
41
+
42
+ # Step 2: Variable availability and converters
43
+
44
+ # Identify rows in the clinical sample characteristics
45
+ trait_row = 2 # 'condition: tumor' vs 'condition: normal'
46
+ age_row = None # No age field in sample characteristics
47
+ gender_row = None # No gender field in sample characteristics
48
+
49
+ # Converters
50
+ def _extract_value(x):
51
+ if x is None:
52
+ return None
53
+ s = str(x)
54
+ if ':' in s:
55
+ s = s.split(':', 1)[1]
56
+ return s.strip()
57
+
58
+ def convert_trait(x):
59
+ v = _extract_value(x)
60
+ if not v:
61
+ return None
62
+ v_low = v.lower()
63
+ if v_low in {'tumor', 'tumour', 'cancer', 'carcinoma'}:
64
+ return 1
65
+ if v_low in {'normal', 'control'}:
66
+ return 0
67
+ return None
68
+
69
+ def convert_age(x):
70
+ v = _extract_value(x)
71
+ if not v:
72
+ return None
73
+ # Extract first number found
74
+ import re
75
+ m = re.search(r'(\d+(\.\d+)?)', v)
76
+ if m:
77
+ try:
78
+ return float(m.group(1))
79
+ except Exception:
80
+ return None
81
+ return None
82
+
83
+ def convert_gender(x):
84
+ v = _extract_value(x)
85
+ if not v:
86
+ return None
87
+ v_low = v.lower()
88
+ if v_low in {'male', 'm'}:
89
+ return 1
90
+ if v_low in {'female', 'f'}:
91
+ return 0
92
+ return None
93
+
94
+ # Step 3: Save metadata with initial filtering
95
+ is_trait_available = trait_row is not None
96
+ _ = validate_and_save_cohort_info(
97
+ is_final=False,
98
+ cohort=cohort,
99
+ info_path=json_path,
100
+ is_gene_available=is_gene_available,
101
+ is_trait_available=is_trait_available
102
+ )
103
+
104
+ # Step 4: Clinical feature extraction (only if clinical data 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
+ clinical_preview = preview_df(selected_clinical_df)
117
+ print(clinical_preview)
118
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
119
+ selected_clinical_df.to_csv(out_clinical_data_file)
120
+
121
+ # Step 3: Gene Data Extraction
122
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
123
+ gene_data = get_genetic_data(matrix_file)
124
+
125
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
126
+ print(gene_data.index[:20])
127
+
128
+ # Step 4: Gene Identifier Review
129
+ 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 appropriate columns for probe IDs and gene symbols based on annotation preview
142
+ probe_col = 'ID'
143
+ gene_symbol_col = 'Gene Symbol'
144
+
145
+ # Build mapping DataFrame
146
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=probe_col, gene_col=gene_symbol_col)
147
+
148
+ # Apply mapping to convert probe-level data to gene-level expression
149
+ gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
150
+
151
+ # Step 7: Data Normalization and Linking
152
+ import os
153
+
154
+ # 1. Normalize the obtained gene data and save
155
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
156
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
157
+ normalized_gene_data.to_csv(out_gene_data_file)
158
+
159
+ # 2. Link the clinical and genetic data
160
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
161
+
162
+ # 3. Handle missing values in the linked data
163
+ linked_data = handle_missing_values(linked_data, trait)
164
+
165
+ # 4. Determine whether the trait and some demographic features are severely biased, and remove biased features.
166
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
167
+
168
+ # 5. Conduct quality check and save the cohort information.
169
+ note_msg = "INFO: Age and Gender not available in clinical annotations for this cohort."
170
+ is_usable = validate_and_save_cohort_info(
171
+ True, cohort, json_path, True, True, is_trait_biased, unbiased_linked_data, note=note_msg
172
+ )
173
+
174
+ # 6. If the linked data is usable, save it
175
+ if is_usable:
176
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
177
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Adrenocortical_Cancer/code/TCGA.py ADDED
@@ -0,0 +1,348 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Adrenocortical_Cancer"
6
+
7
+ # Input paths
8
+ tcga_root_dir = "../DATA/TCGA"
9
+
10
+ # Output paths
11
+ out_data_file = "./output/z1/preprocess/Adrenocortical_Cancer/TCGA.csv"
12
+ out_gene_data_file = "./output/z1/preprocess/Adrenocortical_Cancer/gene_data/TCGA.csv"
13
+ out_clinical_data_file = "./output/z1/preprocess/Adrenocortical_Cancer/clinical_data/TCGA.csv"
14
+ json_path = "./output/z1/preprocess/Adrenocortical_Cancer/cohort_info.json"
15
+
16
+
17
+ # Step 1: Initial Data Loading
18
+ import os
19
+ import pandas as pd
20
+
21
+ # Identify the most relevant TCGA cohort directory for the current trait
22
+ subdirs = [d for d in os.listdir(tcga_root_dir) if os.path.isdir(os.path.join(tcga_root_dir, d))]
23
+ target_keywords = ['adrenocortical', '(acc)'] # prioritize exact trait and abbreviation
24
+ matches = []
25
+ for d in subdirs:
26
+ name = d.lower()
27
+ score = 0
28
+ if 'adrenocortical' in name:
29
+ score += 2
30
+ if '(acc)' in name or '_acc' in name:
31
+ score += 1
32
+ if score > 0:
33
+ matches.append((score, d))
34
+
35
+ selected_dir = None
36
+ if matches:
37
+ # Choose the highest score; if tie, the first one encountered
38
+ matches.sort(key=lambda x: (-x[0], x[1]))
39
+ selected_dir = matches[0][1]
40
+
41
+ # If no suitable directory is found, mark as completed for this trait and stop further processing
42
+ if selected_dir is None:
43
+ validate_and_save_cohort_info(
44
+ is_final=False,
45
+ cohort="TCGA",
46
+ info_path=json_path,
47
+ is_gene_available=False,
48
+ is_trait_available=False
49
+ )
50
+ else:
51
+ cohort_dir = os.path.join(tcga_root_dir, selected_dir)
52
+ # Identify clinical and genetic file paths
53
+ try:
54
+ clinical_file_path, genetic_file_path = tcga_get_relevant_filepaths(cohort_dir)
55
+ except Exception:
56
+ # If file identification fails, mark as unavailable
57
+ validate_and_save_cohort_info(
58
+ is_final=False,
59
+ cohort="TCGA",
60
+ info_path=json_path,
61
+ is_gene_available=False,
62
+ is_trait_available=False
63
+ )
64
+ else:
65
+ # Load clinical and genetic data
66
+ clinical_df = pd.read_csv(clinical_file_path, sep='\t', index_col=0, compression='infer', low_memory=False)
67
+ genetic_df = pd.read_csv(genetic_file_path, sep='\t', index_col=0, compression='infer', low_memory=False)
68
+ # Print clinical column names
69
+ print(clinical_df.columns.tolist())
70
+
71
+ # Step 2: Find Candidate Demographic Features
72
+ import os
73
+ import pandas as pd
74
+
75
+ # Try to use existing clinical_df; otherwise, attempt to load from TCGA ACC cohort
76
+ if 'clinical_df' not in globals():
77
+ # Heuristic to locate ACC cohort directory
78
+ acc_dir = os.path.join(tcga_root_dir, 'ACC')
79
+ if not os.path.isdir(acc_dir):
80
+ subdirs = [d for d in os.listdir(tcga_root_dir) if os.path.isdir(os.path.join(tcga_root_dir, d))]
81
+ acc_candidates = [d for d in subdirs if 'ACC' in d.upper()]
82
+ acc_dir = os.path.join(tcga_root_dir, acc_candidates[0]) if acc_candidates else None
83
+
84
+ if acc_dir:
85
+ try:
86
+ clinical_file_path, _ = tcga_get_relevant_filepaths(acc_dir)
87
+ clinical_df = pd.read_csv(clinical_file_path, sep='\t', index_col=0, dtype=str)
88
+ except Exception:
89
+ clinical_df = None
90
+ else:
91
+ clinical_df = None
92
+
93
+ available_cols = list(clinical_df.columns) if isinstance(clinical_df, pd.DataFrame) else []
94
+
95
+ def is_age_col(col: str) -> bool:
96
+ c = col.lower()
97
+ if 'stage' in c: # avoid false positive from 'stage'
98
+ return False
99
+ if c.startswith('age') or 'age_' in c or '_age' in c or 'age at' in c:
100
+ return True
101
+ if 'days_to_birth' in c or 'birth' in c:
102
+ return True
103
+ return False
104
+
105
+ def is_gender_col(col: str) -> bool:
106
+ c = col.lower().strip()
107
+ if c in {'gender', 'sex'}:
108
+ return True
109
+ if c.startswith('gender') or c.endswith('_gender'):
110
+ return True
111
+ # Avoid false positive from strings containing 'sex' (e.g., 'excess')
112
+ if c == 'sex':
113
+ return True
114
+ return False
115
+
116
+ candidate_age_cols = [c for c in available_cols if is_age_col(c)]
117
+ candidate_gender_cols = [c for c in available_cols if is_gender_col(c)]
118
+
119
+ print(f"candidate_age_cols = {candidate_age_cols}")
120
+ print(f"candidate_gender_cols = {candidate_gender_cols}")
121
+
122
+ # Preview extracted data if clinical_df is available and there are candidate columns
123
+ selected_cols = [c for c in (candidate_age_cols + candidate_gender_cols) if c in available_cols]
124
+ if isinstance(clinical_df, pd.DataFrame) and len(selected_cols) > 0:
125
+ preview_dict = preview_df(clinical_df[selected_cols], n=5)
126
+ print(preview_dict)
127
+ else:
128
+ print({})
129
+
130
+ # Step 3: Select Demographic Features
131
+ import math
132
+
133
+ # Helper to check if a small list of preview values is usable (not mostly missing)
134
+ def _is_valid_preview(values, min_non_missing=3):
135
+ if not isinstance(values, (list, tuple)) or len(values) == 0:
136
+ return False
137
+ def _is_missing(v):
138
+ if v is None:
139
+ return True
140
+ if isinstance(v, float) and math.isnan(v):
141
+ return True
142
+ if isinstance(v, str) and v.strip() == "":
143
+ return True
144
+ return False
145
+ non_missing = sum(0 if _is_missing(v) else 1 for v in values)
146
+ return non_missing >= min_non_missing
147
+
148
+ # Try to locate the preview dictionaries created in prior steps
149
+ age_values_dict = {}
150
+ gender_values_dict = {}
151
+
152
+ # Known possible variable names
153
+ _possible_age_dict_names = ["age_values_dict", "age_preview_dict", "age_dict"]
154
+ _possible_gender_dict_names = ["gender_values_dict", "gender_preview_dict", "gender_dict"]
155
+
156
+ # Pull from known names if available
157
+ for _name in _possible_age_dict_names:
158
+ try:
159
+ _val = eval(_name)
160
+ if isinstance(_val, dict):
161
+ age_values_dict = _val
162
+ break
163
+ except NameError:
164
+ pass
165
+
166
+ for _name in _possible_gender_dict_names:
167
+ try:
168
+ _val = eval(_name)
169
+ if isinstance(_val, dict):
170
+ gender_values_dict = _val
171
+ break
172
+ except NameError:
173
+ pass
174
+
175
+ # If separate dicts not found, try to derive them from any combined dict present in the environment
176
+ if (not age_values_dict or not gender_values_dict):
177
+ # Search for a dict with keys covering candidate columns
178
+ try:
179
+ # Collect candidate keys for age and gender
180
+ age_keys = set(candidate_age_cols) if 'candidate_age_cols' in globals() else set()
181
+ gender_keys = set(candidate_gender_cols) if 'candidate_gender_cols' in globals() else set()
182
+ # Scan global namespace for any dict that might contain these keys
183
+ for _var, _obj in list(globals().items()):
184
+ if isinstance(_obj, dict):
185
+ if not age_values_dict and age_keys and any(k in _obj for k in age_keys):
186
+ age_values_dict = {k: _obj[k] for k in age_keys if k in _obj}
187
+ if not gender_values_dict and gender_keys and any(k in _obj for k in gender_keys):
188
+ gender_values_dict = {k: _obj[k] for k in gender_keys if k in _obj}
189
+ if age_values_dict and gender_values_dict:
190
+ break
191
+ except Exception:
192
+ pass
193
+
194
+ # Initialize selections
195
+ age_col = None
196
+ gender_col = None
197
+
198
+ # Select age column with preference and validity checks
199
+ if isinstance(candidate_age_cols, (list, tuple)) and len(candidate_age_cols) > 0 and isinstance(age_values_dict, dict):
200
+ # Filter to candidates that exist in the preview dict and look valid
201
+ valid_age_candidates = [c for c in candidate_age_cols if c in age_values_dict and _is_valid_preview(age_values_dict.get(c, []))]
202
+ # Apply preference: age_at_initial_pathologic_diagnosis > days_to_birth > first valid
203
+ if 'age_at_initial_pathologic_diagnosis' in valid_age_candidates:
204
+ age_col = 'age_at_initial_pathologic_diagnosis'
205
+ elif 'days_to_birth' in valid_age_candidates:
206
+ age_col = 'days_to_birth'
207
+ elif valid_age_candidates:
208
+ age_col = valid_age_candidates[0]
209
+
210
+ # Select gender column with validity checks
211
+ if isinstance(candidate_gender_cols, (list, tuple)) and len(candidate_gender_cols) > 0 and isinstance(gender_values_dict, dict):
212
+ valid_gender_candidates = [c for c in candidate_gender_cols if c in gender_values_dict and _is_valid_preview(gender_values_dict.get(c, []))]
213
+ if 'gender' in valid_gender_candidates:
214
+ gender_col = 'gender'
215
+ elif valid_gender_candidates:
216
+ gender_col = valid_gender_candidates[0]
217
+
218
+ # If preview dicts are empty, set to None explicitly per instruction
219
+ if not isinstance(age_values_dict, dict) or len(age_values_dict) == 0:
220
+ age_col = None
221
+ if not isinstance(gender_values_dict, dict) or len(gender_values_dict) == 0:
222
+ gender_col = None
223
+
224
+ # Explicitly print out selected columns and their first 5 values (if available)
225
+ print(f"Selected age_col: {age_col}")
226
+ if age_col is not None and isinstance(age_values_dict, dict) and age_col in age_values_dict:
227
+ print(f"age_col first5 values: {age_values_dict[age_col]}")
228
+ else:
229
+ print("age_col first5 values: None")
230
+
231
+ print(f"Selected gender_col: {gender_col}")
232
+ if gender_col is not None and isinstance(gender_values_dict, dict) and gender_col in gender_values_dict:
233
+ print(f"gender_col first5 values: {gender_values_dict[gender_col]}")
234
+ else:
235
+ print("gender_col first5 values: None")
236
+
237
+ # Step 4: Feature Engineering and Validation
238
+ import os
239
+ import pandas as pd
240
+
241
+ # Ensure clinical_df and genetic_df are available (fallback to reload if needed)
242
+ if 'clinical_df' not in globals() or 'genetic_df' not in globals():
243
+ # Locate ACC cohort directory
244
+ subdirs = [d for d in os.listdir(tcga_root_dir) if os.path.isdir(os.path.join(tcga_root_dir, d))]
245
+ acc_dir = None
246
+ for d in subdirs:
247
+ if 'adrenocortical_cancer_(acc)' in d.lower() or d.upper().endswith('(ACC)') or d.upper() == 'ACC':
248
+ acc_dir = os.path.join(tcga_root_dir, d)
249
+ break
250
+ if acc_dir is None:
251
+ # Worst-case, pick any directory containing ACC
252
+ acc_candidates = [d for d in subdirs if 'ACC' in d.upper()]
253
+ acc_dir = os.path.join(tcga_root_dir, acc_candidates[0]) if acc_candidates else None
254
+
255
+ if acc_dir:
256
+ clinical_file_path, genetic_file_path = tcga_get_relevant_filepaths(acc_dir)
257
+ clinical_df = pd.read_csv(clinical_file_path, sep='\t', index_col=0, compression='infer', low_memory=False)
258
+ genetic_df = pd.read_csv(genetic_file_path, sep='\t', index_col=0, compression='infer', low_memory=False)
259
+ else:
260
+ raise RuntimeError("ACC cohort directory not found; cannot proceed.")
261
+
262
+ # Use selected demographic columns from previous step; default to None if missing
263
+ age_col = age_col if 'age_col' in globals() else None
264
+ gender_col = gender_col if 'gender_col' in globals() else None
265
+
266
+ # 1) Extract and standardize clinical features (Trait, optional Age and Gender)
267
+ selected_clinical_df = tcga_select_clinical_features(
268
+ clinical_df=clinical_df,
269
+ trait=trait,
270
+ age_col=age_col,
271
+ gender_col=gender_col
272
+ )
273
+
274
+ # 2) Normalize gene symbols and save normalized gene expression
275
+ normalized_gene_df = normalize_gene_symbols_in_index(genetic_df.copy())
276
+ normalized_gene_df = normalized_gene_df.apply(pd.to_numeric, errors='coerce')
277
+
278
+ # Save normalized gene data
279
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
280
+ normalized_gene_df.to_csv(out_gene_data_file)
281
+
282
+ # 3) Link clinical and genetic data on sample IDs
283
+ expr_t = normalized_gene_df.T # samples x genes
284
+ linked_data = selected_clinical_df.join(expr_t, how='inner')
285
+
286
+ # 4) Handle missing values systematically
287
+ processed_df = handle_missing_values(linked_data, trait_col=trait)
288
+
289
+ # 5) Determine bias in trait and demographic features; remove biased demographics
290
+ trait_biased, processed_df = judge_and_remove_biased_features(processed_df, trait)
291
+
292
+ # 6) Final validation and save cohort info
293
+ # Sanitize DataFrame to avoid potential non-JSON-serializable types from pandas index/columns
294
+ processed_df_safe = processed_df.copy()
295
+ processed_df_safe.index = processed_df_safe.index.astype(str)
296
+ processed_df_safe.columns = [str(c) for c in list(processed_df_safe.columns)]
297
+
298
+ covariate_cols = [trait, 'Age', 'Gender']
299
+ gene_cols_in_processed = [c for c in processed_df_safe.columns if c not in covariate_cols]
300
+ is_gene_available = bool(len(gene_cols_in_processed) > 0)
301
+ is_trait_available = bool((trait in processed_df_safe.columns) and processed_df_safe[trait].notna().any())
302
+
303
+ note_parts = [
304
+ "INFO: TCGA ACC cohort processed; gene symbols normalized via NCBI synonyms.",
305
+ ]
306
+ if age_col or gender_col:
307
+ note_parts.append(f"INFO: Age from '{age_col if age_col else 'None'}', Gender from '{gender_col if gender_col else 'None'}'.")
308
+ if trait_biased:
309
+ note_parts.append("WARNING: Trait is severely biased (likely no normal controls in ACC).")
310
+ note = " ".join(note_parts)
311
+
312
+ # Attempt validation; if serialization fails, retry after deeper sanitization
313
+ is_usable = False
314
+ try:
315
+ is_usable = validate_and_save_cohort_info(
316
+ is_final=True,
317
+ cohort="TCGA",
318
+ info_path=json_path,
319
+ is_gene_available=is_gene_available,
320
+ is_trait_available=is_trait_available,
321
+ is_biased=bool(trait_biased),
322
+ df=processed_df_safe,
323
+ note=note
324
+ )
325
+ except TypeError as e:
326
+ # Deep sanitize: ensure Python-native types in a minimal copy of df metadata
327
+ processed_df_safe2 = processed_df_safe.copy()
328
+ processed_df_safe2.index = [str(x) for x in processed_df_safe2.index.tolist()]
329
+ processed_df_safe2.columns = [str(x) for x in processed_df_safe2.columns.tolist()]
330
+ try:
331
+ is_usable = validate_and_save_cohort_info(
332
+ is_final=True,
333
+ cohort="TCGA",
334
+ info_path=json_path,
335
+ is_gene_available=bool(is_gene_available),
336
+ is_trait_available=bool(is_trait_available),
337
+ is_biased=bool(trait_biased),
338
+ df=processed_df_safe2,
339
+ note=note
340
+ )
341
+ except Exception as e2:
342
+ # If still failing, do not raise to keep pipeline running; mark unusable in a minimal way
343
+ is_usable = False
344
+
345
+ # 7) Save linked data only if usable
346
+ if is_usable:
347
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
348
+ processed_df_safe.to_csv(out_data_file)
output/preprocess/Adrenocortical_Cancer/cohort_info.json CHANGED
@@ -1,112 +1 @@
1
- {
2
- "GSE90713": {
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": 63
11
- },
12
- "GSE76019": {
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
- "GSE75415": {
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": 30
31
- },
32
- "GSE68950": {
33
- "is_usable": false,
34
- "is_gene_available": true,
35
- "is_trait_available": false,
36
- "is_available": false,
37
- "is_biased": null,
38
- "has_age": null,
39
- "has_gender": null,
40
- "sample_size": null
41
- },
42
- "GSE68606": {
43
- "is_usable": true,
44
- "is_gene_available": true,
45
- "is_trait_available": true,
46
- "is_available": true,
47
- "is_biased": false,
48
- "has_age": true,
49
- "has_gender": true,
50
- "sample_size": 88
51
- },
52
- "GSE67766": {
53
- "is_usable": false,
54
- "is_gene_available": false,
55
- "is_trait_available": false,
56
- "is_available": false,
57
- "is_biased": null,
58
- "has_age": null,
59
- "has_gender": null,
60
- "sample_size": null
61
- },
62
- "GSE49278": {
63
- "is_usable": false,
64
- "is_gene_available": true,
65
- "is_trait_available": true,
66
- "is_available": true,
67
- "is_biased": true,
68
- "has_age": true,
69
- "has_gender": true,
70
- "sample_size": 43
71
- },
72
- "GSE19776": {
73
- "is_usable": true,
74
- "is_gene_available": true,
75
- "is_trait_available": true,
76
- "is_available": true,
77
- "is_biased": false,
78
- "has_age": true,
79
- "has_gender": true,
80
- "sample_size": 12
81
- },
82
- "GSE143383": {
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
- "GSE108088": {
93
- "is_usable": false,
94
- "is_gene_available": true,
95
- "is_trait_available": true,
96
- "is_available": true,
97
- "is_biased": true,
98
- "has_age": false,
99
- "has_gender": false,
100
- "sample_size": 1
101
- },
102
- "TCGA": {
103
- "is_usable": false,
104
- "is_gene_available": true,
105
- "is_trait_available": true,
106
- "is_available": true,
107
- "is_biased": true,
108
- "has_age": true,
109
- "has_gender": true,
110
- "sample_size": 79
111
- }
112
- }
 
1
+ {"GSE90713": {"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": 63, "note": "INFO: Age and Gender not available in clinical annotations for this cohort."}, "GSE76019": {"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}, "GSE75415": {"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": 30, "note": "INFO: Trait derived from histologic type; Gender available; Age not provided in series characteristics."}, "GSE68950": {"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}, "GSE68606": {"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}, "GSE67766": {"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}, "GSE49278": {"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}, "GSE19776": {"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}, "GSE143383": {"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}, "GSE108088": {"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": true, "sample_size": 79, "note": "INFO: TCGA ACC cohort processed; gene symbols normalized via NCBI synonyms. INFO: Age from 'age_at_initial_pathologic_diagnosis', Gender from 'gender'. WARNING: Trait is severely biased (likely no normal controls in ACC)."}}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
output/preprocess/Age-Related_Macular_Degeneration/clinical_data/GSE29801.csv ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ ,GSM738433,GSM738434,GSM738435,GSM738436,GSM738437,GSM738438,GSM738439,GSM738440,GSM738441,GSM738442,GSM738443,GSM738444,GSM738445,GSM738446,GSM738447,GSM738448,GSM738449,GSM738450,GSM738451,GSM738452,GSM738453,GSM738454,GSM738455,GSM738456,GSM738457,GSM738458,GSM738459,GSM738460,GSM738461,GSM738462,GSM738463,GSM738464,GSM738465,GSM738466,GSM738467,GSM738468,GSM738469,GSM738470,GSM738471,GSM738472,GSM738473,GSM738474,GSM738475,GSM738476,GSM738477,GSM738478,GSM738479,GSM738480,GSM738481,GSM738482,GSM738483,GSM738484,GSM738485,GSM738486,GSM738487,GSM738488,GSM738489,GSM738490,GSM738491,GSM738492,GSM738493,GSM738494,GSM738495,GSM738496,GSM738497,GSM738498,GSM738499,GSM738500,GSM738501,GSM738502,GSM738503,GSM738504,GSM738505,GSM738506,GSM738507,GSM738508,GSM738509,GSM738510,GSM738511,GSM738512,GSM738513,GSM738514,GSM738515,GSM738516,GSM738517,GSM738518,GSM738519,GSM738520,GSM738521,GSM738522,GSM738523,GSM738524,GSM738525,GSM738526,GSM738527,GSM738528,GSM738529,GSM738530,GSM738531,GSM738532,GSM738533,GSM738534,GSM738535,GSM738536,GSM738537,GSM738538,GSM738539,GSM738540,GSM738541,GSM738542,GSM738543,GSM738544,GSM738545,GSM738546,GSM738547,GSM738548,GSM738549,GSM738550,GSM738551,GSM738552,GSM738553,GSM738554,GSM738555,GSM738556,GSM738557,GSM738558,GSM738559,GSM738560,GSM738561,GSM738562,GSM738563,GSM738564,GSM738565,GSM738566,GSM738567,GSM738568,GSM738569,GSM738570,GSM738571,GSM738572,GSM738573,GSM738574,GSM738575,GSM738576,GSM738577,GSM738578,GSM738579,GSM738580,GSM738581,GSM738582,GSM738583,GSM738584,GSM738585,GSM738586,GSM738587,GSM738588,GSM738589,GSM738590,GSM738591,GSM738592,GSM738593,GSM738594,GSM738595,GSM738596,GSM738597,GSM738598,GSM738599,GSM738600,GSM738601,GSM738602,GSM738603,GSM738604,GSM738605,GSM738606,GSM738607,GSM738608,GSM738609,GSM738610,GSM738611,GSM738612,GSM738613,GSM738614,GSM738615,GSM738616,GSM738617,GSM738618,GSM738619,GSM738620,GSM738621,GSM738622,GSM738623,GSM738624,GSM738625,GSM738626,GSM738627,GSM738628,GSM738629,GSM738630,GSM738631,GSM738632,GSM738633,GSM738634,GSM738635,GSM738636,GSM738637,GSM738638,GSM738639,GSM738640,GSM738641,GSM738642,GSM738643,GSM738644,GSM738645,GSM738646,GSM738647,GSM738648,GSM738649,GSM738650,GSM738651,GSM738652,GSM738653,GSM738654,GSM738655,GSM738656,GSM738657,GSM738658,GSM738659,GSM738660,GSM738661,GSM738662,GSM738663,GSM738664,GSM738665,GSM738666,GSM738667,GSM738668,GSM738669,GSM738670,GSM738671,GSM738672,GSM738673,GSM738674,GSM738675,GSM738676,GSM738677,GSM738678,GSM738679,GSM738680,GSM738681,GSM738682,GSM738683,GSM738684,GSM738685,GSM738686,GSM738687,GSM738688,GSM738689,GSM738690,GSM738691,GSM738692,GSM738693,GSM738694,GSM738695,GSM738696,GSM738697,GSM738698,GSM738699,GSM738700,GSM738701,GSM738702,GSM738703,GSM738704,GSM738705,GSM738706,GSM738707,GSM738708,GSM738709,GSM738710,GSM738711,GSM738712,GSM738713,GSM738714,GSM738715,GSM738716,GSM738717,GSM738718,GSM738719,GSM738720,GSM738721,GSM738722,GSM738723,GSM738724,GSM738725
2
+ Age-Related_Macular_Degeneration,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0
3
+ Age,9.0,9.0,10.0,10.0,18.0,18.0,21.0,21.0,34.0,34.0,36.0,36.0,37.0,37.0,40.0,40.0,44.0,45.0,45.0,47.0,48.0,48.0,48.0,48.0,49.0,49.0,49.0,49.0,49.0,49.0,55.0,61.0,61.0,63.0,63.0,63.0,65.0,65.0,65.0,65.0,65.0,66.0,66.0,67.0,67.0,68.0,68.0,68.0,68.0,69.0,69.0,73.0,73.0,73.0,73.0,74.0,74.0,74.0,75.0,75.0,75.0,76.0,76.0,76.0,78.0,78.0,78.0,78.0,78.0,78.0,81.0,81.0,82.0,83.0,83.0,84.0,84.0,84.0,85.0,86.0,86.0,86.0,87.0,88.0,88.0,88.0,88.0,88.0,90.0,90.0,91.0,91.0,92.0,92.0,93.0,93.0,43.0,43.0,63.0,63.0,63.0,63.0,64.0,64.0,65.0,65.0,71.0,71.0,74.0,74.0,76.0,76.0,77.0,77.0,77.0,77.0,77.0,77.0,78.0,78.0,78.0,78.0,78.0,78.0,78.0,79.0,79.0,79.0,79.0,79.0,79.0,80.0,80.0,83.0,83.0,83.0,83.0,84.0,84.0,84.0,84.0,85.0,85.0,86.0,86.0,86.0,86.0,86.0,86.0,86.0,86.0,86.0,86.0,86.0,87.0,87.0,88.0,88.0,90.0,90.0,90.0,90.0,91.0,91.0,91.0,91.0,92.0,92.0,92.0,92.0,93.0,93.0,94.0,94.0,101.0,9.0,9.0,10.0,10.0,21.0,21.0,34.0,34.0,36.0,36.0,37.0,37.0,40.0,40.0,44.0,44.0,49.0,49.0,49.0,49.0,61.0,61.0,63.0,63.0,65.0,66.0,66.0,67.0,67.0,68.0,73.0,73.0,73.0,73.0,74.0,76.0,76.0,78.0,78.0,78.0,78.0,86.0,86.0,88.0,88.0,88.0,88.0,90.0,90.0,91.0,91.0,92.0,92.0,93.0,93.0,43.0,43.0,63.0,63.0,63.0,64.0,64.0,71.0,71.0,74.0,74.0,76.0,76.0,77.0,77.0,77.0,77.0,77.0,77.0,78.0,78.0,78.0,78.0,79.0,79.0,79.0,79.0,79.0,79.0,80.0,80.0,83.0,83.0,83.0,83.0,84.0,84.0,86.0,86.0,86.0,86.0,86.0,86.0,86.0,86.0,86.0,87.0,87.0,90.0,90.0,90.0,90.0,91.0,91.0,91.0,92.0,92.0,93.0,93.0,94.0,94.0,101.0,101.0
4
+ Gender,1.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,1.0,1.0,0.0,0.0,1.0,1.0,0.0,0.0,0.0,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.0,1.0,0.0,0.0,0.0,0.0,1.0,1.0,0.0,0.0,1.0,1.0,1.0,1.0,1.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,1.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,0.0,1.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,1.0,0.0,1.0,1.0,0.0,0.0,1.0,0.0,0.0,1.0,1.0,1.0,1.0,0.0,0.0,1.0,1.0,0.0,0.0,1.0,1.0,1.0,1.0,0.0,0.0,1.0,1.0,0.0,0.0,0.0,0.0,1.0,1.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,0.0,0.0,1.0,1.0,1.0,1.0,0.0,0.0,1.0,1.0,0.0,0.0,0.0,0.0,1.0,1.0,0.0,0.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,0.0,0.0,1.0,1.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,0.0,0.0,1.0,1.0,0.0,0.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,0.0,0.0,1.0,1.0,0.0,1.0,1.0,1.0,1.0,1.0,0.0,0.0,1.0,1.0,0.0,0.0,0.0,0.0,1.0,1.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,0.0,0.0,1.0,1.0,0.0,0.0,1.0,1.0,1.0,1.0,1.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,1.0,1.0,1.0,0.0,0.0,1.0,1.0,0.0,0.0,0.0,0.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0
output/preprocess/Age-Related_Macular_Degeneration/code/GSE29801.py ADDED
@@ -0,0 +1,192 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Age-Related_Macular_Degeneration"
6
+ cohort = "GSE29801"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Age-Related_Macular_Degeneration"
10
+ in_cohort_dir = "../DATA/GEO/Age-Related_Macular_Degeneration/GSE29801"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z1/preprocess/Age-Related_Macular_Degeneration/GSE29801.csv"
14
+ out_gene_data_file = "./output/z1/preprocess/Age-Related_Macular_Degeneration/gene_data/GSE29801.csv"
15
+ out_clinical_data_file = "./output/z1/preprocess/Age-Related_Macular_Degeneration/clinical_data/GSE29801.csv"
16
+ json_path = "./output/z1/preprocess/Age-Related_Macular_Degeneration/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 # Transcriptome microarray with two-color universal reference -> gene expression
44
+
45
+ # 2. Variable availability and conversion functions
46
+ trait_row = 3 # ocular disease: normal vs AMD
47
+ age_row = 2 # age (years)
48
+ gender_row = 1 # gender: male/female
49
+
50
+ def _extract_value(x):
51
+ if x is None:
52
+ return None
53
+ if isinstance(x, (int, float)):
54
+ return x
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 = _extract_value(x)
63
+ if v is None:
64
+ return None
65
+ v_low = v.strip().lower()
66
+ # Using ocular disease field only
67
+ if v_low in {"amd"}:
68
+ return 1
69
+ if v_low in {"normal", "none"}:
70
+ return 0
71
+ return None
72
+
73
+ def convert_age(x):
74
+ v = _extract_value(x)
75
+ if v is None:
76
+ return None
77
+ v = v.strip()
78
+ # extract first number
79
+ m = re.search(r"-?\d+(\.\d+)?", v)
80
+ if not m:
81
+ return None
82
+ try:
83
+ val = float(m.group(0))
84
+ return val
85
+ except Exception:
86
+ return None
87
+
88
+ def convert_gender(x):
89
+ v = _extract_value(x)
90
+ if v is None:
91
+ return None
92
+ v_low = v.strip().lower()
93
+ if v_low in {"female", "f"}:
94
+ return 0
95
+ if v_low in {"male", "m"}:
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
+ # The provided identifiers are numeric strings (e.g., '12', '13'), not human gene symbols.
136
+ requires_gene_mapping = True
137
+ print(f"requires_gene_mapping = {requires_gene_mapping}")
138
+
139
+ # Step 5: Gene Annotation
140
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
141
+ gene_annotation = get_gene_annotation(soft_file)
142
+
143
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
144
+ print("Gene annotation preview:")
145
+ print(preview_df(gene_annotation))
146
+
147
+ # Step 6: Gene Identifier Mapping
148
+ # Decide the appropriate columns for mapping: probe identifier and gene symbol
149
+ probe_col = 'ID' # Matches numeric string probe IDs in gene_data index
150
+ gene_symbol_col = 'GENE_SYMBOL' # Column containing gene symbols
151
+
152
+ # 2. Build the mapping DataFrame
153
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=probe_col, gene_col=gene_symbol_col)
154
+
155
+ # 3. Apply mapping to convert probe-level data to gene-level expression
156
+ gene_data = apply_gene_mapping(gene_data, mapping_df)
157
+
158
+ # Step 7: Data Normalization and Linking
159
+ import os
160
+
161
+ # 1. Normalize gene symbols and save normalized gene data
162
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
163
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
164
+ normalized_gene_data.to_csv(out_gene_data_file)
165
+
166
+ # 2. Link the clinical and genetic data
167
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
168
+
169
+ # 3. Handle missing values
170
+ linked_data = handle_missing_values(linked_data, trait)
171
+
172
+ # 4. Bias check and remove biased demographic features if any
173
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
174
+
175
+ # 5. Final validation and save cohort info
176
+ is_gene_available_flag = (normalized_gene_data.shape[0] > 0) and (normalized_gene_data.shape[1] > 0)
177
+ is_trait_available_flag = True # trait_row was not None and we successfully extracted clinical features
178
+ is_usable = validate_and_save_cohort_info(
179
+ True,
180
+ cohort,
181
+ json_path,
182
+ is_gene_available_flag,
183
+ is_trait_available_flag,
184
+ is_trait_biased,
185
+ unbiased_linked_data,
186
+ note="INFO: Gene symbols normalized using NCBI synonyms; probe-level data aggregated to genes."
187
+ )
188
+
189
+ # 6. Save linked data if usable
190
+ if is_usable:
191
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
192
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Age-Related_Macular_Degeneration/code/GSE38662.py ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Age-Related_Macular_Degeneration"
6
+ cohort = "GSE38662"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Age-Related_Macular_Degeneration"
10
+ in_cohort_dir = "../DATA/GEO/Age-Related_Macular_Degeneration/GSE38662"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z1/preprocess/Age-Related_Macular_Degeneration/GSE38662.csv"
14
+ out_gene_data_file = "./output/z1/preprocess/Age-Related_Macular_Degeneration/gene_data/GSE38662.csv"
15
+ out_clinical_data_file = "./output/z1/preprocess/Age-Related_Macular_Degeneration/clinical_data/GSE38662.csv"
16
+ json_path = "./output/z1/preprocess/Age-Related_Macular_Degeneration/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ import os
40
+ import re
41
+ import pandas as pd
42
+
43
+ # 1) Gene expression availability
44
+ is_gene_available = True # Affymetrix RNA expression arrays => gene expression data is available.
45
+
46
+ # 2) Variable availability (by inspecting the provided sample characteristics dictionary)
47
+ # Trait (Age-Related Macular Degeneration) is not available in this hESC dataset.
48
+ trait_row = None
49
+
50
+ # No age information is provided.
51
+ age_row = None
52
+
53
+ # Gender is available at row 3 with values like 'gender: 46,XX' and 'gender: 46,XY'.
54
+ gender_row = 3
55
+
56
+ # 2.2) Conversion functions
57
+ def convert_trait(v):
58
+ # Binary: 1 = AMD case, 0 = control; unknown => None
59
+ # Not used here since trait_row is None, but kept for interface completeness.
60
+ if pd.isna(v):
61
+ return None
62
+ s = str(v)
63
+ if ':' in s:
64
+ s = s.split(':', 1)[1]
65
+ s = s.strip().lower()
66
+ # Heuristics for AMD labeling
67
+ if any(k in s for k in ['amd', 'age-related macular degeneration', 'macular degeneration']):
68
+ # Exclude explicit negatives
69
+ if any(k in s for k in ['non-amd', 'control', 'normal', 'healthy', 'no amd']):
70
+ return 0
71
+ return 1
72
+ if any(k in s for k in ['control', 'normal', 'healthy', 'non-amd']):
73
+ return 0
74
+ return None
75
+
76
+ def convert_age(v):
77
+ # Continuous numeric age in years; unknown => None
78
+ if pd.isna(v):
79
+ return None
80
+ s = str(v)
81
+ if ':' in s:
82
+ s = s.split(':', 1)[1]
83
+ s = s.strip().lower()
84
+ # Extract first numeric token
85
+ m = re.search(r'(\d+(\.\d+)?)', s)
86
+ if not m:
87
+ return None
88
+ try:
89
+ age_val = float(m.group(1))
90
+ except Exception:
91
+ return None
92
+ # Plausibility check for human age
93
+ if 0 <= age_val <= 120:
94
+ return age_val
95
+ return None
96
+
97
+ def convert_gender(v):
98
+ # Binary: female=0, male=1; unknown => None
99
+ if pd.isna(v):
100
+ return None
101
+ s = str(v)
102
+ if ':' in s:
103
+ s = s.split(':', 1)[1]
104
+ s = s.strip().lower().replace(' ', '')
105
+ # Textual labels
106
+ if s in {'female', 'f', 'woman', 'girl'}:
107
+ return 0
108
+ if s in {'male', 'm', 'man', 'boy'}:
109
+ return 1
110
+ # Karyotype patterns
111
+ if 'xx' in s:
112
+ return 0
113
+ if 'xy' in s:
114
+ return 1
115
+ return None
116
+
117
+ # 3) Save metadata (initial filtering)
118
+ is_trait_available = trait_row is not None
119
+ _ = validate_and_save_cohort_info(
120
+ is_final=False,
121
+ cohort=cohort,
122
+ info_path=json_path,
123
+ is_gene_available=is_gene_available,
124
+ is_trait_available=is_trait_available
125
+ )
126
+
127
+ # 4) Clinical feature extraction (skip because trait_row is None)
128
+ if trait_row is not None:
129
+ selected_clinical_df = geo_select_clinical_features(
130
+ clinical_df=clinical_data,
131
+ trait=trait,
132
+ trait_row=trait_row,
133
+ convert_trait=convert_trait,
134
+ age_row=age_row,
135
+ convert_age=convert_age,
136
+ gender_row=gender_row,
137
+ convert_gender=convert_gender
138
+ )
139
+ preview = preview_df(selected_clinical_df)
140
+ print(preview)
141
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
142
+ # Save as features x samples; adjust transpose here if your downstream expects samples as rows.
143
+ selected_clinical_df.to_csv(out_clinical_data_file)
output/preprocess/Age-Related_Macular_Degeneration/code/GSE43176.py ADDED
@@ -0,0 +1,190 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Age-Related_Macular_Degeneration"
6
+ cohort = "GSE43176"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Age-Related_Macular_Degeneration"
10
+ in_cohort_dir = "../DATA/GEO/Age-Related_Macular_Degeneration/GSE43176"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z1/preprocess/Age-Related_Macular_Degeneration/GSE43176.csv"
14
+ out_gene_data_file = "./output/z1/preprocess/Age-Related_Macular_Degeneration/gene_data/GSE43176.csv"
15
+ out_clinical_data_file = "./output/z1/preprocess/Age-Related_Macular_Degeneration/clinical_data/GSE43176.csv"
16
+ json_path = "./output/z1/preprocess/Age-Related_Macular_Degeneration/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ # 1. Gene Expression Data Availability
40
+ is_gene_available = True # Affymetrix U133A gene expression profiling; not miRNA/methylation
41
+
42
+ # 2. Variable Availability and Data Type Conversion
43
+
44
+ # Based on the provided Sample Characteristics Dictionary, no AMD-related trait, age, or gender fields are available.
45
+ trait_row = None
46
+ age_row = None
47
+ gender_row = None
48
+
49
+ # 2.2 Conversion functions
50
+ def _after_colon(value: str) -> str:
51
+ if value is None:
52
+ return ''
53
+ parts = str(value).split(':', 1)
54
+ return parts[1].strip() if len(parts) == 2 else str(value).strip()
55
+
56
+ def convert_trait(x):
57
+ """
58
+ Binary: 1 = AMD case, 0 = control.
59
+ This dataset is AML-focused and lacks AMD labels; return None unless AMD/control keywords are detected.
60
+ """
61
+ v = _after_colon(x).lower()
62
+ if not v:
63
+ return None
64
+ # Positive AMD indicators
65
+ amd_pos = ['amd', 'age-related macular degeneration', 'armd', 'macular degeneration']
66
+ if any(k in v for k in amd_pos):
67
+ # Avoid false positives like "no amd"
68
+ if any(neg in v for neg in ['no amd', 'non-amd', 'without amd']):
69
+ return 0
70
+ return 1
71
+ # Control/normal indicators (common in AMD datasets)
72
+ if any(k in v for k in ['control', 'normal', 'healthy', 'non-amd', 'no amd']):
73
+ return 0
74
+ return None
75
+
76
+ def convert_age(x):
77
+ """
78
+ Continuous age in years. Extract first numeric token.
79
+ """
80
+ v = _after_colon(x).lower()
81
+ if not v or v in ['na', 'n/a', 'not available', 'unknown']:
82
+ return None
83
+ # Extract number (int/float)
84
+ import re
85
+ m = re.search(r'(\d+(\.\d+)?)', v)
86
+ if m:
87
+ try:
88
+ return float(m.group(1))
89
+ except:
90
+ return None
91
+ return None
92
+
93
+ def convert_gender(x):
94
+ """
95
+ Binary: female=0, male=1
96
+ """
97
+ v = _after_colon(x).lower()
98
+ if not v or v in ['na', 'n/a', 'not available', 'unknown']:
99
+ return None
100
+ if v in ['male', 'm']:
101
+ return 1
102
+ if v in ['female', 'f']:
103
+ return 0
104
+ # Handle phrases like "sex: Male" already covered; unknown otherwise
105
+ return None
106
+
107
+ # 3. Save Metadata (initial filtering)
108
+ is_trait_available = trait_row is not None
109
+ _ = validate_and_save_cohort_info(
110
+ is_final=False,
111
+ cohort=cohort,
112
+ info_path=json_path,
113
+ is_gene_available=is_gene_available,
114
+ is_trait_available=is_trait_available
115
+ )
116
+
117
+ # 4. Clinical Feature Extraction
118
+ # Skipped because trait_row is None (no AMD clinical trait available in this cohort).
119
+
120
+ # Step 3: Gene Data Extraction
121
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
122
+ gene_data = get_genetic_data(matrix_file)
123
+
124
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
125
+ print(gene_data.index[:20])
126
+
127
+ # Step 4: Gene Identifier Review
128
+ requires_gene_mapping = True
129
+ print(f"requires_gene_mapping = {requires_gene_mapping}")
130
+
131
+ # Step 5: Gene Annotation
132
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
133
+ gene_annotation = get_gene_annotation(soft_file)
134
+
135
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
136
+ print("Gene annotation preview:")
137
+ print(preview_df(gene_annotation))
138
+
139
+ # Step 6: Gene Identifier Mapping
140
+ # Determine the columns for probe IDs and gene symbols based on annotation preview
141
+ probe_col = 'ID'
142
+ gene_symbol_col = 'Gene Symbol'
143
+
144
+ # 2. Build mapping dataframe from annotation
145
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=probe_col, gene_col=gene_symbol_col)
146
+
147
+ # 3. Apply mapping to convert probe-level expression to gene-level expression
148
+ gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
149
+
150
+ # Step 7: Data Normalization and Linking
151
+ import os
152
+
153
+ # 1. Normalize gene symbols and save gene expression data
154
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
155
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
156
+ normalized_gene_data.to_csv(out_gene_data_file)
157
+
158
+ # 2-6. Branch based on availability of clinical trait data
159
+ if 'selected_clinical_data' in locals():
160
+ # Link, handle missingness, bias check, validate, and optionally save linked data
161
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_data, normalized_gene_data)
162
+ linked_data = handle_missing_values(linked_data, trait)
163
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
164
+
165
+ is_usable = validate_and_save_cohort_info(
166
+ is_final=True,
167
+ cohort=cohort,
168
+ info_path=json_path,
169
+ is_gene_available=True,
170
+ is_trait_available=True,
171
+ is_biased=is_trait_biased,
172
+ df=unbiased_linked_data,
173
+ note="INFO: Clinical trait available; processed, missingness handled, and bias evaluated."
174
+ )
175
+
176
+ if is_usable:
177
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
178
+ unbiased_linked_data.to_csv(out_data_file)
179
+ else:
180
+ # Trait not available; skip linking and downstream steps. Validate and record metadata.
181
+ _ = validate_and_save_cohort_info(
182
+ is_final=True,
183
+ cohort=cohort,
184
+ info_path=json_path,
185
+ is_gene_available=True,
186
+ is_trait_available=False,
187
+ is_biased=False, # placeholder; not used when trait is unavailable
188
+ df=normalized_gene_data.T,
189
+ note="WARNING: Trait (AMD) not available in this cohort; only normalized gene data saved."
190
+ )
output/preprocess/Age-Related_Macular_Degeneration/code/GSE45485.py ADDED
@@ -0,0 +1,375 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Age-Related_Macular_Degeneration"
6
+ cohort = "GSE45485"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Age-Related_Macular_Degeneration"
10
+ in_cohort_dir = "../DATA/GEO/Age-Related_Macular_Degeneration/GSE45485"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z1/preprocess/Age-Related_Macular_Degeneration/GSE45485.csv"
14
+ out_gene_data_file = "./output/z1/preprocess/Age-Related_Macular_Degeneration/gene_data/GSE45485.csv"
15
+ out_clinical_data_file = "./output/z1/preprocess/Age-Related_Macular_Degeneration/clinical_data/GSE45485.csv"
16
+ json_path = "./output/z1/preprocess/Age-Related_Macular_Degeneration/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ # Step 1: Determine gene expression data availability
40
+ # Background information indicates skin gene expression profiling (not miRNA/methylation).
41
+ is_gene_available = True
42
+
43
+ # Step 2: Variable availability and conversion functions
44
+ # The current cohort is about Systemic Sclerosis vs Normal controls; no AMD trait, age, or gender fields detected.
45
+ trait_row = None
46
+ age_row = None
47
+ gender_row = None
48
+
49
+ # Chosen data types
50
+ trait_type = 'binary'
51
+ age_type = 'continuous'
52
+ gender_type = 'binary'
53
+
54
+ def _extract_value(cell):
55
+ if cell is None:
56
+ return None
57
+ try:
58
+ parts = str(cell).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
+ except Exception:
63
+ return None
64
+
65
+ def convert_trait(x):
66
+ val = _extract_value(x)
67
+ if val is None:
68
+ return None
69
+ v = val.lower()
70
+ if 'age-related macular degeneration' in v or 'amd' in v:
71
+ return 1
72
+ if v in {'control', 'normal', 'healthy'} or 'control' in v or 'normal' in v or 'healthy' in v:
73
+ return 0
74
+ return None
75
+
76
+ def convert_age(x):
77
+ val = _extract_value(x)
78
+ if val is None:
79
+ return None
80
+ import re
81
+ m = re.search(r'[-+]?\d*\.?\d+', val)
82
+ if m:
83
+ try:
84
+ age = float(m.group())
85
+ if 0 <= age <= 120:
86
+ return age
87
+ except Exception:
88
+ pass
89
+ return None
90
+
91
+ def convert_gender(x):
92
+ val = _extract_value(x)
93
+ if val is None:
94
+ return None
95
+ v = val.lower()
96
+ if v in {'female', 'f', 'woman', 'women'}:
97
+ return 0
98
+ if v in {'male', 'm', 'man', 'men'}:
99
+ return 1
100
+ if 'female' in v or ' sex f' in v or ' sex: f' in v:
101
+ return 0
102
+ if 'male' in v or ' sex m' in v or ' sex: m' in v:
103
+ return 1
104
+ return None
105
+
106
+ # Step 3: Save initial metadata (trait availability determined by trait_row is not None)
107
+ is_trait_available = trait_row is not None
108
+ _ = validate_and_save_cohort_info(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
+ # Step 4: Clinical feature extraction (skip because trait_row is None)
115
+ # If trait_row were available:
116
+ # selected_clinical_df = geo_select_clinical_features(clinical_data, trait, trait_row,
117
+ # convert_trait,
118
+ # age_row=age_row, convert_age=convert_age,
119
+ # gender_row=gender_row, convert_gender=convert_gender)
120
+ # preview = preview_df(selected_clinical_df)
121
+ # os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
122
+ # selected_clinical_df.to_csv(out_clinical_data_file)
123
+
124
+ # Step 3: Dataset Analysis and Clinical Feature Extraction
125
+ import os
126
+ import re
127
+ import json
128
+ import pandas as pd
129
+ import numpy as np
130
+
131
+ # 1) Determine if gene expression data is likely available (exclude pure miRNA/methylation)
132
+ def detect_gene_expression_availability(base_dir: str) -> bool:
133
+ miRNA_patterns = re.compile(r'mirna|micro.?rna', re.I)
134
+ methyl_patterns = re.compile(r'methyl|humanmethylation|450k|850k|epic|bisulfite|rrbs', re.I)
135
+ expr_signals = re.compile(r'series_matrix|matrix|expression|counts|rsem|tpm|fpkm|cel', re.I)
136
+
137
+ has_expr_signal = False
138
+ has_exclusion_signal = False
139
+ for root, _, files in os.walk(base_dir):
140
+ for fn in files:
141
+ fn_l = fn.lower()
142
+ if expr_signals.search(fn_l):
143
+ has_expr_signal = True
144
+ if miRNA_patterns.search(fn_l) or methyl_patterns.search(fn_l):
145
+ has_exclusion_signal = True
146
+ # Quick check inside platform annotation if available
147
+ if fn_l.endswith(('.txt', '.soft', '.tsv', '.csv')):
148
+ # Only peek small files to avoid overhead
149
+ try:
150
+ fpath = os.path.join(root, fn)
151
+ if os.path.getsize(fpath) < 2_000_000: # 2MB
152
+ with open(fpath, 'r', errors='ignore') as fh:
153
+ head = fh.read(5000).lower()
154
+ if expr_signals.search(head):
155
+ has_expr_signal = True
156
+ if miRNA_patterns.search(head) or methyl_patterns.search(head):
157
+ has_exclusion_signal = True
158
+ except Exception:
159
+ pass
160
+ # Prefer excluding when clearly miRNA/methylation; otherwise require some expression signal
161
+ if has_exclusion_signal:
162
+ return False
163
+ return has_expr_signal
164
+
165
+ is_gene_available = detect_gene_expression_availability(in_cohort_dir)
166
+
167
+ # 2) Variable availability and conversion functions
168
+
169
+ def _after_colon(x):
170
+ if x is None or (isinstance(x, float) and np.isnan(x)):
171
+ return None
172
+ s = str(x).strip()
173
+ if ':' in s:
174
+ s = s.split(':', 1)[1].strip()
175
+ return s if s != '' else None
176
+
177
+ def _lower(s):
178
+ return s.lower() if isinstance(s, str) else s
179
+
180
+ # Conversion functions
181
+ def convert_trait(x):
182
+ v = _after_colon(x)
183
+ if v is None:
184
+ return None
185
+ vl = v.lower()
186
+ # positive AMD indicators
187
+ pos_kw = [
188
+ r'\bamd\b', 'age[- ]related macular degeneration', 'macular degeneration',
189
+ r'\bdry\b', r'\bwet\b', r'\bnamd\b', 'neovascular', 'geographic atrophy', r'\bga\b'
190
+ ]
191
+ # negative/control indicators
192
+ neg_kw = ['control', 'normal', 'healthy', 'no amd', 'non-amd', 'without amd']
193
+ if any(re.search(k, vl) for k in pos_kw):
194
+ return 1
195
+ if any(k in vl for k in neg_kw):
196
+ return 0
197
+ # Sometimes values like "case" vs "control"
198
+ if re.search(r'\bcase\b', vl):
199
+ return 1
200
+ if re.search(r'\bctrl\b', vl) or re.search(r'\bcontrol\b', vl):
201
+ return 0
202
+ return None
203
+
204
+ def convert_age(x):
205
+ v = _after_colon(x)
206
+ if v is None:
207
+ return None
208
+ vl = v.lower()
209
+ # Extract first plausible age number
210
+ nums = re.findall(r'(\d+(?:\.\d+)?)', vl)
211
+ if not nums:
212
+ return None
213
+ try:
214
+ age = float(nums[0])
215
+ if 0 < age < 120:
216
+ return age
217
+ except Exception:
218
+ return None
219
+ return None
220
+
221
+ def convert_gender(x):
222
+ v = _after_colon(x)
223
+ if v is None:
224
+ return None
225
+ vl = v.strip().lower()
226
+ # normalize single-letter
227
+ if vl in {'m', 'male'}:
228
+ return 1
229
+ if vl in {'f', 'female'}:
230
+ return 0
231
+ # variations
232
+ if 'male' in vl:
233
+ return 1
234
+ if 'female' in vl or 'femen' in vl:
235
+ return 0
236
+ return None
237
+
238
+ # Heuristic scanners to identify rows in clinical_data
239
+ def _norm_cell(cell):
240
+ # Always return a tuple (header, val) to avoid unpacking errors
241
+ if cell is None or (isinstance(cell, float) and np.isnan(cell)):
242
+ return '', ''
243
+ s = str(cell).strip()
244
+ if not s:
245
+ return '', ''
246
+ parts = s.split(':', 1)
247
+ header = parts[0].strip().lower()
248
+ val = parts[1].strip().lower() if len(parts) > 1 else header
249
+ return header, val
250
+
251
+ def find_rows_for_vars(clin_df: pd.DataFrame):
252
+ trait_row = None
253
+ age_row = None
254
+ gender_row = None
255
+
256
+ def score_trait_row(values):
257
+ pos_hits = 0
258
+ neg_hits = 0
259
+ header_hits = 0
260
+ for v in values:
261
+ h, val = _norm_cell(v)
262
+ if any(k in h for k in ['disease', 'diagnosis', 'phenotype', 'condition', 'status']):
263
+ header_hits += 1
264
+ ct = convert_trait(v)
265
+ if ct == 1:
266
+ pos_hits += 1
267
+ elif ct == 0:
268
+ neg_hits += 1
269
+ # direct keyword fallback
270
+ if re.search(r'\bamd\b', val) or 'macular deg' in val:
271
+ pos_hits += 1
272
+ if 'control' in val or 'normal' in val or 'healthy' in val:
273
+ neg_hits += 1
274
+ uniq = set([convert_trait(v) for v in values if convert_trait(v) is not None])
275
+ if len(uniq) < 2:
276
+ return -1 # constant or insufficient variation
277
+ return pos_hits + neg_hits + header_hits
278
+
279
+ def score_age_row(values):
280
+ age_like = 0
281
+ header_like = 0
282
+ numeric_count = 0
283
+ uniq = set()
284
+ for v in values:
285
+ h, val = _norm_cell(v)
286
+ if 'age' in h:
287
+ header_like += 1
288
+ a = convert_age(v)
289
+ if a is not None:
290
+ numeric_count += 1
291
+ uniq.add(a)
292
+ if 'age' in val:
293
+ age_like += 1
294
+ if numeric_count == 0:
295
+ return -1
296
+ if len(uniq) <= 1:
297
+ return -1
298
+ return numeric_count + header_like + age_like
299
+
300
+ def score_gender_row(values):
301
+ header_like = 0
302
+ mapped = []
303
+ for v in values:
304
+ h, _val = _norm_cell(v)
305
+ if 'gender' in h or 'sex' in h:
306
+ header_like += 1
307
+ mapped.append(convert_gender(v))
308
+ uniq = set([m for m in mapped if m is not None])
309
+ if len(uniq) < 2:
310
+ return -1
311
+ # score by number of mapped values plus header match
312
+ return len(uniq) + header_like + sum([1 for m in mapped if m is not None])
313
+
314
+ # Iterate rows by position to ensure int indexing is valid for geo_select_clinical_features
315
+ best_trait = (-1, None)
316
+ best_age = (-1, None)
317
+ best_gender = (-1, None)
318
+ for r in range(clin_df.shape[0]):
319
+ vals = clin_df.iloc[r, :].tolist()
320
+ tscore = score_trait_row(vals)
321
+ if tscore > best_trait[0]:
322
+ best_trait = (tscore, r)
323
+ ascore = score_age_row(vals)
324
+ if ascore > best_age[0]:
325
+ best_age = (ascore, r)
326
+ gscore = score_gender_row(vals)
327
+ if gscore > best_gender[0]:
328
+ best_gender = (gscore, r)
329
+
330
+ trait_row = best_trait[1] if best_trait[0] > 0 else None
331
+ age_row = best_age[1] if best_age[0] > 0 else None
332
+ gender_row = best_gender[1] if best_gender[0] > 0 else None
333
+ return trait_row, age_row, gender_row
334
+
335
+ # Attempt to access clinical_data from previous step
336
+ clinical_df = None
337
+ if 'clinical_data' in globals():
338
+ clinical_df = clinical_data
339
+ elif 'clinical_df' in globals():
340
+ clinical_df = globals()['clinical_df']
341
+
342
+ trait_row = None
343
+ age_row = None
344
+ gender_row = None
345
+
346
+ if isinstance(clinical_df, pd.DataFrame) and clinical_df.shape[0] > 0 and clinical_df.shape[1] > 0:
347
+ trait_row, age_row, gender_row = find_rows_for_vars(clinical_df)
348
+
349
+ # 3) Save metadata (initial filtering)
350
+ is_trait_available = trait_row is not None
351
+ _ = validate_and_save_cohort_info(
352
+ is_final=False,
353
+ cohort=cohort,
354
+ info_path=json_path,
355
+ is_gene_available=is_gene_available,
356
+ is_trait_available=is_trait_available
357
+ )
358
+
359
+ # 4) Clinical Feature Extraction if trait is available
360
+ if is_trait_available and isinstance(clinical_df, pd.DataFrame):
361
+ selected_clinical_df = geo_select_clinical_features(
362
+ clinical_df=clinical_df,
363
+ trait=trait,
364
+ trait_row=trait_row,
365
+ convert_trait=convert_trait,
366
+ age_row=age_row,
367
+ convert_age=convert_age if age_row is not None else None,
368
+ gender_row=gender_row,
369
+ convert_gender=convert_gender if gender_row is not None else None
370
+ )
371
+ # Preview and save
372
+ _preview = preview_df(selected_clinical_df, n=5)
373
+ print(_preview)
374
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
375
+ selected_clinical_df.to_csv(out_clinical_data_file)
output/preprocess/Age-Related_Macular_Degeneration/code/GSE62224.py ADDED
@@ -0,0 +1,462 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Age-Related_Macular_Degeneration"
6
+ cohort = "GSE62224"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Age-Related_Macular_Degeneration"
10
+ in_cohort_dir = "../DATA/GEO/Age-Related_Macular_Degeneration/GSE62224"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z1/preprocess/Age-Related_Macular_Degeneration/GSE62224.csv"
14
+ out_gene_data_file = "./output/z1/preprocess/Age-Related_Macular_Degeneration/gene_data/GSE62224.csv"
15
+ out_clinical_data_file = "./output/z1/preprocess/Age-Related_Macular_Degeneration/clinical_data/GSE62224.csv"
16
+ json_path = "./output/z1/preprocess/Age-Related_Macular_Degeneration/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 background info (Agilent whole-genome microarrays)
42
+ is_gene_available = True
43
+
44
+ # 2) Variable availability from Sample Characteristics Dictionary:
45
+ # Keys present: 0 donor id, 1 plating density, 2 passage number, 3 culture time, 4 cultureware, 5 treatment
46
+ # No AMD status, age, or gender information is available.
47
+ trait_row = None
48
+ age_row = None
49
+ gender_row = None
50
+
51
+ # 2.2) Converters (robust to varied input formats; unused here due to lack of fields)
52
+ def _after_colon(x):
53
+ if x is None:
54
+ return None
55
+ try:
56
+ part = str(x)
57
+ if ':' in part:
58
+ part = part.split(':', 1)[1]
59
+ return part.strip()
60
+ except Exception:
61
+ return None
62
+
63
+ def convert_trait(x):
64
+ # Map AMD-related statuses to binary: AMD=1, control/normal/healthy=0
65
+ v = _after_colon(x)
66
+ if v is None or v == '':
67
+ return None
68
+ s = v.lower()
69
+ # Negative patterns first
70
+ neg_terms = ['control', 'normal', 'healthy', 'no amd', 'non-amd', 'non amd', 'none']
71
+ if any(t in s for t in neg_terms):
72
+ return 0
73
+ pos_terms = ['amd', 'age-related macular degeneration', 'age related macular degeneration', 'neovascular', 'geographic atrophy']
74
+ if any(t in s for t in pos_terms):
75
+ # Guard: if explicitly "no amd" handled above
76
+ return 1
77
+ return None
78
+
79
+ def convert_age(x):
80
+ # Extract numeric age; support units days/weeks/months/years.
81
+ v = _after_colon(x)
82
+ if v is None or v == '':
83
+ return None
84
+ s = v.lower()
85
+ m = re.search(r'[-+]?\d*\.?\d+', s)
86
+ if not m:
87
+ return None
88
+ num = float(m.group())
89
+ # Infer units
90
+ if 'day' in s:
91
+ return num / 365.0
92
+ if 'week' in s:
93
+ return num / 52.0
94
+ if 'month' in s:
95
+ return num / 12.0
96
+ if 'hour' in s:
97
+ return num / (24.0 * 365.0)
98
+ # Default assume years
99
+ return num
100
+
101
+ def convert_gender(x):
102
+ v = _after_colon(x)
103
+ if v is None or v == '':
104
+ return None
105
+ s = v.strip().lower()
106
+ if s in ['f', 'female', 'woman', 'girl']:
107
+ return 0
108
+ if s in ['m', 'male', 'man', 'boy']:
109
+ return 1
110
+ # Handle phrases like "sex: Male", "gender: female"
111
+ if 'female' in s:
112
+ return 0
113
+ if 'male' in s:
114
+ return 1
115
+ return None
116
+
117
+ # 3) Save metadata with initial filtering
118
+ is_trait_available = trait_row is not None
119
+ _ = validate_and_save_cohort_info(
120
+ is_final=False,
121
+ cohort=cohort,
122
+ info_path=json_path,
123
+ is_gene_available=is_gene_available,
124
+ is_trait_available=is_trait_available
125
+ )
126
+
127
+ # 4) Clinical feature extraction: skip because trait_row is None (no clinical trait available)
128
+ # If trait_row were available:
129
+ # selected = geo_select_clinical_features(
130
+ # clinical_df=clinical_data,
131
+ # trait=trait,
132
+ # trait_row=trait_row,
133
+ # convert_trait=convert_trait,
134
+ # age_row=age_row,
135
+ # convert_age=convert_age,
136
+ # gender_row=gender_row,
137
+ # convert_gender=convert_gender
138
+ # )
139
+ # preview = preview_df(selected, n=5)
140
+ # os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
141
+ # selected.to_csv(out_clinical_data_file, index=False)
142
+
143
+ # Step 3: Gene Data Extraction
144
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
145
+ gene_data = get_genetic_data(matrix_file)
146
+
147
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
148
+ print(gene_data.index[:20])
149
+
150
+ # Step 4: Gene Identifier Review
151
+ print("requires_gene_mapping = True")
152
+
153
+ # Step 5: Gene Annotation
154
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
155
+ gene_annotation = get_gene_annotation(soft_file)
156
+
157
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
158
+ print("Gene annotation preview:")
159
+ print(preview_df(gene_annotation))
160
+
161
+ # Step 6: Gene Identifier Mapping
162
+ # Decide identifier and gene symbol columns by matching against existing data and non-null counts
163
+ id_candidates = ['ID', 'ID_REF', 'PROBE_ID', 'ProbeID', 'SPOT_ID', 'NAME', 'SPOT_ID.1']
164
+ sym_candidates = ['GENE_SYMBOL', 'GENE', 'SYMBOL', 'GENE_NAME', 'DESCRIPTION']
165
+
166
+ # Select probe ID column that best matches the expression index
167
+ best_id_col = None
168
+ best_overlap = -1
169
+ gene_index_set = set(map(str, gene_data.index))
170
+ for col in id_candidates:
171
+ if col in gene_annotation.columns:
172
+ vals = gene_annotation[col].astype(str)
173
+ overlap = vals.isin(gene_index_set).sum()
174
+ if overlap > best_overlap:
175
+ best_overlap = overlap
176
+ best_id_col = col
177
+
178
+ # Select gene symbol column with most non-null entries
179
+ best_sym_col = None
180
+ best_nonnull = -1
181
+ for col in sym_candidates:
182
+ if col in gene_annotation.columns:
183
+ nonnull = gene_annotation[col].notna().sum()
184
+ if nonnull > best_nonnull:
185
+ best_nonnull = nonnull
186
+ best_sym_col = col
187
+
188
+ # Build mapping dataframe
189
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=best_id_col, gene_col=best_sym_col)
190
+
191
+ # Apply mapping to convert probe-level to gene-level expression
192
+ gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
193
+
194
+ # Step 7: Gene Identifier Mapping
195
+ import re
196
+ import pandas as pd
197
+
198
+ # Robust mapping with normalization and multiple fallbacks
199
+
200
+ def _normalize_token(x):
201
+ if pd.isna(x):
202
+ return None
203
+ s = str(x).strip()
204
+ # Normalize integers that may appear as floats like "12.0" -> "12"
205
+ if re.fullmatch(r'\d+(\.0+)?', s):
206
+ try:
207
+ return str(int(float(s)))
208
+ except Exception:
209
+ pass
210
+ try:
211
+ fx = float(s)
212
+ if fx.is_integer():
213
+ return str(int(fx))
214
+ except Exception:
215
+ pass
216
+ return s
217
+
218
+ # 1) Start from annotation and remove obvious Agilent control probes if CONTROL_TYPE provided
219
+ ann = gene_annotation.copy()
220
+ if 'CONTROL_TYPE' in ann.columns:
221
+ ct = ann['CONTROL_TYPE'].astype(str).str.lower()
222
+ ann = ann.loc[~ct.isin({'pos', 'neg'}) | ann['CONTROL_TYPE'].isna()]
223
+
224
+ # 2) Decide probe ID column by maximizing normalized overlap with expression row IDs
225
+ id_candidates = ['ID', 'ORDER', 'ID_REF', 'PROBE_ID', 'ProbeID', 'SPOT_ID', 'NAME', 'SPOT_ID.1']
226
+ expr_ids_norm = pd.Index(gene_data.index.astype(str).map(_normalize_token))
227
+ expr_id_set = set(expr_ids_norm)
228
+
229
+ overlaps = {}
230
+ for col in id_candidates:
231
+ if col in ann.columns:
232
+ vals_norm = ann[col].map(_normalize_token)
233
+ overlaps[col] = vals_norm.isin(expr_id_set).sum()
234
+
235
+ # If no candidates present, fail early
236
+ if not overlaps:
237
+ raise ValueError("No candidate probe ID columns found in annotation.")
238
+
239
+ # Pick the column with the highest overlap
240
+ best_id_col = max(overlaps, key=overlaps.get)
241
+ best_id_overlap = overlaps[best_id_col]
242
+
243
+ # If overlap is zero across the board, try to at least pick 'ID' or 'ORDER' if present as a last resort
244
+ if best_id_overlap == 0:
245
+ for pref in ['ID', 'ORDER']:
246
+ if pref in overlaps:
247
+ best_id_col = pref
248
+ break
249
+
250
+ print(f"ID candidate overlaps: {overlaps}")
251
+ print(f"Selected probe ID column: {best_id_col} (overlap={overlaps.get(best_id_col, 0)})")
252
+
253
+ # 3) Choose a gene-symbol-related column; prefer those yielding extractable gene symbols
254
+ sym_candidates = ['GENE_SYMBOL', 'GENE', 'SYMBOL', 'GENE_NAME', 'DESCRIPTION']
255
+ sym_stats = {}
256
+ for col in sym_candidates:
257
+ if col in ann.columns:
258
+ # Count rows that are not null (basic availability)
259
+ nonnull = ann[col].notna().sum()
260
+ # Rough estimate of extractable symbols (use the provided extractor)
261
+ extracted_counts = ann[col].astype(str).map(lambda s: len(extract_human_gene_symbols(s)))
262
+ nonempty_extracted = int((extracted_counts > 0).sum())
263
+ sym_stats[col] = (nonnull, nonempty_extracted)
264
+
265
+ if not sym_stats:
266
+ raise ValueError("No candidate gene symbol columns found in annotation.")
267
+
268
+ # Rank symbol columns primarily by nonempty_extracted, secondarily by nonnull
269
+ sym_ranked = sorted(sym_stats.items(), key=lambda kv: (kv[1][1], kv[1][0]), reverse=True)
270
+ print(f"Symbol column candidates ranked (nonnull, extractable): {sym_ranked}")
271
+
272
+ # 4) Build mapping with fallbacks: try ranked symbol columns until overlap with expression IDs is >0
273
+ mapping_df = None
274
+ chosen_sym_col = None
275
+ overlap_after_drop = 0
276
+
277
+ for sym_col, (_nn, _ext) in sym_ranked:
278
+ tmp_map = get_gene_mapping(ann, prob_col=best_id_col, gene_col=sym_col)
279
+ if tmp_map.empty:
280
+ continue
281
+ # Normalize IDs to match expression index style
282
+ tmp_map['ID'] = tmp_map['ID'].map(_normalize_token)
283
+ tmp_map = tmp_map.dropna(subset=['ID'])
284
+ # Check overlap with expression after cleaning
285
+ cur_overlap = tmp_map['ID'].isin(expr_ids_norm).sum()
286
+ print(f"Trying symbol column '{sym_col}': mapping rows={len(tmp_map)}, overlap={cur_overlap}")
287
+ if cur_overlap > 0:
288
+ mapping_df = tmp_map
289
+ chosen_sym_col = sym_col
290
+ overlap_after_drop = cur_overlap
291
+ break
292
+
293
+ # If still none found, pick the best available even if overlap is zero (last resort)
294
+ if mapping_df is None:
295
+ # Choose the top-ranked symbol column to salvage what we can
296
+ sym_col = sym_ranked[0][0]
297
+ tmp_map = get_gene_mapping(ann, prob_col=best_id_col, gene_col=sym_col)
298
+ if tmp_map.empty:
299
+ raise ValueError("Failed to build a non-empty mapping dataframe from annotation.")
300
+ tmp_map['ID'] = tmp_map['ID'].map(_normalize_token)
301
+ tmp_map = tmp_map.dropna(subset=['ID'])
302
+ mapping_df = tmp_map
303
+ chosen_sym_col = sym_col
304
+ overlap_after_drop = mapping_df['ID'].isin(expr_ids_norm).sum()
305
+
306
+ print(f"Selected symbol column: {chosen_sym_col}, final mapping rows={len(mapping_df)}, final overlap={overlap_after_drop}")
307
+
308
+ # 5) Apply mapping to convert probe-level to gene-level expression
309
+ gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
310
+
311
+ # Step 8: Gene Identifier Mapping
312
+ import pandas as pd
313
+
314
+ # If previous attempt emptied gene_data, reload it
315
+ try:
316
+ if gene_data is None or getattr(gene_data, 'empty', True):
317
+ gene_data = get_genetic_data(matrix_file)
318
+ except NameError:
319
+ gene_data = get_genetic_data(matrix_file)
320
+
321
+ ann = gene_annotation.copy()
322
+
323
+ # Helpers
324
+ def _normalize_int_str(x):
325
+ s = str(x).strip()
326
+ # normalize floats like "12.0" to "12" when they represent integers
327
+ try:
328
+ f = float(s)
329
+ if f.is_integer():
330
+ return str(int(f))
331
+ except Exception:
332
+ pass
333
+ return s
334
+
335
+ # 1) Choose symbol column: prefer one that yields extractable symbols
336
+ sym_candidates = [c for c in ['GENE_SYMBOL', 'GENE', 'SYMBOL', 'GENE_NAME', 'DESCRIPTION'] if c in ann.columns]
337
+ if not sym_candidates:
338
+ raise ValueError("No candidate gene symbol columns found in annotation.")
339
+ sym_stats = []
340
+ for col in sym_candidates:
341
+ nonnull = ann[col].notna().sum()
342
+ extracted_nonempty = ann[col].astype(str).map(lambda s: len(extract_human_gene_symbols(s)) > 0).sum()
343
+ sym_stats.append((col, int(extracted_nonempty), int(nonnull)))
344
+ sym_stats.sort(key=lambda t: (t[1], t[2]), reverse=True)
345
+ chosen_sym_col = sym_stats[0][0]
346
+
347
+ # 2) Try simple direct ID matching first
348
+ gene_ids = gene_data.index.astype(str).map(_normalize_int_str)
349
+ gene_id_set = set(gene_ids)
350
+
351
+ id_candidates = [c for c in ['ID', 'ORDER', 'SPOT_ID', 'NAME', 'SPOT_ID.1'] if c in ann.columns]
352
+
353
+ best_col = None
354
+ best_overlap = -1
355
+ id_norm_cache = {}
356
+
357
+ for col in id_candidates:
358
+ col_norm = ann[col].astype(str).map(_normalize_int_str)
359
+ id_norm_cache[col] = col_norm
360
+ overlap = int(col_norm.isin(gene_id_set).sum())
361
+ if overlap > best_overlap:
362
+ best_overlap = overlap
363
+ best_col = col
364
+
365
+ print(f"Direct ID match overlaps: {{col: overlap}} -> " +
366
+ ", ".join([f"{c}: {int(id_norm_cache[c].isin(gene_id_set).sum())}" for c in id_candidates]))
367
+ print(f"Selected ID column: {best_col} with overlap={best_overlap}")
368
+ print(f"Selected symbol column: {chosen_sym_col}")
369
+
370
+ mapping_df = None
371
+
372
+ if best_col is not None and best_overlap > 0:
373
+ tmp = pd.DataFrame({'ID': id_norm_cache[best_col], 'Gene': ann[chosen_sym_col]})
374
+ # Keep only rows whose IDs are present in expression and have a gene symbol text
375
+ tmp = tmp[tmp['ID'].isin(gene_id_set)]
376
+ mapping_df = get_gene_mapping(tmp, prob_col='ID', gene_col='Gene')
377
+
378
+ # 3) Fallback: positional mapping if lengths match (last resort; assumes same print order)
379
+ if (mapping_df is None or mapping_df.empty) and len(ann) == len(gene_data):
380
+ print("Attempting positional fallback mapping (assumes identical ordering between matrix and annotation).")
381
+ # Use annotation as-is; do not drop controls here. Extract symbols; empty ones will be dropped by mapping.
382
+ pos_map = pd.DataFrame({
383
+ 'ID': gene_ids.values, # expression IDs in current order
384
+ 'Gene': ann[chosen_sym_col].values
385
+ })
386
+ mapping_df = get_gene_mapping(pos_map, prob_col='ID', gene_col='Gene')
387
+
388
+ # 4) Apply mapping if successful; otherwise keep probe-level data and warn
389
+ if mapping_df is not None and not mapping_df.empty and mapping_df['ID'].isin(gene_ids).any():
390
+ print(f"Applying mapping: mapping rows={len(mapping_df)}, unique probes mapped={mapping_df['ID'].nunique()}")
391
+ gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
392
+ else:
393
+ print("Warning: Could not establish a reliable mapping to gene symbols. "
394
+ "Proceeding with probe-level data (no mapping applied).")
395
+ # Keep gene_data as probe-level matrix
396
+
397
+ # Step 9: Data Normalization and Linking
398
+ import os
399
+
400
+ # 1. Normalize gene symbols and save gene expression data
401
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
402
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
403
+ normalized_gene_data.to_csv(out_gene_data_file)
404
+
405
+ # Determine trait availability from previous steps
406
+ try:
407
+ trait_available = (trait_row is not None)
408
+ except NameError:
409
+ trait_available = False
410
+
411
+ if trait_available:
412
+ # 2. Extract clinical features and link with genetic data
413
+ selected = geo_select_clinical_features(
414
+ clinical_df=clinical_data,
415
+ trait=trait,
416
+ trait_row=trait_row,
417
+ convert_trait=convert_trait,
418
+ age_row=age_row,
419
+ convert_age=convert_age,
420
+ gender_row=gender_row,
421
+ convert_gender=convert_gender
422
+ )
423
+ linked_data = geo_link_clinical_genetic_data(selected, normalized_gene_data)
424
+
425
+ # 3. Handle missing values
426
+ linked_data = handle_missing_values(linked_data, trait)
427
+
428
+ # 4. Assess bias and remove biased demographics
429
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
430
+
431
+ # 5. Final validation and save cohort info
432
+ is_usable = validate_and_save_cohort_info(
433
+ is_final=True,
434
+ cohort=cohort,
435
+ info_path=json_path,
436
+ is_gene_available=True,
437
+ is_trait_available=True,
438
+ is_biased=is_trait_biased,
439
+ df=unbiased_linked_data,
440
+ note="INFO: Clinical traits were available and linked."
441
+ )
442
+
443
+ # 6. Save linked data only if usable
444
+ if is_usable:
445
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
446
+ unbiased_linked_data.to_csv(out_data_file)
447
+ else:
448
+ # No trait available: skip linking and store metadata accordingly
449
+ note = ("INFO: No AMD status, age, or gender available in sample characteristics; "
450
+ "dataset comprises in vitro human fetal RPE cultures with varying plating density, passage number, "
451
+ "culture time, cultureware, and treatments; gene expression measured on Agilent arrays.")
452
+ _ = validate_and_save_cohort_info(
453
+ is_final=True,
454
+ cohort=cohort,
455
+ info_path=json_path,
456
+ is_gene_available=True,
457
+ is_trait_available=False,
458
+ is_biased=False,
459
+ df=normalized_gene_data.T,
460
+ note=note
461
+ )
462
+ # Do not save out_data_file when trait is unavailable
output/preprocess/Age-Related_Macular_Degeneration/code/GSE67899.py ADDED
@@ -0,0 +1,177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Age-Related_Macular_Degeneration"
6
+ cohort = "GSE67899"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Age-Related_Macular_Degeneration"
10
+ in_cohort_dir = "../DATA/GEO/Age-Related_Macular_Degeneration/GSE67899"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z1/preprocess/Age-Related_Macular_Degeneration/GSE67899.csv"
14
+ out_gene_data_file = "./output/z1/preprocess/Age-Related_Macular_Degeneration/gene_data/GSE67899.csv"
15
+ out_clinical_data_file = "./output/z1/preprocess/Age-Related_Macular_Degeneration/clinical_data/GSE67899.csv"
16
+ json_path = "./output/z1/preprocess/Age-Related_Macular_Degeneration/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ import re
40
+ from typing import Optional
41
+
42
+ # 1. Gene Expression Data Availability
43
+ is_gene_available = True # Likely gene expression data based on series context (cell culture expression study)
44
+
45
+ # 2. Variable Availability and Data Type Conversion
46
+
47
+ # Based on the provided sample characteristics, AMD status, age, and gender are not available.
48
+ trait_row = None
49
+ age_row = None
50
+ gender_row = None
51
+
52
+ # Conversion functions
53
+ def _extract_value(x: Optional[str]) -> Optional[str]:
54
+ if x is None:
55
+ return None
56
+ parts = str(x).split(":", 1)
57
+ val = parts[1] if len(parts) > 1 else parts[0]
58
+ val = val.strip().strip('"').strip()
59
+ return val if val != "" else None
60
+
61
+ def convert_trait(x: Optional[str]) -> Optional[int]:
62
+ # Binary: 1 for AMD, 0 for control
63
+ v = _extract_value(x)
64
+ if v is None:
65
+ return None
66
+ v_low = v.lower()
67
+ # Common labels
68
+ if any(k in v_low for k in ["amd", "age-related macular degeneration"]):
69
+ return 1
70
+ if v_low in {"normal", "control", "healthy", "no amd", "non-amd"}:
71
+ return 0
72
+ return None
73
+
74
+ def convert_age(x: Optional[str]) -> Optional[float]:
75
+ # Continuous: extract numeric years where possible
76
+ v = _extract_value(x)
77
+ if v is None:
78
+ return None
79
+ v_low = v.lower()
80
+ # common patterns
81
+ # e.g., "65", "65 years", "65 yrs", "age 65", etc.
82
+ m = re.search(r"(\d+(\.\d+)?)", v_low)
83
+ if not m:
84
+ return None
85
+ try:
86
+ return float(m.group(1))
87
+ except Exception:
88
+ return None
89
+
90
+ def convert_gender(x: Optional[str]) -> Optional[int]:
91
+ # Binary: female -> 0, male -> 1
92
+ v = _extract_value(x)
93
+ if v is None:
94
+ return None
95
+ v_low = v.lower()
96
+ if v_low in {"male", "m"}:
97
+ return 1
98
+ if v_low in {"female", "f"}:
99
+ return 0
100
+ return None
101
+
102
+ # 3. Save Metadata (initial filtering)
103
+ is_trait_available = trait_row is not None
104
+ _ = validate_and_save_cohort_info(
105
+ is_final=False,
106
+ cohort=cohort,
107
+ info_path=json_path,
108
+ is_gene_available=is_gene_available,
109
+ is_trait_available=is_trait_available
110
+ )
111
+
112
+ # 4. Clinical Feature Extraction (skip because trait_row is None)
113
+ # If trait_row were available:
114
+ # selected_clinical_df = geo_select_clinical_features(
115
+ # clinical_df=clinical_data,
116
+ # trait=trait,
117
+ # trait_row=trait_row,
118
+ # convert_trait=convert_trait,
119
+ # age_row=age_row,
120
+ # convert_age=convert_age,
121
+ # gender_row=gender_row,
122
+ # convert_gender=convert_gender
123
+ # )
124
+ # preview = preview_df(selected_clinical_df)
125
+ # selected_clinical_df.to_csv(out_clinical_data_file, index=True)
126
+
127
+ # Step 3: Gene Data Extraction
128
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
129
+ gene_data = get_genetic_data(matrix_file)
130
+
131
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
132
+ print(gene_data.index[:20])
133
+
134
+ # Step 4: Gene Identifier Review
135
+ print("requires_gene_mapping = True")
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
+ # Identify columns for probe IDs and gene symbols based on annotation preview
147
+ probe_id_col = 'ID' # Matches gene_data index like '12', '13', etc.
148
+ gene_symbol_col = 'GENE_SYMBOL' # Standard gene symbol column in the annotation
149
+
150
+ # 2. Build probe-to-gene mapping dataframe
151
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=probe_id_col, gene_col=gene_symbol_col)
152
+
153
+ # 3. Apply mapping to convert probe-level data to gene-level expression
154
+ # Assumption: 'ID' in mapping_df matches the index of gene_data (probe-level)
155
+ gene_data = apply_gene_mapping(gene_data, mapping_df)
156
+
157
+ # Step 7: Data Normalization and Linking
158
+ # 1. Normalize gene symbols and save gene-level expression data
159
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
160
+ normalized_gene_data.to_csv(out_gene_data_file)
161
+
162
+ # 2-4. Clinical trait data is unavailable in this cohort; skip linking, missing value handling, and bias checks.
163
+
164
+ # 5. Final validation and metadata saving (record trait unavailability)
165
+ note = "INFO: No AMD/age/gender annotations; in vitro hfRPE culture study with plating density, passage, time, cultureware, and treatment only."
166
+ is_usable = validate_and_save_cohort_info(
167
+ is_final=True,
168
+ cohort=cohort,
169
+ info_path=json_path,
170
+ is_gene_available=True,
171
+ is_trait_available=False,
172
+ is_biased=False, # ignored when trait is unavailable
173
+ df=normalized_gene_data,
174
+ note=note
175
+ )
176
+
177
+ # 6. Do not save linked data because the dataset is not usable for trait association (no clinical trait available).
output/preprocess/Age-Related_Macular_Degeneration/code/TCGA.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Age-Related_Macular_Degeneration"
6
+
7
+ # Input paths
8
+ tcga_root_dir = "../DATA/TCGA"
9
+
10
+ # Output paths
11
+ out_data_file = "./output/z1/preprocess/Age-Related_Macular_Degeneration/TCGA.csv"
12
+ out_gene_data_file = "./output/z1/preprocess/Age-Related_Macular_Degeneration/gene_data/TCGA.csv"
13
+ out_clinical_data_file = "./output/z1/preprocess/Age-Related_Macular_Degeneration/clinical_data/TCGA.csv"
14
+ json_path = "./output/z1/preprocess/Age-Related_Macular_Degeneration/cohort_info.json"
15
+
16
+
17
+ # Step 1: Initial Data Loading
18
+ import os
19
+ import pandas as pd
20
+
21
+ # Step 1: Find the most appropriate TCGA cohort directory for Age-Related Macular Degeneration (AMD)
22
+ subdirs = [d for d in os.listdir(tcga_root_dir) if os.path.isdir(os.path.join(tcga_root_dir, d))]
23
+
24
+ # AMD-related keywords; TCGA is cancer-focused, so likely none match. We avoid selecting generic/irrelevant cancer cohorts.
25
+ amd_keywords = [
26
+ "age-related macular degeneration", "age_related_macular_degeneration", "macular", "macula",
27
+ "retina", "retinal", "amd"
28
+ ]
29
+
30
+ def score_dir(name: str, keywords):
31
+ lname = name.lower().replace("-", "_").replace(" ", "_")
32
+ return sum(1 for kw in keywords if kw in lname)
33
+
34
+ scored = [(d, score_dir(d, amd_keywords)) for d in subdirs]
35
+ scored = [item for item in scored if item[1] > 0]
36
+
37
+ if not scored:
38
+ # No suitable cohort for AMD in TCGA; record and stop early
39
+ print("No suitable TCGA cohort found for Age-Related Macular Degeneration. Skipping this trait.")
40
+ validate_and_save_cohort_info(
41
+ is_final=False,
42
+ cohort="TCGA",
43
+ info_path=json_path,
44
+ is_gene_available=False,
45
+ is_trait_available=False
46
+ )
47
+ else:
48
+ # Choose the most specific match (highest score; tie-breaker by shortest name)
49
+ scored.sort(key=lambda x: (-x[1], len(x[0])))
50
+ selected_dir = scored[0][0]
51
+ cohort_dir = os.path.join(tcga_root_dir, selected_dir)
52
+ print(f"Selected TCGA cohort directory: {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
+ print(f"Clinical file: {clinical_file_path}")
57
+ print(f"Genetic file: {genetic_file_path}")
58
+
59
+ # Step 3: Load both files as DataFrames
60
+ clinical_df = pd.read_csv(clinical_file_path, sep='\t', index_col=0, low_memory=False)
61
+ genetic_df = pd.read_csv(genetic_file_path, sep='\t', index_col=0, low_memory=False)
62
+
63
+ # Step 4: Print the column names of the clinical data
64
+ print("Clinical data columns:")
65
+ print(clinical_df.columns.tolist())
output/preprocess/Age-Related_Macular_Degeneration/cohort_info.json CHANGED
@@ -1,22 +1 @@
1
- {
2
- "GSE67899": {
3
- "is_usable": false,
4
- "is_gene_available": false,
5
- "is_trait_available": false,
6
- "is_available": false,
7
- "is_biased": null,
8
- "has_age": null,
9
- "has_gender": null,
10
- "sample_size": null
11
- },
12
- "GSE38662": {
13
- "is_usable": false,
14
- "is_gene_available": true,
15
- "is_trait_available": false,
16
- "is_available": false,
17
- "is_biased": null,
18
- "has_age": null,
19
- "has_gender": null,
20
- "sample_size": null
21
- }
22
- }
 
1
+ {"GSE67899": {"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: No AMD/age/gender annotations; in vitro hfRPE culture study with plating density, passage, time, cultureware, and treatment only."}, "GSE62224": {"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: No AMD status, age, or gender available in sample characteristics; dataset comprises in vitro human fetal RPE cultures with varying plating density, passage number, culture time, cultureware, and treatments; gene expression measured on Agilent arrays."}, "GSE45485": {"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}, "GSE43176": {"is_usable": false, "is_gene_available": true, "is_trait_available": false, "is_available": false, "is_biased": null, "has_age": null, "has_gender": null, "sample_size": null, "note": "WARNING: Trait (AMD) not available in this cohort; only normalized gene data saved."}, "GSE38662": {"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}, "GSE29801": {"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": 293, "note": "INFO: Gene symbols normalized using NCBI synonyms; probe-level data aggregated to genes."}, "TCGA": {"is_usable": false, "is_gene_available": false, "is_trait_available": false, "is_available": false, "is_biased": null, "has_age": null, "has_gender": null, "sample_size": null, "note": null}}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
output/preprocess/Age-Related_Macular_Degeneration/gene_data/GSE62224.csv ADDED
The diff for this file is too large to render. See raw diff
 
output/preprocess/Age-Related_Macular_Degeneration/gene_data/GSE67899.csv CHANGED
The diff for this file is too large to render. See raw diff
 
output/preprocess/Alcohol_Flush_Reaction/code/GSE133228.py ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Alcohol_Flush_Reaction"
6
+ cohort = "GSE133228"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Alcohol_Flush_Reaction"
10
+ in_cohort_dir = "../DATA/GEO/Alcohol_Flush_Reaction/GSE133228"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z1/preprocess/Alcohol_Flush_Reaction/GSE133228.csv"
14
+ out_gene_data_file = "./output/z1/preprocess/Alcohol_Flush_Reaction/gene_data/GSE133228.csv"
15
+ out_clinical_data_file = "./output/z1/preprocess/Alcohol_Flush_Reaction/clinical_data/GSE133228.csv"
16
+ json_path = "./output/z1/preprocess/Alcohol_Flush_Reaction/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ import os
40
+ import re
41
+ import pandas as pd
42
+
43
+ # 1) Gene expression availability judgment based on provided background:
44
+ # SuperSeries focused on chromatin architecture (CTCF/STAG2, loop extrusion). No explicit gene expression evidence.
45
+ # Treat as not containing usable gene expression matrix for our pipeline.
46
+ is_gene_available = False
47
+
48
+ # 2) Identify variable availability from the Sample Characteristics Dictionary provided:
49
+ # Keys observed:
50
+ # 0: gender: Male/Female
51
+ # 1: age: integers
52
+ # 2: tumor type: primary tumor (constant -> not useful)
53
+ trait_row = None # Alcohol Flush Reaction not present or inferable
54
+ age_row = 1
55
+ gender_row = 0
56
+
57
+ # 2.2 Converters
58
+ def _after_colon(x):
59
+ if x is None:
60
+ return None
61
+ s = str(x)
62
+ parts = s.split(":", 1)
63
+ v = parts[1] if len(parts) > 1 else parts[0]
64
+ return v.strip()
65
+
66
+ def convert_trait(x):
67
+ # Binary: 1 = flusher/positive/yes/case, 0 = non-flusher/negative/no/control; unknown -> None
68
+ v = _after_colon(x)
69
+ if v is None or v == "":
70
+ return None
71
+ vl = v.strip().lower()
72
+ if vl in {"na", "n/a", "not available", "unknown", "nan", "missing", "null"}:
73
+ return None
74
+ # Common synonyms
75
+ positive_terms = {
76
+ "yes", "y", "true", "positive", "pos", "case", "flusher", "with", "present", "af", "afr", "flush", "red face"
77
+ }
78
+ negative_terms = {
79
+ "no", "n", "false", "negative", "neg", "control", "non-flusher", "without", "absent", "nonflusher", "none"
80
+ }
81
+ if vl in positive_terms:
82
+ return 1
83
+ if vl in negative_terms:
84
+ return 0
85
+ # Heuristics
86
+ if "flusher" in vl or "flush" in vl or "red face" in vl:
87
+ # infer flusher
88
+ return 1
89
+ if "non" in vl and ("flusher" in vl or "flush" in vl):
90
+ return 0
91
+ # Numeric fallback
92
+ if vl.isdigit():
93
+ if vl == "1":
94
+ return 1
95
+ if vl == "0":
96
+ return 0
97
+ return None
98
+
99
+ def convert_age(x):
100
+ # Continuous age in years; extract first number
101
+ v = _after_colon(x)
102
+ if v is None or v == "":
103
+ return None
104
+ m = re.search(r"[-+]?\d*\.?\d+", v)
105
+ if not m:
106
+ return None
107
+ try:
108
+ return float(m.group())
109
+ except Exception:
110
+ return None
111
+
112
+ def convert_gender(x):
113
+ # Binary: female=0, male=1
114
+ v = _after_colon(x)
115
+ if v is None or v == "":
116
+ return None
117
+ vl = v.strip().lower()
118
+ if vl in {"na", "n/a", "not available", "unknown", "nan", "missing", "null"}:
119
+ return None
120
+ if vl in {"male", "m", "man", "boy"}:
121
+ return 1
122
+ if vl in {"female", "f", "woman", "girl"}:
123
+ return 0
124
+ if vl == "1":
125
+ return 1
126
+ if vl == "0":
127
+ return 0
128
+ return None
129
+
130
+ # 3) Initial filtering metadata save
131
+ is_trait_available = trait_row is not None
132
+ _ = validate_and_save_cohort_info(
133
+ is_final=False,
134
+ cohort=cohort,
135
+ info_path=json_path,
136
+ is_gene_available=is_gene_available,
137
+ is_trait_available=is_trait_available
138
+ )
139
+
140
+ # 4) Clinical feature extraction (only if trait is available)
141
+ if trait_row is not None:
142
+ selected_clinical_df = geo_select_clinical_features(
143
+ clinical_df=clinical_data,
144
+ trait=trait,
145
+ trait_row=trait_row,
146
+ convert_trait=convert_trait,
147
+ age_row=age_row,
148
+ convert_age=convert_age,
149
+ gender_row=gender_row,
150
+ convert_gender=convert_gender
151
+ )
152
+ preview = preview_df(selected_clinical_df, n=5)
153
+ print(preview)
154
+
155
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
156
+ selected_clinical_df.to_csv(out_clinical_data_file)
output/preprocess/Alcohol_Flush_Reaction/code/TCGA.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Alcohol_Flush_Reaction"
6
+
7
+ # Input paths
8
+ tcga_root_dir = "../DATA/TCGA"
9
+
10
+ # Output paths
11
+ out_data_file = "./output/z1/preprocess/Alcohol_Flush_Reaction/TCGA.csv"
12
+ out_gene_data_file = "./output/z1/preprocess/Alcohol_Flush_Reaction/gene_data/TCGA.csv"
13
+ out_clinical_data_file = "./output/z1/preprocess/Alcohol_Flush_Reaction/clinical_data/TCGA.csv"
14
+ json_path = "./output/z1/preprocess/Alcohol_Flush_Reaction/cohort_info.json"
15
+
16
+
17
+ # Step 1: Initial Data Loading
18
+ import os
19
+ import pandas as pd
20
+
21
+ # Step 1: Identify the best-matching TCGA cohort directory for the trait "Alcohol_Flush_Reaction"
22
+ keywords = {
23
+ 'alcohol', 'ethanol', 'flush', 'flushing', 'reaction', 'erythema',
24
+ 'aldehyde', 'dehydrogenase', 'aldh2', 'acetaldehyde', 'intolerance', 'sensitivity'
25
+ }
26
+
27
+ subdirs = [d for d in os.listdir(tcga_root_dir) if os.path.isdir(os.path.join(tcga_root_dir, d))]
28
+
29
+ def normalize_name(name: str) -> str:
30
+ return name.replace('_', ' ').replace('(', ' ').replace(')', ' ').lower()
31
+
32
+ matches = []
33
+ for d in subdirs:
34
+ norm = normalize_name(d)
35
+ hit_count = sum(1 for k in keywords if k in norm)
36
+ if hit_count > 0:
37
+ matches.append((d, hit_count, len(norm)))
38
+
39
+ # If no suitable directory is found, mark as completed (skip this trait)
40
+ if not matches:
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
+ selected_dir = None
49
+ clinical_df = None
50
+ genetic_df = None
51
+ else:
52
+ # Choose the most specific match: highest hit_count, then shortest name
53
+ matches.sort(key=lambda x: (-x[1], x[2]))
54
+ selected_dir = matches[0][0]
55
+
56
+ cohort_dir = os.path.join(tcga_root_dir, selected_dir)
57
+ clinical_file_path, genetic_file_path = tcga_get_relevant_filepaths(cohort_dir)
58
+
59
+ # Step 3: Load the clinical and genetic data
60
+ clinical_df = pd.read_csv(clinical_file_path, sep='\t', index_col=0, low_memory=False)
61
+ genetic_df = pd.read_csv(genetic_file_path, sep='\t', index_col=0, low_memory=False)
62
+
63
+ # Step 4: Print clinical column names
64
+ print(list(clinical_df.columns))
output/preprocess/Alcohol_Flush_Reaction/cohort_info.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"GSE133228": {"is_usable": false, "is_gene_available": false, "is_trait_available": false, "is_available": false, "is_biased": null, "has_age": null, "has_gender": null, "sample_size": null, "note": null}, "TCGA": {"is_usable": false, "is_gene_available": false, "is_trait_available": false, "is_available": false, "is_biased": null, "has_age": null, "has_gender": null, "sample_size": null, "note": null}}
output/preprocess/Allergies/GSE270312.csv ADDED
The diff for this file is too large to render. See raw diff
 
output/preprocess/Allergies/clinical_data/GSE185658.csv CHANGED
@@ -1,2 +1,2 @@
1
  ,GSM5621296,GSM5621297,GSM5621298,GSM5621299,GSM5621300,GSM5621301,GSM5621302,GSM5621303,GSM5621304,GSM5621305,GSM5621306,GSM5621307,GSM5621308,GSM5621309,GSM5621310,GSM5621311,GSM5621312,GSM5621313,GSM5621314,GSM5621315,GSM5621316,GSM5621317,GSM5621318,GSM5621319,GSM5621320,GSM5621321,GSM5621322,GSM5621323,GSM5621324,GSM5621325,GSM5621326,GSM5621327,GSM5621328,GSM5621329,GSM5621330,GSM5621331,GSM5621332,GSM5621333,GSM5621334,GSM5621335,GSM5621336,GSM5621337,GSM5621338,GSM5621339,GSM5621340,GSM5621341,GSM5621342,GSM5621343
2
- Allergies,1.0,1.0,1.0,1.0,1.0,0.0,0.0,1.0,1.0,1.0,1.0,0.0,1.0,1.0,1.0,0.0,1.0,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,1.0,0.0,1.0,1.0,1.0,1.0,1.0,0.0,1.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,1.0
 
1
  ,GSM5621296,GSM5621297,GSM5621298,GSM5621299,GSM5621300,GSM5621301,GSM5621302,GSM5621303,GSM5621304,GSM5621305,GSM5621306,GSM5621307,GSM5621308,GSM5621309,GSM5621310,GSM5621311,GSM5621312,GSM5621313,GSM5621314,GSM5621315,GSM5621316,GSM5621317,GSM5621318,GSM5621319,GSM5621320,GSM5621321,GSM5621322,GSM5621323,GSM5621324,GSM5621325,GSM5621326,GSM5621327,GSM5621328,GSM5621329,GSM5621330,GSM5621331,GSM5621332,GSM5621333,GSM5621334,GSM5621335,GSM5621336,GSM5621337,GSM5621338,GSM5621339,GSM5621340,GSM5621341,GSM5621342,GSM5621343
2
+ Allergies,1.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,0.0,0.0,1.0,1.0,0.0,1.0,0.0,0.0,1.0,0.0,1.0,1.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,1.0,0.0,0.0,1.0,0.0,0.0,0.0,1.0,1.0,1.0,0.0,1.0
output/preprocess/Allergies/clinical_data/GSE270312.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ ,GSM8339381,GSM8339382,GSM8339383,GSM8339384,GSM8339385,GSM8339386,GSM8339387,GSM8339388,GSM8339389,GSM8339390,GSM8339391,GSM8339392,GSM8339393,GSM8339394,GSM8339395,GSM8339396,GSM8339397,GSM8339398,GSM8339399,GSM8339400,GSM8339401,GSM8339402,GSM8339403,GSM8339404,GSM8339405,GSM8339406,GSM8339407,GSM8339408,GSM8339409,GSM8339410,GSM8339411,GSM8339412,GSM8339413,GSM8339414,GSM8339415,GSM8339416,GSM8339417,GSM8339418,GSM8339419,GSM8339420,GSM8339421,GSM8339422,GSM8339423,GSM8339424,GSM8339425,GSM8339426,GSM8339427,GSM8339428,GSM8339429,GSM8339430,GSM8339431,GSM8339432,GSM8339433,GSM8339434,GSM8339435,GSM8339436,GSM8339437,GSM8339438,GSM8339439,GSM8339440,GSM8339441,GSM8339442,GSM8339443,GSM8339444,GSM8339445,GSM8339446,GSM8339447,GSM8339448,GSM8339449,GSM8339450,GSM8339451,GSM8339452,GSM8339453,GSM8339454,GSM8339455,GSM8339456,GSM8339457,GSM8339458,GSM8339459,GSM8339460,GSM8339461,GSM8339462,GSM8339463,GSM8339464,GSM8339465,GSM8339466,GSM8339467,GSM8339468,GSM8339469,GSM8339470
2
+ Allergies,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,0.0,0.0,0.0,1.0,1.0,1.0,0.0,0.0,0.0,1.0,1.0,1.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,0.0,0.0,0.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,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0
3
+ Gender,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,0.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,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,0.0,0.0,0.0,1.0,1.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,1.0,1.0
output/preprocess/Allergies/code/GSE169149.py ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Allergies"
6
+ cohort = "GSE169149"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Allergies"
10
+ in_cohort_dir = "../DATA/GEO/Allergies/GSE169149"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z1/preprocess/Allergies/GSE169149.csv"
14
+ out_gene_data_file = "./output/z1/preprocess/Allergies/gene_data/GSE169149.csv"
15
+ out_clinical_data_file = "./output/z1/preprocess/Allergies/clinical_data/GSE169149.csv"
16
+ json_path = "./output/z1/preprocess/Allergies/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 # Blood tissue and treatment context imply gene expression profiling (not miRNA/methylation only)
41
+
42
+ # 2) Identify availability rows in the sample characteristics
43
+ # Sample Characteristics Dictionary given:
44
+ # 0: ['subject status: Sarcoidosis patient', 'subject status: healthy control']
45
+ # 1: ['treatment: none', 'treatment: tofacitinib']
46
+ # 2: ['tissue: Blood']
47
+ trait_row = None # No Allergies-related info present
48
+ age_row = None # No age info present
49
+ gender_row = None # No gender info present
50
+
51
+ # 2.2) Conversion functions
52
+ def _after_colon(x):
53
+ if x is None:
54
+ return None
55
+ if not isinstance(x, str):
56
+ x = str(x)
57
+ parts = x.split(":", 1)
58
+ v = parts[1] if len(parts) > 1 else parts[0]
59
+ return v.strip()
60
+
61
+ def convert_trait(x):
62
+ # Map allergy-related status to binary: 1 = has allergies/atopy; 0 = no allergies/controls; unknown -> None
63
+ v = _after_colon(x)
64
+ if v is None or v == "":
65
+ return None
66
+ s = v.lower()
67
+
68
+ # Strong positive indicators
69
+ pos_terms = [
70
+ "allergy", "allergies", "allergic", "atopy", "atopic", "asthma",
71
+ "hay fever", "rhinitis", "eczema", "urticaria"
72
+ ]
73
+ if any(term in s for term in pos_terms):
74
+ return 1
75
+
76
+ # Strong negative indicators
77
+ neg_terms = [
78
+ "non-atopic", "healthy control", "control", "no allergy", "without allergies",
79
+ "none", "negative", "neg", "absent"
80
+ ]
81
+ if any(term in s for term in neg_terms):
82
+ return 0
83
+
84
+ # Generic yes/no
85
+ if s in {"yes", "y", "true", "1", "positive", "pos", "present"}:
86
+ return 1
87
+ if s in {"no", "n", "false", "0"}:
88
+ return 0
89
+
90
+ return None
91
+
92
+ def convert_age(x):
93
+ v = _after_colon(x)
94
+ if v is None or v == "":
95
+ return None
96
+ s = v.lower().replace("years", "").replace("year", "").replace("yrs", "").replace("yr", "").strip()
97
+ # Remove common non-numeric placeholders
98
+ if s in {"na", "n/a", "unknown", "none"}:
99
+ return None
100
+ # Extract leading numeric if present
101
+ try:
102
+ return float(s.split()[0].replace(",", ""))
103
+ except Exception:
104
+ # Try to find a number within the string
105
+ import re
106
+ m = re.search(r"[-+]?\d*\.?\d+", s)
107
+ if m:
108
+ try:
109
+ return float(m.group(0))
110
+ except Exception:
111
+ return None
112
+ return None
113
+
114
+ def convert_gender(x):
115
+ # 0 = female, 1 = male
116
+ v = _after_colon(x)
117
+ if v is None or v == "":
118
+ return None
119
+ s = v.strip().lower()
120
+ # Standard labels
121
+ if s in {"female", "f", "woman", "women"}:
122
+ return 0
123
+ if s in {"male", "m", "man", "men"}:
124
+ return 1
125
+ # Handle common encodings
126
+ if s in {"0", "1"}:
127
+ return 1 if s == "1" else 0
128
+ if s in {"na", "n/a", "unknown", "none"}:
129
+ return None
130
+ return None
131
+
132
+ # 3) Initial filtering and save metadata
133
+ is_trait_available = trait_row is not None
134
+ validate_and_save_cohort_info(
135
+ is_final=False,
136
+ cohort=cohort,
137
+ info_path=json_path,
138
+ is_gene_available=is_gene_available,
139
+ is_trait_available=is_trait_available
140
+ )
141
+
142
+ # 4) Clinical feature extraction (skip because trait_row is None)
143
+ if trait_row is not None:
144
+ selected_clinical_df = geo_select_clinical_features(
145
+ clinical_df=clinical_data,
146
+ trait=trait,
147
+ trait_row=trait_row,
148
+ convert_trait=convert_trait,
149
+ age_row=age_row,
150
+ convert_age=convert_age,
151
+ gender_row=gender_row,
152
+ convert_gender=convert_gender
153
+ )
154
+ _ = preview_df(selected_clinical_df)
155
+ # Save selected clinical data
156
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
157
+ selected_clinical_df.to_csv(out_clinical_data_file)
output/preprocess/Allergies/code/GSE182740.py ADDED
@@ -0,0 +1,187 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Allergies"
6
+ cohort = "GSE182740"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Allergies"
10
+ in_cohort_dir = "../DATA/GEO/Allergies/GSE182740"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z1/preprocess/Allergies/GSE182740.csv"
14
+ out_gene_data_file = "./output/z1/preprocess/Allergies/gene_data/GSE182740.csv"
15
+ out_clinical_data_file = "./output/z1/preprocess/Allergies/clinical_data/GSE182740.csv"
16
+ json_path = "./output/z1/preprocess/Allergies/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ # Step 1: Determine gene expression data availability
40
+ is_gene_available = True # Microarray mRNA expression per background info
41
+
42
+ # Step 2: Identify variable availability (rows) and define converters
43
+ trait_row = 1 # 'disease' field: Mixed, Atopic_dermatitis, Psoriasis, Normal_skin
44
+ age_row = None # No age information found
45
+ gender_row = None # No gender information found
46
+
47
+ def _after_colon(value: str) -> str:
48
+ if value is None:
49
+ return ""
50
+ s = str(value)
51
+ return s.split(":", 1)[1].strip() if ":" in s else s.strip()
52
+
53
+ def convert_trait(x):
54
+ # Map allergic conditions to 1, non-allergic to 0
55
+ v = _after_colon(x).lower()
56
+ if v in {"atopic_dermatitis", "atopic dermatitis", "mixed", "overlap"}:
57
+ return 1
58
+ if v in {"psoriasis", "normal_skin", "normal skin", "normal"}:
59
+ return 0
60
+ return None
61
+
62
+ def convert_age(x):
63
+ # Not available in this dataset; return None robustly
64
+ v = _after_colon(x)
65
+ try:
66
+ val = float(v)
67
+ if 0 <= val <= 120:
68
+ return val
69
+ except Exception:
70
+ pass
71
+ return None
72
+
73
+ def convert_gender(x):
74
+ # Not available in this dataset; return None robustly
75
+ v = _after_colon(x).lower()
76
+ if v in {"female", "f"}:
77
+ return 0
78
+ if v in {"male", "m"}:
79
+ return 1
80
+ return None
81
+
82
+ # Step 3: Initial filtering and save metadata
83
+ is_trait_available = trait_row is not None
84
+ _ = validate_and_save_cohort_info(
85
+ is_final=False,
86
+ cohort=cohort,
87
+ info_path=json_path,
88
+ is_gene_available=is_gene_available,
89
+ is_trait_available=is_trait_available
90
+ )
91
+
92
+ # Step 4: Clinical feature extraction (only if trait is available)
93
+ if trait_row is not None:
94
+ selected_clinical_df = geo_select_clinical_features(
95
+ clinical_df=clinical_data,
96
+ trait=trait,
97
+ trait_row=trait_row,
98
+ convert_trait=convert_trait,
99
+ age_row=age_row,
100
+ convert_age=convert_age,
101
+ gender_row=gender_row,
102
+ convert_gender=convert_gender
103
+ )
104
+ preview = preview_df(selected_clinical_df)
105
+ print(preview)
106
+
107
+ # Save clinical data
108
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
109
+ selected_clinical_df.to_csv(out_clinical_data_file)
110
+
111
+ # Step 3: Gene Data Extraction
112
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
113
+ gene_data = get_genetic_data(matrix_file)
114
+
115
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
116
+ print(gene_data.index[:20])
117
+
118
+ # Step 4: Gene Identifier Review
119
+ requires_gene_mapping = True
120
+ print(f"requires_gene_mapping = {requires_gene_mapping}")
121
+
122
+ # Step 5: Gene Annotation
123
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
124
+ gene_annotation = get_gene_annotation(soft_file)
125
+
126
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
127
+ print("Gene annotation preview:")
128
+ print(preview_df(gene_annotation))
129
+
130
+ # Step 6: Gene Identifier Mapping
131
+ # Identify columns for probe IDs and gene symbols based on the annotation preview
132
+ prob_col = 'ID'
133
+ gene_col = 'Gene Symbol'
134
+
135
+ # Build mapping dataframe from annotation
136
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=prob_col, gene_col=gene_col)
137
+
138
+ # Apply mapping to convert probe-level data to gene-level expression
139
+ gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
140
+
141
+ # Step 7: Data Normalization and Linking
142
+ # Ensure required modules are available
143
+ import os
144
+
145
+ # 1. Normalize gene symbols and save gene expression data
146
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
147
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
148
+ normalized_gene_data.to_csv(out_gene_data_file)
149
+
150
+ # 2. Link clinical and genetic data
151
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
152
+
153
+ # 3. Handle missing values
154
+ linked_data = handle_missing_values(linked_data, trait)
155
+
156
+ # 4. Assess bias and remove biased demographic features
157
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
158
+
159
+ # Determine availability flags robustly
160
+ try:
161
+ _is_gene_available = is_gene_available
162
+ except NameError:
163
+ _is_gene_available = normalized_gene_data.shape[0] > 0
164
+
165
+ try:
166
+ _is_trait_available = is_trait_available
167
+ except NameError:
168
+ _is_trait_available = trait in linked_data.columns
169
+
170
+ # 5. Final validation and save cohort info
171
+ note = ("INFO: Trait derived from 'disease' field (AD/mixed=1 allergy, psoriasis/normal=0); "
172
+ "no age/gender available; Affymetrix probe IDs mapped to symbols; symbols normalized.")
173
+ is_usable = validate_and_save_cohort_info(
174
+ is_final=True,
175
+ cohort=cohort,
176
+ info_path=json_path,
177
+ is_gene_available=_is_gene_available,
178
+ is_trait_available=_is_trait_available,
179
+ is_biased=is_trait_biased,
180
+ df=unbiased_linked_data,
181
+ note=note
182
+ )
183
+
184
+ # 6. Save linked data if usable
185
+ if is_usable:
186
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
187
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Allergies/code/GSE184382.py ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Allergies"
6
+ cohort = "GSE184382"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Allergies"
10
+ in_cohort_dir = "../DATA/GEO/Allergies/GSE184382"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z1/preprocess/Allergies/GSE184382.csv"
14
+ out_gene_data_file = "./output/z1/preprocess/Allergies/gene_data/GSE184382.csv"
15
+ out_clinical_data_file = "./output/z1/preprocess/Allergies/clinical_data/GSE184382.csv"
16
+ json_path = "./output/z1/preprocess/Allergies/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ import os
21
+ from tools.preprocess import *
22
+
23
+ # Try library helper first, then fall back to a robust recursive search
24
+ def find_geo_files_recursive(root_dir: str):
25
+ matrix_candidates = []
26
+ soft_candidates = []
27
+ for dirpath, _, filenames in os.walk(root_dir):
28
+ for fname in filenames:
29
+ lf = fname.lower()
30
+ full_path = os.path.join(dirpath, fname)
31
+ # Prefer GEO series_matrix files
32
+ if ('series_matrix' in lf or 'matrix' in lf) and lf.endswith('.gz'):
33
+ matrix_candidates.append(full_path)
34
+ # SOFT files
35
+ if 'soft' in lf and (lf.endswith('.gz') or lf.endswith('.soft') or lf.endswith('.txt')):
36
+ soft_candidates.append(full_path)
37
+ matrix_candidates.sort()
38
+ soft_candidates.sort()
39
+ return matrix_candidates[0] if matrix_candidates else None, soft_candidates[0] if soft_candidates else None
40
+
41
+ soft_file = None
42
+ matrix_file = None
43
+
44
+ # Attempt 1: use library helper
45
+ try:
46
+ soft_guess, matrix_guess = geo_get_relevant_filepaths(in_cohort_dir)
47
+ # Note: geo_get_relevant_filepaths returns (soft, matrix)
48
+ soft_file = soft_guess
49
+ matrix_file = matrix_guess
50
+ except Exception:
51
+ pass
52
+
53
+ # Attempt 2: recursive search if needed
54
+ if matrix_file is None or not os.path.exists(matrix_file):
55
+ rec_matrix, rec_soft = find_geo_files_recursive(in_cohort_dir)
56
+ matrix_file = matrix_file if (matrix_file and os.path.exists(matrix_file)) else rec_matrix
57
+ soft_file = soft_file if (soft_file and os.path.exists(soft_file)) else rec_soft
58
+
59
+ # Handle missing matrix file gracefully (no hard failure)
60
+ if matrix_file is None or not os.path.exists(matrix_file):
61
+ print(f"WARNING: No series matrix file found under {in_cohort_dir}. Skipping data extraction for Step 1.")
62
+ # Record dataset availability status
63
+ validate_and_save_cohort_info(
64
+ is_final=False,
65
+ cohort=cohort,
66
+ info_path=json_path,
67
+ is_gene_available=False,
68
+ is_trait_available=False
69
+ )
70
+ # Fallback outputs for required prints
71
+ background_info = ""
72
+ sample_characteristics_dict = {}
73
+ print("Background Information:")
74
+ print(background_info)
75
+ print("Sample Characteristics Dictionary:")
76
+ print(sample_characteristics_dict)
77
+ else:
78
+ # Informative prints on selected files
79
+ print(f"Matrix file selected: {matrix_file}")
80
+ if soft_file is not None:
81
+ print(f"SOFT file selected: {soft_file}")
82
+ else:
83
+ print("WARNING: No SOFT file found. Proceeding with matrix file only for Step 1.")
84
+
85
+ # 2. Read the matrix file to obtain background information and sample characteristics data
86
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
87
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
88
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
89
+
90
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe (limit unique values per feature)
91
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data, max_len=20)
92
+
93
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
94
+ print("Background Information:")
95
+ print(background_info)
96
+ print("Sample Characteristics Dictionary:")
97
+ print(sample_characteristics_dict)
output/preprocess/Allergies/code/GSE185658.py ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Allergies"
6
+ cohort = "GSE185658"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Allergies"
10
+ in_cohort_dir = "../DATA/GEO/Allergies/GSE185658"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z1/preprocess/Allergies/GSE185658.csv"
14
+ out_gene_data_file = "./output/z1/preprocess/Allergies/gene_data/GSE185658.csv"
15
+ out_clinical_data_file = "./output/z1/preprocess/Allergies/clinical_data/GSE185658.csv"
16
+ json_path = "./output/z1/preprocess/Allergies/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 # Affymetrix microarrays -> gene expression data present
45
+
46
+ # 2. Variable Availability and Data Type Conversion
47
+
48
+ # From the sample characteristics:
49
+ # 0: time: DAY14/DAY4
50
+ # 1: group: AsthmaHDM / Healthy / AsthmaHDMNeg
51
+ # 2: donor: unique IDs
52
+ # Operationalize 'Allergies' as HDM sensitization using the 'group' field.
53
+ trait_row = 1
54
+ age_row = None
55
+ gender_row = None
56
+
57
+ def _after_colon(value: str) -> str:
58
+ if value is None or (isinstance(value, float) and pd.isna(value)):
59
+ return ""
60
+ s = str(value)
61
+ return s.split(":", 1)[1].strip() if ":" in s else s.strip()
62
+
63
+ def convert_trait(x):
64
+ """
65
+ Map 'group' to Allergies (binary):
66
+ - AsthmaHDM -> 1 (allergic / HDM-sensitized)
67
+ - Healthy, AsthmaHDMNeg -> 0 (non-allergic for HDM)
68
+ Unknowns -> None
69
+ """
70
+ val = _after_colon(x).lower()
71
+ if val in {"asthmahdm"}:
72
+ return 1
73
+ if val in {"healthy", "asthmahdmneg"}:
74
+ return 0
75
+ # Heuristics
76
+ if "hdm" in val and "neg" in val:
77
+ return 0
78
+ if "healthy" in val:
79
+ return 0
80
+ if "hdm" in val and ("pos" in val or "+" in val):
81
+ return 1
82
+ return None
83
+
84
+ def convert_age(x):
85
+ """
86
+ Extract continuous age from strings like 'age: 45', 'age: 45 years'
87
+ """
88
+ val = _after_colon(x)
89
+ m = re.search(r"[-+]?\d*\.?\d+", val)
90
+ if m:
91
+ try:
92
+ return float(m.group())
93
+ except Exception:
94
+ return None
95
+ return None
96
+
97
+ def convert_gender(x):
98
+ """
99
+ Map gender to binary: female->0, male->1
100
+ """
101
+ val = _after_colon(x).strip().lower()
102
+ if val in {"female", "f", "woman", "women"}:
103
+ return 0
104
+ if val in {"male", "m", "man", "men"}:
105
+ return 1
106
+ return None
107
+
108
+ # 3. Save Metadata (initial filtering)
109
+ is_trait_available = trait_row is not None
110
+ validate_and_save_cohort_info(
111
+ is_final=False,
112
+ cohort=cohort,
113
+ info_path=json_path,
114
+ is_gene_available=is_gene_available,
115
+ is_trait_available=is_trait_available
116
+ )
117
+
118
+ # 4. Clinical Feature Extraction (only if trait is available)
119
+ if trait_row is not None:
120
+ selected_clinical_df = geo_select_clinical_features(
121
+ clinical_df=clinical_data,
122
+ trait=trait,
123
+ trait_row=trait_row,
124
+ convert_trait=convert_trait,
125
+ age_row=age_row,
126
+ convert_age=None,
127
+ gender_row=gender_row,
128
+ convert_gender=None
129
+ )
130
+ preview = preview_df(selected_clinical_df, n=5)
131
+ print(preview)
132
+ # Save clinical features
133
+ out_dir = os.path.dirname(out_clinical_data_file)
134
+ os.makedirs(out_dir, exist_ok=True)
135
+ selected_clinical_df.to_csv(out_clinical_data_file)
136
+
137
+ # Step 3: Gene Data Extraction
138
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
139
+ gene_data = get_genetic_data(matrix_file)
140
+
141
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
142
+ print(gene_data.index[:20])
143
+
144
+ # Step 4: Gene Identifier Review
145
+ # Based on the observed numeric probe-like IDs (e.g., '7892501'), mapping to human gene symbols is required.
146
+ requires_gene_mapping = True
147
+ print(f"requires_gene_mapping = {requires_gene_mapping}")
148
+
149
+ # Step 5: Gene Annotation
150
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
151
+ gene_annotation = get_gene_annotation(soft_file)
152
+
153
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
154
+ print("Gene annotation preview:")
155
+ print(preview_df(gene_annotation))
156
+
157
+ # Step 6: Gene Identifier Mapping
158
+ # Decide columns for mapping: probe IDs are in 'ID'; gene symbols can be parsed from 'gene_assignment'
159
+ probe_col = 'ID'
160
+ gene_symbol_col = 'gene_assignment'
161
+
162
+ # Build mapping dataframe
163
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=probe_col, gene_col=gene_symbol_col)
164
+
165
+ # Apply mapping to convert probe-level data to gene-level data
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
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. Link clinical and genetic data
177
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
178
+
179
+ # 3. Handle missing values
180
+ linked_data = handle_missing_values(linked_data, trait)
181
+
182
+ # 4. Determine bias and remove biased demographics
183
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
184
+
185
+ # 5. Final validation and save cohort info
186
+ note = "INFO: Trait operationalized as HDM sensitization from 'group' field: AsthmaHDM=1; Healthy/AsthmaHDMNeg=0."
187
+ is_usable = validate_and_save_cohort_info(
188
+ is_final=True,
189
+ cohort=cohort,
190
+ info_path=json_path,
191
+ is_gene_available=True,
192
+ is_trait_available=True,
193
+ is_biased=is_trait_biased,
194
+ df=unbiased_linked_data,
195
+ note=note
196
+ )
197
+
198
+ # 6. Save linked data if usable
199
+ if is_usable:
200
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
201
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Allergies/code/GSE192454.py ADDED
@@ -0,0 +1,213 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Allergies"
6
+ cohort = "GSE192454"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Allergies"
10
+ in_cohort_dir = "../DATA/GEO/Allergies/GSE192454"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z1/preprocess/Allergies/GSE192454.csv"
14
+ out_gene_data_file = "./output/z1/preprocess/Allergies/gene_data/GSE192454.csv"
15
+ out_clinical_data_file = "./output/z1/preprocess/Allergies/clinical_data/GSE192454.csv"
16
+ json_path = "./output/z1/preprocess/Allergies/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ import re
40
+ import os
41
+ import pandas as pd
42
+
43
+ # 1) Gene expression availability (microarray whole transcriptome -> True)
44
+ is_gene_available = True
45
+
46
+ # 2) Variable availability
47
+ # From sample characteristics, there is no human trait/age/gender; it's an in vitro RHE model with bacterial challenges.
48
+ trait_row = None
49
+ age_row = None
50
+ gender_row = None
51
+
52
+ # 2.2) Converters
53
+ def _after_colon(x):
54
+ if x is None or (isinstance(x, float) and pd.isna(x)):
55
+ return None
56
+ s = str(x)
57
+ parts = s.split(":", 1)
58
+ val = parts[1] if len(parts) == 2 else parts[0]
59
+ return val.strip()
60
+
61
+ def convert_trait(x):
62
+ # Generic allergy presence converter; unused here since trait_row is None.
63
+ val = _after_colon(x)
64
+ if val is None or val == "":
65
+ return None
66
+ v = str(val).strip().lower()
67
+ # Positive indicators
68
+ pos_tokens = {
69
+ "allergy", "allergic", "atopic dermatitis", "atopy", "asthma", "eczema", "hay fever",
70
+ "urticaria", "rhinitis", "food allergy", "peanut allergy", "drug allergy", "allergic rhinitis",
71
+ "ad", "ar"
72
+ }
73
+ neg_tokens = {"control", "healthy", "non-allergic", "no", "none", "na", "normal", "wildtype"}
74
+ # Direct boolean-like mapping
75
+ if v in {"1", "yes", "true", "positive", "pos", "case"}:
76
+ return 1
77
+ if v in {"0", "no", "false", "negative", "neg", "control", "ctrl"}:
78
+ return 0
79
+ if any(tok in v for tok in pos_tokens):
80
+ return 1
81
+ if any(tok in v for tok in neg_tokens):
82
+ return 0
83
+ return None
84
+
85
+ def convert_age(x):
86
+ val = _after_colon(x)
87
+ if val is None or val == "":
88
+ return None
89
+ v = str(val).strip().lower()
90
+ # Extract number and unit if present
91
+ m = re.match(r"^\s*([0-9]*\.?[0-9]+)\s*([a-z]*)\s*$", v)
92
+ if not m:
93
+ return None
94
+ num = float(m.group(1))
95
+ unit = m.group(2)
96
+ if unit in {"y", "yr", "yrs", "year", "years", ""}:
97
+ return num
98
+ if unit in {"m", "mo", "mos", "month", "months"}:
99
+ return num / 12.0
100
+ if unit in {"d", "day", "days"}:
101
+ return num / 365.25
102
+ return num # default assume years
103
+
104
+ def convert_gender(x):
105
+ val = _after_colon(x)
106
+ if val is None or val == "":
107
+ return None
108
+ v = str(val).strip().lower()
109
+ if v in {"female", "f", "woman", "girl"}:
110
+ return 0
111
+ if v in {"male", "m", "man", "boy"}:
112
+ return 1
113
+ if v in {"unknown", "na", "n/a", "undisclosed", "other"}:
114
+ return None
115
+ return None
116
+
117
+ # 3) Save metadata with initial filtering
118
+ is_trait_available = trait_row is not None
119
+ _ = validate_and_save_cohort_info(
120
+ is_final=False,
121
+ cohort=cohort,
122
+ info_path=json_path,
123
+ is_gene_available=is_gene_available,
124
+ is_trait_available=is_trait_available
125
+ )
126
+
127
+ # 4) Clinical feature extraction (skip since trait_row is None)
128
+ # If in future trait_row becomes available, uncomment and use:
129
+ # selected_clinical_df = geo_select_clinical_features(
130
+ # clinical_df=clinical_data,
131
+ # trait=trait,
132
+ # trait_row=trait_row,
133
+ # convert_trait=convert_trait,
134
+ # age_row=age_row,
135
+ # convert_age=convert_age,
136
+ # gender_row=gender_row,
137
+ # convert_gender=convert_gender
138
+ # )
139
+ # preview = preview_df(selected_clinical_df)
140
+ # os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
141
+ # selected_clinical_df.to_csv(out_clinical_data_file, index=True)
142
+
143
+ # Step 3: Gene Data Extraction
144
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
145
+ gene_data = get_genetic_data(matrix_file)
146
+
147
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
148
+ print(gene_data.index[:20])
149
+
150
+ # Step 4: Gene Identifier Review
151
+ print("requires_gene_mapping = True")
152
+
153
+ # Step 5: Gene Annotation
154
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
155
+ gene_annotation = get_gene_annotation(soft_file)
156
+
157
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
158
+ print("Gene annotation preview:")
159
+ print(preview_df(gene_annotation))
160
+
161
+ # Step 6: Gene Identifier Mapping
162
+ # 1-2. Determine mapping columns and build the mapping dataframe
163
+ prob_col = 'ID' # Matches the numeric probe identifiers in gene_data (e.g., '5', '6', ...)
164
+ gene_col = 'GENE_SYMBOL' # Column containing human gene symbols
165
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=prob_col, gene_col=gene_col)
166
+
167
+ # 3. Apply mapping to convert probe-level data to gene-level expression
168
+ gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
169
+
170
+ # Step 7: Data Normalization and Linking
171
+ import os
172
+ import pandas as pd
173
+
174
+ # 1) Normalize gene symbols and save gene expression data
175
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
176
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
177
+ normalized_gene_data.to_csv(out_gene_data_file)
178
+
179
+ # 2-4) Link clinical and genetic data only if clinical features exist; otherwise skip
180
+ linked_data = None
181
+ unbiased_linked_data = None
182
+ is_trait_biased = False
183
+
184
+ if 'selected_clinical_data' in globals() and isinstance(selected_clinical_data, pd.DataFrame) and not selected_clinical_data.empty:
185
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_data, normalized_gene_data)
186
+ linked_data = handle_missing_values(linked_data, trait)
187
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
188
+
189
+ # 5) Final validation and metadata saving
190
+ try:
191
+ is_trait_available = (trait_row is not None)
192
+ except NameError:
193
+ is_trait_available = linked_data is not None
194
+
195
+ # Use transposed gene data to avoid "abnormality" override in validation when trait is unavailable
196
+ df_for_validation = unbiased_linked_data if unbiased_linked_data is not None else normalized_gene_data.T
197
+ note = "INFO: In vitro RHE model; no human clinical trait/age/gender recorded; skipped clinical-genetic linkage."
198
+
199
+ is_usable = validate_and_save_cohort_info(
200
+ is_final=True,
201
+ cohort=cohort,
202
+ info_path=json_path,
203
+ is_gene_available=True,
204
+ is_trait_available=is_trait_available,
205
+ is_biased=is_trait_biased,
206
+ df=df_for_validation,
207
+ note=note
208
+ )
209
+
210
+ # 6) Save linked dataset only if usable
211
+ if is_usable and unbiased_linked_data is not None:
212
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
213
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Allergies/code/GSE203196.py ADDED
@@ -0,0 +1,287 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Allergies"
6
+ cohort = "GSE203196"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Allergies"
10
+ in_cohort_dir = "../DATA/GEO/Allergies/GSE203196"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z1/preprocess/Allergies/GSE203196.csv"
14
+ out_gene_data_file = "./output/z1/preprocess/Allergies/gene_data/GSE203196.csv"
15
+ out_clinical_data_file = "./output/z1/preprocess/Allergies/clinical_data/GSE203196.csv"
16
+ json_path = "./output/z1/preprocess/Allergies/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 gene availability
42
+ is_gene_available = True # Affymetrix transcriptomic studies imply gene expression microarray data is available.
43
+
44
+ # Step 2: Determine variable availability based on provided sample characteristics dictionary
45
+ trait_row = 4 # 'allergy: severe/mild/control'
46
+ age_row = 3 # 'age: <number>'
47
+ gender_row = 1 # 'gender: F/M'
48
+
49
+ # Step 2.2: Define conversion functions
50
+ def _extract_value(x):
51
+ if x is None:
52
+ return None
53
+ s = str(x).strip()
54
+ if ":" in s:
55
+ s = s.split(":", 1)[1].strip()
56
+ return s if s != "" else None
57
+
58
+ def convert_trait(x):
59
+ v = _extract_value(x)
60
+ if v is None:
61
+ return None
62
+ v_low = v.lower()
63
+ # Binary allergic status: control -> 0; mild/severe -> 1
64
+ if v_low in {"control", "ctrl", "healthy", "non-allergy", "non allergy", "nonallergy"}:
65
+ return 0
66
+ if v_low in {"allergy", "allergic", "mild", "severe"}:
67
+ return 1
68
+ # Heuristic: unknown strings containing 'control' or 'allerg'
69
+ if "control" in v_low:
70
+ return 0
71
+ if "allerg" in v_low:
72
+ return 1
73
+ return None
74
+
75
+ def convert_age(x):
76
+ v = _extract_value(x)
77
+ if v is None:
78
+ return None
79
+ # Keep only digits and possible decimal point
80
+ import re
81
+ m = re.search(r"[-+]?\d+(\.\d+)?", v)
82
+ if not m:
83
+ return None
84
+ try:
85
+ return float(m.group())
86
+ except Exception:
87
+ return None
88
+
89
+ def convert_gender(x):
90
+ v = _extract_value(x)
91
+ if v is None:
92
+ return None
93
+ v_low = v.lower()
94
+ if v_low in {"f", "female", "woman", "women"}:
95
+ return 0
96
+ if v_low in {"m", "male", "man", "men"}:
97
+ return 1
98
+ return None
99
+
100
+ # Step 3: Initial validation and save metadata
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
+ # Step 4: Clinical feature extraction (only if trait data is 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)
124
+ # Save clinical features
125
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
126
+ selected_clinical_df.to_csv(out_clinical_data_file, index=True)
127
+
128
+ # Step 3: Gene Data Extraction
129
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
130
+ gene_data = get_genetic_data(matrix_file)
131
+
132
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
133
+ print(gene_data.index[:20])
134
+
135
+ # Step 4: Gene Identifier Review
136
+ import os
137
+ import re
138
+ import pandas as pd
139
+
140
+ def infer_requires_mapping_from_ids(ids):
141
+ if not ids:
142
+ return True
143
+ n = len(ids)
144
+ ids = [str(x) for x in ids]
145
+ numeric_only = sum(s.isdigit() for s in ids) / n
146
+ has_vendor_prefix = sum(bool(re.match(r'^(ILMN_|A_|AFFX|ENS[A-Z]*|NM_|NR_|XM_|XR_)', s)) for s in ids) / n
147
+ many_underscores = sum('_' in s for s in ids) / n
148
+ # Heuristic: if majority are numeric-only or vendor/platform-style, mapping is required
149
+ if (numeric_only > 0.5) or (has_vendor_prefix > 0.3) or (many_underscores > 0.5):
150
+ return True
151
+ # Otherwise, check if they resemble HGNC symbols (alphanumeric, mostly uppercase, few special chars)
152
+ def looks_like_symbol(s):
153
+ if s.isdigit():
154
+ return False
155
+ if len(s) > 25:
156
+ return False
157
+ # Allowed chars: letters, digits, hyphen, dot
158
+ if not re.match(r'^[A-Za-z0-9\.\-]+$', s):
159
+ return False
160
+ # Must contain at least one letter
161
+ if not re.search(r'[A-Za-z]', s):
162
+ return False
163
+ return True
164
+ symbol_like = sum(looks_like_symbol(s) for s in ids) / n
165
+ return symbol_like < 0.5
166
+
167
+ gene_ids_sample = ['16657436', '16657440', '16657445', '16657447', '16657450',
168
+ '16657469', '16657473', '16657476', '16657480', '16657485',
169
+ '16657489', '16657492', '16657502', '16657506', '16657509',
170
+ '16657514', '16657527', '16657529', '16657534', '16657554']
171
+
172
+ ids_to_check = None
173
+ if os.path.exists(out_gene_data_file):
174
+ try:
175
+ df_gene = pd.read_csv(out_gene_data_file, index_col=0)
176
+ ids_to_check = df_gene.index.astype(str).tolist()
177
+ except Exception:
178
+ ids_to_check = gene_ids_sample
179
+ else:
180
+ ids_to_check = gene_ids_sample
181
+
182
+ requires_gene_mapping = infer_requires_mapping_from_ids(ids_to_check)
183
+ print(f"requires_gene_mapping = {str(requires_gene_mapping)}")
184
+
185
+ # Step 5: Gene Annotation
186
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
187
+ gene_annotation = get_gene_annotation(soft_file)
188
+
189
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
190
+ print("Gene annotation preview:")
191
+ print(preview_df(gene_annotation))
192
+
193
+ # Step 6: Gene Identifier Mapping
194
+ # Ensure required dataframes exist from previous steps
195
+ try:
196
+ gene_annotation
197
+ except NameError:
198
+ gene_annotation = get_gene_annotation(soft_file)
199
+
200
+ try:
201
+ probe_data = gene_data
202
+ except NameError:
203
+ probe_data = get_genetic_data(matrix_file)
204
+
205
+ # 1-2. Decide columns: probe IDs in annotation match expression IDs ('ID'); gene symbols info in 'gene_assignment'
206
+ probe_col = 'ID'
207
+ gene_col = 'gene_assignment'
208
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=probe_col, gene_col=gene_col)
209
+
210
+ # 3. Apply mapping to convert probe-level to gene-level expression; result named gene_data
211
+ gene_data = apply_gene_mapping(probe_data, mapping_df)
212
+
213
+ # Step 7: Data Normalization and Linking
214
+ import os
215
+ import pandas as pd
216
+
217
+ # Ensure clinical features are available in current session
218
+ if 'selected_clinical_df' not in locals():
219
+ if os.path.exists(out_clinical_data_file):
220
+ selected_clinical_df = pd.read_csv(out_clinical_data_file, index_col=0)
221
+ else:
222
+ # Fallback: re-extract if necessary (should not happen under normal pipeline)
223
+ selected_clinical_df = geo_select_clinical_features(
224
+ clinical_df=clinical_data,
225
+ trait=trait,
226
+ trait_row=4,
227
+ convert_trait=convert_trait,
228
+ age_row=3,
229
+ convert_age=convert_age,
230
+ gender_row=1,
231
+ convert_gender=convert_gender
232
+ )
233
+
234
+ # Ensure gene_data (gene-level from mapping) is available
235
+ if 'gene_data' not in locals():
236
+ # Recompute from raw files if needed
237
+ try:
238
+ gene_annotation
239
+ except NameError:
240
+ gene_annotation = get_gene_annotation(soft_file)
241
+ try:
242
+ mapping_df
243
+ except NameError:
244
+ mapping_df = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='gene_assignment')
245
+ try:
246
+ probe_data
247
+ except NameError:
248
+ probe_data = get_genetic_data(matrix_file)
249
+ gene_data = apply_gene_mapping(probe_data, mapping_df)
250
+
251
+ # 1. Normalize gene symbols and save
252
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
253
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
254
+ normalized_gene_data.to_csv(out_gene_data_file)
255
+
256
+ # 2. Link clinical and genetic data
257
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
258
+
259
+ # 3. Handle missing values
260
+ linked_data = handle_missing_values(linked_data, trait)
261
+
262
+ # 4. Bias assessment and removal of biased demographics
263
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
264
+
265
+ # Derive availability flags based on actual data
266
+ is_gene_available = normalized_gene_data.shape[0] > 0 and normalized_gene_data.shape[1] > 0
267
+ is_trait_available = (trait in selected_clinical_df.index) and (not selected_clinical_df.loc[trait].isna().all())
268
+
269
+ # Optional note: dataset contains multiple cell types which may be a confounder if not modeled
270
+ note = "INFO: Samples span multiple cell types (CD14+, CD3+, platelets); consider including cell type as a covariate in downstream analyses."
271
+
272
+ # 5. Final validation and metadata saving
273
+ is_usable = validate_and_save_cohort_info(
274
+ is_final=True,
275
+ cohort=cohort,
276
+ info_path=json_path,
277
+ is_gene_available=is_gene_available,
278
+ is_trait_available=is_trait_available,
279
+ is_biased=is_trait_biased,
280
+ df=unbiased_linked_data,
281
+ note=note
282
+ )
283
+
284
+ # 6. Save linked data if usable
285
+ if is_usable:
286
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
287
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Allergies/code/GSE203409.py ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Allergies"
6
+ cohort = "GSE203409"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Allergies"
10
+ in_cohort_dir = "../DATA/GEO/Allergies/GSE203409"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z1/preprocess/Allergies/GSE203409.csv"
14
+ out_gene_data_file = "./output/z1/preprocess/Allergies/gene_data/GSE203409.csv"
15
+ out_clinical_data_file = "./output/z1/preprocess/Allergies/clinical_data/GSE203409.csv"
16
+ json_path = "./output/z1/preprocess/Allergies/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ import re
40
+
41
+ # 1. Gene Expression Data Availability
42
+ is_gene_available = True # Gene expression profiling of keratinocytes is suitable
43
+
44
+ # 2. Variable Availability and Data Type Conversion
45
+
46
+ # Given the dataset is an in vitro keratinocyte cell line experiment, there is no human trait/age/gender.
47
+ trait_row = None
48
+ age_row = None
49
+ gender_row = None
50
+
51
+ def _extract_value(x):
52
+ if x is None:
53
+ return None
54
+ if isinstance(x, str):
55
+ parts = x.split(":", 1)
56
+ return parts[1].strip() if len(parts) == 2 else x.strip()
57
+ return x
58
+
59
+ def convert_trait(x):
60
+ # Heuristic mapper for allergy-related datasets (not used here since trait_row is None)
61
+ val = _extract_value(x)
62
+ if val is None:
63
+ return None
64
+ s = val.lower()
65
+ # Map obvious control/healthy to 0
66
+ if any(k in s for k in ["control", "untreated", "healthy", "shc"]):
67
+ return 0
68
+ # Map allergen exposure or allergic status to 1
69
+ if any(k in s for k in ["allerg", "derp", "mite", "sensitized", "atopic"]):
70
+ return 1
71
+ # Cytokines/mediators not clearly allergy phenotype; set None
72
+ return None
73
+
74
+ def convert_age(x):
75
+ # Extract numeric age if present
76
+ val = _extract_value(x)
77
+ if val is None:
78
+ return None
79
+ nums = re.findall(r"[+-]?\d+(?:\.\d+)?", str(val))
80
+ if not nums:
81
+ return None
82
+ try:
83
+ age = float(nums[0])
84
+ except Exception:
85
+ return None
86
+ # Filter unrealistic ages
87
+ if age < 0 or age > 120:
88
+ return None
89
+ return age
90
+
91
+ def convert_gender(x):
92
+ val = _extract_value(x)
93
+ if val is None:
94
+ return None
95
+ s = str(val).strip().lower()
96
+ if s in ["female", "f", "woman", "women"]:
97
+ return 0
98
+ if s in ["male", "m", "man", "men"]:
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_clinical_df = geo_select_clinical_features(
115
+ clinical_df=clinical_data,
116
+ trait=trait,
117
+ trait_row=trait_row,
118
+ convert_trait=convert_trait,
119
+ age_row=age_row,
120
+ convert_age=convert_age,
121
+ gender_row=gender_row,
122
+ convert_gender=convert_gender
123
+ )
124
+ clinical_preview = preview_df(selected_clinical_df)
125
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
126
+ selected_clinical_df.to_csv(out_clinical_data_file, index=True)
127
+
128
+ # Step 3: Gene Data Extraction
129
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
130
+ gene_data = get_genetic_data(matrix_file)
131
+
132
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
133
+ print(gene_data.index[:20])
134
+
135
+ # Step 4: Gene Identifier Review
136
+ print("requires_gene_mapping = True")
137
+
138
+ # Step 5: Gene Annotation
139
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
140
+ gene_annotation = get_gene_annotation(soft_file)
141
+
142
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
143
+ print("Gene annotation preview:")
144
+ print(preview_df(gene_annotation))
145
+
146
+ # Step 6: Gene Identifier Mapping
147
+ # Decide on the columns: probe IDs are in 'ID' and gene symbols are in 'Symbol'
148
+ id_col = 'ID'
149
+ gene_symbol_col = 'Symbol'
150
+
151
+ # 2. Get the gene mapping dataframe
152
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=id_col, gene_col=gene_symbol_col)
153
+
154
+ # 3. Convert probe-level data to gene-level expression using the mapping
155
+ gene_data = apply_gene_mapping(gene_data, mapping_df)
156
+
157
+ # Step 7: Data Normalization and Linking
158
+ import os
159
+
160
+ # 1. Normalize gene symbols and save gene-level data
161
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
162
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
163
+ normalized_gene_data.to_csv(out_gene_data_file)
164
+
165
+ # Determine if clinical data (trait) is available from earlier steps
166
+ is_trait_available = (('trait_row' in locals()) and (trait_row is not None))
167
+
168
+ if is_trait_available:
169
+ # 2. Link clinical and genetic data
170
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_data, normalized_gene_data)
171
+ # 3. Handle missing values
172
+ linked_data = handle_missing_values(linked_data, trait)
173
+ # 4. Bias checks
174
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
175
+ # 5. Final validation and save cohort info
176
+ is_usable = validate_and_save_cohort_info(
177
+ is_final=True,
178
+ cohort=cohort,
179
+ info_path=json_path,
180
+ is_gene_available=True,
181
+ is_trait_available=True,
182
+ is_biased=is_trait_biased,
183
+ df=unbiased_linked_data,
184
+ note="INFO: Clinical features available and linked."
185
+ )
186
+ # 6. Save linked data if usable
187
+ if is_usable:
188
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
189
+ unbiased_linked_data.to_csv(out_data_file)
190
+ else:
191
+ # No clinical trait/age/gender in this in vitro dataset; skip linking and downstream steps
192
+ _ = validate_and_save_cohort_info(
193
+ is_final=True,
194
+ cohort=cohort,
195
+ info_path=json_path,
196
+ is_gene_available=True,
197
+ is_trait_available=False,
198
+ is_biased=False, # placeholder; trait not available
199
+ df=normalized_gene_data,
200
+ note="INFO: In vitro keratinocyte cell line; no human trait/age/gender available."
201
+ )