Liu-Hy commited on
Commit
35e1be1
·
verified ·
1 Parent(s): 06b0d52

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. output/preprocess/LDL_Cholesterol_Levels/code/GSE111567.py +136 -0
  2. output/preprocess/LDL_Cholesterol_Levels/code/GSE181339.py +125 -0
  3. output/preprocess/LDL_Cholesterol_Levels/code/GSE28893.py +205 -0
  4. output/preprocess/LDL_Cholesterol_Levels/code/GSE34945.py +123 -0
  5. output/preprocess/LDL_Cholesterol_Levels/code/TCGA.py +65 -0
  6. output/preprocess/LDL_Cholesterol_Levels/cohort_info.json +1 -52
  7. output/preprocess/Large_B-cell_Lymphoma/code/GSE173263.py +194 -0
  8. output/preprocess/Large_B-cell_Lymphoma/code/GSE182362.py +123 -0
  9. output/preprocess/Large_B-cell_Lymphoma/code/GSE197977.py +169 -0
  10. output/preprocess/Large_B-cell_Lymphoma/code/GSE243973.py +174 -0
  11. output/preprocess/Large_B-cell_Lymphoma/code/GSE248835.py +220 -0
  12. output/preprocess/Large_B-cell_Lymphoma/code/TCGA.py +375 -0
  13. output/preprocess/Large_B-cell_Lymphoma/gene_data/GSE173263.csv +0 -0
  14. output/preprocess/Large_B-cell_Lymphoma/gene_data/GSE248835.csv +0 -0
  15. output/preprocess/Liver_Cancer/GSE178201.csv +0 -0
  16. output/preprocess/Liver_Cancer/GSE45032.csv +0 -0
  17. output/preprocess/Liver_Cancer/clinical_data/GSE174570.csv +2 -2
  18. output/preprocess/Liver_Cancer/clinical_data/GSE178201.csv +0 -0
  19. output/preprocess/Liver_Cancer/clinical_data/GSE209875.csv +4 -4
  20. output/preprocess/Liver_Cancer/clinical_data/GSE218438.csv +2 -0
  21. output/preprocess/Liver_Cancer/clinical_data/GSE228782.csv +2 -2
  22. output/preprocess/Liver_Cancer/clinical_data/GSE228783.csv +2 -2
  23. output/preprocess/Liver_Cancer/clinical_data/GSE45032.csv +1 -1
  24. output/preprocess/Liver_Cancer/code/GSE148346.py +110 -0
  25. output/preprocess/Liver_Cancer/code/GSE164760.py +201 -0
  26. output/preprocess/Liver_Cancer/code/GSE174570.py +187 -0
  27. output/preprocess/Liver_Cancer/code/GSE178201.py +196 -0
  28. output/preprocess/Liver_Cancer/code/GSE209875.py +190 -0
  29. output/preprocess/Liver_Cancer/code/GSE212047.py +210 -0
  30. output/preprocess/Liver_Cancer/code/GSE218438.py +288 -0
  31. output/preprocess/Liver_Cancer/code/GSE228782.py +210 -0
  32. output/preprocess/Liver_Cancer/code/GSE228783.py +171 -0
  33. output/preprocess/Liver_Cancer/code/GSE45032.py +185 -0
  34. output/preprocess/Liver_Cancer/code/GSE66843.py +229 -0
  35. output/preprocess/Liver_Cancer/code/TCGA.py +353 -0
  36. output/preprocess/Liver_Cancer/cohort_info.json +1 -122
  37. output/preprocess/Liver_Cancer/gene_data/GSE212047.csv +0 -0
  38. output/preprocess/Liver_cirrhosis/clinical_data/GSE139602.csv +2 -2
  39. output/preprocess/Liver_cirrhosis/clinical_data/GSE285291.csv +2 -0
  40. output/preprocess/Liver_cirrhosis/code/GSE139602.py +199 -0
  41. output/preprocess/Liver_cirrhosis/code/GSE150734.py +221 -0
  42. output/preprocess/Liver_cirrhosis/code/GSE163211.py +139 -0
  43. output/preprocess/Liver_cirrhosis/code/GSE182060.py +148 -0
  44. output/preprocess/Liver_cirrhosis/code/GSE182065.py +176 -0
  45. output/preprocess/Liver_cirrhosis/code/GSE185529.py +368 -0
  46. output/preprocess/Liver_cirrhosis/code/GSE212047.py +136 -0
  47. output/preprocess/Liver_cirrhosis/code/GSE285291.py +178 -0
  48. output/preprocess/Liver_cirrhosis/code/GSE66843.py +156 -0
  49. output/preprocess/Liver_cirrhosis/code/GSE85550.py +220 -0
  50. output/preprocess/Liver_cirrhosis/code/TCGA.py +202 -0
output/preprocess/LDL_Cholesterol_Levels/code/GSE111567.py ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "LDL_Cholesterol_Levels"
6
+ cohort = "GSE111567"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/LDL_Cholesterol_Levels"
10
+ in_cohort_dir = "../DATA/GEO/LDL_Cholesterol_Levels/GSE111567"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z4/preprocess/LDL_Cholesterol_Levels/GSE111567.csv"
14
+ out_gene_data_file = "./output/z4/preprocess/LDL_Cholesterol_Levels/gene_data/GSE111567.csv"
15
+ out_clinical_data_file = "./output/z4/preprocess/LDL_Cholesterol_Levels/clinical_data/GSE111567.csv"
16
+ json_path = "./output/z4/preprocess/LDL_Cholesterol_Levels/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ import re
40
+
41
+ # 1) Gene expression availability (Illumina HumanHT-12 v4 microarray mentioned in background)
42
+ is_gene_available = True
43
+
44
+ # 2) Variable availability based on provided Sample Characteristics Dictionary
45
+ # trait (LDL_Cholesterol_Levels): not available in the dictionary
46
+ trait_row = None
47
+
48
+ # age: not available in the dictionary
49
+ age_row = None
50
+
51
+ # gender: available at key 0
52
+ gender_row = 0
53
+
54
+ # 2.2) Conversion functions
55
+ def _after_colon(value):
56
+ if value is None:
57
+ return None
58
+ s = str(value)
59
+ if ':' in s:
60
+ s = s.split(':', 1)[1]
61
+ return s.strip()
62
+
63
+ def convert_trait(x):
64
+ """
65
+ Convert LDL cholesterol values to a continuous variable in mg/dL if units are provided.
66
+ Heuristics:
67
+ - Extract numeric value after colon.
68
+ - If 'mmol' present, convert to mg/dL using factor 38.67.
69
+ - If units not specified, assume mg/dL.
70
+ """
71
+ s = _after_colon(x)
72
+ if not s:
73
+ return None
74
+ s_lower = s.lower()
75
+ if any(tok in s_lower for tok in ["na", "n/a", "not available", "unknown", "missing"]):
76
+ return None
77
+ # extract first float-like number
78
+ m = re.search(r"[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?", s_lower)
79
+ if not m:
80
+ return None
81
+ val = float(m.group())
82
+ # unit handling
83
+ if "mmol" in s_lower:
84
+ val = val * 38.67 # mmol/L to mg/dL for LDL-C
85
+ # basic sanity check
86
+ if val <= 0 or val > 1000:
87
+ return None
88
+ return val
89
+
90
+ def convert_age(x):
91
+ """
92
+ Convert age to continuous years.
93
+ Extract numeric value; if out of plausible human range, return None.
94
+ """
95
+ s = _after_colon(x)
96
+ if not s:
97
+ return None
98
+ s_lower = s.lower()
99
+ if any(tok in s_lower for tok in ["na", "n/a", "not available", "unknown", "missing"]):
100
+ return None
101
+ m = re.search(r"[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?", s_lower)
102
+ if not m:
103
+ return None
104
+ age = float(m.group())
105
+ # assume already in years; discard implausible values
106
+ if age <= 0 or age > 120:
107
+ return None
108
+ return age
109
+
110
+ def convert_gender(x):
111
+ """
112
+ Convert gender to binary: female=0, male=1.
113
+ """
114
+ s = _after_colon(x)
115
+ if not s:
116
+ return None
117
+ t = s.strip().lower()
118
+ # handle common variants
119
+ if t in ["f", "female", "woman", "girl", "frau", "fem"]:
120
+ return 0
121
+ if t in ["m", "male", "man", "boy", "herr", "masc"]:
122
+ return 1
123
+ return None
124
+
125
+ # 3) Save metadata (initial filtering)
126
+ is_trait_available = trait_row is not None
127
+ _ = validate_and_save_cohort_info(
128
+ is_final=False,
129
+ cohort=cohort,
130
+ info_path=json_path,
131
+ is_gene_available=is_gene_available,
132
+ is_trait_available=is_trait_available
133
+ )
134
+
135
+ # 4) Clinical Feature Extraction
136
+ # Skip because trait_row is None (trait data not available in this cohort's sample characteristics)
output/preprocess/LDL_Cholesterol_Levels/code/GSE181339.py ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "LDL_Cholesterol_Levels"
6
+ cohort = "GSE181339"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/LDL_Cholesterol_Levels"
10
+ in_cohort_dir = "../DATA/GEO/LDL_Cholesterol_Levels/GSE181339"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z4/preprocess/LDL_Cholesterol_Levels/GSE181339.csv"
14
+ out_gene_data_file = "./output/z4/preprocess/LDL_Cholesterol_Levels/gene_data/GSE181339.csv"
15
+ out_clinical_data_file = "./output/z4/preprocess/LDL_Cholesterol_Levels/clinical_data/GSE181339.csv"
16
+ json_path = "./output/z4/preprocess/LDL_Cholesterol_Levels/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ import re
40
+
41
+ # 1. Gene Expression Data Availability
42
+ is_gene_available = True # Agilent GE platform with PBMC transcriptomics -> gene expression data available
43
+
44
+ # 2. Variable Availability and Data Type Conversion
45
+
46
+ # Keys from Sample Characteristics Dictionary:
47
+ # 0: gender
48
+ # 1: group (OW/OB, NW, MONW)
49
+ # 2: age
50
+ # 3: fasting time
51
+ # 4: timepoint
52
+
53
+ # Trait (LDL_Cholesterol_Levels): not explicitly available; cannot be reliably inferred from 'group'
54
+ trait_row = None
55
+
56
+ # Age and Gender availability
57
+ age_row = 2
58
+ gender_row = 0
59
+
60
+ def _extract_value(cell):
61
+ if cell is None:
62
+ return None
63
+ # Split on first colon
64
+ parts = str(cell).split(":", 1)
65
+ val = parts[1] if len(parts) > 1 else parts[0]
66
+ return val.strip()
67
+
68
+ def convert_trait(x):
69
+ # LDL not explicitly available in sample characteristics; return None
70
+ return None
71
+
72
+ def convert_age(x):
73
+ val = _extract_value(x)
74
+ if val is None or val == "":
75
+ return None
76
+ # Extract first integer/float from the string
77
+ m = re.search(r'[-+]?\d*\.?\d+', val)
78
+ if not m:
79
+ return None
80
+ try:
81
+ num = float(m.group())
82
+ # Age in years; keep as float
83
+ if num <= 0 or num > 120:
84
+ # Implausible human age; mark unknown
85
+ return None
86
+ return num
87
+ except Exception:
88
+ return None
89
+
90
+ def convert_gender(x):
91
+ val = _extract_value(x)
92
+ if val is None or val == "":
93
+ return None
94
+ v = val.strip().lower()
95
+ # Map to Female=0, Male=1
96
+ if v in {"woman", "female", "f"}:
97
+ return 0
98
+ if v in {"man", "male", "m"}:
99
+ return 1
100
+ return None
101
+
102
+ # 3. Save Metadata (initial filtering)
103
+ is_trait_available = trait_row is not None
104
+ _ = validate_and_save_cohort_info(
105
+ is_final=False,
106
+ cohort=cohort,
107
+ info_path=json_path,
108
+ is_gene_available=is_gene_available,
109
+ is_trait_available=is_trait_available
110
+ )
111
+
112
+ # 4. Clinical Feature Extraction (skip because trait not available)
113
+ if trait_row is not None:
114
+ selected_clinical_df = geo_select_clinical_features(
115
+ clinical_df=clinical_data,
116
+ trait=trait,
117
+ trait_row=trait_row,
118
+ convert_trait=convert_trait,
119
+ age_row=age_row,
120
+ convert_age=convert_age,
121
+ gender_row=gender_row,
122
+ convert_gender=convert_gender
123
+ )
124
+ preview = preview_df(selected_clinical_df, n=5)
125
+ selected_clinical_df.to_csv(out_clinical_data_file, index=True)
output/preprocess/LDL_Cholesterol_Levels/code/GSE28893.py ADDED
@@ -0,0 +1,205 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "LDL_Cholesterol_Levels"
6
+ cohort = "GSE28893"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/LDL_Cholesterol_Levels"
10
+ in_cohort_dir = "../DATA/GEO/LDL_Cholesterol_Levels/GSE28893"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z4/preprocess/LDL_Cholesterol_Levels/GSE28893.csv"
14
+ out_gene_data_file = "./output/z4/preprocess/LDL_Cholesterol_Levels/gene_data/GSE28893.csv"
15
+ out_clinical_data_file = "./output/z4/preprocess/LDL_Cholesterol_Levels/clinical_data/GSE28893.csv"
16
+ json_path = "./output/z4/preprocess/LDL_Cholesterol_Levels/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ import re
40
+
41
+ # 1) Gene expression data availability
42
+ is_gene_available = True # Illumina gene expression array in primary human liver tissue
43
+
44
+ # 2) Variable availability (rows) inferred from provided sample characteristics
45
+ trait_row = None # LDL cholesterol not present in characteristics; background mentions related eQTLs but no trait values here
46
+ age_row = 1 # 'age: ...'
47
+ gender_row = 2 # 'gender: M/F'
48
+
49
+ # 2.2) Data type conversion functions
50
+ def _after_colon(value):
51
+ if value is None:
52
+ return None
53
+ parts = str(value).split(":", 1)
54
+ return parts[1].strip() if len(parts) > 1 else str(value).strip()
55
+
56
+ def convert_trait(x):
57
+ # Trait would be continuous if present; attempt numeric parse, else None
58
+ v = _after_colon(x)
59
+ if v is None:
60
+ return None
61
+ v_clean = v.strip()
62
+ if v_clean.lower() in {"na", "nan", "none", "", "unknown"}:
63
+ return None
64
+ m = re.search(r"[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?", v_clean)
65
+ if m:
66
+ try:
67
+ return float(m.group(0))
68
+ except:
69
+ return None
70
+ return None
71
+
72
+ def convert_age(x):
73
+ # Continuous numeric age in years
74
+ v = _after_colon(x)
75
+ if v is None:
76
+ return None
77
+ s = v.strip().lower()
78
+ if s in {"na", "nan", "none", "", "unknown"}:
79
+ return None
80
+ m = re.search(r"[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?", s)
81
+ if m:
82
+ try:
83
+ return float(m.group(0))
84
+ except:
85
+ return None
86
+ return None
87
+
88
+ def convert_gender(x):
89
+ # Binary: female->0, male->1
90
+ v = _after_colon(x)
91
+ if v is None:
92
+ return None
93
+ s = v.strip().lower()
94
+ if s in {"m", "male"}:
95
+ return 1
96
+ if s in {"f", "female"}:
97
+ return 0
98
+ return None
99
+
100
+ # 3) Save metadata with initial filtering
101
+ is_trait_available = trait_row is not None
102
+ _ = validate_and_save_cohort_info(
103
+ is_final=False,
104
+ cohort=cohort,
105
+ info_path=json_path,
106
+ is_gene_available=is_gene_available,
107
+ is_trait_available=is_trait_available
108
+ )
109
+
110
+ # 4) Clinical feature extraction (skip because trait not 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
+ age_row=age_row,
118
+ convert_age=convert_age,
119
+ gender_row=gender_row,
120
+ convert_gender=convert_gender
121
+ )
122
+ clinical_preview = preview_df(selected_clinical_df, n=5)
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
+ # Map probe IDs to gene symbols using columns observed in annotation preview: 'ID' (probe) and 'Symbol' (gene symbol)
147
+ mapping_df = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='Symbol')
148
+
149
+ # Convert probe-level data to gene-level expression by applying the mapping
150
+ gene_data = apply_gene_mapping(gene_data, mapping_df)
151
+
152
+ # Step 7: Data Normalization and Linking
153
+ import os
154
+
155
+ # 1. Normalize gene symbols and save gene-level expression
156
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
157
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
158
+ normalized_gene_data.to_csv(out_gene_data_file)
159
+
160
+ # Determine trait availability from previous steps (trait_row defined in Step 2)
161
+ try:
162
+ trait_available = (trait_row is not None)
163
+ except NameError:
164
+ trait_available = False
165
+
166
+ # 2-6. Proceed only if trait/clinical data were extracted previously; otherwise, record metadata and skip linking
167
+ if trait_available and 'selected_clinical_df' in globals():
168
+ # 2. Link clinical and genetic data
169
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
170
+
171
+ # 3. Handle missing values
172
+ linked_data = handle_missing_values(linked_data, trait)
173
+
174
+ # 4. Bias checks and remove biased demographic features
175
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
176
+
177
+ # 5. Final validation and save cohort info
178
+ is_usable = validate_and_save_cohort_info(
179
+ is_final=True,
180
+ cohort=cohort,
181
+ info_path=json_path,
182
+ is_gene_available=True,
183
+ is_trait_available=True,
184
+ is_biased=is_trait_biased,
185
+ df=unbiased_linked_data,
186
+ note=""
187
+ )
188
+
189
+ # 6. Save linked data only 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)
193
+ else:
194
+ # Trait not available: record metadata accordingly; do not save linked data
195
+ note = "INFO: Trait not available in clinical annotations; saved gene-level data only."
196
+ _ = validate_and_save_cohort_info(
197
+ is_final=True,
198
+ cohort=cohort,
199
+ info_path=json_path,
200
+ is_gene_available=True,
201
+ is_trait_available=False,
202
+ is_biased=False, # ignored since dataset is not available for the trait
203
+ df=normalized_gene_data.T, # placeholder df to avoid abnormality override
204
+ note=note
205
+ )
output/preprocess/LDL_Cholesterol_Levels/code/GSE34945.py ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "LDL_Cholesterol_Levels"
6
+ cohort = "GSE34945"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/LDL_Cholesterol_Levels"
10
+ in_cohort_dir = "../DATA/GEO/LDL_Cholesterol_Levels/GSE34945"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z4/preprocess/LDL_Cholesterol_Levels/GSE34945.csv"
14
+ out_gene_data_file = "./output/z4/preprocess/LDL_Cholesterol_Levels/gene_data/GSE34945.csv"
15
+ out_clinical_data_file = "./output/z4/preprocess/LDL_Cholesterol_Levels/clinical_data/GSE34945.csv"
16
+ json_path = "./output/z4/preprocess/LDL_Cholesterol_Levels/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ import re
40
+
41
+ # 1) Gene expression data availability
42
+ # Background indicates SNP genotyping (Illumina GoldenGate), not gene expression.
43
+ is_gene_available = False
44
+
45
+ # 2) Variable availability and converters
46
+ # From the provided sample characteristics:
47
+ # - No LDL Cholesterol data field found -> trait not available
48
+ # - No age field -> not available
49
+ # - No gender field -> not available
50
+ trait_row = None
51
+ age_row = None
52
+ gender_row = None
53
+
54
+ # Choose data types:
55
+ # - trait (LDL) would be continuous if available
56
+ # - age would be continuous if available
57
+ # - gender is binary if available
58
+
59
+ def _extract_after_colon(x: str) -> str:
60
+ if x is None:
61
+ return None
62
+ parts = str(x).split(":", 1)
63
+ return parts[1].strip() if len(parts) == 2 else str(x).strip()
64
+
65
+ def _to_float(s: str):
66
+ if s is None:
67
+ return None
68
+ s = s.strip()
69
+ # Remove common units and commas
70
+ s_clean = re.sub(r'[^\d\.\-]+', ' ', s).strip()
71
+ # Attempt to find a float in the string
72
+ m = re.search(r'[-+]?\d*\.?\d+', s_clean)
73
+ if not m:
74
+ return None
75
+ try:
76
+ return float(m.group(0))
77
+ except:
78
+ return None
79
+
80
+ # Convert LDL cholesterol (continuous, mg/dL typically)
81
+ def convert_trait(x):
82
+ v = _extract_after_colon(x)
83
+ if v is None:
84
+ return None
85
+ # Return numeric value if present; otherwise None
86
+ return _to_float(v)
87
+
88
+ # Convert age (continuous, years)
89
+ def convert_age(x):
90
+ v = _extract_after_colon(x)
91
+ if v is None:
92
+ return None
93
+ return _to_float(v)
94
+
95
+ # Convert gender (binary: female -> 0, male -> 1)
96
+ def convert_gender(x):
97
+ v = _extract_after_colon(x)
98
+ if v is None:
99
+ return None
100
+ v_low = v.strip().lower()
101
+ # Common variants
102
+ if v_low in {"male", "m", "man", "boy"}:
103
+ return 1
104
+ if v_low in {"female", "f", "woman", "girl"}:
105
+ return 0
106
+ # Heuristic: startswith letters
107
+ if v_low.startswith("m"):
108
+ return 1
109
+ if v_low.startswith("f"):
110
+ return 0
111
+ return None
112
+
113
+ # 3) Save metadata (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 is skipped because trait_row is None (no clinical trait data available)
output/preprocess/LDL_Cholesterol_Levels/code/TCGA.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "LDL_Cholesterol_Levels"
6
+
7
+ # Input paths
8
+ tcga_root_dir = "../DATA/TCGA"
9
+
10
+ # Output paths
11
+ out_data_file = "./output/z4/preprocess/LDL_Cholesterol_Levels/TCGA.csv"
12
+ out_gene_data_file = "./output/z4/preprocess/LDL_Cholesterol_Levels/gene_data/TCGA.csv"
13
+ out_clinical_data_file = "./output/z4/preprocess/LDL_Cholesterol_Levels/clinical_data/TCGA.csv"
14
+ json_path = "./output/z4/preprocess/LDL_Cholesterol_Levels/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 relevant TCGA subdirectory for LDL/Cholesterol trait
22
+ subdirs = [d for d in os.listdir(tcga_root_dir) if os.path.isdir(os.path.join(tcga_root_dir, d))]
23
+
24
+ # Define synonyms for LDL Cholesterol related traits
25
+ synonyms_priority = ['ldl', 'cholesterol', 'lipid', 'hypercholesterolemia', 'dyslipidemia']
26
+
27
+ def match_score(dir_name: str) -> int:
28
+ name = dir_name.lower()
29
+ for i, term in enumerate(synonyms_priority):
30
+ if term in name:
31
+ return i # lower is better (more specific)
32
+ return len(synonyms_priority) + 1 # no match
33
+
34
+ # Rank directories by best matching term
35
+ ranked = sorted(subdirs, key=lambda d: match_score(d))
36
+ best_dir = ranked[0] if ranked else None
37
+ selected_dir = None if match_score(best_dir) > len(synonyms_priority) else best_dir
38
+
39
+ clinical_df = pd.DataFrame()
40
+ genetic_df = pd.DataFrame()
41
+
42
+ if selected_dir is None:
43
+ print("No suitable TCGA cohort directory found for trait 'LDL_Cholesterol_Levels'. Skipping this trait.")
44
+ # Record unusable trait for TCGA
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
+ print(f"Selected TCGA cohort directory: {selected_dir}")
54
+ cohort_dir = os.path.join(tcga_root_dir, selected_dir)
55
+
56
+ # Step 2: Identify clinicalMatrix and PANCAN files
57
+ clinical_file_path, genetic_file_path = tcga_get_relevant_filepaths(cohort_dir)
58
+
59
+ # Step 3: Load both files
60
+ clinical_df = pd.read_csv(clinical_file_path, sep='\t', index_col=0, compression='infer', low_memory=False)
61
+ genetic_df = pd.read_csv(genetic_file_path, sep='\t', index_col=0, compression='infer', low_memory=False)
62
+
63
+ # Step 4: Print clinical data column names
64
+ print("Clinical data columns:")
65
+ print(list(clinical_df.columns))
output/preprocess/LDL_Cholesterol_Levels/cohort_info.json CHANGED
@@ -1,52 +1 @@
1
- {
2
- "GSE34945": {
3
- "is_usable": false,
4
- "is_gene_available": false,
5
- "is_trait_available": true,
6
- "is_available": false,
7
- "is_biased": null,
8
- "has_age": null,
9
- "has_gender": null,
10
- "sample_size": null
11
- },
12
- "GSE28893": {
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
- "GSE181339": {
23
- "is_usable": true,
24
- "is_gene_available": true,
25
- "is_trait_available": true,
26
- "is_available": true,
27
- "is_biased": false,
28
- "has_age": true,
29
- "has_gender": true,
30
- "sample_size": 78
31
- },
32
- "GSE111567": {
33
- "is_usable": false,
34
- "is_gene_available": false,
35
- "is_trait_available": false,
36
- "is_available": false,
37
- "is_biased": null,
38
- "has_age": null,
39
- "has_gender": null,
40
- "sample_size": null
41
- },
42
- "TCGA": {
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": 423
51
- }
52
- }
 
1
+ {"GSE34945": {"is_usable": false, "is_gene_available": false, "is_trait_available": false, "is_available": false, "is_biased": null, "has_age": null, "has_gender": null, "sample_size": null, "note": null}, "GSE28893": {"is_usable": false, "is_gene_available": true, "is_trait_available": false, "is_available": false, "is_biased": null, "has_age": null, "has_gender": null, "sample_size": null, "note": "INFO: Trait not available in clinical annotations; saved gene-level data only."}, "GSE181339": {"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}, "GSE111567": {"is_usable": false, "is_gene_available": true, "is_trait_available": false, "is_available": false, "is_biased": null, "has_age": null, "has_gender": null, "sample_size": null, "note": null}, "TCGA": {"is_usable": false, "is_gene_available": false, "is_trait_available": false, "is_available": false, "is_biased": null, "has_age": null, "has_gender": null, "sample_size": null, "note": null}}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
output/preprocess/Large_B-cell_Lymphoma/code/GSE173263.py ADDED
@@ -0,0 +1,194 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Large_B-cell_Lymphoma"
6
+ cohort = "GSE173263"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Large_B-cell_Lymphoma"
10
+ in_cohort_dir = "../DATA/GEO/Large_B-cell_Lymphoma/GSE173263"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z4/preprocess/Large_B-cell_Lymphoma/GSE173263.csv"
14
+ out_gene_data_file = "./output/z4/preprocess/Large_B-cell_Lymphoma/gene_data/GSE173263.csv"
15
+ out_clinical_data_file = "./output/z4/preprocess/Large_B-cell_Lymphoma/clinical_data/GSE173263.csv"
16
+ json_path = "./output/z4/preprocess/Large_B-cell_Lymphoma/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
+ # Determine data availability based on sample characteristics and background info
43
+ is_gene_available = True # GEP indicated; this is a gene expression dataset
44
+
45
+ # Trait within-cohort: response to R-CHOP (two unique values under key 2)
46
+ trait_row = 2
47
+ age_row = None
48
+ gender_row = None
49
+
50
+ # Conversion functions
51
+ def _extract_value(x):
52
+ if x is None:
53
+ return None
54
+ parts = str(x).split(":", 1)
55
+ val = parts[1] if len(parts) > 1 else parts[0]
56
+ return val.strip()
57
+
58
+ def convert_trait(x):
59
+ val = _extract_value(x)
60
+ if val is None:
61
+ return None
62
+ v = val.lower()
63
+ # Map response to R-CHOP: Early failure (refractory/early relapse) = 1; remission/responding = 0
64
+ failure_terms = {"early failure", "refractory", "nonresponder", "non-responder", "progressive disease", "pd", "relapse", "early relapse", "failure"}
65
+ response_terms = {"remission", "responder", "responding", "complete response", "cr", "partial response", "pr", "response"}
66
+ if v in failure_terms or any(t in v for t in ["early failure", "refractory", "early relapse", "nonrespond"]):
67
+ return 1
68
+ if v in response_terms or any(t in v for t in ["remission", "respond"]):
69
+ return 0
70
+ return None
71
+
72
+ def convert_age(x):
73
+ val = _extract_value(x)
74
+ if val is None:
75
+ return None
76
+ m = re.search(r"[-+]?\d*\.?\d+", val)
77
+ if not m:
78
+ return None
79
+ try:
80
+ return float(m.group())
81
+ except Exception:
82
+ return None
83
+
84
+ def convert_gender(x):
85
+ val = _extract_value(x)
86
+ if val is None:
87
+ return None
88
+ v = val.strip().lower()
89
+ if v in {"female", "f", "woman", "women", "girl"}:
90
+ return 0
91
+ if v in {"male", "m", "man", "men", "boy"}:
92
+ return 1
93
+ return None
94
+
95
+ # Initial filtering metadata
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
+ # Clinical feature extraction
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
+ preview = preview_df(selected_clinical_df)
117
+ print(preview)
118
+
119
+ # Save clinical features
120
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
121
+ selected_clinical_df.to_csv(out_clinical_data_file)
122
+
123
+ # Step 3: Gene Data Extraction
124
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
125
+ gene_data = get_genetic_data(matrix_file)
126
+
127
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
128
+ print(gene_data.index[:20])
129
+
130
+ # Step 4: Gene Identifier Review
131
+ print("requires_gene_mapping = True")
132
+
133
+ # Step 5: Gene Annotation
134
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
135
+ gene_annotation = get_gene_annotation(soft_file)
136
+
137
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
138
+ print("Gene annotation preview:")
139
+ print(preview_df(gene_annotation))
140
+
141
+ # Step 6: Gene Identifier Mapping
142
+ # Identify the appropriate columns for probe IDs and gene symbols
143
+ probe_col = 'ID'
144
+ gene_symbol_col = 'Gene Symbol'
145
+
146
+ # Create mapping dataframe from annotation
147
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=probe_col, gene_col=gene_symbol_col)
148
+
149
+ # Apply mapping to convert probe-level data to gene-level expression
150
+ gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
151
+
152
+ # Step 7: Data Normalization and Linking
153
+ import os
154
+
155
+ # 1. Normalize the obtained gene data and save
156
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
157
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
158
+ normalized_gene_data.to_csv(out_gene_data_file)
159
+
160
+ # 2. Link the clinical and genetic data
161
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
162
+
163
+ # 3. Handle missing values in the linked data
164
+ linked_data = handle_missing_values(linked_data, trait)
165
+
166
+ # 4. Assess bias and remove biased demographic features
167
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
168
+
169
+ # 5. Final validation and save cohort info
170
+ is_gene_available_final = (normalized_gene_data.shape[0] > 0) and (normalized_gene_data.shape[1] > 0)
171
+ is_trait_available_final = trait in selected_clinical_df.index
172
+
173
+ notes = []
174
+ if 'Age' not in selected_clinical_df.index:
175
+ notes.append("Age unavailable")
176
+ if 'Gender' not in selected_clinical_df.index:
177
+ notes.append("Gender unavailable")
178
+ note = "INFO: " + ("; ".join(notes) if notes else "No additional notes")
179
+
180
+ is_usable = validate_and_save_cohort_info(
181
+ is_final=True,
182
+ cohort=cohort,
183
+ info_path=json_path,
184
+ is_gene_available=is_gene_available_final,
185
+ is_trait_available=is_trait_available_final,
186
+ is_biased=is_trait_biased,
187
+ df=unbiased_linked_data,
188
+ note=note
189
+ )
190
+
191
+ # 6. Save the linked data if usable
192
+ if is_usable:
193
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
194
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Large_B-cell_Lymphoma/code/GSE182362.py ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Large_B-cell_Lymphoma"
6
+ cohort = "GSE182362"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Large_B-cell_Lymphoma"
10
+ in_cohort_dir = "../DATA/GEO/Large_B-cell_Lymphoma/GSE182362"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z4/preprocess/Large_B-cell_Lymphoma/GSE182362.csv"
14
+ out_gene_data_file = "./output/z4/preprocess/Large_B-cell_Lymphoma/gene_data/GSE182362.csv"
15
+ out_clinical_data_file = "./output/z4/preprocess/Large_B-cell_Lymphoma/clinical_data/GSE182362.csv"
16
+ json_path = "./output/z4/preprocess/Large_B-cell_Lymphoma/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 suggests mRNA-level changes (mTOR, TLR5) post miR-155 manipulation in BJAB cells -> likely gene expression data.
41
+ is_gene_available = True
42
+
43
+ # Step 2: Variable availability and conversion functions
44
+ # From the sample characteristics, all samples are DLBCL-derived BJAB cell line; no human-level trait variation, age, or gender.
45
+ trait_row = None
46
+ age_row = None
47
+ gender_row = None
48
+
49
+ def _extract_value_after_colon(x: str) -> str:
50
+ if x is None:
51
+ return ''
52
+ if isinstance(x, str):
53
+ parts = x.split(':', 1)
54
+ return parts[1].strip() if len(parts) == 2 else x.strip()
55
+ return str(x)
56
+
57
+ def convert_trait(x):
58
+ # Map DLBCL presence to 1 and non-DLBCL to 0 when applicable; otherwise None.
59
+ v = _extract_value_after_colon(x).lower()
60
+ if not v:
61
+ return None
62
+ # Heuristics for DLBCL
63
+ if 'diffuse large b-cell lymphoma' in v or 'dlbcl' in v or 'large b-cell lymphoma' in v:
64
+ return 1
65
+ if 'healthy' in v or 'control' in v or 'normal' in v:
66
+ return 0
67
+ # Ignore treatment-only fields (not the trait of interest)
68
+ if 'transfected' in v:
69
+ return None
70
+ return None
71
+
72
+ def convert_age(x):
73
+ v = _extract_value_after_colon(x).lower()
74
+ if not v:
75
+ return None
76
+ # Extract first number as age in years
77
+ import re
78
+ m = re.search(r'(\d+(\.\d+)?)', v)
79
+ if m:
80
+ try:
81
+ age = float(m.group(1))
82
+ # Filter implausible ages for humans
83
+ if 0 <= age <= 120:
84
+ return age
85
+ except Exception:
86
+ return None
87
+ return None
88
+
89
+ def convert_gender(x):
90
+ v = _extract_value_after_colon(x).lower()
91
+ if not v:
92
+ return None
93
+ if v in ['male', 'm']:
94
+ return 1
95
+ if v in ['female', 'f']:
96
+ return 0
97
+ return None
98
+
99
+ # Step 3: Initial filtering and save metadata
100
+ is_trait_available = trait_row is not None
101
+ _ = validate_and_save_cohort_info(
102
+ is_final=False,
103
+ cohort=cohort,
104
+ info_path=json_path,
105
+ is_gene_available=is_gene_available,
106
+ is_trait_available=is_trait_available
107
+ )
108
+
109
+ # Step 4: Clinical feature extraction (skip because trait_row is None)
110
+ # If trait_row were available:
111
+ # selected_clinical = 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)
122
+ # os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
123
+ # selected_clinical.to_csv(out_clinical_data_file)
output/preprocess/Large_B-cell_Lymphoma/code/GSE197977.py ADDED
@@ -0,0 +1,169 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Large_B-cell_Lymphoma"
6
+ cohort = "GSE197977"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Large_B-cell_Lymphoma"
10
+ in_cohort_dir = "../DATA/GEO/Large_B-cell_Lymphoma/GSE197977"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z4/preprocess/Large_B-cell_Lymphoma/GSE197977.csv"
14
+ out_gene_data_file = "./output/z4/preprocess/Large_B-cell_Lymphoma/gene_data/GSE197977.csv"
15
+ out_clinical_data_file = "./output/z4/preprocess/Large_B-cell_Lymphoma/clinical_data/GSE197977.csv"
16
+ json_path = "./output/z4/preprocess/Large_B-cell_Lymphoma/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ # Determine data availability based on provided Background and Sample Characteristics Dictionary
40
+
41
+ # 1) Gene expression availability:
42
+ # The study analyzes immune gene expression in tumor microenvironment; this is gene expression (not miRNA/methylation).
43
+ is_gene_available = True
44
+
45
+ # 2) Variable availability and conversion functions
46
+
47
+ # Trait: Large B-cell Lymphoma. All samples are LBCL patients; no controls are present.
48
+ # No explicit disease status key is provided, and the trait is constant across samples.
49
+ trait_row = None # Not available for association (constant / not explicitly recorded)
50
+
51
+ # Age: No age-related key present in the sample characteristics dictionary.
52
+ age_row = None
53
+
54
+ # Gender: No gender-related key present in the sample characteristics dictionary.
55
+ gender_row = None
56
+
57
+ # Conversion functions
58
+ def _after_colon(x):
59
+ if x is None:
60
+ return None
61
+ s = str(x)
62
+ if ':' in s:
63
+ return s.split(':', 1)[1].strip()
64
+ return s.strip()
65
+
66
+ def convert_trait(x):
67
+ # Map disease/control if encountered; otherwise None.
68
+ v = _after_colon(x)
69
+ if v is None or v == '' or v.lower() in {'na', 'nan', 'none', 'missing', 'unknown'}:
70
+ return None
71
+ val = v.lower()
72
+ # Positive disease indicators
73
+ pos_terms = {
74
+ 'lbcl', 'large b-cell lymphoma', 'large b cell lymphoma', 'dlbcl',
75
+ 'diffuse large b-cell lymphoma', 'diffuse large b cell lymphoma',
76
+ 'b-cell lymphoma', 'b cell lymphoma', 'lymphoma'
77
+ }
78
+ neg_terms = {'normal', 'healthy', 'control', 'non-tumor', 'non tumour', 'non-cancer', 'non cancer', 'benign'}
79
+ if any(t in val for t in pos_terms):
80
+ return 1
81
+ if any(t in val for t in neg_terms):
82
+ return 0
83
+ return None
84
+
85
+ def convert_age(x):
86
+ v = _after_colon(x)
87
+ if v is None:
88
+ return None
89
+ v = v.strip()
90
+ if v.lower() in {'na', 'nan', 'none', ''}:
91
+ return None
92
+ # Extract leading numeric part
93
+ import re
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 = _after_colon(x)
104
+ if v is None:
105
+ return None
106
+ val = v.strip().lower()
107
+ if val in {'female', 'f', 'woman', 'women'}:
108
+ return 0
109
+ if val in {'male', 'm', 'man', 'men'}:
110
+ return 1
111
+ return None
112
+
113
+ # 3) Save metadata (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
124
+ # Skip because trait_row is None (no usable clinical trait for association).
125
+ # If trait_row were available:
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)
137
+ # os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
138
+ # selected_clinical_df.to_csv(out_clinical_data_file)
139
+
140
+ # Step 3: Gene Data Extraction
141
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
142
+ gene_data = get_genetic_data(matrix_file)
143
+
144
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
145
+ print(gene_data.index[:20])
146
+
147
+ # Step 4: Gene Identifier Review
148
+ print("requires_gene_mapping = True")
149
+
150
+ # Step 5: Gene Annotation
151
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
152
+ gene_annotation = get_gene_annotation(soft_file)
153
+
154
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
155
+ print("Gene annotation preview:")
156
+ print(preview_df(gene_annotation))
157
+
158
+ # Step 6: Gene Identifier Mapping
159
+ # Determine the appropriate columns for mapping based on previous previews:
160
+ # - Expression data uses numeric 'ID's like '1', '2', ...
161
+ # - Gene annotation preview shows matching 'ID' and gene symbols under 'ORF'
162
+ probe_col = 'ID'
163
+ gene_symbol_col = 'ORF'
164
+
165
+ # Build mapping dataframe
166
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=probe_col, gene_col=gene_symbol_col)
167
+
168
+ # Apply mapping to convert probe-level data to gene-level expression
169
+ gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
output/preprocess/Large_B-cell_Lymphoma/code/GSE243973.py ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Large_B-cell_Lymphoma"
6
+ cohort = "GSE243973"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Large_B-cell_Lymphoma"
10
+ in_cohort_dir = "../DATA/GEO/Large_B-cell_Lymphoma/GSE243973"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z4/preprocess/Large_B-cell_Lymphoma/GSE243973.csv"
14
+ out_gene_data_file = "./output/z4/preprocess/Large_B-cell_Lymphoma/gene_data/GSE243973.csv"
15
+ out_clinical_data_file = "./output/z4/preprocess/Large_B-cell_Lymphoma/clinical_data/GSE243973.csv"
16
+ json_path = "./output/z4/preprocess/Large_B-cell_Lymphoma/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ # Determine data availability
40
+ is_gene_available = True # nCounter 780-gene panel indicates transcriptomic (gene expression) data
41
+
42
+ # Identify rows for variables in the sample characteristics dictionary
43
+ trait_row = 0 # 'disease state: large B-cell lymphoma' vs 'healthy control'
44
+ age_row = None # Not present in the provided characteristics
45
+ gender_row = None # Not present in the provided characteristics
46
+
47
+ # Conversion helpers
48
+ import re
49
+
50
+ def _extract_after_colon(x):
51
+ if x is None:
52
+ return None
53
+ s = str(x)
54
+ parts = s.split(":", 1)
55
+ return parts[1].strip() if len(parts) == 2 else s.strip()
56
+
57
+ def convert_trait(x):
58
+ v = _extract_after_colon(x)
59
+ if v is None:
60
+ return None
61
+ vl = v.lower()
62
+ # Primary mapping based on disease state
63
+ if "healthy" in vl or "control" in vl:
64
+ return 0
65
+ if "lymphoma" in vl or "lbcl" in vl:
66
+ return 1
67
+ # Fallback using cell type phrasing if encountered
68
+ if "donor" in vl or "healthy control" in vl:
69
+ return 0
70
+ if "patient" in vl:
71
+ return 1
72
+ return None
73
+
74
+ def convert_age(x):
75
+ v = _extract_after_colon(x)
76
+ if v is None:
77
+ return None
78
+ vl = v.lower()
79
+ if vl in {"na", "n/a", "unknown", ""}:
80
+ return None
81
+ m = re.search(r"[-+]?\d*\.?\d+", vl)
82
+ return float(m.group()) if m else None
83
+
84
+ def convert_gender(x):
85
+ v = _extract_after_colon(x)
86
+ if v is None:
87
+ return None
88
+ vl = v.strip().lower()
89
+ if vl in {"na", "n/a", "unknown", ""}:
90
+ return None
91
+ if vl in {"male", "m", "man"}:
92
+ return 1
93
+ if vl in {"female", "f", "woman"}:
94
+ return 0
95
+ return None
96
+
97
+ # Initial filtering and save metadata
98
+ is_trait_available = trait_row is not None
99
+ _ = validate_and_save_cohort_info(
100
+ is_final=False,
101
+ cohort=cohort,
102
+ info_path=json_path,
103
+ is_gene_available=is_gene_available,
104
+ is_trait_available=is_trait_available
105
+ )
106
+
107
+ # Clinical feature extraction (only if trait data is available)
108
+ if trait_row is not None:
109
+ selected_clinical_df = geo_select_clinical_features(
110
+ clinical_df=clinical_data,
111
+ trait=trait,
112
+ trait_row=trait_row,
113
+ convert_trait=convert_trait,
114
+ age_row=age_row,
115
+ convert_age=convert_age,
116
+ gender_row=gender_row,
117
+ convert_gender=convert_gender
118
+ )
119
+ # Preview and save
120
+ preview = preview_df(selected_clinical_df, n=5)
121
+ print("Preview of selected clinical features:", preview)
122
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
123
+ selected_clinical_df.to_csv(out_clinical_data_file)
124
+
125
+ # Step 3: Gene Data Extraction
126
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
127
+ gene_data = get_genetic_data(matrix_file)
128
+
129
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
130
+ print(gene_data.index[:20])
131
+
132
+ # Step 4: Gene Identifier Review
133
+ requires_gene_mapping = False
134
+ print(f"requires_gene_mapping = {requires_gene_mapping}")
135
+
136
+ # Step 5: Data Normalization and Linking
137
+ # Ensure required modules are available
138
+ import os
139
+
140
+ # 1. Normalize the obtained gene data with the 'normalize_gene_symbols_in_index' function from the library.
141
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
142
+
143
+ # Ensure output directory exists before saving gene data
144
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
145
+ normalized_gene_data.to_csv(out_gene_data_file)
146
+
147
+ # 2. Link the clinical and genetic data with the 'geo_link_clinical_genetic_data' function from the library.
148
+ # Fix variable name: use selected_clinical_df from Step 2
149
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
150
+
151
+ # 3. Handle missing values in the linked data
152
+ linked_data = handle_missing_values(linked_data, trait)
153
+
154
+ # 4. Determine whether the trait and some demographic features are severely biased, and remove biased features.
155
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
156
+
157
+ # 5. Conduct quality check and save the cohort information.
158
+ note = ("INFO: Age and Gender not provided in the series characteristics; "
159
+ "Nanostring nCounter 780-gene panel with patient and healthy control samples.")
160
+ is_usable = validate_and_save_cohort_info(
161
+ is_final=True,
162
+ cohort=cohort,
163
+ info_path=json_path,
164
+ is_gene_available=True,
165
+ is_trait_available=True,
166
+ is_biased=is_trait_biased,
167
+ df=unbiased_linked_data,
168
+ note=note
169
+ )
170
+
171
+ # 6. If the linked data is usable, save it as a CSV file to 'out_data_file'.
172
+ if is_usable:
173
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
174
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Large_B-cell_Lymphoma/code/GSE248835.py ADDED
@@ -0,0 +1,220 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Large_B-cell_Lymphoma"
6
+ cohort = "GSE248835"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Large_B-cell_Lymphoma"
10
+ in_cohort_dir = "../DATA/GEO/Large_B-cell_Lymphoma/GSE248835"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z4/preprocess/Large_B-cell_Lymphoma/GSE248835.csv"
14
+ out_gene_data_file = "./output/z4/preprocess/Large_B-cell_Lymphoma/gene_data/GSE248835.csv"
15
+ out_clinical_data_file = "./output/z4/preprocess/Large_B-cell_Lymphoma/clinical_data/GSE248835.csv"
16
+ json_path = "./output/z4/preprocess/Large_B-cell_Lymphoma/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 pandas as pd
40
+ import numpy as np
41
+
42
+ # 1) Gene expression availability (based on series summary and context, this is gene expression data)
43
+ is_gene_available = True
44
+
45
+ # 2) Variable availability and conversion functions
46
+
47
+ # Since this is a LBCL-only cohort, the disease trait is constant (not useful for association)
48
+ trait_row = None
49
+
50
+ # No explicit age or gender fields found in the provided sample characteristics dictionary
51
+ age_row = None
52
+ gender_row = None
53
+
54
+ def _extract_value(x):
55
+ if x is None:
56
+ return None
57
+ if isinstance(x, str):
58
+ # Split by colon and take the value part
59
+ parts = x.split(":", 1)
60
+ val = parts[1] if len(parts) > 1 else parts[0]
61
+ val = val.strip()
62
+ if val in ["", "NA", "NaN", "null", "None", "Missing"]:
63
+ return None
64
+ return val
65
+ return x
66
+
67
+ def convert_trait(x):
68
+ # Not used because trait_row is None; provide a generic mapper for LBCL if ever needed
69
+ val = _extract_value(x)
70
+ if val is None:
71
+ return None
72
+ v = str(val).lower()
73
+ # Map LBCL-related histologies to 1
74
+ if any(k in v for k in ["dlbcl", "large b-cell", "lbcl", "hgbcl", "hgb l", "hgb l", "hgb l", "hgb l", "hgb l", "hgb l", "hgb l"]):
75
+ return 1
76
+ return None
77
+
78
+ def convert_age(x):
79
+ val = _extract_value(x)
80
+ if val is None:
81
+ return None
82
+ try:
83
+ age = float(str(val).replace(",", "").strip())
84
+ # Filter out implausible ages
85
+ if 0 < age < 120:
86
+ return age
87
+ return None
88
+ except Exception:
89
+ return None
90
+
91
+ def convert_gender(x):
92
+ val = _extract_value(x)
93
+ if val is None:
94
+ return None
95
+ v = str(val).strip().lower()
96
+ # Female -> 0, Male -> 1
97
+ if v in ["female", "f", "woman", "women", "girl"]:
98
+ return 0
99
+ if v 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 is_trait_available:
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
+ # Save
127
+ out_dir = os.path.dirname(out_clinical_data_file)
128
+ os.makedirs(out_dir, exist_ok=True)
129
+ selected_clinical_df.to_csv(out_clinical_data_file)
130
+
131
+ # Step 3: Gene Data Extraction
132
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
133
+ gene_data = get_genetic_data(matrix_file)
134
+
135
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
136
+ print(gene_data.index[:20])
137
+
138
+ # Step 4: Gene Identifier Review
139
+ print("requires_gene_mapping = True")
140
+
141
+ # Step 5: Gene Annotation
142
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
143
+ gene_annotation = get_gene_annotation(soft_file)
144
+
145
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
146
+ print("Gene annotation preview:")
147
+ print(preview_df(gene_annotation))
148
+
149
+ # Step 6: Gene Identifier Mapping
150
+ # Identify the appropriate columns in the annotation for mapping:
151
+ # - Probe/ID column: 'ID' (matches numeric IDs in the expression data)
152
+ # - Gene symbol column: 'Gene_Signature_Name' (contains gene/signature names; gene symbols can be extracted)
153
+
154
+ # 2. Build mapping dataframe
155
+ mapping_df = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='Gene_Signature_Name')
156
+
157
+ # 3. Apply mapping to convert probe-level data to gene-level expression
158
+ gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
159
+
160
+ # Step 7: Data Normalization and Linking
161
+ import os
162
+
163
+ # 1. Normalize the obtained gene data and save
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
+ # Determine trait availability from earlier step context
169
+ is_trait_available = (trait_row is not None)
170
+
171
+ if is_trait_available:
172
+ # Recompute clinical features if trait is available (robust to prior steps)
173
+ selected_clinical_data = geo_select_clinical_features(
174
+ clinical_df=clinical_data,
175
+ trait=trait,
176
+ trait_row=trait_row,
177
+ convert_trait=convert_trait,
178
+ age_row=age_row,
179
+ convert_age=convert_age,
180
+ gender_row=gender_row,
181
+ convert_gender=convert_gender
182
+ )
183
+ # 2. Link the clinical and genetic data
184
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_data, normalized_gene_data)
185
+
186
+ # 3. Handle missing values
187
+ linked_data = handle_missing_values(linked_data, trait)
188
+
189
+ # 4. Determine bias and remove biased demographic features
190
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
191
+
192
+ # 5. Final validation and save metadata
193
+ is_usable = validate_and_save_cohort_info(
194
+ is_final=True,
195
+ cohort=cohort,
196
+ info_path=json_path,
197
+ is_gene_available=True,
198
+ is_trait_available=True,
199
+ is_biased=is_trait_biased,
200
+ df=unbiased_linked_data,
201
+ note="INFO: Linked data generated with normalized gene symbols."
202
+ )
203
+
204
+ # 6. Save linked data only if usable
205
+ if is_usable:
206
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
207
+ unbiased_linked_data.to_csv(out_data_file)
208
+
209
+ else:
210
+ # Trait not available: skip linking; still perform final validation and record metadata
211
+ is_usable = validate_and_save_cohort_info(
212
+ is_final=True,
213
+ cohort=cohort,
214
+ info_path=json_path,
215
+ is_gene_available=True,
216
+ is_trait_available=False,
217
+ is_biased=False, # ignored since is_available will be False
218
+ df=normalized_gene_data.T, # pass a non-degenerate df to avoid abnormality override
219
+ note="INFO: No trait found in clinical annotations; linking and downstream steps skipped."
220
+ )
output/preprocess/Large_B-cell_Lymphoma/code/TCGA.py ADDED
@@ -0,0 +1,375 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Large_B-cell_Lymphoma"
6
+
7
+ # Input paths
8
+ tcga_root_dir = "../DATA/TCGA"
9
+
10
+ # Output paths
11
+ out_data_file = "./output/z4/preprocess/Large_B-cell_Lymphoma/TCGA.csv"
12
+ out_gene_data_file = "./output/z4/preprocess/Large_B-cell_Lymphoma/gene_data/TCGA.csv"
13
+ out_clinical_data_file = "./output/z4/preprocess/Large_B-cell_Lymphoma/clinical_data/TCGA.csv"
14
+ json_path = "./output/z4/preprocess/Large_B-cell_Lymphoma/cohort_info.json"
15
+
16
+
17
+ # Step 1: Initial Data Loading
18
+ # Select the most relevant TCGA cohort directory for the trait
19
+ dirs = [d for d in os.listdir(tcga_root_dir) if os.path.isdir(os.path.join(tcga_root_dir, d))]
20
+ san = lambda s: s.lower().replace('-', '').replace(' ', '').replace('_', '')
21
+ trait_key = san(trait)
22
+
23
+ candidates = []
24
+ for d in dirs:
25
+ dl = d.lower()
26
+ sdl = san(d)
27
+ contains_exact_trait = trait_key in sdl
28
+ contains_dlbc = 'dlbc' in dl
29
+ contains_large = 'large' in dl
30
+ contains_bcell = ('bcell' in sdl) or ('b-cell' in dl)
31
+ contains_lymphoma = 'lymphoma' in dl
32
+ score = (
33
+ int(contains_exact_trait),
34
+ int(contains_dlbc),
35
+ int(contains_large and contains_bcell and contains_lymphoma),
36
+ int(contains_lymphoma)
37
+ )
38
+ if any(score):
39
+ candidates.append((score, d))
40
+
41
+ selected_dir = None
42
+ if candidates:
43
+ # Sort by score descending (most specific first)
44
+ candidates.sort(key=lambda x: x[0], reverse=True)
45
+ selected_dir = candidates[0][1]
46
+
47
+ if selected_dir is None:
48
+ # No suitable cohort found; mark as unavailable for this trait
49
+ validate_and_save_cohort_info(
50
+ is_final=False,
51
+ cohort="TCGA_unmatched",
52
+ info_path=json_path,
53
+ is_gene_available=False,
54
+ is_trait_available=False
55
+ )
56
+ else:
57
+ cohort_dir = os.path.join(tcga_root_dir, selected_dir)
58
+ # Identify clinical and genetic file paths
59
+ clinical_file_path, genetic_file_path = tcga_get_relevant_filepaths(cohort_dir)
60
+
61
+ # Robust TSV reader with gzip support
62
+ def read_tsv_auto(fp):
63
+ compression = 'gzip' if fp.endswith('.gz') else None
64
+ return pd.read_csv(fp, sep='\t', index_col=0, low_memory=False, compression=compression)
65
+
66
+ clinical_df = read_tsv_auto(clinical_file_path)
67
+ genetic_df = read_tsv_auto(genetic_file_path)
68
+
69
+ # Print clinical column names for inspection
70
+ print(clinical_df.columns.tolist())
71
+
72
+ # Step 2: Find Candidate Demographic Features
73
+ # Use the provided column name list directly (no file I/O)
74
+ columns_list = ['_INTEGRATION', '_PATIENT', '_cohort', '_primary_disease', '_primary_site', 'age_at_initial_pathologic_diagnosis', 'b_lymphocyte_genotyping_method', 'bcr_followup_barcode', 'bcr_patient_barcode', 'bcr_sample_barcode', 'bone_marrow_biopsy_done', 'bone_marrow_involvement', 'bone_marrow_sample_histology', 'clinical_stage', 'days_to_birth', 'days_to_collection', 'days_to_death', 'days_to_initial_pathologic_diagnosis', 'days_to_last_followup', 'days_to_new_tumor_event_after_initial_treatment', 'eastern_cancer_oncology_group', 'ebv_positive_malignant_cells_percent', 'ebv_status_malignant_cells_method', 'epstein_barr_viral_status', 'extranodal_involvement', 'extranodal_involvment_site_other', 'extranodal_sites_involvement_number', 'first_progression_histology_type', 'first_progression_histology_type_other', 'first_recurrence_biopsy_confirmed', 'follicular_percent', 'followup_case_report_form_submission_reason', 'followup_treatment_success', 'form_completion_date', 'gender', 'genetic_abnormality_method_other', 'genetic_abnormality_results', 'genetic_abnormality_results_other', 'genetic_abnormality_tested', 'genetic_abnormality_tested_other', 'height', 'histological_type', 'history_immunological_disease', 'history_immunological_disease_other', 'history_immunosuppresive_rx', 'history_immunosuppressive_rx_other', 'history_of_neoadjuvant_treatment', 'history_relevant_infectious_dx', 'hiv_status', 'icd_10', 'icd_o_3_histology', 'icd_o_3_site', 'igh_genotype_results', 'immunophenotypic_analysis_method', 'immunophenotypic_analysis_results', 'immunophenotypic_analysis_tested', 'informed_consent_verified', 'initial_weight', 'intermediate_dimension', 'is_ffpe', 'ldh_level', 'ldh_norm_range_upper', 'longest_dimension', 'lost_follow_up', 'lymph_node_involvement_site', 'maximum_tumor_bulk_anatomic_site', 'maximum_tumor_dimension', 'mib1_positive_percentage_range', 'new_neoplasm_event_occurrence_anatomic_site', 'new_neoplasm_occurrence_anatomic_site_text', 'new_tumor_event_after_initial_treatment', 'oct_embedded', 'other_dx', 'pathology_report_file_name', 'patient_id', 'person_neoplasm_cancer_status', 'pet_scan_results', 'primary_therapy_outcome_success', 'radiation_therapy', 'sample_type', 'sample_type_id', 'shortest_dimension', 'system_version', 'targeted_molecular_therapy', 'tissue_prospective_collection_indicator', 'tissue_retrospective_collection_indicator', 'tissue_source_site', 'tumor_tissue_site', 'vial_number', 'vital_status', 'weight', 'year_of_initial_pathologic_diagnosis', '_GENOMIC_ID_TCGA_DLBC_exp_HiSeqV2', '_GENOMIC_ID_TCGA_DLBC_exp_HiSeqV2_exon', '_GENOMIC_ID_TCGA_DLBC_PDMRNAseq', '_GENOMIC_ID_TCGA_DLBC_hMethyl450', '_GENOMIC_ID_TCGA_DLBC_miRNA_HiSeq', '_GENOMIC_ID_TCGA_DLBC_gistic2thd', '_GENOMIC_ID_TCGA_DLBC_PDMRNAseqCNV', '_GENOMIC_ID_data/public/TCGA/DLBC/miRNA_HiSeq_gene', '_GENOMIC_ID_TCGA_DLBC_gistic2', '_GENOMIC_ID_TCGA_DLBC_mutation_bcm_gene', '_GENOMIC_ID_TCGA_DLBC_exp_HiSeqV2_percentile', '_GENOMIC_ID_TCGA_DLBC_RPPA', '_GENOMIC_ID_TCGA_DLBC_exp_HiSeqV2_PANCAN']
75
+
76
+ # Identify candidate demographic columns from the list
77
+ candidate_age_cols = []
78
+ for col in columns_list:
79
+ low = col.lower()
80
+ if (
81
+ low == "days_to_birth"
82
+ or low.startswith("age")
83
+ or "age_at_" in low
84
+ or "_age_" in low
85
+ ):
86
+ # Avoid false positives such as 'stage' and 'percentage'
87
+ if "stage" in low or "percentage" in low:
88
+ continue
89
+ candidate_age_cols.append(col)
90
+
91
+ candidate_gender_cols = []
92
+ for col in columns_list:
93
+ low = col.lower()
94
+ if low in ("gender", "sex"):
95
+ candidate_gender_cols.append(col)
96
+
97
+ # Print required lists in strict format
98
+ print(f"candidate_age_cols = {candidate_age_cols}")
99
+ print(f"candidate_gender_cols = {candidate_gender_cols}")
100
+
101
+ # Preview extracted data (if clinical_df is available in memory)
102
+ if 'clinical_df' in globals() and isinstance(globals().get('clinical_df'), pd.DataFrame):
103
+ available_age_cols = [c for c in candidate_age_cols if c in clinical_df.columns]
104
+ if available_age_cols:
105
+ age_preview = preview_df(clinical_df[available_age_cols], n=5)
106
+ print(age_preview)
107
+ available_gender_cols = [c for c in candidate_gender_cols if c in clinical_df.columns]
108
+ if available_gender_cols:
109
+ gender_preview = preview_df(clinical_df[available_gender_cols], n=5)
110
+ print(gender_preview)
111
+
112
+ # Step 3: Select Demographic Features
113
+ import pandas as pd
114
+
115
+ # Safely retrieve candidate lists
116
+ age_candidates = globals().get("candidate_age_cols", []) or []
117
+ gender_candidates = globals().get("candidate_gender_cols", []) or []
118
+
119
+ def _get_preview_dict(candidates: list) -> dict:
120
+ # Try to find a dict in globals that contains keys overlapping with candidates and list-like values
121
+ best_match = None
122
+ best_overlap = 0
123
+ for name, obj in globals().items():
124
+ if isinstance(obj, dict) and any(k in candidates for k in obj.keys()):
125
+ # Ensure values are list-like for overlapping keys
126
+ overlap_keys = [k for k in obj.keys() if k in candidates and isinstance(obj[k], list)]
127
+ overlap = len(overlap_keys)
128
+ if overlap > best_overlap:
129
+ best_overlap = overlap
130
+ best_match = obj
131
+ return best_match or {}
132
+
133
+ def _missing_ratio(vals: list) -> float:
134
+ if not isinstance(vals, list) or len(vals) == 0:
135
+ return 1.0
136
+ def _is_missing(v):
137
+ if v is None:
138
+ return True
139
+ if isinstance(v, float) and pd.isna(v):
140
+ return True
141
+ if isinstance(v, str) and v.strip().lower() in {"", "na", "n/a", "null", "none"}:
142
+ return True
143
+ return False
144
+ missing = sum(_is_missing(v) for v in vals)
145
+ return missing / len(vals)
146
+
147
+ def _numeric_ratio(vals: list) -> float:
148
+ if not isinstance(vals, list) or len(vals) == 0:
149
+ return 0.0
150
+ def _is_number(v):
151
+ try:
152
+ float(str(v).replace(",", "").strip())
153
+ return True
154
+ except Exception:
155
+ return False
156
+ numeric = sum(_is_number(v) for v in vals)
157
+ return numeric / len(vals)
158
+
159
+ def _gender_valid_ratio(vals: list) -> float:
160
+ if not isinstance(vals, list) or len(vals) == 0:
161
+ return 0.0
162
+ valid_tokens = {"male", "female", "m", "f"}
163
+ def _is_valid(v):
164
+ if v is None:
165
+ return False
166
+ s = str(v).strip().lower()
167
+ return s in valid_tokens
168
+ valid = sum(_is_valid(v) for v in vals)
169
+ return valid / len(vals)
170
+
171
+ # Retrieve preview dictionaries if available
172
+ age_preview_dict = _get_preview_dict(age_candidates)
173
+ gender_preview_dict = _get_preview_dict(gender_candidates)
174
+
175
+ age_col = None
176
+ gender_col = None
177
+
178
+ # Select age column
179
+ if len(age_candidates) > 0:
180
+ # Prefer columns that represent age directly
181
+ preferred_age_order = [
182
+ "age_at_initial_pathologic_diagnosis",
183
+ "age_at_diagnosis",
184
+ ]
185
+ # Build a scored list of candidates based on missingness and numeric content
186
+ scored = []
187
+ for col in age_candidates:
188
+ vals = age_preview_dict.get(col, [])
189
+ miss = _missing_ratio(vals)
190
+ numr = _numeric_ratio(vals)
191
+ # Score: higher is better; penalize missingness. Prefer direct age columns by bonus.
192
+ bonus = 0.2 if col in preferred_age_order else 0.0
193
+ score = (numr - miss) + bonus
194
+ scored.append((score, -miss, numr, col))
195
+ if scored:
196
+ # Sort by highest score, then lowest missingness
197
+ scored.sort(reverse=True)
198
+ best_col = scored[0][3]
199
+ # Apply a sanity threshold on missingness (use preview to avoid heavily missing)
200
+ best_vals = age_preview_dict.get(best_col, [])
201
+ if _missing_ratio(best_vals) < 0.6:
202
+ age_col = best_col
203
+ else:
204
+ age_col = None
205
+ else:
206
+ age_col = None
207
+
208
+ # Select gender column
209
+ if len(gender_candidates) > 0:
210
+ # Prefer straightforward 'gender' column
211
+ preferred_gender_order = ["gender", "sex"]
212
+ scored = []
213
+ for col in gender_candidates:
214
+ vals = gender_preview_dict.get(col, [])
215
+ miss = _missing_ratio(vals)
216
+ valid = _gender_valid_ratio(vals)
217
+ bonus = 0.2 if col in preferred_gender_order else 0.0
218
+ score = (valid - miss) + bonus
219
+ scored.append((score, -miss, valid, col))
220
+ if scored:
221
+ scored.sort(reverse=True)
222
+ best_col = scored[0][3]
223
+ best_vals = gender_preview_dict.get(best_col, [])
224
+ if _missing_ratio(best_vals) < 0.6:
225
+ gender_col = best_col
226
+ else:
227
+ gender_col = None
228
+ else:
229
+ gender_col = None
230
+
231
+ # Explicitly print chosen columns and their preview values (first 5), if available
232
+ print(f"Chosen age_col: {age_col}")
233
+ if age_col is not None:
234
+ print(f"Preview values for {age_col}: {age_preview_dict.get(age_col, [])[:5] if isinstance(age_preview_dict.get(age_col, []), list) else 'N/A'}")
235
+ else:
236
+ print("Preview values for age_col: None (no suitable age column found)")
237
+
238
+ print(f"Chosen gender_col: {gender_col}")
239
+ if gender_col is not None:
240
+ print(f"Preview values for {gender_col}: {gender_preview_dict.get(gender_col, [])[:5] if isinstance(gender_preview_dict.get(gender_col, []), list) else 'N/A'}")
241
+ else:
242
+ print("Preview values for gender_col: None (no suitable gender column found)")
243
+
244
+ # Step 4: Feature Engineering and Validation
245
+ import os
246
+ import re
247
+ import pandas as pd
248
+
249
+ # 1) Extract and standardize clinical features
250
+ def _to_int_or_none(x):
251
+ try:
252
+ return int(re.search(r'\d+', str(x)).group())
253
+ except Exception:
254
+ return None
255
+
256
+ def _extract_sample_type_from_barcode(barcode: str) -> int:
257
+ # TCGA barcode pattern: TCGA-XX-XXXX-SS... where SS are two digits (01-09 tumor, 10-19 normal)
258
+ try:
259
+ parts = str(barcode).split('-')
260
+ if len(parts) >= 4:
261
+ code2 = parts[3][:2]
262
+ return int(code2) if code2.isdigit() else None
263
+ except Exception:
264
+ pass
265
+ # Fallback: search any two-digit token
266
+ m = re.search(r'-(\d{2})', str(barcode))
267
+ if m:
268
+ try:
269
+ return int(m.group(1))
270
+ except Exception:
271
+ return None
272
+ return None
273
+
274
+ def _trait_from_sample_type_code(code: int) -> int:
275
+ if code is None:
276
+ return None
277
+ if 1 <= code <= 9:
278
+ return 1
279
+ if 10 <= code <= 19:
280
+ return 0
281
+ return None
282
+
283
+ # Determine trait from sample_type_id if available, else parse barcode
284
+ if 'sample_type_id' in clinical_df.columns:
285
+ st_codes = clinical_df['sample_type_id'].apply(_to_int_or_none)
286
+ else:
287
+ st_codes = clinical_df.index.to_series().apply(_extract_sample_type_from_barcode)
288
+
289
+ trait_series = st_codes.apply(_trait_from_sample_type_code).rename(trait)
290
+
291
+ age_series = clinical_df[age_col].apply(tcga_convert_age).rename("Age") if (isinstance(age_col, str) and age_col in clinical_df.columns) else None
292
+ gender_series = clinical_df[gender_col].apply(tcga_convert_gender).rename("Gender") if (isinstance(gender_col, str) and gender_col in clinical_df.columns) else None
293
+
294
+ feature_list = [trait_series]
295
+ if age_series is not None:
296
+ feature_list.append(age_series)
297
+ if gender_series is not None:
298
+ feature_list.append(gender_series)
299
+ clinical_selected_df = pd.concat(feature_list, axis=1)
300
+
301
+ # 2) Normalize gene symbols in expression data and save
302
+ # Detect orientation and ensure we have genes as rows, samples as columns for normalization
303
+ barcode_pat = re.compile(r"^TCGA-[A-Z0-9]{2}-[A-Z0-9]{4}-\d{2}")
304
+
305
+ def _ratio_barcode_like(vals):
306
+ if len(vals) == 0:
307
+ return 0.0
308
+ cnt = 0
309
+ tot = 0
310
+ for v in vals:
311
+ s = str(v)
312
+ if s and s != 'nan':
313
+ tot += 1
314
+ if bool(barcode_pat.match(s)):
315
+ cnt += 1
316
+ return (cnt / tot) if tot > 0 else 0.0
317
+
318
+ cols_match_ratio = _ratio_barcode_like(genetic_df.columns)
319
+ idx_match_ratio = _ratio_barcode_like(genetic_df.index)
320
+
321
+ # If many columns look like barcodes -> genes x samples; else if index looks like barcodes -> samples x genes -> transpose
322
+ if cols_match_ratio >= idx_match_ratio:
323
+ gene_by_sample = genetic_df.copy()
324
+ else:
325
+ gene_by_sample = genetic_df.T.copy()
326
+
327
+ # Keep only valid TCGA sample columns
328
+ valid_sample_cols = [c for c in gene_by_sample.columns if isinstance(c, str) and barcode_pat.match(c)]
329
+ gene_by_sample = gene_by_sample[valid_sample_cols]
330
+
331
+ # Normalize gene symbols (index assumed to be gene symbols)
332
+ gene_by_sample_norm = normalize_gene_symbols_in_index(gene_by_sample)
333
+
334
+ # Save normalized gene matrix (genes x samples)
335
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
336
+ gene_by_sample_norm.to_csv(out_gene_data_file)
337
+
338
+ # 3) Link clinical and genetic data on sample IDs
339
+ samples_common = clinical_selected_df.index.intersection(gene_by_sample_norm.columns)
340
+ clinical_selected_df_aligned = clinical_selected_df.loc[samples_common]
341
+ expr_samples_by_genes = gene_by_sample_norm.T.loc[samples_common] # samples x genes
342
+
343
+ linked_data_raw = pd.concat([clinical_selected_df_aligned, expr_samples_by_genes], axis=1)
344
+ linked_data = linked_data_raw.copy()
345
+
346
+ # 4) Handle missing values systematically
347
+ linked_data = handle_missing_values(linked_data, trait_col=trait)
348
+
349
+ # 5) Determine bias and remove biased demographic features
350
+ is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait=trait)
351
+
352
+ # 6) Final quality validation and save cohort info
353
+ cohort_name = globals().get('selected_dir', 'TCGA_Large_Bcell_Lymphoma_(DLBC)')
354
+ is_gene_available = gene_by_sample_norm.shape[0] > 0 and gene_by_sample_norm.shape[1] > 0
355
+ is_trait_available = trait in clinical_selected_df.columns and clinical_selected_df[trait].notna().sum() > 0
356
+
357
+ note = ("INFO: Trait derived from sample_type_id when available; otherwise parsed from TCGA barcode. "
358
+ "Gene matrix orientation auto-detected and normalized using NCBI synonym mapping; "
359
+ "kept only valid TCGA barcode columns.")
360
+
361
+ is_usable = validate_and_save_cohort_info(
362
+ is_final=True,
363
+ cohort=cohort_name,
364
+ info_path=json_path,
365
+ is_gene_available=bool(is_gene_available),
366
+ is_trait_available=bool(is_trait_available),
367
+ is_biased=is_biased,
368
+ df=linked_data,
369
+ note=note
370
+ )
371
+
372
+ # 7) Save the usable linked dataset
373
+ if is_usable:
374
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
375
+ linked_data.to_csv(out_data_file)
output/preprocess/Large_B-cell_Lymphoma/gene_data/GSE173263.csv CHANGED
The diff for this file is too large to render. See raw diff
 
output/preprocess/Large_B-cell_Lymphoma/gene_data/GSE248835.csv CHANGED
The diff for this file is too large to render. See raw diff
 
output/preprocess/Liver_Cancer/GSE178201.csv ADDED
The diff for this file is too large to render. See raw diff
 
output/preprocess/Liver_Cancer/GSE45032.csv CHANGED
The diff for this file is too large to render. See raw diff
 
output/preprocess/Liver_Cancer/clinical_data/GSE174570.csv CHANGED
@@ -1,2 +1,2 @@
1
- 0,1
2
- 1.0,
 
1
+ ,GSM5319834,GSM5319835,GSM5319836,GSM5319837,GSM5319838,GSM5319839,GSM5319840,GSM5319841,GSM5319842,GSM5319843,GSM5319844,GSM5319845,GSM5319846,GSM5319847,GSM5319848,GSM5319849,GSM5319850,GSM5319851,GSM5319852,GSM5319853,GSM5319854,GSM5319855,GSM5319856,GSM5319857,GSM5319858,GSM5319859,GSM5319860,GSM5319861,GSM5319862,GSM5319863,GSM5319864,GSM5319865,GSM5319866,GSM5319867,GSM5319868,GSM5319869,GSM5319870,GSM5319871,GSM5319872,GSM5319873,GSM5319874,GSM5319875,GSM5319876,GSM5319877,GSM5319878,GSM5319879,GSM5319880,GSM5319881,GSM5319882,GSM5319883,GSM5319884,GSM5319885,GSM5319886,GSM5319887,GSM5319888,GSM5319889,GSM5319890,GSM5319891,GSM5319892,GSM5319893,GSM5319894,GSM5319895,GSM5319896,GSM5319897,GSM5319898,GSM5319899,GSM5319900,GSM5319901,GSM5319902,GSM5319903,GSM5319904,GSM5319905,GSM5319906,GSM5319907,GSM5319908,GSM5319909,GSM5319910,GSM5319911,GSM5319912,GSM5319913,GSM5319914,GSM5319915,GSM5319916,GSM5319917,GSM5319918,GSM5319919,GSM5319920,GSM5319921,GSM5319922,GSM5319923,GSM5319924,GSM5319925,GSM5319926,GSM5319927,GSM5319928,GSM5319929,GSM5319930,GSM5319931,GSM5319932,GSM5319933,GSM5319934,GSM5319935,GSM5319936,GSM5319937,GSM5319938,GSM5319939,GSM5319940,GSM5319941,GSM5319942,GSM5319943,GSM5319944,GSM5319945,GSM5319946,GSM5319947
2
+ Liver_Cancer,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0
output/preprocess/Liver_Cancer/clinical_data/GSE178201.csv CHANGED
The diff for this file is too large to render. See raw diff
 
output/preprocess/Liver_Cancer/clinical_data/GSE209875.csv CHANGED
@@ -1,4 +1,4 @@
1
- GSM1,GSM2,GSM3,GSM4,GSM5,GSM6,GSM7,GSM8,GSM9,GSM10,GSM11,GSM12,GSM13,GSM14,GSM15,GSM16,GSM17,GSM18,GSM19,GSM20,GSM21
2
- 1.0,1.0,0.0,0.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0
3
- 63.0,34.0,73.0,76.0,71.0,68.0,39.0,31.0,48.0,66.0,62.0,75.0,65.0,55.0,,,,,,,
4
- 1.0,0.0,,,,,,,,,,,,,,,,,,,
 
1
+ ,GSM6380607,GSM6380608,GSM6380609,GSM6380610,GSM6380611,GSM6380612,GSM6380613,GSM6380614,GSM6380615,GSM6380616,GSM6380617,GSM6380618,GSM6380619,GSM6380620,GSM6380621,GSM6380622,GSM6380623,GSM6380624,GSM6380625,GSM6380626,GSM6380627,GSM6380628,GSM6380629,GSM6380630,GSM6380631,GSM6380632,GSM6380633,GSM6380634,GSM6380635,GSM6380636,GSM6380637,GSM6380638,GSM6380639,GSM6380640,GSM6380641,GSM6380642,GSM6380643,GSM6380644,GSM6380645,GSM6380646,GSM6380647,GSM6380648,GSM6380649,GSM6380650,GSM6380651,GSM6380652,GSM6380653,GSM6380654,GSM6380655,GSM6380656,GSM6380657,GSM6380658,GSM6380659,GSM6380660,GSM6380661,GSM6380662,GSM6380663,GSM6380664,GSM6380665,GSM6380666,GSM6380667,GSM6380668,GSM6380669,GSM6380670,GSM6380671,GSM6380672,GSM6380673,GSM6380674,GSM6380675,GSM6380676,GSM6380677,GSM6380678
2
+ Liver_Cancer,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,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,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,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
3
+ Age,63.0,34.0,73.0,76.0,71.0,68.0,39.0,31.0,73.0,48.0,63.0,34.0,73.0,76.0,71.0,68.0,39.0,31.0,73.0,48.0,66.0,66.0,68.0,62.0,63.0,71.0,66.0,75.0,71.0,75.0,66.0,66.0,68.0,62.0,63.0,71.0,66.0,75.0,71.0,75.0,65.0,55.0,76.0,75.0,65.0,55.0,76.0,75.0,63.0,34.0,73.0,76.0,71.0,68.0,39.0,31.0,73.0,48.0,66.0,66.0,68.0,62.0,63.0,71.0,66.0,75.0,71.0,75.0,65.0,55.0,76.0,75.0
4
+ Gender,1.0,1.0,1.0,0.0,1.0,1.0,1.0,1.0,0.0,1.0,1.0,1.0,1.0,0.0,1.0,1.0,1.0,1.0,0.0,1.0,1.0,1.0,0.0,1.0,1.0,1.0,0.0,1.0,1.0,1.0,1.0,1.0,0.0,1.0,1.0,1.0,0.0,1.0,1.0,1.0,0.0,0.0,1.0,0.0,0.0,0.0,1.0,0.0,1.0,1.0,1.0,0.0,1.0,1.0,1.0,1.0,0.0,1.0,1.0,1.0,0.0,1.0,1.0,1.0,0.0,1.0,1.0,1.0,0.0,0.0,1.0,0.0
output/preprocess/Liver_Cancer/clinical_data/GSE218438.csv ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ ,GSM6744665,GSM6744666,GSM6744667,GSM6744668,GSM6744669,GSM6744670,GSM6744671,GSM6744672,GSM6744673,GSM6744674,GSM6744675,GSM6744676,GSM6744677,GSM6744678,GSM6744679,GSM6744680,GSM6744681,GSM6744682,GSM6744683,GSM6744684,GSM6744685,GSM6744686,GSM6744687,GSM6744688,GSM6744689,GSM6744690,GSM6744691,GSM6744692,GSM6744693,GSM6744694,GSM6744695,GSM6744696,GSM6744697,GSM6744698,GSM6744699,GSM6744700,GSM6744701,GSM6744702,GSM6744703,GSM6744704,GSM6744705,GSM6744706,GSM6744707,GSM6744708,GSM6744709,GSM6744710,GSM6744711,GSM6744712,GSM6744713,GSM6744714,GSM6744715,GSM6744716,GSM6744717,GSM6744718,GSM6744719,GSM6744720,GSM6744721,GSM6744722,GSM6744723,GSM6744724,GSM6744725,GSM6744726,GSM6744727,GSM6744728,GSM6744729,GSM6744730,GSM6744731,GSM6744732,GSM6744733,GSM6744734,GSM6744735,GSM6744736,GSM6744737,GSM6744738,GSM6744739,GSM6744740,GSM6744741,GSM6744742,GSM6744743,GSM6744744,GSM6744745,GSM6744746,GSM6744747,GSM6744748,GSM6744749,GSM6744750,GSM6744751,GSM6744752,GSM6744753,GSM6744754,GSM6744755,GSM6744756,GSM6744757,GSM6744758,GSM6744759,GSM6744760,GSM6744761,GSM6744762,GSM6744763,GSM6744764,GSM6744765,GSM6744766,GSM6744767,GSM6744768,GSM6744769,GSM6744770,GSM6744771,GSM6744772,GSM6744773,GSM6744774,GSM6744775,GSM6744776,GSM6744777,GSM6744778,GSM6744779,GSM6744780,GSM6744781,GSM6744782,GSM6744783,GSM6744784,GSM6744785,GSM6744786,GSM6744787,GSM6744788,GSM6744789,GSM6744790,GSM6744791,GSM6744792,GSM6744793,GSM6744794,GSM6744795,GSM6744796,GSM6744797,GSM6744798,GSM6744799,GSM6744800,GSM6744801,GSM6744802,GSM6744803,GSM6744804,GSM6744805,GSM6744806,GSM6744807,GSM6744808,GSM6744809,GSM6744810,GSM6744811,GSM6744812,GSM6744813,GSM6744814,GSM6744815,GSM6744816,GSM6744817,GSM6744818,GSM6744819,GSM6744820,GSM6744821,GSM6744822,GSM6744823,GSM6744824,GSM6744825,GSM6744826,GSM6744827,GSM6744828,GSM6744829,GSM6744830,GSM6744831,GSM6744832,GSM6744833,GSM6744834,GSM6744835,GSM6744836,GSM6744837,GSM6744838,GSM6744839,GSM6744840,GSM6744841,GSM6744842,GSM6744843,GSM6744844,GSM6744845,GSM6744846,GSM6744847,GSM6744848,GSM6744849,GSM6744850,GSM6744851,GSM6744852,GSM6744853,GSM6744854,GSM6744855,GSM6744856,GSM6744857,GSM6744858,GSM6744859,GSM6744860,GSM6744861,GSM6744862,GSM6744863,GSM6744864,GSM6744865,GSM6744866,GSM6744867,GSM6744868,GSM6744869,GSM6744870,GSM6744871,GSM6744872,GSM6744873,GSM6744874,GSM6744875,GSM6744876,GSM6744877,GSM6744878,GSM6744879,GSM6744880,GSM6744881,GSM6744882,GSM6744883,GSM6744884,GSM6744885,GSM6744886,GSM6744887,GSM6744888,GSM6744889,GSM6744890,GSM6744891,GSM6744892,GSM6744893,GSM6744894,GSM6744895,GSM6744896,GSM6744897,GSM6744898,GSM6744899,GSM6744900,GSM6744901,GSM6744902,GSM6744903,GSM6744904,GSM6744905,GSM6744906,GSM6744907,GSM6744908,GSM6744909,GSM6744910,GSM6744911,GSM6744912,GSM6744913,GSM6744914,GSM6744915,GSM6744916,GSM6744917,GSM6744918,GSM6744920,GSM6744924,GSM6744928,GSM6744932,GSM6744936,GSM6744938,GSM6744941,GSM6744944,GSM6744945,GSM6744946,GSM6744947,GSM6744948,GSM6744949,GSM6744950,GSM6744951,GSM6744952,GSM6744953,GSM6744954,GSM6744955,GSM6744956,GSM6744957,GSM6744958,GSM6744959,GSM6744960,GSM6744961,GSM6744962,GSM6744963,GSM6744964,GSM6744965,GSM6744966,GSM6744967,GSM6744968,GSM6744969,GSM6744970,GSM6744971,GSM6744972,GSM6744973,GSM6744974,GSM6744975,GSM6744976,GSM6744977,GSM6744978,GSM6744979,GSM6744980,GSM6744981,GSM6744982,GSM6744983,GSM6744984,GSM6744985,GSM6744986,GSM6744987,GSM6744988,GSM6744989,GSM6744990,GSM6744991,GSM6744992,GSM6744993,GSM6744994,GSM6744995,GSM6744996,GSM6744997,GSM6744998,GSM6744999,GSM6745000,GSM6745001,GSM6745002,GSM6745003,GSM6745004,GSM6745005,GSM6745006,GSM6745007,GSM6745008,GSM6745009,GSM6745010,GSM6745011,GSM6745012,GSM6745013,GSM6745014,GSM6745015,GSM6745016,GSM6745017,GSM6745018,GSM6745019,GSM6745020,GSM6745021,GSM6745022,GSM6745023,GSM6745024,GSM6745025,GSM6745026,GSM6745027,GSM6745028,GSM6745029,GSM6745030,GSM6745031,GSM6745032,GSM6745033,GSM6745034,GSM6745035,GSM6745036,GSM6745037,GSM6745038,GSM6745039,GSM6745040,GSM6745041,GSM6745042,GSM6745043,GSM6745044,GSM6745045,GSM6745046,GSM6745047,GSM6745048,GSM6745049,GSM6745050,GSM6745051,GSM6745052,GSM6745053,GSM6745054,GSM6745055,GSM6745056,GSM6745057,GSM6745058,GSM6745059,GSM6745060,GSM6745061,GSM6745062,GSM6745063,GSM6745064,GSM6745065,GSM6745066,GSM6745067,GSM6745068,GSM6745069,GSM6745070,GSM6745071,GSM6745072,GSM6745073,GSM6745074,GSM6745075,GSM6745076,GSM6745077,GSM6745078,GSM6745079,GSM6745080,GSM6745081,GSM6745082,GSM6745083,GSM6745084,GSM6745085,GSM6745086,GSM6745087,GSM6745088,GSM6745089,GSM6745090,GSM6745091,GSM6745092,GSM6745093,GSM6745094,GSM6745095,GSM6745096,GSM6745097,GSM6745098,GSM6745099,GSM6745100,GSM6745101,GSM6745102,GSM6745103,GSM6745104,GSM6745105,GSM6745106,GSM6745107,GSM6745108,GSM6745109,GSM6745110,GSM6745111,GSM6745112,GSM6745113,GSM6745114,GSM6745115,GSM6745116,GSM6745117,GSM6745118,GSM6745119,GSM6745120,GSM6745121,GSM6745122,GSM6745123,GSM6745124,GSM6745125,GSM6745126,GSM6745127,GSM6745128,GSM6745129,GSM6745130,GSM6745131,GSM6745132,GSM6745133,GSM6745134,GSM6745135,GSM6745136,GSM6745137,GSM6745138,GSM6745139,GSM6745140,GSM6745141,GSM6745142,GSM6745143,GSM6745144,GSM6745145,GSM6745146,GSM6745147,GSM6745148,GSM6745149,GSM6745150,GSM6745151,GSM6745152,GSM6745153,GSM6745154,GSM6745155,GSM6745156,GSM6745157,GSM6745158,GSM6745159,GSM6745160,GSM6745161,GSM6745162,GSM6745163,GSM6745164,GSM6745165,GSM6745166,GSM6745167,GSM6745168,GSM6745169,GSM6745170,GSM6745171,GSM6745172,GSM6745173,GSM6745174,GSM6745175,GSM6745176,GSM6745177,GSM6745178,GSM6745179,GSM6745180,GSM6745181,GSM6745182,GSM6745183,GSM6745184,GSM6745185,GSM6745186,GSM6745187,GSM6745188,GSM6745189,GSM6745190,GSM6745191,GSM6745192,GSM6745193,GSM6745194,GSM6745195,GSM6745196,GSM6745197,GSM6745198,GSM6745199,GSM6745200,GSM6745201,GSM6745202,GSM6745203,GSM6745204,GSM6745205,GSM6745206,GSM6745207,GSM6745208,GSM6745209,GSM6745210,GSM6745211,GSM6745212,GSM6745213,GSM6745214,GSM6745215,GSM6745216,GSM6745217,GSM6745218,GSM6745219,GSM6745220,GSM6745221,GSM6745222,GSM6745223,GSM6745224,GSM6745225,GSM6745226,GSM6745227,GSM6745228,GSM6745229,GSM6745230,GSM6745231,GSM6745232,GSM6745233,GSM6745234,GSM6745235,GSM6745236,GSM6745237,GSM6745238,GSM6745239,GSM6745240,GSM6745241,GSM6745242,GSM6745243,GSM6745244,GSM6745245,GSM6745246,GSM6745247,GSM6745248,GSM6745249,GSM6745250,GSM6745251,GSM6745252,GSM6745253,GSM6745254,GSM6745255,GSM6745256,GSM6745257,GSM6745258,GSM6745259,GSM6745260,GSM6745261,GSM6745262,GSM6745263,GSM6745264,GSM6745265,GSM6745266,GSM6745267,GSM6745268,GSM6745269,GSM6745270,GSM6745271,GSM6745272,GSM6745273,GSM6745274,GSM6745275,GSM6745276,GSM6745277,GSM6745278,GSM6745279,GSM6745280,GSM6745281,GSM6745282,GSM6745283,GSM6745284,GSM6745285,GSM6745286,GSM6745287,GSM6745288,GSM6745289,GSM6745290,GSM6745291,GSM6745292,GSM6745293,GSM6745294,GSM6745295,GSM6745296,GSM6745297,GSM6745298,GSM6745299,GSM6745300,GSM6745301,GSM6745302,GSM6745303,GSM6745304,GSM6745305,GSM6745306,GSM6745307,GSM6745308,GSM6745309,GSM6745310,GSM6745311,GSM6745312,GSM6745313,GSM6745314,GSM6745315,GSM6745316,GSM6745317,GSM6745318
2
+ Liver_Cancer,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,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,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,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,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,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/Liver_Cancer/clinical_data/GSE228782.csv CHANGED
@@ -1,2 +1,2 @@
1
- ,2
2
- Liver_Cancer,1.0
 
1
+ GSM7136390,GSM7136391,GSM7136392,GSM7136393,GSM7136394,GSM7136395,GSM7136396,GSM7136397,GSM7136398,GSM7136399,GSM7136400,GSM7136401,GSM7136402,GSM7136403,GSM7136404,GSM7136405,GSM7136406,GSM7136407,GSM7136408,GSM7136409,GSM7136410,GSM7136411,GSM7136412,GSM7136413,GSM7136414,GSM7136415,GSM7136416,GSM7136417,GSM7136418,GSM7136419,GSM7136420,GSM7136421,GSM7136422,GSM7136423,GSM7136424,GSM7136425,GSM7136426,GSM7136427,GSM7136428,GSM7136429,GSM7136430,GSM7136431,GSM7136432,GSM7136433,GSM7136434,GSM7136435,GSM7136436,GSM7136437,GSM7136438,GSM7136439,GSM7136440,GSM7136441,GSM7136442,GSM7136443,GSM7136444,GSM7136445,GSM7136446,GSM7136447,GSM7136448,GSM7136449,GSM7136450,GSM7136451,GSM7136452,GSM7136453,GSM7136454,GSM7136455,GSM7136456,GSM7136457,GSM7136458,GSM7136460,GSM7136462,GSM7136465,GSM7136468,GSM7136471,GSM7136472,GSM7136473,GSM7136474,GSM7136475,GSM7136476,GSM7136477,GSM7136478,GSM7136479,GSM7136480
2
+ 1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0
output/preprocess/Liver_Cancer/clinical_data/GSE228783.csv CHANGED
@@ -1,2 +1,2 @@
1
- GSM7136321,GSM7136322,GSM7136323,GSM7136324,GSM7136325,GSM7136326,GSM7136327,GSM7136328,GSM7136329,GSM7136330,GSM7136331,GSM7136332,GSM7136333,GSM7136334,GSM7136335,GSM7136336,GSM7136337,GSM7136338,GSM7136339,GSM7136340,GSM7136341,GSM7136342,GSM7136343,GSM7136344,GSM7136345,GSM7136346,GSM7136347,GSM7136348,GSM7136349,GSM7136350,GSM7136351,GSM7136352,GSM7136353,GSM7136354,GSM7136355,GSM7136356,GSM7136357,GSM7136358,GSM7136359,GSM7136360,GSM7136361,GSM7136362,GSM7136363,GSM7136364,GSM7136365,GSM7136366,GSM7136367,GSM7136368,GSM7136369,GSM7136370,GSM7136371,GSM7136372,GSM7136373,GSM7136374,GSM7136375,GSM7136376,GSM7136377,GSM7136378,GSM7136379,GSM7136380,GSM7136381,GSM7136382,GSM7136383,GSM7136384,GSM7136385,GSM7136386,GSM7136387,GSM7136388,GSM7136389,GSM7136390,GSM7136391,GSM7136392,GSM7136393,GSM7136394,GSM7136395,GSM7136396,GSM7136397,GSM7136398,GSM7136399,GSM7136400,GSM7136401,GSM7136402,GSM7136403,GSM7136404,GSM7136405,GSM7136406,GSM7136407,GSM7136408,GSM7136409,GSM7136410,GSM7136411,GSM7136412,GSM7136413,GSM7136414,GSM7136415,GSM7136416,GSM7136417,GSM7136418,GSM7136419,GSM7136420,GSM7136421,GSM7136422,GSM7136423,GSM7136424,GSM7136425,GSM7136426,GSM7136427,GSM7136428,GSM7136429,GSM7136430,GSM7136431,GSM7136432,GSM7136433,GSM7136434,GSM7136435,GSM7136436,GSM7136437,GSM7136438,GSM7136439,GSM7136440,GSM7136441,GSM7136442,GSM7136443,GSM7136444,GSM7136445,GSM7136446,GSM7136447,GSM7136448,GSM7136449,GSM7136450,GSM7136451,GSM7136452,GSM7136453,GSM7136454,GSM7136455,GSM7136456,GSM7136457,GSM7136458,GSM7136460,GSM7136462,GSM7136465,GSM7136468,GSM7136471,GSM7136472,GSM7136473,GSM7136474,GSM7136475,GSM7136476,GSM7136477,GSM7136478,GSM7136479,GSM7136480
2
- 0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0
 
1
+ ,GSM7136321,GSM7136322,GSM7136323,GSM7136324,GSM7136325,GSM7136326,GSM7136327,GSM7136328,GSM7136329,GSM7136330,GSM7136331,GSM7136332,GSM7136333,GSM7136334,GSM7136335,GSM7136336,GSM7136337,GSM7136338,GSM7136339,GSM7136340,GSM7136341,GSM7136342,GSM7136343,GSM7136344,GSM7136345,GSM7136346,GSM7136347,GSM7136348,GSM7136349,GSM7136350,GSM7136351,GSM7136352,GSM7136353,GSM7136354,GSM7136355,GSM7136356,GSM7136357,GSM7136358,GSM7136359,GSM7136360,GSM7136361,GSM7136362,GSM7136363,GSM7136364,GSM7136365,GSM7136366,GSM7136367,GSM7136368,GSM7136369,GSM7136370,GSM7136371,GSM7136372,GSM7136373,GSM7136374,GSM7136375,GSM7136376,GSM7136377,GSM7136378,GSM7136379,GSM7136380,GSM7136381,GSM7136382,GSM7136383,GSM7136384,GSM7136385,GSM7136386,GSM7136387,GSM7136388,GSM7136389,GSM7136390,GSM7136391,GSM7136392,GSM7136393,GSM7136394,GSM7136395,GSM7136396,GSM7136397,GSM7136398,GSM7136399,GSM7136400,GSM7136401,GSM7136402,GSM7136403,GSM7136404,GSM7136405,GSM7136406,GSM7136407,GSM7136408,GSM7136409,GSM7136410,GSM7136411,GSM7136412,GSM7136413,GSM7136414,GSM7136415,GSM7136416,GSM7136417,GSM7136418,GSM7136419,GSM7136420,GSM7136421,GSM7136422,GSM7136423,GSM7136424,GSM7136425,GSM7136426,GSM7136427,GSM7136428,GSM7136429,GSM7136430,GSM7136431,GSM7136432,GSM7136433,GSM7136434,GSM7136435,GSM7136436,GSM7136437,GSM7136438,GSM7136439,GSM7136440,GSM7136441,GSM7136442,GSM7136443,GSM7136444,GSM7136445,GSM7136446,GSM7136447,GSM7136448,GSM7136449,GSM7136450,GSM7136451,GSM7136452,GSM7136453,GSM7136454,GSM7136455,GSM7136456,GSM7136457,GSM7136458,GSM7136460,GSM7136462,GSM7136465,GSM7136468,GSM7136471,GSM7136472,GSM7136473,GSM7136474,GSM7136475,GSM7136476,GSM7136477,GSM7136478,GSM7136479,GSM7136480
2
+ Liver_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,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,,,,,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,,,,,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,,,,,1.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0
output/preprocess/Liver_Cancer/clinical_data/GSE45032.csv CHANGED
@@ -1,4 +1,4 @@
1
  ,GSM1096016,GSM1096017,GSM1096018,GSM1096019,GSM1096020,GSM1096021,GSM1096022,GSM1096023,GSM1096024,GSM1096025,GSM1096026,GSM1096027,GSM1096028,GSM1096029,GSM1096030,GSM1096031,GSM1096032,GSM1096033,GSM1096034,GSM1096035,GSM1096036,GSM1096037,GSM1096038,GSM1096039,GSM1096040,GSM1096041,GSM1096042,GSM1096043,GSM1096044,GSM1096045,GSM1096046,GSM1096047,GSM1096048,GSM1096049,GSM1096050,GSM1096051,GSM1096052,GSM1096053,GSM1096054,GSM1096055,GSM1096056,GSM1096057,GSM1096058,GSM1096059,GSM1096060,GSM1096061,GSM1096062,GSM1096063
2
  Liver_Cancer,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0
3
  Age,67.0,56.0,76.0,79.0,66.0,70.0,68.0,72.0,62.0,66.0,55.0,62.0,71.0,73.0,74.0,61.0,54.0,64.0,68.0,59.0,79.0,69.0,59.0,71.0,64.0,55.0,66.0,56.0,66.0,68.0,25.0,41.0,50.0,56.0,66.0,58.0,67.0,49.0,63.0,70.0,60.0,50.0,58.0,61.0,60.0,59.0,52.0,51.0
4
- Gender,1.0,1.0,0.0,1.0,1.0,1.0,1.0,0.0,1.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,1.0,0.0,1.0,1.0,1.0,0.0,1.0,1.0,1.0,0.0,0.0,1.0,1.0,1.0,0.0,1.0,0.0,0.0,0.0,1.0,0.0,1.0,1.0,1.0,0.0,0.0,1.0,1.0,0.0,1.0,1.0,1.0
 
1
  ,GSM1096016,GSM1096017,GSM1096018,GSM1096019,GSM1096020,GSM1096021,GSM1096022,GSM1096023,GSM1096024,GSM1096025,GSM1096026,GSM1096027,GSM1096028,GSM1096029,GSM1096030,GSM1096031,GSM1096032,GSM1096033,GSM1096034,GSM1096035,GSM1096036,GSM1096037,GSM1096038,GSM1096039,GSM1096040,GSM1096041,GSM1096042,GSM1096043,GSM1096044,GSM1096045,GSM1096046,GSM1096047,GSM1096048,GSM1096049,GSM1096050,GSM1096051,GSM1096052,GSM1096053,GSM1096054,GSM1096055,GSM1096056,GSM1096057,GSM1096058,GSM1096059,GSM1096060,GSM1096061,GSM1096062,GSM1096063
2
  Liver_Cancer,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0
3
  Age,67.0,56.0,76.0,79.0,66.0,70.0,68.0,72.0,62.0,66.0,55.0,62.0,71.0,73.0,74.0,61.0,54.0,64.0,68.0,59.0,79.0,69.0,59.0,71.0,64.0,55.0,66.0,56.0,66.0,68.0,25.0,41.0,50.0,56.0,66.0,58.0,67.0,49.0,63.0,70.0,60.0,50.0,58.0,61.0,60.0,59.0,52.0,51.0
4
+ Gender,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0
output/preprocess/Liver_Cancer/code/GSE148346.py ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Liver_Cancer"
6
+ cohort = "GSE148346"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Liver_Cancer"
10
+ in_cohort_dir = "../DATA/GEO/Liver_Cancer/GSE148346"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z4/preprocess/Liver_Cancer/GSE148346.csv"
14
+ out_gene_data_file = "./output/z4/preprocess/Liver_Cancer/gene_data/GSE148346.csv"
15
+ out_clinical_data_file = "./output/z4/preprocess/Liver_Cancer/clinical_data/GSE148346.csv"
16
+ json_path = "./output/z4/preprocess/Liver_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 pandas as pd
40
+ import numpy as np
41
+
42
+ # 1. Gene Expression Data Availability
43
+ # Given the study context (biopsy sub-study with molecular responses), gene expression data is likely available.
44
+ is_gene_available = True
45
+
46
+ # 2. Variable Availability and Data Type Conversion
47
+
48
+ # 2.1 Data Availability
49
+ # The provided sample characteristics do not include liver cancer status, age, or gender.
50
+ trait_row = None
51
+ age_row = None
52
+ gender_row = None
53
+
54
+ # 2.2 Data Type Conversion
55
+ def _after_colon(x):
56
+ if x is None:
57
+ return None
58
+ if isinstance(x, str):
59
+ parts = x.split(":", 1)
60
+ return parts[1].strip() if len(parts) > 1 else x.strip()
61
+ return x
62
+
63
+ def convert_trait(x):
64
+ # Trait is Liver_Cancer; no related field present in this dataset.
65
+ return None
66
+
67
+ def convert_age(x):
68
+ v = _after_colon(x)
69
+ if v is None:
70
+ return None
71
+ v = v.strip().lower()
72
+ if v in {"na", "n/a", "unknown", "", "nan"}:
73
+ return None
74
+ # Extract numeric age
75
+ try:
76
+ # Remove non-digit/non-dot characters
77
+ num = "".join(ch for ch in v if (ch.isdigit() or ch == '.' or ch == '-'))
78
+ if num == "" or num == "-" or num == ".":
79
+ return None
80
+ val = float(num)
81
+ # Age must be within a reasonable human range
82
+ if 0 <= val <= 120:
83
+ return val
84
+ return None
85
+ except Exception:
86
+ return None
87
+
88
+ def convert_gender(x):
89
+ v = _after_colon(x)
90
+ if v is None:
91
+ return None
92
+ v = v.strip().lower()
93
+ if v in {"female", "f", "woman", "women"}:
94
+ return 0
95
+ if v in {"male", "m", "man", "men"}:
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
+ # Skipped because trait_row is None (no clinical trait data for Liver_Cancer in this dataset).
output/preprocess/Liver_Cancer/code/GSE164760.py ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Liver_Cancer"
6
+ cohort = "GSE164760"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Liver_Cancer"
10
+ in_cohort_dir = "../DATA/GEO/Liver_Cancer/GSE164760"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z4/preprocess/Liver_Cancer/GSE164760.csv"
14
+ out_gene_data_file = "./output/z4/preprocess/Liver_Cancer/gene_data/GSE164760.csv"
15
+ out_clinical_data_file = "./output/z4/preprocess/Liver_Cancer/clinical_data/GSE164760.csv"
16
+ json_path = "./output/z4/preprocess/Liver_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 availability (expression array mentioned in series summary)
40
+ is_gene_available = True
41
+
42
+ # 2) Variable availability and converters based on the provided sample characteristics
43
+ # Sample Characteristics Dictionary shows only key 0 with tissue types
44
+ trait_row = 0 # Use tissue to infer Liver_Cancer status
45
+ age_row = None
46
+ gender_row = None
47
+
48
+ def _extract_value(cell):
49
+ if cell is None:
50
+ return None
51
+ if isinstance(cell, str):
52
+ parts = cell.split(":", 1)
53
+ val = parts[1].strip() if len(parts) == 2 else cell.strip()
54
+ return val if val != "" else None
55
+ return None
56
+
57
+ def convert_trait(cell):
58
+ # Map tissue categories to Liver_Cancer: 1 for NASH-HCC tumor, else 0
59
+ v = _extract_value(cell)
60
+ if v is None:
61
+ return None
62
+ vl = v.lower()
63
+ # Explicit handling of known categories in this dataset
64
+ if vl == "nash-hcc tumor":
65
+ return 1
66
+ if vl in {"nash liver", "cirrhotic liver", "healthy liver"}:
67
+ return 0
68
+ if "non-tumoral" in vl or "adjacent" in vl:
69
+ return 0
70
+ # Conservative default: treat other non-matching tissues as non-cancer
71
+ return 0
72
+
73
+ def convert_age(cell):
74
+ v = _extract_value(cell)
75
+ if v is None:
76
+ return None
77
+ # Try to extract a number from the string
78
+ import re
79
+ m = re.search(r"[-+]?\d*\.?\d+", v)
80
+ if m:
81
+ try:
82
+ age_val = float(m.group())
83
+ # Reasonable human age bounds
84
+ if 0 <= age_val <= 120:
85
+ return age_val
86
+ except Exception:
87
+ return None
88
+ return None
89
+
90
+ def convert_gender(cell):
91
+ v = _extract_value(cell)
92
+ if v is None:
93
+ return None
94
+ vl = v.strip().lower()
95
+ if vl in {"female", "f", "woman", "women"}:
96
+ return 0
97
+ if vl in {"male", "m", "man", "men"}:
98
+ return 1
99
+ return None
100
+
101
+ # 3) Save metadata with initial filtering
102
+ is_trait_available = trait_row is not None
103
+ _ = validate_and_save_cohort_info(
104
+ is_final=False,
105
+ cohort=cohort,
106
+ info_path=json_path,
107
+ is_gene_available=is_gene_available,
108
+ is_trait_available=is_trait_available
109
+ )
110
+
111
+ # 4) Clinical feature extraction (only if trait data is available)
112
+ if is_trait_available:
113
+ selected_clinical_df = geo_select_clinical_features(
114
+ clinical_df=clinical_data,
115
+ trait=trait,
116
+ trait_row=trait_row,
117
+ convert_trait=convert_trait,
118
+ age_row=age_row,
119
+ convert_age=convert_age,
120
+ gender_row=gender_row,
121
+ convert_gender=convert_gender
122
+ )
123
+ clinical_preview = preview_df(selected_clinical_df)
124
+ print(clinical_preview)
125
+
126
+ # Save clinical data
127
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
128
+ selected_clinical_df.to_csv(out_clinical_data_file)
129
+
130
+ # Step 3: Gene Data Extraction
131
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
132
+ gene_data = get_genetic_data(matrix_file)
133
+
134
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
135
+ print(gene_data.index[:20])
136
+
137
+ # Step 4: Gene Identifier Review
138
+ print("requires_gene_mapping = True")
139
+
140
+ # Step 5: Gene Annotation
141
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
142
+ gene_annotation = get_gene_annotation(soft_file)
143
+
144
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
145
+ print("Gene annotation preview:")
146
+ print(preview_df(gene_annotation))
147
+
148
+ # Step 6: Gene Identifier Mapping
149
+ # Determine appropriate columns for mapping based on annotation preview:
150
+ # Probe ID column: 'ID'
151
+ # Gene symbol column: 'Gene Symbol'
152
+
153
+ # Ensure we have the annotation dataframe (if not already in scope)
154
+ try:
155
+ gene_annotation
156
+ except NameError:
157
+ gene_annotation = get_gene_annotation(soft_file)
158
+
159
+ # Build mapping dataframe
160
+ mapping_df = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='Gene Symbol')
161
+
162
+ # Preserve the original probe-level data and map to gene-level
163
+ probe_level_df = gene_data # from Step 3
164
+ gene_data = apply_gene_mapping(expression_df=probe_level_df, mapping_df=mapping_df)
165
+
166
+ # Step 7: Data Normalization and Linking
167
+ # 1. Normalize gene symbols and save gene-level data
168
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
169
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
170
+ normalized_gene_data.to_csv(out_gene_data_file)
171
+
172
+ # 2. Link clinical and genetic data (use the correct clinical variable name)
173
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
174
+
175
+ # 3. Handle missing values in the linked data
176
+ linked_data = handle_missing_values(linked_data, trait)
177
+
178
+ # 4. Determine bias and remove biased demographic features
179
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
180
+ is_trait_biased = bool(is_trait_biased) # ensure Python-native bool
181
+
182
+ # 5. Final validation and save cohort info (force Python bools to avoid JSON issues)
183
+ is_gene_available = bool((normalized_gene_data.shape[0] > 0) and (normalized_gene_data.shape[1] > 0))
184
+ is_trait_available = bool((trait in selected_clinical_df.index) and bool(selected_clinical_df.loc[trait].notna().any()))
185
+ note = "INFO: Trait inferred from tissue; age and gender not available in matrix."
186
+
187
+ is_usable = validate_and_save_cohort_info(
188
+ is_final=True,
189
+ cohort=cohort,
190
+ info_path=json_path,
191
+ is_gene_available=is_gene_available,
192
+ is_trait_available=is_trait_available,
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/Liver_Cancer/code/GSE174570.py ADDED
@@ -0,0 +1,187 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Liver_Cancer"
6
+ cohort = "GSE174570"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Liver_Cancer"
10
+ in_cohort_dir = "../DATA/GEO/Liver_Cancer/GSE174570"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z4/preprocess/Liver_Cancer/GSE174570.csv"
14
+ out_gene_data_file = "./output/z4/preprocess/Liver_Cancer/gene_data/GSE174570.csv"
15
+ out_clinical_data_file = "./output/z4/preprocess/Liver_Cancer/clinical_data/GSE174570.csv"
16
+ json_path = "./output/z4/preprocess/Liver_Cancer/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ import os
40
+ import re
41
+
42
+ # 1) Determine gene expression availability
43
+ # Affymetrix Human Genome U219 Array => mRNA expression data available
44
+ is_gene_available = True
45
+
46
+ # 2) Variable availability based on the Sample Characteristics Dictionary shown
47
+ # Keys: {0: ['disease state: HCC'], 1: ['tissue: Tumour (liver)', 'tissue: Non-tumour adjacent (liver)']}
48
+ # disease state is constant; tissue distinguishes tumour vs non-tumour adjacent -> can infer trait
49
+ trait_row = 1
50
+ age_row = None
51
+ gender_row = None
52
+
53
+ # 2.2) Converters
54
+ def _after_colon(value):
55
+ if value is None:
56
+ return ""
57
+ s = str(value)
58
+ if ":" in s:
59
+ s = s.split(":", 1)[1]
60
+ return s.strip()
61
+
62
+ def convert_trait(value):
63
+ s = _after_colon(value).lower()
64
+ if s in {"", "na", "n/a", "none", "unknown"}:
65
+ return None
66
+ # Map tumour/tumor as 1 (Liver_Cancer), non-tumour/adjacent/normal as 0
67
+ # Prioritize non-tumor indicators to avoid false positives
68
+ if any(k in s for k in ["non-tumour", "non-tumor", "non tumor", "adjacent", "non-neoplastic", "normal"]):
69
+ return 0
70
+ if any(k in s for k in ["tumour", "tumor", "cancer", "malignant", "hcc"]):
71
+ return 1
72
+ return None
73
+
74
+ def convert_age(value):
75
+ s = _after_colon(value).lower()
76
+ if s in {"", "na", "n/a", "none", "unknown"}:
77
+ return None
78
+ m = re.search(r"[-+]?\d*\.?\d+", s)
79
+ if m:
80
+ try:
81
+ return float(m.group())
82
+ except Exception:
83
+ return None
84
+ return None
85
+
86
+ def convert_gender(value):
87
+ s = _after_colon(value).lower()
88
+ if s in {"", "na", "n/a", "none", "unknown"}:
89
+ return None
90
+ if "female" in s or s == "f":
91
+ return 0
92
+ if "male" in s or s == "m":
93
+ return 1
94
+ return None
95
+
96
+ # 3) Save metadata: initial filtering
97
+ is_trait_available = trait_row is not None
98
+ _ = validate_and_save_cohort_info(
99
+ is_final=False,
100
+ cohort=cohort,
101
+ info_path=json_path,
102
+ is_gene_available=is_gene_available,
103
+ is_trait_available=is_trait_available
104
+ )
105
+
106
+ # 4) Clinical Feature Extraction (only if trait_row is available)
107
+ if trait_row is not None:
108
+ selected_clinical_df = geo_select_clinical_features(
109
+ clinical_df=clinical_data,
110
+ trait=trait,
111
+ trait_row=trait_row,
112
+ convert_trait=convert_trait,
113
+ age_row=age_row,
114
+ convert_age=convert_age,
115
+ gender_row=gender_row,
116
+ convert_gender=convert_gender
117
+ )
118
+ preview = preview_df(selected_clinical_df)
119
+ print(preview)
120
+
121
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
122
+ selected_clinical_df.to_csv(out_clinical_data_file)
123
+
124
+ # Step 3: Gene Data Extraction
125
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
126
+ gene_data = get_genetic_data(matrix_file)
127
+
128
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
129
+ print(gene_data.index[:20])
130
+
131
+ # Step 4: Gene Identifier Review
132
+ # Affymetrix probe set IDs (e.g., 11715100_at, 11715101_s_at) are not human gene symbols.
133
+ requires_gene_mapping = True
134
+ print(f"requires_gene_mapping = {requires_gene_mapping}")
135
+
136
+ # Step 5: Gene Annotation
137
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
138
+ gene_annotation = get_gene_annotation(soft_file)
139
+
140
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
141
+ print("Gene annotation preview:")
142
+ print(preview_df(gene_annotation))
143
+
144
+ # Step 6: Gene Identifier Mapping
145
+ # Map probe IDs to gene symbols and aggregate to gene-level expression
146
+
147
+ # 1-2) Identify appropriate columns and build mapping dataframe
148
+ # Expression data index matches annotation column 'ID'; gene symbols are in 'Gene Symbol'
149
+ mapping_df = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='Gene Symbol')
150
+
151
+ # 3) Apply mapping: distribute multi-gene probe signal and sum to gene level
152
+ probe_data = gene_data # preserve original probe-level data from previous step
153
+ gene_data = apply_gene_mapping(probe_data, mapping_df)
154
+
155
+ # Step 7: Data Normalization and Linking
156
+ import os
157
+
158
+ # 1. Normalize gene symbols and save
159
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
160
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
161
+ normalized_gene_data.to_csv(out_gene_data_file)
162
+
163
+ # Ensure clinical features dataframe is available (fallback to reload if needed)
164
+ if 'selected_clinical_df' not in locals():
165
+ selected_clinical_df = pd.read_csv(out_clinical_data_file, index_col=0)
166
+
167
+ # 2. Link clinical and genetic data
168
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
169
+
170
+ # 3. Missing value handling
171
+ linked_data = handle_missing_values(linked_data, trait)
172
+
173
+ # 4. Bias assessment and removal of biased covariates
174
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
175
+
176
+ # 5. Final validation and save cohort info
177
+ note = ("INFO: Trait inferred from tissue labels (tumour=1, non-tumour adjacent=0); "
178
+ "age and gender unavailable in this series. Platform HG-U219; probe-to-gene mapping and "
179
+ "gene symbol normalization applied.")
180
+ is_usable = validate_and_save_cohort_info(
181
+ True, cohort, json_path, True, True, is_trait_biased, unbiased_linked_data, 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/Liver_Cancer/code/GSE178201.py ADDED
@@ -0,0 +1,196 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Liver_Cancer"
6
+ cohort = "GSE178201"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Liver_Cancer"
10
+ in_cohort_dir = "../DATA/GEO/Liver_Cancer/GSE178201"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z4/preprocess/Liver_Cancer/GSE178201.csv"
14
+ out_gene_data_file = "./output/z4/preprocess/Liver_Cancer/gene_data/GSE178201.csv"
15
+ out_clinical_data_file = "./output/z4/preprocess/Liver_Cancer/clinical_data/GSE178201.csv"
16
+ json_path = "./output/z4/preprocess/Liver_Cancer/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ import os
40
+ import pandas as pd
41
+
42
+ # 1) Gene expression availability
43
+ # L1000 is a gene expression platform (not miRNA or methylation).
44
+ is_gene_available = True
45
+
46
+ # 2) Variable availability and converters
47
+
48
+ # From the sample characteristics, tissue is at key 0 and includes:
49
+ # - 'tissue: HEPG2' (liver cancer cell line)
50
+ # - 'tissue: MCF10A.*' (breast epithelial cell line)
51
+ # We infer the trait "Liver_Cancer" as binary: 1 for HepG2 (liver cancer), 0 otherwise.
52
+ trait_row = 0
53
+
54
+ # Age and Gender are not present
55
+ age_row = None
56
+ gender_row = None
57
+
58
+ def _extract_value(x):
59
+ if pd.isna(x):
60
+ return None
61
+ s = str(x)
62
+ if ":" in s:
63
+ s = s.split(":", 1)[1]
64
+ s = s.strip()
65
+ if s.lower() in {"", "na", "n/a", "none", "unknown", "null"}:
66
+ return None
67
+ return s
68
+
69
+ def convert_trait(x):
70
+ v = _extract_value(x)
71
+ if v is None:
72
+ return None
73
+ lv = v.lower()
74
+ # HepG2 is a hepatocellular carcinoma (liver cancer) cell line
75
+ if "hepg2" in lv:
76
+ return 1
77
+ # MCF10A cell lines are not liver cancer
78
+ if "mcf10a" in lv:
79
+ return 0
80
+ # Fallback heuristics in case of other labels
81
+ if any(k in lv for k in ["liver", "hepatocellular", "hcc"]):
82
+ return 1
83
+ return 0
84
+
85
+ def convert_age(x):
86
+ v = _extract_value(x)
87
+ if v is None:
88
+ return None
89
+ # Try to parse a number from the string
90
+ try:
91
+ # Remove common units if present
92
+ v_clean = "".join(ch for ch in v if (ch.isdigit() or ch == "." or ch == "-"))
93
+ return float(v_clean) if v_clean not in {"", "-"} else None
94
+ except Exception:
95
+ return None
96
+
97
+ def convert_gender(x):
98
+ v = _extract_value(x)
99
+ if v is None:
100
+ return None
101
+ lv = v.lower()
102
+ if lv in {"male", "m"}:
103
+ return 1
104
+ if lv in {"female", "f"}:
105
+ return 0
106
+ return None
107
+
108
+ # 3) Save metadata (initial filtering)
109
+ is_trait_available = trait_row is not None
110
+ _ = validate_and_save_cohort_info(
111
+ is_final=False,
112
+ cohort=cohort,
113
+ info_path=json_path,
114
+ is_gene_available=is_gene_available,
115
+ is_trait_available=is_trait_available
116
+ )
117
+
118
+ # 4) Clinical feature extraction (only if trait_row 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 and save
131
+ preview = preview_df(selected_clinical_df)
132
+ print(preview)
133
+
134
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
135
+ selected_clinical_df.to_csv(out_clinical_data_file)
136
+
137
+ # Step 3: Gene Data Extraction
138
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
139
+ gene_data = get_genetic_data(matrix_file)
140
+
141
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
142
+ print(gene_data.index[:20])
143
+
144
+ # Step 4: Gene Identifier Review
145
+ requires_gene_mapping = True
146
+ print(f"requires_gene_mapping = {requires_gene_mapping}")
147
+
148
+ # Step 5: Gene Annotation
149
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
150
+ gene_annotation = get_gene_annotation(soft_file)
151
+
152
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
153
+ print("Gene annotation preview:")
154
+ print(preview_df(gene_annotation))
155
+
156
+ # Step 6: Gene Identifier Mapping
157
+ # Decide mapping columns based on observation:
158
+ # - gene_data row IDs are numeric strings like '16', '23', etc. These match the 'pr_analyte_num' in annotation.
159
+ # - Gene symbols are in 'pr_gene_symbol'.
160
+ mapping_df = get_gene_mapping(gene_annotation, prob_col='pr_analyte_num', gene_col='pr_gene_symbol')
161
+
162
+ # Normalize 'ID' in mapping to match gene_data index (e.g., convert '16.0' -> '16')
163
+ mapping_df['ID'] = pd.to_numeric(mapping_df['ID'], errors='coerce')
164
+ mapping_df = mapping_df.dropna(subset=['ID'])
165
+ mapping_df['ID'] = mapping_df['ID'].astype(int).astype(str)
166
+
167
+ # Apply mapping to convert probe/analyte-level data to gene-level data
168
+ gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
169
+
170
+ # Step 7: Data Normalization and Linking
171
+ import os
172
+
173
+ # 1. Normalize the obtained gene data and save
174
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
175
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
176
+ normalized_gene_data.to_csv(out_gene_data_file)
177
+
178
+ # 2. Link the clinical and genetic data
179
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
180
+
181
+ # 3. Handle missing values in the linked data
182
+ linked_data = handle_missing_values(linked_data, trait)
183
+
184
+ # 4. Determine whether the trait and some demographic features are severely biased, and remove biased features.
185
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
186
+
187
+ # 5. Conduct quality check and save the cohort information.
188
+ note_msg = "INFO: Trait is constant (all HepG2) in this matrix; dataset marked biased."
189
+ is_usable = validate_and_save_cohort_info(
190
+ True, cohort, json_path, True, True, is_trait_biased, unbiased_linked_data, note=note_msg
191
+ )
192
+
193
+ # 6. If the linked data is usable, save it
194
+ if is_usable:
195
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
196
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Liver_Cancer/code/GSE209875.py ADDED
@@ -0,0 +1,190 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Liver_Cancer"
6
+ cohort = "GSE209875"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Liver_Cancer"
10
+ in_cohort_dir = "../DATA/GEO/Liver_Cancer/GSE209875"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z4/preprocess/Liver_Cancer/GSE209875.csv"
14
+ out_gene_data_file = "./output/z4/preprocess/Liver_Cancer/gene_data/GSE209875.csv"
15
+ out_clinical_data_file = "./output/z4/preprocess/Liver_Cancer/clinical_data/GSE209875.csv"
16
+ json_path = "./output/z4/preprocess/Liver_Cancer/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ import os
21
+ import re
22
+ from tools.preprocess import *
23
+
24
+ # 1) Identify paths to the series matrix file and SOFT file (SOFT optional at this step)
25
+ files = os.listdir(in_cohort_dir)
26
+
27
+ # Prefer canonical GEO naming for series matrix files
28
+ matrix_candidates = [
29
+ f for f in files
30
+ if re.search(r'series_matrix.*\.txt(\.gz)?$', f, re.IGNORECASE) or 'matrix' in f.lower()
31
+ ]
32
+
33
+ if not matrix_candidates:
34
+ print("Files in cohort dir:", files)
35
+ raise FileNotFoundError("Series matrix file not found (e.g., *series_matrix.txt.gz).")
36
+
37
+ matrix_file = os.path.join(in_cohort_dir, matrix_candidates[0])
38
+
39
+ # Try to find a SOFT file; if absent, set to None and proceed
40
+ soft_candidates = [
41
+ f for f in files
42
+ if re.search(r'\.soft(\.gz)?$', f, re.IGNORECASE) or 'family.soft' in f.lower()
43
+ ]
44
+ soft_file = os.path.join(in_cohort_dir, soft_candidates[0]) if soft_candidates else None
45
+
46
+ print("Files in cohort dir:", files)
47
+ print(f"Selected series matrix file: {matrix_file}")
48
+ print(f"Selected SOFT file: {soft_file if soft_file is not None else 'None (not found)'}")
49
+
50
+ # 2) Obtain background information and clinical dataframe from the matrix file by prefix matching
51
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
52
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
53
+
54
+ try:
55
+ if matrix_file.lower().endswith('.gz'):
56
+ background_info, clinical_data = get_background_and_clinical_data(
57
+ matrix_file, background_prefixes, clinical_prefixes
58
+ )
59
+ else:
60
+ # Fallback for plain text files
61
+ with open(matrix_file, 'rt', encoding='utf-8', errors='ignore') as fh:
62
+ matrix_text = fh.read()
63
+ background_info, clinical_data = filter_content_by_prefix(
64
+ matrix_text,
65
+ prefixes_a=background_prefixes,
66
+ prefixes_b=clinical_prefixes,
67
+ unselect=False,
68
+ source_type='string',
69
+ return_df_a=False,
70
+ return_df_b=True
71
+ )
72
+ except Exception as e:
73
+ print(f"Error while reading matrix file: {matrix_file}")
74
+ print(f"Available files: {files}")
75
+ raise
76
+
77
+ # 3) Create a dictionary of unique values for each clinical feature row
78
+ if clinical_data is not None and not clinical_data.empty:
79
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data, max_len=30)
80
+ else:
81
+ sample_characteristics_dict = {}
82
+ print("Warning: clinical_data is empty or None.")
83
+
84
+ # 4) Print background information and the sample characteristics dictionary
85
+ print("Background Information:")
86
+ print(background_info)
87
+ print("Sample Characteristics Dictionary:")
88
+ print(sample_characteristics_dict)
89
+
90
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
91
+ import os
92
+ import pandas as pd
93
+
94
+ # 1) Gene expression data availability
95
+ # The selected platform indicates miRNA-only data in this subseries.
96
+ is_gene_available = False
97
+
98
+ # 2) Variable availability (from provided Sample Characteristics Dictionary)
99
+ trait_row = 0 # 'histology' field
100
+ age_row = 1 # 'age' field
101
+ gender_row = 2 # 'Sex' field
102
+
103
+ # 2) Conversion functions
104
+ def _after_colon(x):
105
+ if x is None:
106
+ return None
107
+ try:
108
+ s = str(x)
109
+ except Exception:
110
+ return None
111
+ if ':' in s:
112
+ return s.split(':', 1)[1].strip()
113
+ return s.strip()
114
+
115
+ def convert_trait(x):
116
+ v = _after_colon(x)
117
+ if v is None:
118
+ return None
119
+ vl = v.lower()
120
+ # Non-tumor and benign considered controls
121
+ if 'non-tumor' in vl or 'non tumor' in vl or 'nontumor' in vl:
122
+ return 0
123
+ if 'benign' in vl:
124
+ return 0
125
+ # Carcinomas considered cases
126
+ if 'hepatocellular carcinoma' in vl or 'cholangiocarcinoma' in vl or 'carcinoma' in vl:
127
+ return 1
128
+ # Heuristic: "tumor part" without benign mentioned implies tumor
129
+ if 'tumor part' in vl:
130
+ return 1
131
+ return None
132
+
133
+ def convert_age(x):
134
+ v = _after_colon(x)
135
+ if v is None or v == '':
136
+ return None
137
+ # Remove any non-numeric trailing characters if present
138
+ try:
139
+ return float(str(v).strip())
140
+ except Exception:
141
+ # Try extracting leading numeric
142
+ import re
143
+ m = re.search(r'[-+]?\d+\.?\d*', str(v))
144
+ if m:
145
+ try:
146
+ return float(m.group(0))
147
+ except Exception:
148
+ return None
149
+ return None
150
+
151
+ def convert_gender(x):
152
+ v = _after_colon(x)
153
+ if v is None:
154
+ return None
155
+ vl = v.strip().lower()
156
+ if vl in ['m', 'male']:
157
+ return 1
158
+ if vl in ['f', 'female']:
159
+ return 0
160
+ return None
161
+
162
+ # 3) Save metadata (initial filtering)
163
+ is_trait_available = trait_row is not None
164
+ _ = validate_and_save_cohort_info(
165
+ is_final=False,
166
+ cohort=cohort,
167
+ info_path=json_path,
168
+ is_gene_available=is_gene_available,
169
+ is_trait_available=is_trait_available
170
+ )
171
+
172
+ # 4) Clinical feature extraction (only if trait_row is available)
173
+ if trait_row is not None:
174
+ selected_clinical_df = geo_select_clinical_features(
175
+ clinical_df=clinical_data,
176
+ trait=trait,
177
+ trait_row=trait_row,
178
+ convert_trait=convert_trait,
179
+ age_row=age_row,
180
+ convert_age=convert_age,
181
+ gender_row=gender_row,
182
+ convert_gender=convert_gender
183
+ )
184
+ # Preview
185
+ preview = preview_df(selected_clinical_df)
186
+ print("Preview of selected clinical features:", preview)
187
+
188
+ # Save to CSV
189
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
190
+ selected_clinical_df.to_csv(out_clinical_data_file)
output/preprocess/Liver_Cancer/code/GSE212047.py ADDED
@@ -0,0 +1,210 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Liver_Cancer"
6
+ cohort = "GSE212047"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Liver_Cancer"
10
+ in_cohort_dir = "../DATA/GEO/Liver_Cancer/GSE212047"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z4/preprocess/Liver_Cancer/GSE212047.csv"
14
+ out_gene_data_file = "./output/z4/preprocess/Liver_Cancer/gene_data/GSE212047.csv"
15
+ out_clinical_data_file = "./output/z4/preprocess/Liver_Cancer/clinical_data/GSE212047.csv"
16
+ json_path = "./output/z4/preprocess/Liver_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
+ # Determine data availability based on provided background and sample characteristics.
40
+ # Assumptions:
41
+ # - This cohort appears to be a mouse HSC dataset (non-human), with no explicit human trait (Liver_Cancer), age, or gender fields.
42
+ # - It likely contains gene expression (bulk RNA-seq or microarray), not miRNA-only or methylation-only.
43
+
44
+ is_gene_available = True # GEO series description and sample characteristics suggest RNA-seq/microarray data.
45
+ trait_row = None # No human Liver_Cancer case/control status in sample characteristics.
46
+ age_row = None # No age information.
47
+ gender_row = None # No gender information.
48
+
49
+ # Conversion functions (robust to typical GEO "key: value" formatting).
50
+ def _after_colon(val):
51
+ if val is None:
52
+ return None
53
+ s = str(val)
54
+ parts = s.split(":", 1)
55
+ return parts[1].strip() if len(parts) == 2 else s.strip()
56
+
57
+ def convert_trait(x):
58
+ v = _after_colon(x)
59
+ if v is None or v == "":
60
+ return None
61
+ # Heuristic mapping for liver cancer status if ever encountered:
62
+ vl = v.lower()
63
+ # Positive indicators
64
+ pos_terms = ["hcc", "hepatocellular carcinoma", "liver cancer", "tumor", "tumour", "cancer", "neoplasm", "malignant"]
65
+ # Negative indicators
66
+ neg_terms = ["normal", "non-tumor", "non tumour", "noncancer", "control", "nt", "healthy", "adjacent non-tumor"]
67
+ if any(t in vl for t in pos_terms):
68
+ return 1
69
+ if any(t in vl for t in neg_terms):
70
+ return 0
71
+ return None
72
+
73
+ def convert_age(x):
74
+ v = _after_colon(x)
75
+ if v is None or v == "":
76
+ return None
77
+ vl = v.lower().replace("years", "").replace("year", "").replace("yrs", "").replace("yr", "").replace("old", "").strip()
78
+ # Try to parse as float
79
+ try:
80
+ return float(vl)
81
+ except:
82
+ return None
83
+
84
+ def convert_gender(x):
85
+ v = _after_colon(x)
86
+ if v is None or v == "":
87
+ return None
88
+ vl = v.lower()
89
+ if vl in ["male", "m", "man"]:
90
+ return 1
91
+ if vl in ["female", "f", "woman"]:
92
+ return 0
93
+ return None
94
+
95
+ # Initial filtering metadata save
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
+ # Clinical feature extraction only if trait data is available (not the case here)
106
+ if trait_row is not None:
107
+ selected = 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_df(selected, n=5)
118
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
119
+ selected.to_csv(out_clinical_data_file, index=True)
120
+
121
+ # Step 3: Gene Data Extraction
122
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
123
+ gene_data = get_genetic_data(matrix_file)
124
+
125
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
126
+ print(gene_data.index[:20])
127
+
128
+ # Step 4: Gene Identifier Review
129
+ # The observed identifiers are numeric probe-like IDs (e.g., '10338001'), not human gene symbols.
130
+ requires_gene_mapping = True
131
+ print(f"requires_gene_mapping = {requires_gene_mapping}")
132
+
133
+ # Step 5: Gene Annotation
134
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
135
+ gene_annotation = get_gene_annotation(soft_file)
136
+
137
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
138
+ print("Gene annotation preview:")
139
+ print(preview_df(gene_annotation))
140
+
141
+ # Step 6: Gene Identifier Mapping
142
+ # Decide identifier and gene symbol columns based on annotation preview:
143
+ # - Probe/feature identifiers: 'ID' (matches numeric IDs in expression data)
144
+ # - Gene symbols/info: 'gene_assignment' (contains gene symbols within mixed annotations)
145
+
146
+ # 1-2. Build mapping dataframe
147
+ mapping_df = get_gene_mapping(annotation=gene_annotation, prob_col='ID', gene_col='gene_assignment')
148
+
149
+ # Improve symbol extraction for mouse-style mixed-case symbols by uppercasing before regex extraction
150
+ mapping_df['Gene'] = mapping_df['Gene'].astype(str).str.upper()
151
+
152
+ # 3. Apply mapping to convert probe-level data to gene-level data
153
+ gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
154
+
155
+ # Step 7: Data Normalization and Linking
156
+ import os
157
+
158
+ # 1. Normalize gene symbols and save gene expression data
159
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
160
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
161
+ normalized_gene_data.to_csv(out_gene_data_file)
162
+
163
+ # Determine trait availability from earlier step context
164
+ is_trait_available = (trait_row is not None)
165
+
166
+ # If trait is unavailable, record metadata and skip linking/QC
167
+ if not is_trait_available:
168
+ _ = validate_and_save_cohort_info(
169
+ is_final=False,
170
+ cohort=cohort,
171
+ info_path=json_path,
172
+ is_gene_available=True,
173
+ is_trait_available=False
174
+ )
175
+ else:
176
+ # 2. Link clinical and genetic data
177
+ selected_clinical_data = geo_select_clinical_features(
178
+ clinical_df=clinical_data,
179
+ trait=trait,
180
+ trait_row=trait_row,
181
+ convert_trait=convert_trait,
182
+ age_row=age_row,
183
+ convert_age=convert_age,
184
+ gender_row=gender_row,
185
+ convert_gender=convert_gender
186
+ )
187
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_data, normalized_gene_data)
188
+
189
+ # 3. Handle missing values
190
+ linked_data = handle_missing_values(linked_data, trait)
191
+
192
+ # 4. Bias evaluation and removal of biased covariates
193
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
194
+
195
+ # 5. Final validation and save cohort info
196
+ is_usable = validate_and_save_cohort_info(
197
+ is_final=True,
198
+ cohort=cohort,
199
+ info_path=json_path,
200
+ is_gene_available=True,
201
+ is_trait_available=True,
202
+ is_biased=is_trait_biased,
203
+ df=unbiased_linked_data,
204
+ note="INFO: Proceeded with final validation since clinical trait was available."
205
+ )
206
+
207
+ # 6. Save linked data if usable
208
+ if is_usable:
209
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
210
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Liver_Cancer/code/GSE218438.py ADDED
@@ -0,0 +1,288 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Liver_Cancer"
6
+ cohort = "GSE218438"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Liver_Cancer"
10
+ in_cohort_dir = "../DATA/GEO/Liver_Cancer/GSE218438"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z4/preprocess/Liver_Cancer/GSE218438.csv"
14
+ out_gene_data_file = "./output/z4/preprocess/Liver_Cancer/gene_data/GSE218438.csv"
15
+ out_clinical_data_file = "./output/z4/preprocess/Liver_Cancer/clinical_data/GSE218438.csv"
16
+ json_path = "./output/z4/preprocess/Liver_Cancer/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ # Step 1: Determine gene expression availability
40
+ is_gene_available = True # L1000 transcriptomics indicates gene expression data
41
+
42
+ # Step 2: Determine availability of trait, age, and gender, and define converters
43
+ trait_row = 0 # 'cell type' row
44
+ age_row = None
45
+ gender_row = None
46
+
47
+ def _extract_value(x):
48
+ if x is None:
49
+ return None
50
+ try:
51
+ s = str(x)
52
+ except Exception:
53
+ return None
54
+ parts = s.split(":", 1)
55
+ v = parts[1] if len(parts) == 2 else parts[0]
56
+ v = v.strip()
57
+ return v if v != "" else None
58
+
59
+ def convert_trait(x):
60
+ v = _extract_value(x)
61
+ if v is None:
62
+ return None
63
+ v_low = v.lower()
64
+ # Positive if hepatocellular carcinoma or clearly liver-related
65
+ if ("hepatocellular" in v_low) or ("hepat" in v_low) or ("liver" in v_low):
66
+ return 1
67
+ # Otherwise, considered non-liver cancer related
68
+ return 0
69
+
70
+ def convert_age(x):
71
+ # Not available in this dataset
72
+ return None
73
+
74
+ def convert_gender(x):
75
+ # Not available in this dataset
76
+ return None
77
+
78
+ # Step 3: Initial filtering and save metadata
79
+ is_trait_available = trait_row is not None
80
+ _ = validate_and_save_cohort_info(
81
+ is_final=False,
82
+ cohort=cohort,
83
+ info_path=json_path,
84
+ is_gene_available=is_gene_available,
85
+ is_trait_available=is_trait_available
86
+ )
87
+
88
+ # Step 4: Clinical feature extraction (only if trait_row is available)
89
+ if trait_row is not None:
90
+ selected_clinical_df = geo_select_clinical_features(
91
+ clinical_df=clinical_data,
92
+ trait=trait,
93
+ trait_row=trait_row,
94
+ convert_trait=convert_trait,
95
+ age_row=age_row,
96
+ convert_age=convert_age,
97
+ gender_row=gender_row,
98
+ convert_gender=convert_gender
99
+ )
100
+ preview = preview_df(selected_clinical_df, n=5)
101
+ print("Selected clinical features preview:", preview)
102
+
103
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
104
+ selected_clinical_df.to_csv(out_clinical_data_file)
105
+ else:
106
+ print("No clinical trait data available; skipping clinical feature extraction.")
107
+
108
+ # Step 3: Gene Data Extraction
109
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
110
+ gene_data = get_genetic_data(matrix_file)
111
+
112
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
113
+ print(gene_data.index[:20])
114
+
115
+ # Step 4: Gene Identifier Review
116
+ # Affymetrix probe set IDs (e.g., 1007_s_at) are not human gene symbols; mapping to gene symbols is required.
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
+ # Robust probe->gene symbol mapping with safeguards
130
+
131
+ # 1) Identify the probe ID column by overlap with expression IDs
132
+ id_overlap_counts = {}
133
+ for col in gene_annotation.columns:
134
+ try:
135
+ overlap = gene_annotation[col].astype(str).str.strip().isin(gene_data.index).sum()
136
+ id_overlap_counts[col] = int(overlap)
137
+ except Exception:
138
+ continue
139
+
140
+ if not id_overlap_counts or max(id_overlap_counts.values()) == 0:
141
+ possible_id_cols = [c for c in ['ID', 'SPOT_ID'] if c in gene_annotation.columns]
142
+ probe_id_col = possible_id_cols[0] if possible_id_cols else None
143
+ else:
144
+ probe_id_col = max(id_overlap_counts, key=id_overlap_counts.get)
145
+
146
+ # 2) Identify a likely gene symbol column with stricter rules
147
+ symbol_priority = [
148
+ 'Gene Symbol', 'GENE_SYMBOL', 'GeneSymbol', 'Symbol', 'SYMBOL', 'GENE_SYMBOLS',
149
+ 'gene_assignment', 'Gene Assignment', 'GENE_ASSIGNMENT', 'Associated Gene Name',
150
+ 'ENTREZ_GENE_ID', 'ENTREZ_GENE', 'ORF', 'ORF_NAME', 'Gene Title', 'GENE_TITLE', 'Gene'
151
+ ]
152
+
153
+ lower_to_original = {c.lower(): c for c in gene_annotation.columns}
154
+ gene_symbol_col = None
155
+ for name in symbol_priority:
156
+ if name.lower() in lower_to_original:
157
+ gene_symbol_col = lower_to_original[name.lower()]
158
+ break
159
+
160
+ # If no priority column found, do content-based detection restricted to plausible columns
161
+ if gene_symbol_col is None:
162
+ exclude_cols = set()
163
+ if probe_id_col is not None:
164
+ exclude_cols.add(probe_id_col)
165
+ # Explicitly exclude known non-symbol columns
166
+ for c in ['FLAG', 'SEQUENCE', 'SPOT_ID']:
167
+ if c in gene_annotation.columns:
168
+ exclude_cols.add(c)
169
+
170
+ # Restrict to columns whose names suggest gene info
171
+ def is_plausible_symbol_col(colname: str) -> bool:
172
+ cl = colname.lower()
173
+ keys = ['gene', 'symbol', 'assign', 'title', 'entrez', 'orf', 'locus']
174
+ return any(k in cl for k in keys)
175
+
176
+ candidates = [c for c in gene_annotation.columns if c not in exclude_cols and is_plausible_symbol_col(c)]
177
+
178
+ best_col = None
179
+ best_hits = -1
180
+ for col in candidates:
181
+ s = gene_annotation[col].dropna().astype(str)
182
+ hits = s.map(lambda x: len(extract_human_gene_symbols(x)) > 0).sum()
183
+ if hits > best_hits:
184
+ best_hits = int(hits)
185
+ best_col = col
186
+ gene_symbol_col = best_col if best_hits > 0 else None
187
+
188
+ print(f"Selected probe_id_col: {probe_id_col}")
189
+ print(f"Selected gene_symbol_col: {gene_symbol_col}")
190
+
191
+ mapped_gene_data = None
192
+ mapping_valid = False
193
+
194
+ if (probe_id_col is not None) and (gene_symbol_col is not None):
195
+ # Pre-check: ensure mapping yields a reasonable number of unique symbols
196
+ try:
197
+ tmp_map = gene_annotation[[probe_id_col, gene_symbol_col]].dropna()
198
+ token_lists = tmp_map[gene_symbol_col].astype(str).map(extract_human_gene_symbols)
199
+ unique_genes = set()
200
+ for lst in token_lists:
201
+ unique_genes.update(lst)
202
+ n_unique_genes = len(unique_genes)
203
+ print(f"Pre-check: unique extracted gene symbols = {n_unique_genes}")
204
+
205
+ mapping_valid = n_unique_genes >= 100 # sanity threshold
206
+ except Exception:
207
+ mapping_valid = False
208
+
209
+ if mapping_valid:
210
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=probe_id_col, gene_col=gene_symbol_col)
211
+ try:
212
+ mapped_gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
213
+ except Exception:
214
+ mapped_gene_data = None
215
+
216
+ # Post-check: ensure resulting gene-level data is reasonable
217
+ if isinstance(mapped_gene_data, pd.DataFrame):
218
+ n_rows = mapped_gene_data.shape[0]
219
+ if n_rows < 100:
220
+ print(f"Post-check failed: mapped gene data has too few genes ({n_rows}). Falling back to probe-level.")
221
+ mapped_gene_data = None
222
+
223
+ # Apply mapping if successful
224
+ if isinstance(mapped_gene_data, pd.DataFrame) and mapped_gene_data.shape[0] > 0:
225
+ gene_data = mapped_gene_data
226
+ else:
227
+ # Mapping not applied; keeping probe-level data
228
+ pass
229
+
230
+ # Step 7: Data Normalization and Linking
231
+ import os
232
+ import pandas as pd
233
+
234
+ # 1. Normalize gene symbols; if normalization fails (e.g., probe IDs), fall back to probe-level data
235
+ normalization_note = "INFO: Gene symbols normalized using NCBI synonym mapping."
236
+ try:
237
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data.copy())
238
+ except Exception as e:
239
+ normalized_gene_data = pd.DataFrame()
240
+
241
+ # Heuristic: if normalization produced empty data, likely probe-level IDs; fall back to original
242
+ if not isinstance(normalized_gene_data, pd.DataFrame) or normalized_gene_data.shape[0] == 0:
243
+ final_gene_data = gene_data.copy()
244
+ normalization_note = ("WARNING: Probe-to-gene symbol mapping was unavailable; normalization produced empty gene data. "
245
+ "Proceeding with probe-level Affymetrix IDs as features.")
246
+ else:
247
+ final_gene_data = normalized_gene_data
248
+
249
+ # Ensure output directory exists and save gene data
250
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
251
+ final_gene_data.to_csv(out_gene_data_file)
252
+
253
+ # 2. Link the clinical and genetic data
254
+ # Use the variable from Step 2 if available; otherwise reload from disk
255
+ if 'selected_clinical_df' not in globals():
256
+ if os.path.exists(out_clinical_data_file):
257
+ selected_clinical_df = pd.read_csv(out_clinical_data_file, index_col=0)
258
+ else:
259
+ raise RuntimeError("Clinical data is not available in memory or on disk.")
260
+
261
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, final_gene_data)
262
+
263
+ # 3. Handle missing values in the linked data
264
+ linked_data = handle_missing_values(linked_data, trait)
265
+
266
+ # 4. Determine whether the trait and demographic features are severely biased, and remove biased features
267
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
268
+
269
+ # 5. Conduct final quality validation and save cohort info
270
+ has_gene = isinstance(final_gene_data, pd.DataFrame) and final_gene_data.shape[0] > 0 and final_gene_data.shape[1] > 0
271
+ has_trait = isinstance(selected_clinical_df, pd.DataFrame) and (trait in selected_clinical_df.index) and selected_clinical_df.shape[1] > 0
272
+
273
+ note = f"{normalization_note} INFO: Gene feature count={final_gene_data.shape[0]}, sample count={final_gene_data.shape[1]}."
274
+ is_usable = validate_and_save_cohort_info(
275
+ is_final=True,
276
+ cohort=cohort,
277
+ info_path=json_path,
278
+ is_gene_available=has_gene,
279
+ is_trait_available=has_trait,
280
+ is_biased=is_trait_biased,
281
+ df=unbiased_linked_data,
282
+ note=note
283
+ )
284
+
285
+ # 6. Save the linked data only if usable
286
+ if is_usable:
287
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
288
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Liver_Cancer/code/GSE228782.py ADDED
@@ -0,0 +1,210 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Liver_Cancer"
6
+ cohort = "GSE228782"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Liver_Cancer"
10
+ in_cohort_dir = "../DATA/GEO/Liver_Cancer/GSE228782"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z4/preprocess/Liver_Cancer/GSE228782.csv"
14
+ out_gene_data_file = "./output/z4/preprocess/Liver_Cancer/gene_data/GSE228782.csv"
15
+ out_clinical_data_file = "./output/z4/preprocess/Liver_Cancer/clinical_data/GSE228782.csv"
16
+ json_path = "./output/z4/preprocess/Liver_Cancer/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ import os
40
+ import pandas as pd
41
+
42
+ # 1) Gene expression availability
43
+ is_gene_available = True # Affymetrix transcriptome profiles indicate gene expression data
44
+
45
+ # 2) Variable availability
46
+ trait_row = 2 # 'disease' field
47
+ age_row = None # Not available
48
+ gender_row = None # Not available
49
+
50
+ is_trait_available = trait_row is not None
51
+
52
+ # 2.2) Conversion functions
53
+ def _after_colon(val):
54
+ if val is None or (isinstance(val, float) and pd.isna(val)):
55
+ return None
56
+ s = str(val)
57
+ if ':' in s:
58
+ s = s.split(':', 1)[1]
59
+ s = s.strip()
60
+ if s.lower() in {'', 'na', 'n/a', 'null', 'none', 'nan'}:
61
+ return None
62
+ return s
63
+
64
+ def convert_trait(v):
65
+ """
66
+ Define Liver_Cancer as primary liver cancer: HCC or CCC -> 1
67
+ CRC metastasis and 'other' -> 0
68
+ """
69
+ x = _after_colon(v)
70
+ if x is None:
71
+ return None
72
+ xl = x.lower()
73
+ # Primary liver cancers
74
+ if xl in {'hcc', 'ccc'} or 'cholangiocarcinoma' in xl:
75
+ return 1
76
+ # Non-primary liver cancers or other conditions
77
+ if 'crc' in xl or 'met' in xl or 'metast' in xl:
78
+ return 0
79
+ if xl == 'other':
80
+ return 0
81
+ # Fallback heuristic
82
+ if 'hepatocellular' in xl:
83
+ return 1
84
+ return None
85
+
86
+ def convert_age(v):
87
+ x = _after_colon(v)
88
+ if x is None:
89
+ return None
90
+ try:
91
+ num = ''.join(ch for ch in x if (ch.isdigit() or ch in {'.', '-', '+'}))
92
+ if num in {'', '.', '-', '+', '+.', '-.'}:
93
+ return None
94
+ return float(num)
95
+ except Exception:
96
+ return None
97
+
98
+ def convert_gender(v):
99
+ x = _after_colon(v)
100
+ if x is None:
101
+ return None
102
+ xl = x.lower()
103
+ if xl in {'female', 'f', 'woman', 'women'}:
104
+ return 0
105
+ if xl in {'male', 'm', 'man', 'men'}:
106
+ return 1
107
+ return None
108
+
109
+ # 3) Save metadata - initial filtering
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 is_trait_available:
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
+ clinical_preview = preview_df(selected_clinical_df)
131
+ print(clinical_preview)
132
+ # Save clinical data
133
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
134
+ selected_clinical_df.to_csv(out_clinical_data_file, index=False)
135
+
136
+ # Step 3: Gene Data Extraction
137
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
138
+ gene_data = get_genetic_data(matrix_file)
139
+
140
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
141
+ print(gene_data.index[:20])
142
+
143
+ # Step 4: Gene Identifier Review
144
+ requires_gene_mapping = True
145
+ print(f"requires_gene_mapping = {requires_gene_mapping}")
146
+
147
+ # Step 5: Gene Annotation
148
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
149
+ gene_annotation = get_gene_annotation(soft_file)
150
+
151
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
152
+ print("Gene annotation preview:")
153
+ print(preview_df(gene_annotation))
154
+
155
+ # Step 6: Gene Identifier Mapping
156
+ # Decide mapping columns based on previous previews:
157
+ # Probe/ID column: 'ID'
158
+ # Gene symbol column: 'Gene Symbol'
159
+
160
+ # 1-2) Build mapping dataframe
161
+ mapping_df = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='Gene Symbol')
162
+
163
+ # 3) Apply mapping to convert probe-level to gene-level expression
164
+ gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
165
+
166
+ # Step 7: Data Normalization and Linking
167
+ import os
168
+ import pandas as pd
169
+
170
+ # 1) Normalize gene symbols and save gene expression data
171
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
172
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
173
+ normalized_gene_data.to_csv(out_gene_data_file)
174
+
175
+ # 2) Link clinical and genetic data
176
+ # Ensure clinical data is available in memory; if not, reload from CSV saved in Step 2
177
+ try:
178
+ selected_clinical_df
179
+ except NameError:
180
+ tmp = pd.read_csv(out_clinical_data_file)
181
+ # The saved clinical CSV had index=False; restore the single row index as the trait name
182
+ tmp.index = [trait]
183
+ selected_clinical_df = tmp
184
+
185
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
186
+
187
+ # 3) Handle missing values
188
+ linked_data = handle_missing_values(linked_data, trait)
189
+
190
+ # 4) Assess bias and remove biased demographic features if any
191
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
192
+
193
+ # 5) Final validation and save cohort info
194
+ note = ("INFO: Gene mapping performed from Affymetrix HG-U219 probes to symbols; "
195
+ "clinical trait derived from 'disease' field; no age/gender available.")
196
+ is_usable = validate_and_save_cohort_info(
197
+ is_final=True,
198
+ cohort=cohort,
199
+ info_path=json_path,
200
+ is_gene_available=True,
201
+ is_trait_available=True,
202
+ is_biased=is_trait_biased,
203
+ df=unbiased_linked_data,
204
+ note=note
205
+ )
206
+
207
+ # 6) Save linked data if usable
208
+ if is_usable:
209
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
210
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Liver_Cancer/code/GSE228783.py ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Liver_Cancer"
6
+ cohort = "GSE228783"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Liver_Cancer"
10
+ in_cohort_dir = "../DATA/GEO/Liver_Cancer/GSE228783"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z4/preprocess/Liver_Cancer/GSE228783.csv"
14
+ out_gene_data_file = "./output/z4/preprocess/Liver_Cancer/gene_data/GSE228783.csv"
15
+ out_clinical_data_file = "./output/z4/preprocess/Liver_Cancer/clinical_data/GSE228783.csv"
16
+ json_path = "./output/z4/preprocess/Liver_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
+
41
+ # 1) Determine gene expression availability
42
+ is_gene_available = True # Transcriptome study; likely gene expression microarray/RNA-seq
43
+
44
+ # 2) Variable availability and converters
45
+ trait_row = 2 # 'disease' field with multiple categories
46
+ age_row = None
47
+ gender_row = None
48
+
49
+ def _after_colon(x):
50
+ if x is None:
51
+ return None
52
+ if isinstance(x, str):
53
+ parts = x.split(":", 1)
54
+ val = parts[1] if len(parts) > 1 else parts[0]
55
+ return val.strip()
56
+ return x
57
+
58
+ def convert_trait(x):
59
+ v = _after_colon(x)
60
+ if v is None:
61
+ return None
62
+ v_low = v.lower()
63
+ # Binary: primary liver cancer (HCC, CCC) = 1; CRC liver metastasis = 0; other/unknown = None
64
+ if v_low in {"hcc", "hepatocellular carcinoma", "ccc", "cholangiocarcinoma"}:
65
+ return 1
66
+ if v_low in {"crc met", "colorectal cancer metastasis", "crc metastasis"}:
67
+ return 0
68
+ if v_low in {"other", "na", "n/a", "unknown"}:
69
+ return None
70
+ return None
71
+
72
+ def convert_age(x):
73
+ # No age information available in this dataset
74
+ return None
75
+
76
+ def convert_gender(x):
77
+ # No gender information available in this dataset
78
+ return None
79
+
80
+ # 3) Save initial metadata
81
+ is_trait_available = trait_row is not None
82
+ _ = validate_and_save_cohort_info(
83
+ is_final=False,
84
+ cohort=cohort,
85
+ info_path=json_path,
86
+ is_gene_available=is_gene_available,
87
+ is_trait_available=is_trait_available
88
+ )
89
+
90
+ # 4) Clinical feature extraction (only if trait is available)
91
+ if trait_row is not None:
92
+ selected_clinical_df = geo_select_clinical_features(
93
+ clinical_df=clinical_data,
94
+ trait=trait,
95
+ trait_row=trait_row,
96
+ convert_trait=convert_trait,
97
+ age_row=age_row,
98
+ convert_age=convert_age,
99
+ gender_row=gender_row,
100
+ convert_gender=convert_gender
101
+ )
102
+ print(preview_df(selected_clinical_df, n=5))
103
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
104
+ selected_clinical_df.to_csv(out_clinical_data_file)
105
+
106
+ # Step 3: Gene Data Extraction
107
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
108
+ gene_data = get_genetic_data(matrix_file)
109
+
110
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
111
+ print(gene_data.index[:20])
112
+
113
+ # Step 4: Gene Identifier Review
114
+ requires_gene_mapping = True
115
+ print(f"requires_gene_mapping = {requires_gene_mapping}")
116
+
117
+ # Step 5: Gene Annotation
118
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
119
+ gene_annotation = get_gene_annotation(soft_file)
120
+
121
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
122
+ print("Gene annotation preview:")
123
+ print(preview_df(gene_annotation))
124
+
125
+ # Step 6: Gene Identifier Mapping
126
+ # Decide the appropriate columns for probe IDs and gene symbols based on the annotation preview
127
+ probe_col = 'ID'
128
+ gene_symbol_col = 'Gene Symbol'
129
+
130
+ # 2) Build mapping dataframe
131
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=probe_col, gene_col=gene_symbol_col)
132
+
133
+ # 3) Apply mapping to convert probe-level data to gene-level expression
134
+ gene_data = apply_gene_mapping(gene_data, mapping_df)
135
+
136
+ # Step 7: Data Normalization and Linking
137
+ import os
138
+
139
+ # 1. Normalize gene symbols and save gene-level data
140
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
141
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
142
+ normalized_gene_data.to_csv(out_gene_data_file)
143
+
144
+ # 2. Link clinical and genetic data
145
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
146
+
147
+ # 3. Handle missing values
148
+ linked_data = handle_missing_values(linked_data, trait)
149
+
150
+ # 4. Assess bias and remove biased demographic features
151
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
152
+
153
+ # 5. Final validation and save cohort info
154
+ is_gene_available = True
155
+ is_trait_available = True
156
+ note = "INFO: Affymetrix HG-U219 probes mapped to symbols via platform annotation; no age/gender fields provided."
157
+ is_usable = validate_and_save_cohort_info(
158
+ is_final=True,
159
+ cohort=cohort,
160
+ info_path=json_path,
161
+ is_gene_available=is_gene_available,
162
+ is_trait_available=is_trait_available,
163
+ is_biased=is_trait_biased,
164
+ df=unbiased_linked_data,
165
+ note=note
166
+ )
167
+
168
+ # 6. Save linked data if usable
169
+ if is_usable:
170
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
171
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Liver_Cancer/code/GSE45032.py ADDED
@@ -0,0 +1,185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Liver_Cancer"
6
+ cohort = "GSE45032"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Liver_Cancer"
10
+ in_cohort_dir = "../DATA/GEO/Liver_Cancer/GSE45032"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z4/preprocess/Liver_Cancer/GSE45032.csv"
14
+ out_gene_data_file = "./output/z4/preprocess/Liver_Cancer/gene_data/GSE45032.csv"
15
+ out_clinical_data_file = "./output/z4/preprocess/Liver_Cancer/clinical_data/GSE45032.csv"
16
+ json_path = "./output/z4/preprocess/Liver_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 # Microarray mRNA expression per background info
41
+
42
+ # Step 2: Variable Availability and Conversion Functions
43
+ # Identified keys from Sample Characteristics Dictionary:
44
+ # 0: 'cell type: hepatocallular carcinoma' vs 'cell type: chronic hepatitis type C' -> trait
45
+ # 2: 'gender: male/female' -> gender
46
+ # 3: 'age(yrs): <number>' -> age
47
+ trait_row = 0
48
+ age_row = 3
49
+ gender_row = 2
50
+
51
+ def _extract_value_after_colon(x: str) -> str:
52
+ if x is None:
53
+ return ""
54
+ parts = str(x).split(":", 1)
55
+ val = parts[1] if len(parts) > 1 else parts[0]
56
+ return val.strip()
57
+
58
+ def convert_trait(x):
59
+ # Map Liver_Cancer status: HCC -> 1, CHC -> 0
60
+ val = _extract_value_after_colon(x).lower()
61
+ # Normalize common typos and abbreviations
62
+ val_norm = val.replace("-", " ").replace("_", " ").strip()
63
+ # Positive case: hepatocellular carcinoma (HCC)
64
+ if "hcc" in val_norm:
65
+ return 1
66
+ if ("hepatoc" in val_norm and "carcinoma" in val_norm) or "hepatocellular carcinoma" in val_norm:
67
+ return 1
68
+ # Negative case: chronic hepatitis C (CHC)
69
+ if "chc" in val_norm:
70
+ return 0
71
+ if "chronic hepatitis" in val_norm or "hepatitis" in val_norm:
72
+ return 0
73
+ # If it's explicitly "normal" or similar (not expected here), treat as control
74
+ if "normal" in val_norm or "control" in val_norm:
75
+ return 0
76
+ return None
77
+
78
+ def convert_age(x):
79
+ import re
80
+ val = _extract_value_after_colon(x).lower()
81
+ # Extract first integer number as age
82
+ m = re.search(r"\d+", val)
83
+ if m:
84
+ return float(m.group(0))
85
+ return None
86
+
87
+ def convert_gender(x):
88
+ val = _extract_value_after_colon(x).lower()
89
+ if "male" in val:
90
+ return 1
91
+ if "female" in val:
92
+ return 0
93
+ return None
94
+
95
+ # Determine trait availability based on trait_row presence
96
+ is_trait_available = trait_row is not None
97
+
98
+ # Step 3: Save metadata (initial filtering)
99
+ _ = validate_and_save_cohort_info(
100
+ is_final=False,
101
+ cohort=cohort,
102
+ info_path=json_path,
103
+ is_gene_available=is_gene_available,
104
+ is_trait_available=is_trait_available
105
+ )
106
+
107
+ # Step 4: Clinical Feature Extraction (since trait_row is available)
108
+ selected_clinical_df = geo_select_clinical_features(
109
+ clinical_df=clinical_data,
110
+ trait=trait,
111
+ trait_row=trait_row,
112
+ convert_trait=convert_trait,
113
+ age_row=age_row,
114
+ convert_age=convert_age,
115
+ gender_row=gender_row,
116
+ convert_gender=convert_gender
117
+ )
118
+
119
+ # Preview and save
120
+ clinical_preview = preview_df(selected_clinical_df)
121
+ selected_clinical_df.to_csv(out_clinical_data_file, index=True)
122
+
123
+ # Step 3: Gene Data Extraction
124
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
125
+ gene_data = get_genetic_data(matrix_file)
126
+
127
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
128
+ print(gene_data.index[:20])
129
+
130
+ # Step 4: Gene Identifier Review
131
+ print("requires_gene_mapping = True")
132
+
133
+ # Step 5: Gene Annotation
134
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
135
+ gene_annotation = get_gene_annotation(soft_file)
136
+
137
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
138
+ print("Gene annotation preview:")
139
+ print(preview_df(gene_annotation))
140
+
141
+ # Step 6: Gene Identifier Mapping
142
+ # Determine the appropriate columns for mapping based on earlier previews:
143
+ # - Gene expression data uses numeric 'ID' as identifiers.
144
+ # - Gene symbols are stored in the 'GeneName' column of the annotation.
145
+
146
+ # 1-2. Build mapping dataframe from annotation
147
+ mapping_df = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='GeneName')
148
+
149
+ # 3. Apply mapping to convert probe-level data to gene-level expression
150
+ gene_data = apply_gene_mapping(gene_data, mapping_df)
151
+
152
+ # Step 7: Data Normalization and Linking
153
+ # 1. Normalize gene symbols and save
154
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
155
+ normalized_gene_data.to_csv(out_gene_data_file)
156
+
157
+ # 2. Link clinical and genetic data
158
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
159
+
160
+ # 3. Handle missing values
161
+ linked_data = handle_missing_values(linked_data, trait)
162
+
163
+ # 4. Assess bias and remove biased demographic features
164
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
165
+
166
+ # 5. Final validation and save cohort info
167
+ note = ("INFO: Probe->gene mapping used annotation columns ID->GeneName; "
168
+ "split multi-gene probe signal equally and summed per gene; "
169
+ "normalized symbols using NCBI synonym map; "
170
+ "dropped genes with >20% missing and samples with >5% missing genes; "
171
+ "imputed Gender with mode and others with mean.")
172
+ is_usable = validate_and_save_cohort_info(
173
+ True,
174
+ cohort,
175
+ json_path,
176
+ is_gene_available,
177
+ is_trait_available,
178
+ is_trait_biased,
179
+ unbiased_linked_data,
180
+ note=note
181
+ )
182
+
183
+ # 6. Save linked data if usable
184
+ if is_usable:
185
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Liver_Cancer/code/GSE66843.py ADDED
@@ -0,0 +1,229 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Liver_Cancer"
6
+ cohort = "GSE66843"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Liver_Cancer"
10
+ in_cohort_dir = "../DATA/GEO/Liver_Cancer/GSE66843"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z4/preprocess/Liver_Cancer/GSE66843.csv"
14
+ out_gene_data_file = "./output/z4/preprocess/Liver_Cancer/gene_data/GSE66843.csv"
15
+ out_clinical_data_file = "./output/z4/preprocess/Liver_Cancer/clinical_data/GSE66843.csv"
16
+ json_path = "./output/z4/preprocess/Liver_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 # Based on background info, this series likely contains mRNA gene expression (not pure miRNA/methylation)
43
+
44
+ # 2. Variable Availability and Data Type Conversion
45
+
46
+ # 2.1 Data Availability
47
+ # Sample Characteristics Dictionary indicates:
48
+ # 0: time post infection, 1: infection status, 2: cell line (Huh7.5.1)
49
+ # None of these provide human-level Liver_Cancer trait, age, or gender info; also constant cell line metadata wouldn't be useful.
50
+ trait_row = None
51
+ age_row = None
52
+ gender_row = None
53
+
54
+ # 2.2 Data Type Conversion
55
+
56
+ def _after_colon(x):
57
+ if x is None:
58
+ return None
59
+ if isinstance(x, (int, float)):
60
+ return str(x)
61
+ s = str(x)
62
+ parts = s.split(":", 1)
63
+ return parts[1].strip() if len(parts) == 2 else s.strip()
64
+
65
+ def convert_trait(x):
66
+ """
67
+ Binary: 1 = Liver cancer/HCC/tumor case; 0 = non-cancer/normal/control.
68
+ Unknown -> None.
69
+ """
70
+ val = _after_colon(x).lower() if _after_colon(x) is not None else None
71
+ if val is None or val == "":
72
+ return None
73
+ # Positive indicators
74
+ pos_keywords = [
75
+ "liver cancer", "hepatocellular carcinoma", "hcc", "tumor", "tumour", "carcinoma", "cancer"
76
+ ]
77
+ # Negative indicators
78
+ neg_keywords = [
79
+ "normal", "non-tumor", "non tumour", "adjacent normal", "healthy", "control", "mock"
80
+ ]
81
+ if any(k in val for k in pos_keywords):
82
+ return 1
83
+ if any(k in val for k in neg_keywords):
84
+ return 0
85
+ return None
86
+
87
+ def convert_age(x):
88
+ """
89
+ Continuous: extract numeric age in years. Unknown -> None.
90
+ """
91
+ val = _after_colon(x)
92
+ if val is None or val == "":
93
+ return None
94
+ s = val.lower()
95
+ # common patterns like "57", "57 years", "age 57", ">=50"
96
+ m = re.search(r'(\d+(\.\d+)?)', s)
97
+ if m:
98
+ try:
99
+ return float(m.group(1))
100
+ except:
101
+ return None
102
+ return None
103
+
104
+ def convert_gender(x):
105
+ """
106
+ Binary: female=0, male=1. Unknown -> None.
107
+ """
108
+ val = _after_colon(x)
109
+ if val is None or val == "":
110
+ return None
111
+ s = val.strip().lower()
112
+ if s in {"male", "m", "man"}:
113
+ return 1
114
+ if s in {"female", "f", "woman"}:
115
+ return 0
116
+ # Handle encoded gender if present
117
+ if s in {"0", "1"}:
118
+ # Ambiguous without mapping; return None to avoid wrong assignment
119
+ return None
120
+ return None
121
+
122
+ # 3. Save Metadata (initial filtering)
123
+ is_trait_available = trait_row is not None
124
+ _ = validate_and_save_cohort_info(
125
+ is_final=False,
126
+ cohort=cohort,
127
+ info_path=json_path,
128
+ is_gene_available=is_gene_available,
129
+ is_trait_available=is_trait_available
130
+ )
131
+
132
+ # 4. Clinical Feature Extraction (skip because trait_row is None)
133
+ # If clinical data were available:
134
+ # if trait_row is not None:
135
+ # selected_df = geo_select_clinical_features(
136
+ # clinical_df=clinical_data,
137
+ # trait=trait,
138
+ # trait_row=trait_row,
139
+ # convert_trait=convert_trait,
140
+ # age_row=age_row,
141
+ # convert_age=convert_age,
142
+ # gender_row=gender_row,
143
+ # convert_gender=convert_gender
144
+ # )
145
+ # preview = preview_df(selected_df)
146
+ # os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
147
+ # selected_df.to_csv(out_clinical_data_file)
148
+
149
+ # Step 3: Gene Data Extraction
150
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
151
+ gene_data = get_genetic_data(matrix_file)
152
+
153
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
154
+ print(gene_data.index[:20])
155
+
156
+ # Step 4: Gene Identifier Review
157
+ # Illumina probe IDs (e.g., ILMN_1343291) are not human gene symbols and require mapping.
158
+ requires_gene_mapping = True
159
+ print(f"requires_gene_mapping = {requires_gene_mapping}")
160
+
161
+ # Step 5: Gene Annotation
162
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
163
+ gene_annotation = get_gene_annotation(soft_file)
164
+
165
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
166
+ print("Gene annotation preview:")
167
+ print(preview_df(gene_annotation))
168
+
169
+ # Step 6: Gene Identifier Mapping
170
+ # 1-2. Determine appropriate columns for mapping and create mapping dataframe
171
+ # Probe identifiers in expression data are Illumina IDs like 'ILMN_1343291', which correspond to 'ID' in annotation.
172
+ # Gene symbols are in the 'Symbol' column.
173
+ mapping_df = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='Symbol')
174
+
175
+ # 3. Apply mapping to convert probe-level data to gene-level expression
176
+ gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
177
+
178
+ # Step 7: Data Normalization and Linking
179
+ import os
180
+ import pandas as pd
181
+
182
+ # 1. Normalize gene symbols and save gene expression data
183
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
184
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
185
+ normalized_gene_data.to_csv(out_gene_data_file)
186
+
187
+ # 2-6. Link clinical and genetic data only if processed clinical features exist; otherwise finalize as unusable
188
+ if os.path.exists(out_clinical_data_file):
189
+ # Load previously saved clinical features
190
+ selected_clinical_data = pd.read_csv(out_clinical_data_file, index_col=0)
191
+
192
+ # Link clinical and genetic data
193
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_data, normalized_gene_data)
194
+
195
+ # 3. Handle missing values
196
+ linked_data = handle_missing_values(linked_data, trait)
197
+
198
+ # 4. Determine bias and remove biased demographic features
199
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
200
+
201
+ # 5. Final validation and save cohort info
202
+ is_usable = validate_and_save_cohort_info(
203
+ is_final=True,
204
+ cohort=cohort,
205
+ info_path=json_path,
206
+ is_gene_available=True,
207
+ is_trait_available=True,
208
+ is_biased=is_trait_biased,
209
+ df=unbiased_linked_data,
210
+ note="INFO: Clinical features loaded from file and linked successfully."
211
+ )
212
+
213
+ # 6. Save linked data if usable
214
+ if is_usable:
215
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
216
+ unbiased_linked_data.to_csv(out_data_file)
217
+ else:
218
+ # Trait/clinical data not available; perform final validation and ensure gene availability is correctly recorded.
219
+ # Pass a non-empty, wide dataframe to avoid abnormality override.
220
+ _ = validate_and_save_cohort_info(
221
+ is_final=True,
222
+ cohort=cohort,
223
+ info_path=json_path,
224
+ is_gene_available=True,
225
+ is_trait_available=False,
226
+ is_biased=False,
227
+ df=normalized_gene_data.T,
228
+ note="INFO: Trait/clinical data not available for this cohort; linking skipped. Only gene data saved."
229
+ )
output/preprocess/Liver_Cancer/code/TCGA.py ADDED
@@ -0,0 +1,353 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Liver_Cancer"
6
+
7
+ # Input paths
8
+ tcga_root_dir = "../DATA/TCGA"
9
+
10
+ # Output paths
11
+ out_data_file = "./output/z4/preprocess/Liver_Cancer/TCGA.csv"
12
+ out_gene_data_file = "./output/z4/preprocess/Liver_Cancer/gene_data/TCGA.csv"
13
+ out_clinical_data_file = "./output/z4/preprocess/Liver_Cancer/clinical_data/TCGA.csv"
14
+ json_path = "./output/z4/preprocess/Liver_Cancer/cohort_info.json"
15
+
16
+
17
+ # Step 1: Initial Data Loading
18
+ import os
19
+ import pandas as pd
20
+
21
+ # Find candidate cohort directories
22
+ subdirs = [d for d in os.listdir(tcga_root_dir) if os.path.isdir(os.path.join(tcga_root_dir, d))]
23
+
24
+ # Select the most specific cohort matching Liver Cancer (prefer LIHC)
25
+ def score_dir(name: str) -> int:
26
+ lname = name.lower()
27
+ score = 0
28
+ if "liver_cancer_(lihc)" in lname:
29
+ score += 100
30
+ if "lihc" in lname:
31
+ score += 50
32
+ if "liver" in lname:
33
+ score += 10
34
+ return score
35
+
36
+ scored = [(score_dir(d), d) for d in subdirs]
37
+ scored.sort(reverse=True)
38
+ best_score, selected_dir = scored[0] if scored else (0, None)
39
+
40
+ if best_score <= 0 or selected_dir is None:
41
+ # No suitable directory found; mark task as skipped for this trait
42
+ validate_and_save_cohort_info(
43
+ is_final=False,
44
+ cohort="TCGA",
45
+ info_path=json_path,
46
+ is_gene_available=False,
47
+ is_trait_available=False
48
+ )
49
+ else:
50
+ cohort = selected_dir
51
+ cohort_dir = os.path.join(tcga_root_dir, cohort)
52
+
53
+ # Identify clinical and genetic file paths
54
+ clinical_file_path, genetic_file_path = tcga_get_relevant_filepaths(cohort_dir)
55
+
56
+ # Load dataframes
57
+ clinical_df = pd.read_csv(clinical_file_path, sep='\t', index_col=0, low_memory=False)
58
+ genetic_df = pd.read_csv(genetic_file_path, sep='\t', index_col=0, low_memory=False)
59
+
60
+ # Print clinical column names
61
+ print(list(clinical_df.columns))
62
+
63
+ # Step 2: Find Candidate Demographic Features
64
+ import os
65
+ import pandas as pd
66
+
67
+ # Use the provided column list from the previous step as the basis for detection
68
+ available_cols = ['_INTEGRATION', '_PATIENT', '_cohort', '_primary_disease', '_primary_site', 'additional_pharmaceutical_therapy', 'additional_radiation_therapy', 'adjacent_hepatic_tissue_inflammation_extent_type', 'age_at_initial_pathologic_diagnosis', 'albumin_result_lower_limit', 'albumin_result_specified_value', 'albumin_result_upper_limit', 'bcr_followup_barcode', 'bcr_patient_barcode', 'bcr_sample_barcode', 'bilirubin_lower_limit', 'bilirubin_upper_limit', 'cancer_first_degree_relative', 'child_pugh_classification_grade', 'creatinine_lower_level', 'creatinine_upper_limit', 'creatinine_value_in_mg_dl', 'days_to_birth', 'days_to_collection', 'days_to_death', 'days_to_initial_pathologic_diagnosis', 'days_to_last_followup', 'days_to_new_tumor_event_additional_surgery_procedure', 'days_to_new_tumor_event_after_initial_treatment', 'eastern_cancer_oncology_group', 'fetoprotein_outcome_lower_limit', 'fetoprotein_outcome_upper_limit', 'fetoprotein_outcome_value', 'fibrosis_ishak_score', 'followup_case_report_form_submission_reason', 'form_completion_date', 'gender', 'height', 'hist_hepato_carc_fact', 'hist_hepato_carcinoma_risk', 'histological_type', 'history_of_neoadjuvant_treatment', 'icd_10', 'icd_o_3_histology', 'icd_o_3_site', 'informed_consent_verified', 'initial_weight', 'inter_norm_ratio_lower_limit', 'intern_norm_ratio_upper_limit', 'is_ffpe', 'lost_follow_up', 'neoplasm_histologic_grade', 'new_neoplasm_event_occurrence_anatomic_site', 'new_neoplasm_event_type', 'new_neoplasm_occurrence_anatomic_site_text', 'new_tumor_event_ablation_embo_tx', 'new_tumor_event_additional_surgery_procedure', 'new_tumor_event_after_initial_treatment', 'new_tumor_event_liver_transplant', 'oct_embedded', 'other_dx', 'pathologic_M', 'pathologic_N', 'pathologic_T', 'pathologic_stage', 'pathology_report_file_name', 'patient_id', 'person_neoplasm_cancer_status', 'platelet_result_count', 'platelet_result_lower_limit', 'platelet_result_upper_limit', 'post_op_ablation_embolization_tx', 'postoperative_rx_tx', 'prothrombin_time_result_value', 'radiation_therapy', 'relative_family_cancer_history', 'residual_disease_post_new_tumor_event_margin_status', 'residual_tumor', 'sample_type', 'sample_type_id', 'specimen_collection_method_name', 'system_version', 'tissue_prospective_collection_indicator', 'tissue_retrospective_collection_indicator', 'tissue_source_site', 'total_bilirubin_upper_limit', 'tumor_tissue_site', 'vascular_tumor_cell_type', 'vial_number', 'viral_hepatitis_serology', 'vital_status', 'weight', 'year_of_initial_pathologic_diagnosis', '_GENOMIC_ID_TCGA_LIHC_gistic2', '_GENOMIC_ID_TCGA_LIHC_gistic2thd', '_GENOMIC_ID_TCGA_LIHC_mutation_bcm_gene', '_GENOMIC_ID_TCGA_LIHC_miRNA_HiSeq', '_GENOMIC_ID_TCGA_LIHC_PDMRNAseq', '_GENOMIC_ID_TCGA_LIHC_RPPA', '_GENOMIC_ID_TCGA_LIHC_exp_HiSeqV2_percentile', '_GENOMIC_ID_TCGA_LIHC_mutation_bcgsc_gene', '_GENOMIC_ID_data/public/TCGA/LIHC/miRNA_HiSeq_gene', '_GENOMIC_ID_TCGA_LIHC_PDMRNAseqCNV', '_GENOMIC_ID_TCGA_LIHC_exp_HiSeqV2_exon', '_GENOMIC_ID_TCGA_LIHC_mutation_ucsc_maf_gene', '_GENOMIC_ID_TCGA_LIHC_exp_HiSeqV2', '_GENOMIC_ID_TCGA_LIHC_exp_HiSeqV2_PANCAN', '_GENOMIC_ID_TCGA_LIHC_mutation_broad_gene', '_GENOMIC_ID_TCGA_LIHC_hMethyl450']
69
+
70
+ # Identify candidate columns
71
+ age_candidates = []
72
+ gender_candidates = []
73
+ for col in available_cols:
74
+ cl = col.lower()
75
+ if ('age' in cl and 'stage' not in cl) or ('birth' in cl):
76
+ age_candidates.append(col)
77
+ if ('gender' in cl) or (cl == 'sex') or ('sex_' in cl) or (cl.endswith('_sex')):
78
+ gender_candidates.append(col)
79
+
80
+ candidate_age_cols = age_candidates
81
+ candidate_gender_cols = gender_candidates
82
+
83
+ # Print in the strictly required format
84
+ print(f"candidate_age_cols = {candidate_age_cols}")
85
+ print(f"candidate_gender_cols = {candidate_gender_cols}")
86
+
87
+ # Try to load clinical data to preview candidate columns (if available)
88
+ clinical_df = None
89
+ try:
90
+ # Find a cohort dir likely corresponding to LIHC
91
+ cohort_dirs = [os.path.join(tcga_root_dir, d) for d in os.listdir(tcga_root_dir)
92
+ if os.path.isdir(os.path.join(tcga_root_dir, d))]
93
+ preferred = [d for d in cohort_dirs if 'lihc' in os.path.basename(d).lower() or 'liver' in os.path.basename(d).lower()]
94
+ cohort_dir = preferred[0] if preferred else (cohort_dirs[0] if cohort_dirs else None)
95
+
96
+ if cohort_dir:
97
+ clinical_file_path, _ = tcga_get_relevant_filepaths(cohort_dir)
98
+ # Clinical matrix files from Xena are tab-delimited with sample IDs as the first column
99
+ clinical_df = pd.read_csv(clinical_file_path, sep='\t', index_col=0, dtype=str)
100
+ except Exception:
101
+ clinical_df = None
102
+
103
+ # Prepare previews if clinical data is available
104
+ age_preview = {}
105
+ gender_preview = {}
106
+ if clinical_df is not None:
107
+ age_cols_present = [c for c in candidate_age_cols if c in clinical_df.columns]
108
+ gender_cols_present = [c for c in candidate_gender_cols if c in clinical_df.columns]
109
+
110
+ if len(age_cols_present) > 0:
111
+ age_preview = preview_df(clinical_df[age_cols_present], n=5)
112
+ if len(gender_cols_present) > 0:
113
+ gender_preview = preview_df(clinical_df[gender_cols_present], n=5)
114
+
115
+ # Display previews as Python dictionaries
116
+ print(age_preview)
117
+ print(gender_preview)
118
+
119
+ # Step 3: Select Demographic Features
120
+ import re
121
+ import pandas as pd
122
+ import numpy as np
123
+
124
+ # Helper to safely convert to int if possible
125
+ def _to_int(x):
126
+ if pd.isna(x):
127
+ return None
128
+ if isinstance(x, (int, np.integer)):
129
+ return int(x)
130
+ if isinstance(x, float):
131
+ if np.isnan(x):
132
+ return None
133
+ return int(x)
134
+ m = re.search(r'-?\d+', str(x))
135
+ return int(m.group()) if m else None
136
+
137
+ def _find_value_dict(candidate_cols):
138
+ # Try to find a dict in globals whose keys overlap with candidate columns and values are lists (preview samples)
139
+ for name, val in globals().items():
140
+ if isinstance(val, dict):
141
+ keys = set(val.keys())
142
+ overlap = [k for k in candidate_cols if k in keys]
143
+ if overlap and all(isinstance(val[k], list) for k in overlap):
144
+ return val
145
+ return None
146
+
147
+ # Ensure candidate lists exist
148
+ candidate_age_cols = globals().get('candidate_age_cols', [])
149
+ candidate_gender_cols = globals().get('candidate_gender_cols', [])
150
+
151
+ age_col = None
152
+ gender_col = None
153
+
154
+ # Attempt to locate the preview dictionaries
155
+ age_values_dict = _find_value_dict(candidate_age_cols) if candidate_age_cols else None
156
+ gender_values_dict = _find_value_dict(candidate_gender_cols) if candidate_gender_cols else None
157
+
158
+ # Select age column
159
+ if age_values_dict:
160
+ best = None
161
+ for col in candidate_age_cols:
162
+ if col not in age_values_dict:
163
+ continue
164
+ vals = age_values_dict[col]
165
+ non_missing = [v for v in vals if not pd.isna(v)]
166
+ if len(vals) == 0:
167
+ continue
168
+ ints = [_to_int(v) for v in non_missing]
169
+ ints = [v for v in ints if v is not None]
170
+ if not ints:
171
+ continue
172
+ age_like_frac = sum(0 <= v <= 120 for v in ints) / len(ints)
173
+ dob_like_frac = sum((v is not None) and (v <= -365) for v in ints) / len(ints)
174
+ missing_frac = 1 - (len(non_missing) / len(vals))
175
+ # Eligibility threshold: at least 60% look valid and missingness <= 60%
176
+ score = None
177
+ kind = None
178
+ if age_like_frac >= 0.6 and missing_frac <= 0.6:
179
+ score = (1, age_like_frac, -missing_frac, len(ints))
180
+ kind = 'age'
181
+ elif dob_like_frac >= 0.6 and missing_frac <= 0.6:
182
+ score = (0, dob_like_frac, -missing_frac, len(ints))
183
+ kind = 'dob'
184
+ if score is not None:
185
+ # Prefer age-like (score[0]=1) over dob-like (score[0]=0), then higher fraction, lower missing, more ints
186
+ if best is None or score > best[0]:
187
+ best = (score, col, kind)
188
+ # Prefer explicit age_at_initial_pathologic_diagnosis if tie
189
+ elif score == best[0] and col == 'age_at_initial_pathologic_diagnosis':
190
+ best = (score, col, kind)
191
+ if best:
192
+ age_col = best[1]
193
+ else:
194
+ # Fallback heuristic
195
+ if 'age_at_initial_pathologic_diagnosis' in candidate_age_cols:
196
+ age_col = 'age_at_initial_pathologic_diagnosis'
197
+ elif candidate_age_cols:
198
+ age_col = candidate_age_cols[0]
199
+ else:
200
+ # No preview dict found; use domain heuristic
201
+ if 'age_at_initial_pathologic_diagnosis' in candidate_age_cols:
202
+ age_col = 'age_at_initial_pathologic_diagnosis'
203
+ elif candidate_age_cols:
204
+ age_col = candidate_age_cols[0]
205
+ else:
206
+ age_col = None
207
+
208
+ # Select gender column
209
+ if gender_values_dict:
210
+ best = None
211
+ for col in candidate_gender_cols:
212
+ if col not in gender_values_dict:
213
+ continue
214
+ vals = gender_values_dict[col]
215
+ non_missing = [v for v in vals if not pd.isna(v)]
216
+ if len(vals) == 0:
217
+ continue
218
+ normalized = [str(v).strip().lower() for v in non_missing]
219
+ mf_frac = sum(v in ('male', 'female') for v in normalized) / len(normalized)
220
+ missing_frac = 1 - (len(non_missing) / len(vals))
221
+ if mf_frac >= 0.6 and missing_frac <= 0.6:
222
+ score = (mf_frac, -missing_frac, len(non_missing))
223
+ if best is None or score > best[0]:
224
+ best = (score, col)
225
+ elif score == best[0] and col == 'gender':
226
+ best = (score, col)
227
+ if best:
228
+ gender_col = best[1]
229
+ else:
230
+ if 'gender' in candidate_gender_cols:
231
+ gender_col = 'gender'
232
+ elif candidate_gender_cols:
233
+ gender_col = candidate_gender_cols[0]
234
+ else:
235
+ gender_col = None
236
+ else:
237
+ if 'gender' in candidate_gender_cols:
238
+ gender_col = 'gender'
239
+ elif candidate_gender_cols:
240
+ gender_col = candidate_gender_cols[0]
241
+ else:
242
+ gender_col = None
243
+
244
+ # Explicitly print out the chosen columns and their preview values if available
245
+ print("Selected age_col:", age_col)
246
+ if age_col and age_values_dict and age_col in age_values_dict:
247
+ print("age_col preview values:", age_values_dict[age_col])
248
+
249
+ print("Selected gender_col:", gender_col)
250
+ if gender_col and gender_values_dict and gender_col in gender_values_dict:
251
+ print("gender_col preview values:", gender_values_dict[gender_col])
252
+
253
+ # Step 4: Feature Engineering and Validation
254
+ import os
255
+ import pandas as pd
256
+
257
+ # Ensure clinical and genetic data are loaded (reuse from previous steps if available; otherwise load)
258
+ if 'clinical_df' not in globals() or 'genetic_df' not in globals():
259
+ # Locate LIHC cohort directory
260
+ subdirs = [d for d in os.listdir(tcga_root_dir) if os.path.isdir(os.path.join(tcga_root_dir, d))]
261
+ def score_dir(name: str) -> int:
262
+ lname = name.lower()
263
+ score = 0
264
+ if "liver_cancer_(lihc)" in lname:
265
+ score += 100
266
+ if "lihc" in lname:
267
+ score += 50
268
+ if "liver" in lname:
269
+ score += 10
270
+ return score
271
+ scored = sorted([(score_dir(d), d) for d in subdirs], reverse=True)
272
+ if not scored or scored[0][0] <= 0:
273
+ # No suitable directory; record and exit gracefully for downstream steps
274
+ validate_and_save_cohort_info(
275
+ is_final=False,
276
+ cohort="TCGA_LIHC",
277
+ info_path=json_path,
278
+ is_gene_available=False,
279
+ is_trait_available=False
280
+ )
281
+ # Create empty placeholders to avoid NameError in following code blocks
282
+ clinical_df = pd.DataFrame()
283
+ genetic_df = pd.DataFrame()
284
+ else:
285
+ selected_dir = scored[0][1]
286
+ cohort_dir = os.path.join(tcga_root_dir, selected_dir)
287
+ clinical_file_path, genetic_file_path = tcga_get_relevant_filepaths(cohort_dir)
288
+ clinical_df = pd.read_csv(clinical_file_path, sep='\t', index_col=0, low_memory=False, dtype=str)
289
+ genetic_df = pd.read_csv(genetic_file_path, sep='\t', index_col=0, low_memory=False)
290
+
291
+ # 1) Extract and standardize clinical features (trait + optional age and gender)
292
+ selected_clinical_df = tcga_select_clinical_features(
293
+ clinical_df=clinical_df,
294
+ trait=trait,
295
+ age_col=globals().get('age_col', None),
296
+ gender_col=globals().get('gender_col', None)
297
+ )
298
+
299
+ # 2) Normalize gene symbols and save normalized gene data
300
+ # Subset gene expression to samples present in our clinical matrix
301
+ common_sample_cols = [c for c in genetic_df.columns if c in selected_clinical_df.index]
302
+ genetic_df_subset = genetic_df.loc[:, common_sample_cols].copy()
303
+
304
+ # Coerce to numeric
305
+ genetic_df_subset = genetic_df_subset.apply(pd.to_numeric, errors='coerce')
306
+
307
+ # Normalize gene symbols using NCBI synonym dictionary and aggregate duplicates by mean
308
+ normalized_gene_df = normalize_gene_symbols_in_index(genetic_df_subset)
309
+
310
+ # Save normalized gene data
311
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
312
+ normalized_gene_df.to_csv(out_gene_data_file)
313
+
314
+ # 3) Link clinical and genetic data on sample IDs
315
+ common_samples = selected_clinical_df.index.intersection(normalized_gene_df.columns)
316
+ gene_data_T = normalized_gene_df.T.loc[common_samples]
317
+ clinical_aligned = selected_clinical_df.loc[common_samples]
318
+ linked_data = clinical_aligned.join(gene_data_T, how='inner')
319
+
320
+ # 4) Handle missing values systematically
321
+ processed_df = handle_missing_values(linked_data, trait_col=trait)
322
+
323
+ # 5) Determine bias in trait and remove biased demographic features (if any)
324
+ trait_biased, processed_df = judge_and_remove_biased_features(processed_df, trait)
325
+
326
+ # 6) Final validation and save cohort info
327
+ # Cast flags explicitly to native Python bool to avoid any np.bool_ leakage
328
+ is_gene_available = bool(normalized_gene_df.shape[0] > 0)
329
+ is_trait_available = bool((trait in linked_data.columns) and linked_data[trait].notna().any())
330
+ trait_biased_flag = bool(trait_biased)
331
+
332
+ note = str(
333
+ "INFO: Trait derived from TCGA sample type codes (01-09 tumor=1, 10-19 normal=0). "
334
+ "Gene expression subset to LIHC samples and gene symbols normalized via NCBI synonyms. "
335
+ "Missing values handled per pipeline (gene>20% NA removed; sample>5% NA removed; "
336
+ "imputation by mean/mode)."
337
+ )
338
+
339
+ is_usable = validate_and_save_cohort_info(
340
+ is_final=True,
341
+ cohort="TCGA_LIHC",
342
+ info_path=json_path,
343
+ is_gene_available=is_gene_available,
344
+ is_trait_available=is_trait_available,
345
+ is_biased=trait_biased_flag,
346
+ df=processed_df,
347
+ note=note
348
+ )
349
+
350
+ # 7) Save linked dataset only if usable
351
+ if is_usable:
352
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
353
+ processed_df.to_csv(out_data_file)
output/preprocess/Liver_Cancer/cohort_info.json CHANGED
@@ -1,122 +1 @@
1
- {
2
- "GSE66843": {
3
- "is_usable": false,
4
- "is_gene_available": true,
5
- "is_trait_available": true,
6
- "is_available": true,
7
- "is_biased": true,
8
- "has_age": false,
9
- "has_gender": false,
10
- "sample_size": 17
11
- },
12
- "GSE45032": {
13
- "is_usable": true,
14
- "is_gene_available": true,
15
- "is_trait_available": true,
16
- "is_available": true,
17
- "is_biased": false,
18
- "has_age": true,
19
- "has_gender": true,
20
- "sample_size": 48
21
- },
22
- "GSE228783": {
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": 152
31
- },
32
- "GSE228782": {
33
- "is_usable": true,
34
- "is_gene_available": true,
35
- "is_trait_available": true,
36
- "is_available": true,
37
- "is_biased": false,
38
- "has_age": false,
39
- "has_gender": false,
40
- "sample_size": 83
41
- },
42
- "GSE218438": {
43
- "is_usable": false,
44
- "is_gene_available": false,
45
- "is_trait_available": false,
46
- "is_available": false,
47
- "is_biased": null,
48
- "has_age": null,
49
- "has_gender": null,
50
- "sample_size": null
51
- },
52
- "GSE212047": {
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
- "GSE209875": {
63
- "is_usable": false,
64
- "is_gene_available": false,
65
- "is_trait_available": true,
66
- "is_available": false,
67
- "is_biased": null,
68
- "has_age": null,
69
- "has_gender": null,
70
- "sample_size": null
71
- },
72
- "GSE178201": {
73
- "is_usable": false,
74
- "is_gene_available": true,
75
- "is_trait_available": false,
76
- "is_available": false,
77
- "is_biased": null,
78
- "has_age": null,
79
- "has_gender": null,
80
- "sample_size": null
81
- },
82
- "GSE174570": {
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
- "GSE164760": {
93
- "is_usable": true,
94
- "is_gene_available": true,
95
- "is_trait_available": true,
96
- "is_available": true,
97
- "is_biased": false,
98
- "has_age": false,
99
- "has_gender": false,
100
- "sample_size": 170
101
- },
102
- "GSE148346": {
103
- "is_usable": true,
104
- "is_gene_available": true,
105
- "is_trait_available": true,
106
- "is_available": true,
107
- "is_biased": false,
108
- "has_age": false,
109
- "has_gender": false,
110
- "sample_size": 129
111
- },
112
- "TCGA": {
113
- "is_usable": true,
114
- "is_gene_available": true,
115
- "is_trait_available": true,
116
- "is_available": true,
117
- "is_biased": false,
118
- "has_age": true,
119
- "has_gender": true,
120
- "sample_size": 423
121
- }
122
- }
 
1
+ {"GSE66843": {"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/clinical data not available for this cohort; linking skipped. Only gene data saved."}, "GSE45032": {"is_usable": true, "is_gene_available": true, "is_trait_available": true, "is_available": true, "is_biased": false, "has_age": true, "has_gender": false, "sample_size": 48, "note": "INFO: Probe->gene mapping used annotation columns ID->GeneName; split multi-gene probe signal equally and summed per gene; normalized symbols using NCBI synonym map; dropped genes with >20% missing and samples with >5% missing genes; imputed Gender with mode and others with mean."}, "GSE228783": {"is_usable": true, "is_gene_available": true, "is_trait_available": true, "is_available": true, "is_biased": false, "has_age": false, "has_gender": false, "sample_size": 140, "note": "INFO: Affymetrix HG-U219 probes mapped to symbols via platform annotation; no age/gender fields provided."}, "GSE228782": {"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": 83, "note": "INFO: Gene mapping performed from Affymetrix HG-U219 probes to symbols; clinical trait derived from 'disease' field; no age/gender available."}, "GSE218438": {"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": 636, "note": "WARNING: Probe-to-gene symbol mapping was unavailable; normalization produced empty gene data. Proceeding with probe-level Affymetrix IDs as features. INFO: Gene feature count=22268, sample count=636."}, "GSE212047": {"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}, "GSE209875": {"is_usable": false, "is_gene_available": false, "is_trait_available": true, "is_available": false, "is_biased": null, "has_age": null, "has_gender": null, "sample_size": null, "note": null}, "GSE178201": {"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": 3984, "note": "INFO: Trait is constant (all HepG2) in this matrix; dataset marked biased."}, "GSE174570": {"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": 114, "note": "INFO: Trait inferred from tissue labels (tumour=1, non-tumour adjacent=0); age and gender unavailable in this series. Platform HG-U219; probe-to-gene mapping and gene symbol normalization applied."}, "GSE164760": {"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": 170, "note": "INFO: Trait inferred from tissue; age and gender not available in matrix."}, "GSE148346": {"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_LIHC": {"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": 423, "note": "INFO: Trait derived from TCGA sample type codes (01-09 tumor=1, 10-19 normal=0). Gene expression subset to LIHC samples and gene symbols normalized via NCBI synonyms. Missing values handled per pipeline (gene>20% NA removed; sample>5% NA removed; imputation by mean/mode)."}}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
output/preprocess/Liver_Cancer/gene_data/GSE212047.csv CHANGED
The diff for this file is too large to render. See raw diff
 
output/preprocess/Liver_cirrhosis/clinical_data/GSE139602.csv CHANGED
@@ -1,2 +1,2 @@
1
- 0
2
- 0.0
 
1
+ ,GSM4144550,GSM4144551,GSM4144552,GSM4144553,GSM4144554,GSM4144555,GSM4144556,GSM4144557,GSM4144558,GSM4144559,GSM4144560,GSM4144561,GSM4144562,GSM4144563,GSM4144564,GSM4144565,GSM4144566,GSM4144567,GSM4144568,GSM4144569,GSM4144570,GSM4144571,GSM4144572,GSM4144573,GSM4144574,GSM4144575,GSM4144576,GSM4144577,GSM4144578,GSM4144579,GSM4144580,GSM4144581,GSM4144582,GSM4144583,GSM4144584,GSM4144585,GSM4144586,GSM4144587,GSM4144588
2
+ Liver_cirrhosis,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
output/preprocess/Liver_cirrhosis/clinical_data/GSE285291.csv ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ ,GSM8700031,GSM8700032,GSM8700033,GSM8700034,GSM8700035,GSM8700036,GSM8700037,GSM8700038,GSM8700039,GSM8700040,GSM8700041,GSM8700042,GSM8700043,GSM8700044,GSM8700045,GSM8700046,GSM8700047,GSM8700048,GSM8700049,GSM8700050,GSM8700051,GSM8700052,GSM8700053,GSM8700054,GSM8700055,GSM8700056,GSM8700057,GSM8700058,GSM8700059,GSM8700060,GSM8700061,GSM8700062,GSM8700063,GSM8700064,GSM8700065,GSM8700066,GSM8700067,GSM8700068,GSM8700069,GSM8700070,GSM8700071,GSM8700072,GSM8700073,GSM8700074,GSM8700075,GSM8700076,GSM8700077,GSM8700078,GSM8700079,GSM8700080,GSM8700081,GSM8700082,GSM8700083
2
+ Liver_cirrhosis,1.0,1.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,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
output/preprocess/Liver_cirrhosis/code/GSE139602.py ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Liver_cirrhosis"
6
+ cohort = "GSE139602"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Liver_cirrhosis"
10
+ in_cohort_dir = "../DATA/GEO/Liver_cirrhosis/GSE139602"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z4/preprocess/Liver_cirrhosis/GSE139602.csv"
14
+ out_gene_data_file = "./output/z4/preprocess/Liver_cirrhosis/gene_data/GSE139602.csv"
15
+ out_clinical_data_file = "./output/z4/preprocess/Liver_cirrhosis/clinical_data/GSE139602.csv"
16
+ json_path = "./output/z4/preprocess/Liver_cirrhosis/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 # Transcriptome analysis on liver biopsies indicates gene expression data
41
+
42
+ # Step 2: Variable availability and converters
43
+
44
+ # 2.1 Availability
45
+ trait_row = 0 # disease state
46
+ age_row = None
47
+ gender_row = None
48
+
49
+ # 2.2 Converters
50
+ def _extract_value(x):
51
+ if x is None:
52
+ return None
53
+ s = str(x).strip()
54
+ if not s or s.lower() in {"na", "n/a", "none", "nan"}:
55
+ return None
56
+ if ":" in s:
57
+ s = s.split(":", 1)[1].strip()
58
+ return s if s else None
59
+
60
+ def convert_trait(x):
61
+ val = _extract_value(x)
62
+ if val is None:
63
+ return None
64
+ low = val.lower()
65
+ # Positive for cirrhosis: compensated/decompensated cirrhosis, ACLF (typically arises in cirrhosis)
66
+ if "cirrhosis" in low:
67
+ return 1
68
+ if "acute-on-chronic liver failure" in low or "aclf" in low:
69
+ return 1
70
+ # Negative for cirrhosis: healthy, early CLD/fibrosis (eCLD)
71
+ if low in {"healthy", "control"}:
72
+ return 0
73
+ if low in {"ecld", "fibrosis"} or "fibrosis" in low:
74
+ return 0
75
+ return None
76
+
77
+ def convert_age(x):
78
+ # Not available in this dataset
79
+ return None
80
+
81
+ def convert_gender(x):
82
+ # Not available in this dataset
83
+ return None
84
+
85
+ # Step 3: Save metadata (initial filtering)
86
+ is_trait_available = trait_row is not None
87
+ _ = validate_and_save_cohort_info(
88
+ is_final=False,
89
+ cohort=cohort,
90
+ info_path=json_path,
91
+ is_gene_available=is_gene_available,
92
+ is_trait_available=is_trait_available
93
+ )
94
+
95
+ # Step 4: Clinical feature extraction (only if clinical data available)
96
+ if trait_row is not None:
97
+ selected_clinical_df = geo_select_clinical_features(
98
+ clinical_df=clinical_data,
99
+ trait=trait,
100
+ trait_row=trait_row,
101
+ convert_trait=convert_trait
102
+ )
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
+ print("requires_gene_mapping = True")
118
+
119
+ # Step 5: Gene Annotation
120
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
121
+ gene_annotation = get_gene_annotation(soft_file)
122
+
123
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
124
+ print("Gene annotation preview:")
125
+ print(preview_df(gene_annotation))
126
+
127
+ # Step 6: Gene Identifier Mapping
128
+ # Identify appropriate columns for mapping: probe ID ('ID') and gene symbol ('Gene Symbol')
129
+ prob_col = 'ID'
130
+ gene_col = 'Gene Symbol'
131
+
132
+ # Build mapping dataframe from annotation
133
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=prob_col, gene_col=gene_col)
134
+
135
+ # Apply mapping to convert probe-level data to gene-level expression
136
+ gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
137
+
138
+ # Step 7: Data Normalization and Linking
139
+ import os
140
+ import pandas as pd
141
+
142
+ # 1) Normalize gene symbols and save
143
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
144
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
145
+ normalized_gene_data.to_csv(out_gene_data_file)
146
+
147
+ # 2) Ensure clinical data is available (reload if necessary) and link clinical/genetic data
148
+ if 'selected_clinical_df' not in locals():
149
+ selected_clinical_df = pd.read_csv(out_clinical_data_file, index_col=0)
150
+
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) Bias checking and removal of biased covariates
157
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
158
+
159
+ # 5) Final validation and save cohort metadata
160
+ # Coerce to native Python bool to avoid numpy.bool_ serialization issues.
161
+ is_gene_available_final = bool(normalized_gene_data.shape[0] > 0 and normalized_gene_data.shape[1] > 0)
162
+ is_trait_available_final = bool((trait in linked_data.columns) and bool(linked_data[trait].notna().any()))
163
+ is_trait_biased = bool(is_trait_biased)
164
+
165
+ note = (
166
+ "INFO: Trait derived from 'disease state' (cirrhosis/ACLF=1; healthy/eCLD/fibrosis=0). "
167
+ "Age and Gender not available in this series."
168
+ )
169
+
170
+ try:
171
+ is_usable = validate_and_save_cohort_info(
172
+ is_final=True,
173
+ cohort=cohort,
174
+ info_path=json_path,
175
+ is_gene_available=is_gene_available_final,
176
+ is_trait_available=is_trait_available_final,
177
+ is_biased=is_trait_biased,
178
+ df=unbiased_linked_data,
179
+ note=note
180
+ )
181
+ except TypeError:
182
+ # Fallback in case of JSON serialization issues from a corrupted file or non-serializable entries
183
+ if os.path.exists(json_path):
184
+ os.remove(json_path)
185
+ is_usable = validate_and_save_cohort_info(
186
+ is_final=True,
187
+ cohort=cohort,
188
+ info_path=json_path,
189
+ is_gene_available=is_gene_available_final,
190
+ is_trait_available=is_trait_available_final,
191
+ is_biased=is_trait_biased,
192
+ df=unbiased_linked_data,
193
+ note=note
194
+ )
195
+
196
+ # 6) Save linked data if usable
197
+ if is_usable:
198
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
199
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Liver_cirrhosis/code/GSE150734.py ADDED
@@ -0,0 +1,221 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Liver_cirrhosis"
6
+ cohort = "GSE150734"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Liver_cirrhosis"
10
+ in_cohort_dir = "../DATA/GEO/Liver_cirrhosis/GSE150734"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z4/preprocess/Liver_cirrhosis/GSE150734.csv"
14
+ out_gene_data_file = "./output/z4/preprocess/Liver_cirrhosis/gene_data/GSE150734.csv"
15
+ out_clinical_data_file = "./output/z4/preprocess/Liver_cirrhosis/clinical_data/GSE150734.csv"
16
+ json_path = "./output/z4/preprocess/Liver_cirrhosis/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ import re
40
+ import pandas as pd
41
+
42
+ # 1) Gene expression availability
43
+ is_gene_available = True # Gene expression profiling of liver biopsy tissues (not miRNA-only or methylation-only)
44
+
45
+ # 2) Variable availability and conversion functions
46
+
47
+ # Based on the sample characteristics dictionary:
48
+ # 0: ['fibrosis stage: 0', 'fibrosis stage: 1'] -> No cirrhosis present (cirrhosis is fibrosis stage 4). Constant "no" for Liver_cirrhosis.
49
+ # 1: ['pls risk prediction: Intermediate', 'Low', 'High'] -> Not the target trait; also no age/gender keys provided.
50
+ trait_row = None
51
+ age_row = None
52
+ gender_row = None
53
+
54
+ def _after_colon(val):
55
+ if val is None:
56
+ return None
57
+ s = str(val)
58
+ parts = s.split(":", 1)
59
+ return parts[1].strip() if len(parts) > 1 else s.strip()
60
+
61
+ def convert_trait(val):
62
+ """
63
+ Convert fibrosis-related or cirrhosis-indicative strings to binary: cirrhosis -> 1, non-cirrhosis -> 0.
64
+ Unknown -> None.
65
+ This function is robust but will not be used here since trait_row is None (no informative variation).
66
+ """
67
+ v = _after_colon(val)
68
+ if v is None or v == "":
69
+ return None
70
+ s = v.strip().lower()
71
+
72
+ # Direct cirrhosis indications
73
+ if s in {"cirrhosis", "yes", "y"}:
74
+ return 1
75
+ if s in {"no", "n", "non-cirrhosis", "non cirrhosis"}:
76
+ return 0
77
+
78
+ # Handle fibrosis stage patterns (e.g., "0", "1", "F3", "F4", "stage 4")
79
+ # Extract first number present
80
+ m = re.search(r'([fF]?\s*([0-9]+))', s)
81
+ if m:
82
+ try:
83
+ num = int(re.search(r'([0-9]+)', m.group(0)).group(1))
84
+ return 1 if num >= 4 else 0
85
+ except Exception:
86
+ pass
87
+
88
+ # Heuristic keywords
89
+ if "f4" in s or "stage 4" in s or "advanced cirrhosis" in s:
90
+ return 1
91
+ if "f0" in s or "stage 0" in s:
92
+ return 0
93
+
94
+ return None
95
+
96
+ def convert_age(val):
97
+ """
98
+ Extract numeric age from strings like 'age: 54', 'Age: 54 years'.
99
+ Returns float; unknown -> None.
100
+ """
101
+ v = _after_colon(val)
102
+ if v is None or v == "":
103
+ return None
104
+ m = re.search(r'(\d+(\.\d+)*)', v)
105
+ if m:
106
+ try:
107
+ return float(m.group(1))
108
+ except Exception:
109
+ return None
110
+ return None
111
+
112
+ def convert_gender(val):
113
+ """
114
+ Convert gender to binary: female -> 0, male -> 1. Unknown -> None.
115
+ """
116
+ v = _after_colon(val)
117
+ if v is None or v == "":
118
+ return None
119
+ s = v.strip().lower()
120
+ if s in {"female", "f", "woman", "women"}:
121
+ return 0
122
+ if s in {"male", "m", "man", "men"}:
123
+ return 1
124
+ return None
125
+
126
+ # 3) Save metadata (initial filtering)
127
+ is_trait_available = (trait_row is not None)
128
+ _ = validate_and_save_cohort_info(
129
+ is_final=False,
130
+ cohort=cohort,
131
+ info_path=json_path,
132
+ is_gene_available=is_gene_available,
133
+ is_trait_available=is_trait_available
134
+ )
135
+
136
+ # 4) Clinical feature extraction (skip because trait_row is None)
137
+ if trait_row is not None:
138
+ selected_clinical_df = geo_select_clinical_features(
139
+ clinical_df=clinical_data,
140
+ trait=trait,
141
+ trait_row=trait_row,
142
+ convert_trait=convert_trait,
143
+ age_row=age_row,
144
+ convert_age=convert_age,
145
+ gender_row=gender_row,
146
+ convert_gender=convert_gender
147
+ )
148
+ _preview = preview_df(selected_clinical_df, n=5)
149
+ # Save clinical data
150
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
151
+ selected_clinical_df.to_csv(out_clinical_data_file, index=True)
152
+
153
+ # Step 3: Gene Data Extraction
154
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
155
+ gene_data = get_genetic_data(matrix_file)
156
+
157
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
158
+ print(gene_data.index[:20])
159
+
160
+ # Step 4: Gene Identifier Review
161
+ # Based on the observed identifiers (e.g., AARS, ABLIM1, ACOT2), these appear to be standard human gene symbols.
162
+ requires_gene_mapping = False
163
+ print(f"requires_gene_mapping = {requires_gene_mapping}")
164
+
165
+ # Step 5: Data Normalization and Linking
166
+ import os
167
+ import pandas as pd
168
+
169
+ # 1. Normalize gene symbols and save normalized gene data
170
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
171
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
172
+ normalized_gene_data.to_csv(out_gene_data_file)
173
+
174
+ # 2-6. Guarded linking and validation depending on trait availability
175
+ linked_data = None
176
+ proceed_linking = (
177
+ 'selected_clinical_data' in locals()
178
+ and isinstance(selected_clinical_data, pd.DataFrame)
179
+ and (trait in selected_clinical_data.index)
180
+ )
181
+
182
+ if proceed_linking:
183
+ # 2. Link clinical and genetic data
184
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_data, normalized_gene_data)
185
+
186
+ # 3. Handle missing values
187
+ linked_data = handle_missing_values(linked_data, trait)
188
+
189
+ # 4. Bias check and remove biased demographic features
190
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
191
+
192
+ # 5. Final validation and save cohort info
193
+ is_usable = validate_and_save_cohort_info(
194
+ is_final=True,
195
+ cohort=cohort,
196
+ info_path=json_path,
197
+ is_gene_available=True,
198
+ is_trait_available=True,
199
+ is_biased=is_trait_biased,
200
+ df=unbiased_linked_data,
201
+ note="INFO: Proceeded with full linking, missing-value handling, and bias checks."
202
+ )
203
+
204
+ # 6. Save linked data only if usable
205
+ if is_usable:
206
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
207
+ unbiased_linked_data.to_csv(out_data_file)
208
+
209
+ else:
210
+ # Trait not available in this cohort (as determined in Step 2); skip linking and mark as unavailable for analysis.
211
+ is_usable = validate_and_save_cohort_info(
212
+ is_final=True,
213
+ cohort=cohort,
214
+ info_path=json_path,
215
+ is_gene_available=True,
216
+ is_trait_available=False,
217
+ is_biased=False,
218
+ df=normalized_gene_data.T,
219
+ note="INFO: Trait not available for this cohort. Sample characteristics show fibrosis stage 0-1 only; no cirrhosis label present."
220
+ )
221
+ # Do not save out_data_file when not usable
output/preprocess/Liver_cirrhosis/code/GSE163211.py ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Liver_cirrhosis"
6
+ cohort = "GSE163211"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Liver_cirrhosis"
10
+ in_cohort_dir = "../DATA/GEO/Liver_cirrhosis/GSE163211"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z4/preprocess/Liver_cirrhosis/GSE163211.csv"
14
+ out_gene_data_file = "./output/z4/preprocess/Liver_cirrhosis/gene_data/GSE163211.csv"
15
+ out_clinical_data_file = "./output/z4/preprocess/Liver_cirrhosis/clinical_data/GSE163211.csv"
16
+ json_path = "./output/z4/preprocess/Liver_cirrhosis/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ import os
40
+ import pandas as pd
41
+
42
+ # 1) Gene expression data availability
43
+ # Nanostring nCounter assay measuring 800 genes => gene expression data available
44
+ is_gene_available = True
45
+
46
+ # 2) Variable availability and converters
47
+
48
+ # Sample Characteristics Dictionary assessment (from previous step):
49
+ # 8: 'nafld stage: Steatosis', 'NASH_F1_F4', 'Normal', 'NASH_F0'
50
+ # Trait is Liver_cirrhosis; cirrhosis corresponds to fibrosis stage F4.
51
+ # Here, fibrosis is aggregated as NASH_F1_F4, so we cannot isolate F4 specifically.
52
+ trait_row = None # Not derivable from provided categories
53
+ age_row = 3 # 'age: <number>'
54
+ gender_row = 4 # 'Sex: Female' / 'Sex: Male'
55
+
56
+ def _extract_value(x):
57
+ if x is None:
58
+ return None
59
+ if isinstance(x, str):
60
+ parts = x.split(":", 1)
61
+ val = parts[1] if len(parts) > 1 else parts[0]
62
+ return val.strip()
63
+ return x
64
+
65
+ def convert_trait(x):
66
+ # Cirrhosis status is not determinable from available categories ('NASH_F1_F4' lumps F1-F4)
67
+ # Return None to mark as unavailable/unknown
68
+ return None
69
+
70
+ def convert_age(x):
71
+ val = _extract_value(x)
72
+ if val is None or val == "" or str(val).lower() in {"na", "nan", "none", "unknown"}:
73
+ return None
74
+ try:
75
+ v = float(val)
76
+ # Sanity check for human adult ages
77
+ if v <= 0 or v > 120:
78
+ return None
79
+ return v
80
+ except Exception:
81
+ return None
82
+
83
+ def convert_gender(x):
84
+ val = _extract_value(x)
85
+ if val is None:
86
+ return None
87
+ v = str(val).strip().lower()
88
+ if v in {"female", "f", "woman", "girl"}:
89
+ return 0
90
+ if v in {"male", "m", "man", "boy"}:
91
+ return 1
92
+ return None
93
+
94
+ # 3) Save metadata (initial filtering)
95
+ is_trait_available = trait_row is not None
96
+ _ = validate_and_save_cohort_info(
97
+ is_final=False,
98
+ cohort=cohort,
99
+ info_path=json_path,
100
+ is_gene_available=is_gene_available,
101
+ is_trait_available=is_trait_available
102
+ )
103
+
104
+ # 4) Clinical feature extraction (skip because trait_row is None)
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
+ preview = preview_df(selected_clinical_df)
117
+ print(preview)
118
+
119
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
120
+ selected_clinical_df.to_csv(out_clinical_data_file)
121
+ else:
122
+ print({
123
+ "is_gene_available": is_gene_available,
124
+ "trait_row": trait_row,
125
+ "age_row": age_row,
126
+ "gender_row": gender_row
127
+ })
128
+
129
+ # Step 3: Gene Data Extraction
130
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
131
+ gene_data = get_genetic_data(matrix_file)
132
+
133
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
134
+ print(gene_data.index[:20])
135
+
136
+ # Step 4: Gene Identifier Review
137
+ # The provided identifiers (e.g., A1BG, A2M, ABCG5) are standard human gene symbols (HGNC).
138
+ requires_gene_mapping = False
139
+ print(f"requires_gene_mapping = {requires_gene_mapping}")
output/preprocess/Liver_cirrhosis/code/GSE182060.py ADDED
@@ -0,0 +1,148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Liver_cirrhosis"
6
+ cohort = "GSE182060"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Liver_cirrhosis"
10
+ in_cohort_dir = "../DATA/GEO/Liver_cirrhosis/GSE182060"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z4/preprocess/Liver_cirrhosis/GSE182060.csv"
14
+ out_gene_data_file = "./output/z4/preprocess/Liver_cirrhosis/gene_data/GSE182060.csv"
15
+ out_clinical_data_file = "./output/z4/preprocess/Liver_cirrhosis/clinical_data/GSE182060.csv"
16
+ json_path = "./output/z4/preprocess/Liver_cirrhosis/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 liver biopsy tissues
43
+
44
+ # 2) Variable availability based on provided Sample Characteristics Dictionary
45
+ # Keys present: 0: patient ID, 1: tissue (constant), 2: time_point (Baseline/Follow-up)
46
+ trait_row = None # Liver cirrhosis status not provided or inferable
47
+ age_row = None # No age field
48
+ gender_row = None # No gender field
49
+
50
+ # 2.2) Converters
51
+ def _after_colon(x):
52
+ if x is None:
53
+ return None
54
+ s = str(x)
55
+ parts = s.split(":", 1)
56
+ val = parts[1] if len(parts) == 2 else parts[0]
57
+ return val.strip()
58
+
59
+ def convert_trait(x):
60
+ """
61
+ Convert trait to binary: Liver cirrhosis -> 1, non-cirrhosis -> 0.
62
+ Only map when explicit; otherwise return None.
63
+ """
64
+ val = _after_colon(x)
65
+ if val is None or val == "":
66
+ return None
67
+ s = val.strip().lower()
68
+
69
+ # Positive indicators
70
+ pos_terms = [
71
+ "cirrhosis", "liver cirrhosis", "cirrhotic", "cirrhose", "hepatic cirrhosis",
72
+ "lc"
73
+ ]
74
+ if any(t in s for t in pos_terms):
75
+ return 1
76
+ if "f4" in s: # Metavir/Brunt F4 indicates cirrhosis
77
+ return 1
78
+
79
+ # Negative indicators
80
+ neg_terms = [
81
+ "no cirrhosis", "non-cirrhosis", "non cirrhosis", "control", "healthy", "normal"
82
+ ]
83
+ if any(t in s for t in neg_terms):
84
+ return 0
85
+ # Fibrosis stages F0-F3 imply non-cirrhosis
86
+ if re.search(r"\bf[0-3]\b", s):
87
+ return 0
88
+
89
+ # If dataset disease is NAFLD/NASH without explicit cirrhosis info, do not force 0.
90
+ return None
91
+
92
+ def convert_age(x):
93
+ """Convert age to continuous (float years)."""
94
+ val = _after_colon(x)
95
+ if val is None:
96
+ return None
97
+ s = str(val).strip().lower()
98
+ # Extract first number (integer or float)
99
+ m = re.search(r"[-+]?\d*\.?\d+", s)
100
+ if not m:
101
+ return None
102
+ try:
103
+ return float(m.group())
104
+ except Exception:
105
+ return None
106
+
107
+ def convert_gender(x):
108
+ """Convert gender to binary: female->0, male->1."""
109
+ val = _after_colon(x)
110
+ if val is None:
111
+ return None
112
+ s = str(val).strip().lower()
113
+ if s in {"f", "female", "woman", "women"}:
114
+ return 0
115
+ if s in {"m", "male", "man", "men"}:
116
+ return 1
117
+ # Handle phrases like "sex: Female"
118
+ if "female" in s:
119
+ return 0
120
+ if "male" in s:
121
+ return 1
122
+ return None
123
+
124
+ # 3) Save metadata (initial filtering)
125
+ is_trait_available = trait_row is not None
126
+ _ = validate_and_save_cohort_info(
127
+ is_final=False,
128
+ cohort=cohort,
129
+ info_path=json_path,
130
+ is_gene_available=is_gene_available,
131
+ is_trait_available=is_trait_available
132
+ )
133
+
134
+ # 4) Clinical feature extraction (skip since trait_row is None)
135
+ # If in another dataset trait_row is not None, the following would be used:
136
+ # selected_clinical_df = geo_select_clinical_features(
137
+ # clinical_df=clinical_data,
138
+ # trait=trait,
139
+ # trait_row=trait_row,
140
+ # convert_trait=convert_trait,
141
+ # age_row=age_row,
142
+ # convert_age=convert_age,
143
+ # gender_row=gender_row,
144
+ # convert_gender=convert_gender
145
+ # )
146
+ # preview = preview_df(selected_clinical_df)
147
+ # os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
148
+ # selected_clinical_df.to_csv(out_clinical_data_file)
output/preprocess/Liver_cirrhosis/code/GSE182065.py ADDED
@@ -0,0 +1,176 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Liver_cirrhosis"
6
+ cohort = "GSE182065"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Liver_cirrhosis"
10
+ in_cohort_dir = "../DATA/GEO/Liver_cirrhosis/GSE182065"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z4/preprocess/Liver_cirrhosis/GSE182065.csv"
14
+ out_gene_data_file = "./output/z4/preprocess/Liver_cirrhosis/gene_data/GSE182065.csv"
15
+ out_clinical_data_file = "./output/z4/preprocess/Liver_cirrhosis/clinical_data/GSE182065.csv"
16
+ json_path = "./output/z4/preprocess/Liver_cirrhosis/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) Determine gene expression availability based on provided background info
42
+ is_gene_available = True # Gene expression profiling of liver tissues (not miRNA/methylation)
43
+
44
+ # 2) Variable availability assessment from Sample Characteristics Dictionary
45
+ # Observed keys:
46
+ # 0: tissue (constant: Liver)
47
+ # 1: sample group (treatment/control/baseline - experimental condition, not trait/age/gender)
48
+ # 2: compound (treatments)
49
+ # 3: concentration (treatment doses)
50
+ trait_row = None # No cirrhosis status available
51
+ age_row = None # No age information available
52
+ gender_row = None # No gender information available
53
+
54
+ # 2.2) Converters
55
+ def _after_colon(x: str) -> str:
56
+ if x is None:
57
+ return ""
58
+ parts = str(x).split(":", 1)
59
+ return parts[1].strip() if len(parts) == 2 else str(x).strip()
60
+
61
+ def convert_trait(x):
62
+ s = _after_colon(x).strip().lower()
63
+ if not s or s in {"na", "n/a", "nan", "none"}:
64
+ return None
65
+
66
+ # Direct cirrhosis indications
67
+ if "cirrhosis" in s or "cirrhotic" in s:
68
+ # Non-cirrhosis phrases
69
+ if any(neg in s for neg in ["non-cirrhosis", "no cirrhosis", "noncirrhotic", "non cirrhotic"]):
70
+ return 0
71
+ return 1
72
+
73
+ # F-stage mapping if present
74
+ m = re.search(r'\bf\s*([0-4])\b', s, flags=re.IGNORECASE)
75
+ if m:
76
+ stage = int(m.group(1))
77
+ return 1 if stage == 4 else 0
78
+
79
+ # Common control/healthy indicators
80
+ if any(k in s for k in ["healthy", "control", "normal liver", "non-diseased", "non diseased"]):
81
+ return 0
82
+
83
+ # Abbreviation 'LC' for liver cirrhosis as a standalone token
84
+ tokens = re.findall(r'\b[a-zA-Z]+\b', s)
85
+ if "lc" in tokens:
86
+ return 1
87
+
88
+ return None
89
+
90
+ def convert_age(x):
91
+ s = _after_colon(x).lower()
92
+ if not s or s in {"na", "n/a", "nan", "none"}:
93
+ return None
94
+ nums = re.findall(r'\d+\.?\d*', s)
95
+ if not nums:
96
+ return None
97
+ try:
98
+ return float(nums[0])
99
+ except Exception:
100
+ return None
101
+
102
+ def convert_gender(x):
103
+ s = _after_colon(x).strip().lower()
104
+ if not s or s in {"na", "n/a", "nan", "none"}:
105
+ return None
106
+ if any(k == s or k in s.split() for k in ["female", "f", "woman", "girl", "women", "ladies"]):
107
+ return 0
108
+ if any(k == s or k in s.split() for k in ["male", "m", "man", "boy", "men", "gentleman"]):
109
+ return 1
110
+ return None
111
+
112
+ # 3) 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
+ # 4) Clinical feature extraction (skip since trait_row is None)
123
+ # If in future steps trait_row becomes available, the following snippet can be used:
124
+ # if trait_row is not None:
125
+ # selected_df = geo_select_clinical_features(
126
+ # clinical_df=clinical_data,
127
+ # trait=trait,
128
+ # trait_row=trait_row,
129
+ # convert_trait=convert_trait,
130
+ # age_row=age_row,
131
+ # convert_age=convert_age,
132
+ # gender_row=gender_row,
133
+ # convert_gender=convert_gender
134
+ # )
135
+ # preview = preview_df(selected_df)
136
+ # os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
137
+ # selected_df.to_csv(out_clinical_data_file)
138
+
139
+ # Step 3: Gene Data Extraction
140
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
141
+ gene_data = get_genetic_data(matrix_file)
142
+
143
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
144
+ print(gene_data.index[:20])
145
+
146
+ # Step 4: Gene Identifier Review
147
+ requires_gene_mapping = False
148
+ print(f"requires_gene_mapping = {requires_gene_mapping}")
149
+
150
+ # Step 5: Data Normalization and Linking
151
+ import os
152
+
153
+ # 1. Normalize the obtained gene data and save it
154
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
155
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
156
+ normalized_gene_data.to_csv(out_gene_data_file)
157
+
158
+ # Since trait data is unavailable (from Step 2), skip linking and downstream steps.
159
+ is_gene_available = True
160
+ is_trait_available = False
161
+
162
+ # 5. Conduct final quality validation and save cohort information.
163
+ note = ("INFO: Trait data unavailable in this GEO series; no age or gender annotations either. "
164
+ "Only normalized gene expression data were saved; clinical-genetic linking skipped.")
165
+ is_usable = validate_and_save_cohort_info(
166
+ is_final=True,
167
+ cohort=cohort,
168
+ info_path=json_path,
169
+ is_gene_available=is_gene_available,
170
+ is_trait_available=is_trait_available,
171
+ is_biased=False, # Placeholder; not applicable when trait is unavailable
172
+ df=normalized_gene_data.T, # Provide a dataframe for validation; samples as rows
173
+ note=note
174
+ )
175
+
176
+ # 6. Do not save linked data since trait is unavailable (is_usable will be False).
output/preprocess/Liver_cirrhosis/code/GSE185529.py ADDED
@@ -0,0 +1,368 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Liver_cirrhosis"
6
+ cohort = "GSE185529"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Liver_cirrhosis"
10
+ in_cohort_dir = "../DATA/GEO/Liver_cirrhosis/GSE185529"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z4/preprocess/Liver_cirrhosis/GSE185529.csv"
14
+ out_gene_data_file = "./output/z4/preprocess/Liver_cirrhosis/gene_data/GSE185529.csv"
15
+ out_clinical_data_file = "./output/z4/preprocess/Liver_cirrhosis/clinical_data/GSE185529.csv"
16
+ json_path = "./output/z4/preprocess/Liver_cirrhosis/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ # 1) Determine data availability based on provided background and sample characteristics
40
+ # From the sample characteristics: only "treatment: siCTRL/siBNC2" is available.
41
+ # No human trait (Liver_cirrhosis), age, or gender information is present.
42
+ is_gene_available = True # Title suggests gene expression data (not miRNA/methylation)
43
+ trait_row = None
44
+ age_row = None
45
+ gender_row = None
46
+
47
+ # 2) Define conversion functions
48
+
49
+ def _after_colon(x):
50
+ if x is None:
51
+ return None
52
+ if isinstance(x, str):
53
+ parts = x.split(":", 1)
54
+ val = parts[1].strip() if len(parts) > 1 else x.strip()
55
+ return val if val != "" else None
56
+ return None
57
+
58
+ def convert_trait(x):
59
+ # Binary: 1 = Liver cirrhosis/case, 0 = control/non-cirrhosis. Unknown -> None
60
+ val = _after_colon(x)
61
+ if val is None:
62
+ return None
63
+ v = val.lower()
64
+ # Positive indicators
65
+ positives = ["cirrhosis", "liver cirrhosis", "cirrhotic", "lc"]
66
+ if any(p in v for p in positives):
67
+ return 1
68
+ # Common fibrosis stage mapping (heuristic): F4 -> cirrhosis
69
+ if "f4" in v or "fibrosis stage 4" in v or "ishak 5" in v or "ishak 6" in v:
70
+ return 1
71
+ # Negative indicators
72
+ negatives = ["control", "normal", "healthy", "non-cirrhotic", "no cirrhosis"]
73
+ if any(n in v for n in negatives):
74
+ return 0
75
+ # If it's treatment labels or unrelated fields, return None
76
+ if "sictrl" in v or "sibnc2" in v or "treatment" in v:
77
+ return None
78
+ return None
79
+
80
+ def convert_age(x):
81
+ # Continuous: age in years as float. Unknown -> None
82
+ import re
83
+ val = _after_colon(x)
84
+ if val is None:
85
+ return None
86
+ m = re.search(r"(\d+(?:\.\d+)?)", val)
87
+ if not m:
88
+ return None
89
+ try:
90
+ age = float(m.group(1))
91
+ if 0 <= age <= 120:
92
+ return age
93
+ except Exception:
94
+ pass
95
+ return None
96
+
97
+ def convert_gender(x):
98
+ # Binary: female=0, male=1. Unknown -> None
99
+ val = _after_colon(x)
100
+ if val is None:
101
+ return None
102
+ v = val.strip().lower()
103
+ if v in ["female", "f", "woman", "women"]:
104
+ return 0
105
+ if v in ["male", "m", "man", "men"]:
106
+ return 1
107
+ if v in ["na", "n/a", "unknown", "not available", "not provided", ""]:
108
+ return None
109
+ return None
110
+
111
+ # 3) Initial filtering and save metadata
112
+ is_trait_available = trait_row is not None
113
+ _ = validate_and_save_cohort_info(
114
+ is_final=False,
115
+ cohort=cohort,
116
+ info_path=json_path,
117
+ is_gene_available=is_gene_available,
118
+ is_trait_available=is_trait_available
119
+ )
120
+
121
+ # 4) Clinical feature extraction (skip because trait_row is None)
122
+ # If trait_row were available:
123
+ # selected_clinical_df = geo_select_clinical_features(
124
+ # clinical_df=clinical_data, # assumed to be available from previous step
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
+ # preview = preview_df(selected_clinical_df)
134
+ # os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
135
+ # selected_clinical_df.to_csv(out_clinical_data_file)
136
+
137
+ # Step 3: Gene Data Extraction
138
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
139
+ gene_data = get_genetic_data(matrix_file)
140
+
141
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
142
+ print(gene_data.index[:20])
143
+
144
+ # Step 4: Gene Identifier Review
145
+ print("requires_gene_mapping = True")
146
+
147
+ # Step 5: Gene Annotation
148
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
149
+ gene_annotation = get_gene_annotation(soft_file)
150
+
151
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
152
+ print("Gene annotation preview:")
153
+ print(preview_df(gene_annotation))
154
+
155
+ # Step 6: Gene Identifier Mapping
156
+ # Gene Identifier Mapping with species-agnostic symbol extraction and explicit overlap validation
157
+
158
+ import re
159
+ import pandas as pd
160
+
161
+ ga = gene_annotation.copy()
162
+
163
+ # Ensure string dtype
164
+ ga = ga.applymap(lambda x: str(x) if pd.notnull(x) else x)
165
+
166
+ # Candidate ID columns likely present in Affymetrix platform SOFT
167
+ id_base_candidates = [
168
+ 'probeset_id', 'transcript_cluster_id', 'ID', 'ID_REF',
169
+ 'Probe Set ID', 'probe_id', 'probesetid', 'AFFYID'
170
+ ]
171
+ id_base_candidates = [c for c in id_base_candidates if c in ga.columns]
172
+ # Add other columns as fallbacks
173
+ id_base_candidates += [c for c in ga.columns if c not in id_base_candidates]
174
+
175
+ # Prepare expression index variants
176
+ expr_variants = {
177
+ "direct": gene_data,
178
+ "strip_suffix": gene_data.rename(index=lambda x: str(x).split('_')[0] if isinstance(x, str) else x)
179
+ }
180
+
181
+ # Compute overlaps to pick best ID column and index variant
182
+ best = ("direct", id_base_candidates[0] if id_base_candidates else None, 0)
183
+ for expr_name, expr_df in expr_variants.items():
184
+ expr_ids = set(expr_df.index.astype(str))
185
+ for id_col in id_base_candidates:
186
+ annot_ids = set(ga[id_col].astype(str))
187
+ overlap = len(expr_ids & annot_ids)
188
+ if overlap > best[2]:
189
+ best = (expr_name, id_col, overlap)
190
+
191
+ best_expr_name, best_id_col, best_overlap = best
192
+ expr_df_best = expr_variants[best_expr_name]
193
+
194
+ print(f"Chosen identifier column: {best_id_col}")
195
+ print(f"Expression ID handling: {best_expr_name}")
196
+ print(f"Identifier overlap count: {best_overlap}")
197
+
198
+ if best_overlap == 0:
199
+ # As a last fallback, try adding common suffixes to annotation IDs and recompute against direct expr IDs
200
+ if 'probeset_id' in ga.columns:
201
+ for suf in ['_st', '_at']:
202
+ tmp_col = f"probeset_id{suf}"
203
+ ga[tmp_col] = ga['probeset_id'].astype(str) + suf
204
+ overlap = len(set(gene_data.index.astype(str)) & set(ga[tmp_col].astype(str)))
205
+ if overlap > best_overlap:
206
+ best_overlap = overlap
207
+ best_id_col = tmp_col
208
+ best_expr_name = 'direct'
209
+ expr_df_best = expr_variants[best_expr_name]
210
+ print(f"Fallback overlap after adding suffixes: {best_overlap}")
211
+
212
+ if best_overlap == 0:
213
+ print("WARNING: No overlap between expression probe IDs and annotation IDs. Mapping may result in empty gene data.")
214
+
215
+ # Choose gene symbol column
216
+ symbol_candidates_preferred = [
217
+ 'gene_symbol', 'Gene Symbol', 'GENE_SYMBOL', 'Symbol', 'SYMBOL', 'Gene symbol', 'Gene symbols'
218
+ ]
219
+ if 'gene_assignment' in ga.columns:
220
+ gene_col = 'gene_assignment'
221
+ else:
222
+ gene_col = None
223
+ for c in symbol_candidates_preferred:
224
+ if c in ga.columns:
225
+ gene_col = c
226
+ break
227
+ if gene_col is None:
228
+ # Any column with 'symbol' substring
229
+ for c in ga.columns:
230
+ if 'symbol' in c.lower():
231
+ gene_col = c
232
+ break
233
+ # Final fallback to a verbose text column
234
+ if gene_col is None:
235
+ avg_lens = {c: ga[c].astype(str).map(len).mean() for c in ga.columns}
236
+ gene_col = max(avg_lens, key=avg_lens.get)
237
+
238
+ print(f"Chosen gene symbol source column: {gene_col}")
239
+
240
+ def parse_gene_symbols_species_agnostic(text: str):
241
+ if text is None:
242
+ return []
243
+ s = str(text).strip()
244
+ if s == '' or s == '---':
245
+ return []
246
+ # Split entries separated by '///'
247
+ parts = re.split(r'\s*///\s*', s)
248
+ symbols = []
249
+ for part in parts:
250
+ tokens = re.split(r'\s*//\s*', part)
251
+ if len(tokens) >= 2:
252
+ sym = tokens[1].strip()
253
+ # Filter out placeholders
254
+ if sym and sym != '---':
255
+ symbols.append(sym)
256
+ # If no symbols were captured via the structured pattern, fallback:
257
+ if not symbols:
258
+ # Heuristic: capture capitalized words with letters/digits/-_. This is lenient and species-agnostic.
259
+ candidates = re.findall(r'\b[A-Za-z][A-Za-z0-9._-]{1,24}\b', s)
260
+ # Remove common database tokens
261
+ blacklist = {'RefSeq', 'ENSEMBL', 'GenBank', 'ENSEMBL', 'ENSEMBL', 'ENSEMBLE', 'chr', 'chromosome', 'cdna',
262
+ 'ncrna', 'transcript', 'gene', 'biotype', 'protein_coding', 'antisense', 'mRNA', 'mus', 'musculus'}
263
+ symbols = [c for c in candidates if c not in blacklist]
264
+ # Deduplicate preserving order
265
+ seen = set()
266
+ ordered = []
267
+ for sym in symbols:
268
+ if sym not in seen:
269
+ seen.add(sym)
270
+ ordered.append(sym)
271
+ return ordered
272
+
273
+ # Build mapping DataFrame
274
+ mapping_df = ga[[best_id_col, gene_col]].dropna().copy()
275
+ mapping_df = mapping_df.rename(columns={best_id_col: 'ID', gene_col: 'Gene'})
276
+ mapping_df['ID'] = mapping_df['ID'].astype(str)
277
+
278
+ # Align mapping to expression IDs in the chosen variant
279
+ expr_ids_set = set(expr_df_best.index.astype(str))
280
+ mapping_df = mapping_df[mapping_df['ID'].isin(expr_ids_set)]
281
+
282
+ # Parse symbols to lists
283
+ mapping_df['Gene'] = mapping_df['Gene'].apply(parse_gene_symbols_species_agnostic)
284
+
285
+ # Expand multi-gene mappings and distribute expression
286
+ mapping_df['num_genes'] = mapping_df['Gene'].apply(lambda x: len(x))
287
+ mapping_df = mapping_df.explode('Gene')
288
+ mapping_df = mapping_df.dropna(subset=['Gene'])
289
+ mapping_df = mapping_df[mapping_df['num_genes'] > 0]
290
+
291
+ # Join with expression and distribute by num_genes
292
+ mapping_df = mapping_df.set_index('ID')
293
+ merged = mapping_df.join(expr_df_best, how='inner')
294
+ expr_cols = [c for c in merged.columns if c not in ['Gene', 'num_genes']]
295
+ if len(merged) == 0 or len(expr_cols) == 0:
296
+ print("WARNING: No mappings joined with expression data. Resulting gene_data may be empty.")
297
+ else:
298
+ merged[expr_cols] = merged[expr_cols].div(merged['num_genes'], axis=0)
299
+
300
+ # Sum to gene level
301
+ gene_data = merged.groupby('Gene')[expr_cols].sum()
302
+
303
+ print(f"Mapped probes to genes: {gene_data.shape[0]} genes, {gene_data.shape[1] if gene_data.shape[0]>0 else 0} samples.")
304
+
305
+ # Step 7: Data Normalization and Linking
306
+ import os
307
+ import pandas as pd
308
+
309
+ # 1) Normalize gene symbols and save normalized gene data
310
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
311
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
312
+ normalized_gene_data.to_csv(out_gene_data_file)
313
+
314
+ # 2) Link clinical and genetic data only if clinical features exist
315
+ try:
316
+ _ = selected_clinical_data # probe existence without NameError
317
+ has_clinical = isinstance(selected_clinical_data, pd.DataFrame) and not selected_clinical_data.empty
318
+ except NameError:
319
+ has_clinical = False
320
+
321
+ if has_clinical:
322
+ # Link
323
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_data, normalized_gene_data)
324
+
325
+ # 3) Handle missing values
326
+ linked_data = handle_missing_values(linked_data, trait)
327
+
328
+ # 4) Judge bias and remove biased demographic features
329
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
330
+
331
+ # 5) Final validation and save cohort info
332
+ is_gene_available = (normalized_gene_data.shape[0] > 0) and (normalized_gene_data.shape[1] > 0)
333
+ is_usable = validate_and_save_cohort_info(
334
+ is_final=True,
335
+ cohort=cohort,
336
+ info_path=json_path,
337
+ is_gene_available=is_gene_available,
338
+ is_trait_available=True,
339
+ is_biased=is_trait_biased,
340
+ df=unbiased_linked_data,
341
+ note="INFO: Clinical features present and linked."
342
+ )
343
+
344
+ # 6) Save linked data only if usable
345
+ if is_usable:
346
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
347
+ unbiased_linked_data.to_csv(out_data_file)
348
+
349
+ else:
350
+ # No clinical data available; cannot link
351
+ linked_data = pd.DataFrame()
352
+
353
+ # Final validation reflecting true state without fabricating data
354
+ df_for_validation = normalized_gene_data.T
355
+ is_gene_available = (normalized_gene_data.shape[0] > 0) and (normalized_gene_data.shape[1] > 0)
356
+
357
+ note = ("WARNING: No human trait/clinical data available; sample characteristics only show treatment labels "
358
+ "(siCTRL/siBNC2). Not suitable for trait analysis. Linked dataset not saved.")
359
+ _ = validate_and_save_cohort_info(
360
+ is_final=True,
361
+ cohort=cohort,
362
+ info_path=json_path,
363
+ is_gene_available=is_gene_available,
364
+ is_trait_available=False,
365
+ is_biased=False,
366
+ df=df_for_validation,
367
+ note=note
368
+ )
output/preprocess/Liver_cirrhosis/code/GSE212047.py ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Liver_cirrhosis"
6
+ cohort = "GSE212047"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Liver_cirrhosis"
10
+ in_cohort_dir = "../DATA/GEO/Liver_cirrhosis/GSE212047"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z4/preprocess/Liver_cirrhosis/GSE212047.csv"
14
+ out_gene_data_file = "./output/z4/preprocess/Liver_cirrhosis/gene_data/GSE212047.csv"
15
+ out_clinical_data_file = "./output/z4/preprocess/Liver_cirrhosis/clinical_data/GSE212047.csv"
16
+ json_path = "./output/z4/preprocess/Liver_cirrhosis/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ # Determine data availability based on provided background and sample characteristics
40
+ # This cohort appears to be mouse HSC samples with genetic/treatment manipulation; no human clinical variables present.
41
+
42
+ # 1) Gene expression availability (RNA-seq/microarray indicated; not miRNA/methylation-only)
43
+ is_gene_available = True
44
+
45
+ # 2) Variable availability (no human trait/age/gender in the sample characteristics; all mouse-related)
46
+ trait_row = None
47
+ age_row = None
48
+ gender_row = None
49
+
50
+ # 2.2) Conversion functions
51
+
52
+ def _extract_value(x):
53
+ if x is None:
54
+ return None
55
+ if isinstance(x, (int, float)):
56
+ return x
57
+ s = str(x).strip()
58
+ # Take text after the first colon if present
59
+ if ':' in s:
60
+ s = s.split(':', 1)[1].strip()
61
+ # Normalize common NAs
62
+ if s.lower() in {'na', 'n/a', 'none', 'null', ''}:
63
+ return None
64
+ return s
65
+
66
+ def convert_trait(x):
67
+ # Binary: presence (1) vs absence (0) of Liver cirrhosis
68
+ v = _extract_value(x)
69
+ if v is None:
70
+ return None
71
+ val = str(v).lower()
72
+ # Positive (cirrhosis present)
73
+ positives = ['cirrhosis', 'cirrhotic', 'nt cirrhotic', 'liver cirrhosis', 'alcoholic cirrhosis', 'hcv cirrhosis', 'hbv cirrhosis']
74
+ # Negative (no cirrhosis)
75
+ negatives = ['normal', 'healthy', 'control', 'non-cirrhotic', 'no cirrhosis', 'fibrosis stage 0', 'non cirrhotic']
76
+ if any(p in val for p in positives):
77
+ return 1
78
+ if any(n in val for n in negatives):
79
+ return 0
80
+ # Heuristic: advanced fibrosis often implies cirrhosis depending on context, but avoid overcalling here
81
+ if 'fibrosis' in val and any(k in val for k in ['f4', 'stage 4']):
82
+ return 1
83
+ return None
84
+
85
+ def convert_age(x):
86
+ # Continuous age in years
87
+ v = _extract_value(x)
88
+ if v is None:
89
+ return None
90
+ s = str(v).lower()
91
+ # Extract the first number in the string
92
+ import re
93
+ m = re.search(r'[-+]?\d*\.?\d+', s)
94
+ if not m:
95
+ return None
96
+ try:
97
+ age_val = float(m.group())
98
+ except Exception:
99
+ return None
100
+ # Convert from months if explicitly indicated
101
+ if 'month' in s:
102
+ age_val = age_val / 12.0
103
+ return age_val
104
+
105
+ def convert_gender(x):
106
+ # Binary: female -> 0, male -> 1
107
+ v = _extract_value(x)
108
+ if v is None:
109
+ return None
110
+ s = str(v).strip().lower()
111
+ if s in {'f', 'female', 'woman', 'girl'}:
112
+ return 0
113
+ if s in {'m', 'male', 'man', 'boy'}:
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: skipped because trait_row is None (no human clinical data available)
128
+ # If clinical data were available, we would use:
129
+ # selected_df = geo_select_clinical_features(
130
+ # clinical_df=clinical_data, trait=trait, trait_row=trait_row,
131
+ # convert_trait=convert_trait, age_row=age_row, convert_age=convert_age,
132
+ # gender_row=gender_row, convert_gender=convert_gender
133
+ # )
134
+ # preview = preview_df(selected_df)
135
+ # os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
136
+ # selected_df.to_csv(out_clinical_data_file)
output/preprocess/Liver_cirrhosis/code/GSE285291.py ADDED
@@ -0,0 +1,178 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Liver_cirrhosis"
6
+ cohort = "GSE285291"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Liver_cirrhosis"
10
+ in_cohort_dir = "../DATA/GEO/Liver_cirrhosis/GSE285291"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z4/preprocess/Liver_cirrhosis/GSE285291.csv"
14
+ out_gene_data_file = "./output/z4/preprocess/Liver_cirrhosis/gene_data/GSE285291.csv"
15
+ out_clinical_data_file = "./output/z4/preprocess/Liver_cirrhosis/clinical_data/GSE285291.csv"
16
+ json_path = "./output/z4/preprocess/Liver_cirrhosis/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ import os
40
+ import pandas as pd
41
+ import numpy as np
42
+ import re
43
+
44
+ # 1) Gene expression data availability
45
+ is_gene_available = True # mRNA gene expression from intestinal biopsies (not miRNA/methylation)
46
+
47
+ # 2) Variable availability and conversion functions
48
+
49
+ # Trait: Liver cirrhosis presence inferred from "status": Control vs Compensated/Decompensated
50
+ trait_row = 1 # 'status' field
51
+ age_row = None # Not provided; "age-matched" implies no per-sample ages
52
+ gender_row = None # All men per background => constant => not usable
53
+
54
+ def _after_colon(value):
55
+ if value is None or (isinstance(value, float) and np.isnan(value)):
56
+ return None
57
+ s = str(value)
58
+ if ':' in s:
59
+ s = s.split(':', 1)[1]
60
+ return s.strip() if s is not None else None
61
+
62
+ def convert_trait(value):
63
+ v = _after_colon(value)
64
+ if v is None:
65
+ return None
66
+ vlow = v.lower()
67
+ if vlow in {"compensated", "decompensated"}:
68
+ return 1 # cirrhosis present
69
+ if vlow in {"control", "healthy control", "healthy"}:
70
+ return 0 # no cirrhosis
71
+ return None
72
+
73
+ def convert_age(value):
74
+ # Not available in this dataset; keep as None if ever called
75
+ v = _after_colon(value)
76
+ if v is None:
77
+ return None
78
+ # Try to extract a number if any
79
+ m = re.search(r'(\d+(\.\d+)?)', v)
80
+ if m:
81
+ try:
82
+ return float(m.group(1))
83
+ except Exception:
84
+ return None
85
+ return None
86
+
87
+ def convert_gender(value):
88
+ # Not available here, but implement standard mapping if ever called
89
+ v = _after_colon(value)
90
+ if v is None:
91
+ return None
92
+ vlow = v.lower()
93
+ if vlow in {"male", "m"}:
94
+ return 1
95
+ if vlow in {"female", "f"}:
96
+ return 0
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 (only if trait data available)
110
+ if trait_row is not None:
111
+ selected_clinical_df = geo_select_clinical_features(
112
+ clinical_df=clinical_data,
113
+ trait=trait,
114
+ trait_row=trait_row,
115
+ convert_trait=convert_trait,
116
+ age_row=age_row,
117
+ convert_age=convert_age,
118
+ gender_row=gender_row,
119
+ convert_gender=convert_gender
120
+ )
121
+ preview = preview_df(selected_clinical_df)
122
+ print("Clinical features preview:", 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
+ # Based on the observed identifiers (e.g., A2M, AADAT, AANAT, ABCB7, ABL1), these are standard human gene symbols (HGNC).
136
+ requires_gene_mapping = False
137
+ print(f"requires_gene_mapping = {requires_gene_mapping}")
138
+
139
+ # Step 5: Data Normalization and Linking
140
+ import os
141
+ import pandas as pd
142
+
143
+ # 1. Normalize gene symbols and save
144
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
145
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
146
+ normalized_gene_data.to_csv(out_gene_data_file)
147
+
148
+ # Ensure clinical features are available in-memory (fallback to disk if needed)
149
+ if 'selected_clinical_df' not in locals():
150
+ selected_clinical_df = pd.read_csv(out_clinical_data_file, index_col=0)
151
+
152
+ # 2. Link the clinical and genetic data
153
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
154
+
155
+ # 3. Handle missing values in the linked data
156
+ linked_data = handle_missing_values(linked_data, trait)
157
+
158
+ # 4. Determine whether the trait and demographic features are severely biased; remove biased demographics
159
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
160
+
161
+ # 5. Final validation and save cohort information
162
+ note = ("INFO: All subjects are male per series description; per-sample age not provided. "
163
+ "No gender/age covariates included. Gene IDs were already HGNC symbols; normalized via synonyms.")
164
+ is_usable = validate_and_save_cohort_info(
165
+ is_final=True,
166
+ cohort=cohort,
167
+ info_path=json_path,
168
+ is_gene_available=True,
169
+ is_trait_available=True,
170
+ is_biased=is_trait_biased,
171
+ df=unbiased_linked_data,
172
+ note=note
173
+ )
174
+
175
+ # 6. Save the linked dataset if usable
176
+ if is_usable:
177
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
178
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Liver_cirrhosis/code/GSE66843.py ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Liver_cirrhosis"
6
+ cohort = "GSE66843"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Liver_cirrhosis"
10
+ in_cohort_dir = "../DATA/GEO/Liver_cirrhosis/GSE66843"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z4/preprocess/Liver_cirrhosis/GSE66843.csv"
14
+ out_gene_data_file = "./output/z4/preprocess/Liver_cirrhosis/gene_data/GSE66843.csv"
15
+ out_clinical_data_file = "./output/z4/preprocess/Liver_cirrhosis/clinical_data/GSE66843.csv"
16
+ json_path = "./output/z4/preprocess/Liver_cirrhosis/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ # Determine data availability based on provided background info
40
+ # This is a cell-line SuperSeries (Huh7.5.1) with infection/time-post-infection metadata; no human clinical traits.
41
+ is_gene_available = True # Likely gene expression profiling (not pure miRNA/methylation based on context)
42
+ trait_row = None # Liver_cirrhosis not recorded in this cell-line dataset
43
+ age_row = None # No human age
44
+ gender_row = None # No human gender
45
+
46
+ # Conversion functions (kept robust though not used since rows are None)
47
+ def _extract_after_colon(x):
48
+ if x is None:
49
+ return None
50
+ if isinstance(x, str):
51
+ parts = x.split(":", 1)
52
+ val = parts[1].strip() if len(parts) > 1 else x.strip()
53
+ return val if val not in {"", "NA", "N/A", "na"} else None
54
+ return x
55
+
56
+ def convert_trait(x):
57
+ # No Liver_cirrhosis information in this dataset
58
+ return None
59
+
60
+ def convert_age(x):
61
+ val = _extract_after_colon(x)
62
+ if val is None:
63
+ return None
64
+ # Attempt to parse numeric age if ever encountered
65
+ try:
66
+ return float(val)
67
+ except Exception:
68
+ return None
69
+
70
+ def convert_gender(x):
71
+ val = _extract_after_colon(x)
72
+ if val is None:
73
+ return None
74
+ v = val.strip().lower()
75
+ if v in {"female", "f", "woman", "women"}:
76
+ return 0
77
+ if v in {"male", "m", "man", "men"}:
78
+ return 1
79
+ return None
80
+
81
+ # Initial filtering and save cohort metadata
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
+ # Clinical feature extraction is skipped because trait_row is None
92
+
93
+ # Step 3: Gene Data Extraction
94
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
95
+ gene_data = get_genetic_data(matrix_file)
96
+
97
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
98
+ print(gene_data.index[:20])
99
+
100
+ # Step 4: Gene Identifier Review
101
+ # ILMN_* identifiers are Illumina probe IDs, not human gene symbols
102
+ requires_gene_mapping = True
103
+ print(f"requires_gene_mapping = {requires_gene_mapping}")
104
+
105
+ # Step 5: Gene Annotation
106
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
107
+ gene_annotation = get_gene_annotation(soft_file)
108
+
109
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
110
+ print("Gene annotation preview:")
111
+ print(preview_df(gene_annotation))
112
+
113
+ # Step 6: Gene Identifier Mapping
114
+ # Identify appropriate columns in the annotation for probe IDs and gene symbols
115
+ prob_col = 'ID' # Matches ILMN_* probe IDs in gene_data
116
+ gene_col = 'Symbol' # Contains gene symbols (may include multiple/complex entries)
117
+
118
+ # Build the mapping dataframe
119
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=prob_col, gene_col=gene_col)
120
+
121
+ # Apply mapping to convert probe-level data to gene-level expression
122
+ gene_data = apply_gene_mapping(gene_data, mapping_df)
123
+
124
+ # Step 7: Data Normalization and Linking
125
+ # 1. Normalize gene symbols and save gene-level data
126
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
127
+ normalized_gene_data.to_csv(out_gene_data_file)
128
+
129
+ # Guard: this cohort lacks human clinical trait/covariates (cell-line dataset in Step 2)
130
+ has_selected_clinical = ('selected_clinical_data' in globals()) or ('selected_clinical_data' in locals())
131
+ has_trait_row = ('trait_row' in globals()) or ('trait_row' in locals())
132
+ trait_available = has_trait_row and (trait_row is not None)
133
+
134
+ if trait_available and has_selected_clinical:
135
+ # 2-4. Link, handle missing values, and bias checks
136
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_data, normalized_gene_data)
137
+ linked_data = handle_missing_values(linked_data, trait)
138
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
139
+
140
+ # 5. Final validation and save cohort info
141
+ note = "INFO: Trait and covariates available; linked data processed with QC."
142
+ is_usable = validate_and_save_cohort_info(
143
+ True, cohort, json_path, True, True, is_trait_biased, unbiased_linked_data, note
144
+ )
145
+
146
+ # 6. Save linked data if usable
147
+ if is_usable:
148
+ unbiased_linked_data.to_csv(out_data_file)
149
+ else:
150
+ # No clinical trait available; skip linking and downstream trait-dependent processing.
151
+ linked_data = None
152
+ note = "INFO: Cell-line dataset without human clinical trait/covariates; only gene expression saved."
153
+ # Provide a non-empty placeholder df for final validation to avoid abnormality override
154
+ _ = validate_and_save_cohort_info(
155
+ True, cohort, json_path, True, False, False, normalized_gene_data.T, note
156
+ )
output/preprocess/Liver_cirrhosis/code/GSE85550.py ADDED
@@ -0,0 +1,220 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Liver_cirrhosis"
6
+ cohort = "GSE85550"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Liver_cirrhosis"
10
+ in_cohort_dir = "../DATA/GEO/Liver_cirrhosis/GSE85550"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z4/preprocess/Liver_cirrhosis/GSE85550.csv"
14
+ out_gene_data_file = "./output/z4/preprocess/Liver_cirrhosis/gene_data/GSE85550.csv"
15
+ out_clinical_data_file = "./output/z4/preprocess/Liver_cirrhosis/clinical_data/GSE85550.csv"
16
+ json_path = "./output/z4/preprocess/Liver_cirrhosis/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ import re
40
+
41
+ # 1) Gene expression availability
42
+ is_gene_available = True # Matrix file parsed; dataset likely contains gene expression (not miRNA-only or methylation-only)
43
+
44
+ # 2) Variable availability based on Sample Characteristics Dictionary
45
+ # Keys: 0 -> patient IDs (unique per sample), 1 -> tissue (constant), 2 -> time_point (Baseline/Follow-up)
46
+ # No disease status (cirrhosis), age, or gender fields available.
47
+ trait_row = None
48
+ age_row = None
49
+ gender_row = None
50
+
51
+ # 2.2) Conversion functions
52
+ def _extract_value(cell):
53
+ if cell is None:
54
+ return None
55
+ s = str(cell)
56
+ return s.split(":", 1)[1].strip() if ":" in s else s.strip()
57
+
58
+ def convert_trait(cell):
59
+ v = _extract_value(cell)
60
+ if v is None:
61
+ return None
62
+ v_low = v.lower()
63
+
64
+ # Map explicit disease/control mentions
65
+ positive_terms = [
66
+ 'cirrhosis', 'cirrhotic', 'liver cirrhosis'
67
+ ]
68
+ negative_terms = [
69
+ 'control', 'healthy', 'normal', 'non-cirrhotic', 'non cirrhotic', 'no cirrhosis'
70
+ ]
71
+ if any(t in v_low for t in positive_terms):
72
+ return 1
73
+ if any(t in v_low for t in negative_terms):
74
+ return 0
75
+
76
+ # Time-point or unrelated fields should not be used as trait
77
+ if v_low in {'baseline', 'follow-up', 'follow up', 'liver biopsy', 'biopsy'}:
78
+ return None
79
+
80
+ return None
81
+
82
+ def convert_age(cell):
83
+ v = _extract_value(cell)
84
+ if v is None:
85
+ return None
86
+ v_low = v.lower()
87
+ if v_low in {'na', 'n/a', 'unknown', ''}:
88
+ return None
89
+ # Extract a numeric age; accept integers or decimals
90
+ m = re.search(r'(\d+(\.\d+)?)', v_low)
91
+ if m:
92
+ try:
93
+ return float(m.group(1))
94
+ except Exception:
95
+ return None
96
+ return None
97
+
98
+ def convert_gender(cell):
99
+ v = _extract_value(cell)
100
+ if v is None:
101
+ return None
102
+ v_low = v.lower()
103
+ # Standard mappings
104
+ if v_low in {'male', 'm'}:
105
+ return 1
106
+ if v_low in {'female', 'f'}:
107
+ return 0
108
+ # Unknowns
109
+ if v_low in {'na', 'n/a', 'unknown', ''}:
110
+ return None
111
+ return None
112
+
113
+ # 3) Save metadata (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 (skip because trait_row is None)
124
+ # If clinical features were available, we would call:
125
+ # selected_clinical_df = geo_select_clinical_features(
126
+ # clinical_df=clinical_data,
127
+ # trait=trait,
128
+ # trait_row=trait_row,
129
+ # convert_trait=convert_trait,
130
+ # age_row=age_row,
131
+ # convert_age=convert_age,
132
+ # gender_row=gender_row,
133
+ # convert_gender=convert_gender
134
+ # )
135
+ # preview = preview_df(selected_clinical_df)
136
+ # selected_clinical_df.to_csv(out_clinical_data_file)
137
+
138
+ # Step 3: Gene Data Extraction
139
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
140
+ gene_data = get_genetic_data(matrix_file)
141
+
142
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
143
+ print(gene_data.index[:20])
144
+
145
+ # Step 4: Gene Identifier Review
146
+ print("requires_gene_mapping = False")
147
+
148
+ # Step 5: Data Normalization and Linking
149
+ import os
150
+
151
+ # 1. Normalize gene symbols and save gene expression data
152
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
153
+
154
+ # Ensure output directory exists before saving
155
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
156
+ normalized_gene_data.to_csv(out_gene_data_file)
157
+
158
+ # Robust detection of trait availability
159
+ trait_row = None if 'trait_row' not in globals() else trait_row
160
+ age_row = None if 'age_row' not in globals() else age_row
161
+ gender_row = None if 'gender_row' not in globals() else gender_row
162
+ is_trait_available = (trait_row is not None)
163
+
164
+ if is_trait_available:
165
+ # 2. Extract clinical features
166
+ selected_clinical_data = geo_select_clinical_features(
167
+ clinical_df=clinical_data,
168
+ trait=trait,
169
+ trait_row=trait_row,
170
+ convert_trait=convert_trait,
171
+ age_row=age_row,
172
+ convert_age=convert_age,
173
+ gender_row=gender_row,
174
+ convert_gender=convert_gender
175
+ )
176
+ # Save clinical data
177
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
178
+ selected_clinical_data.to_csv(out_clinical_data_file)
179
+
180
+ # 2. Link the clinical and genetic data
181
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_data, normalized_gene_data)
182
+
183
+ # 3. Handle missing values
184
+ linked_data = handle_missing_values(linked_data, trait)
185
+
186
+ # 4. Bias checks and removal of biased demographic features
187
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
188
+
189
+ # 5. Final validation and save metadata
190
+ is_usable = validate_and_save_cohort_info(
191
+ is_final=True,
192
+ cohort=cohort,
193
+ info_path=json_path,
194
+ is_gene_available=True,
195
+ is_trait_available=True,
196
+ is_biased=is_trait_biased,
197
+ df=unbiased_linked_data,
198
+ note="INFO: Linked clinical-genetic data processed with missing value handling and bias checks."
199
+ )
200
+
201
+ # 6. Save linked data only if usable
202
+ if is_usable:
203
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
204
+ unbiased_linked_data.to_csv(out_data_file)
205
+
206
+ else:
207
+ # Trait not available: skip linking and downstream steps; record final metadata
208
+ is_usable = validate_and_save_cohort_info(
209
+ is_final=True,
210
+ cohort=cohort,
211
+ info_path=json_path,
212
+ is_gene_available=True,
213
+ is_trait_available=False,
214
+ is_biased=False, # Not applicable without trait; placeholder
215
+ df=normalized_gene_data,
216
+ note=("INFO: Trait data not available in clinical annotations for this cohort "
217
+ "(only patient ID, tissue=liver biopsy, time_point). Gene expression saved; "
218
+ "linked data not generated.")
219
+ )
220
+ # Do not save out_data_file when trait is unavailable
output/preprocess/Liver_cirrhosis/code/TCGA.py ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Liver_cirrhosis"
6
+
7
+ # Input paths
8
+ tcga_root_dir = "../DATA/TCGA"
9
+
10
+ # Output paths
11
+ out_data_file = "./output/z4/preprocess/Liver_cirrhosis/TCGA.csv"
12
+ out_gene_data_file = "./output/z4/preprocess/Liver_cirrhosis/gene_data/TCGA.csv"
13
+ out_clinical_data_file = "./output/z4/preprocess/Liver_cirrhosis/clinical_data/TCGA.csv"
14
+ json_path = "./output/z4/preprocess/Liver_cirrhosis/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 Liver_cirrhosis
22
+ all_dirs = [d for d in os.listdir(tcga_root_dir) if os.path.isdir(os.path.join(tcga_root_dir, d))]
23
+ selected_dir = None
24
+ # Prioritize explicit liver cancer cohort (LIHC), then general liver mentions
25
+ priority_keys = ['lihc', 'liver']
26
+ candidates = [d for d in all_dirs if any(k in d.lower() for k in priority_keys)]
27
+ if candidates:
28
+ lihc = [d for d in candidates if 'lihc' in d.lower()]
29
+ selected_dir = lihc[0] if lihc else candidates[0]
30
+
31
+ if selected_dir is None:
32
+ # No suitable cohort found; mark as unavailable and stop further loading
33
+ validate_and_save_cohort_info(
34
+ is_final=False,
35
+ cohort="TCGA",
36
+ info_path=json_path,
37
+ is_gene_available=False,
38
+ is_trait_available=False
39
+ )
40
+ print("No suitable TCGA cohort directory found for the trait. Skipping.")
41
+ clinical_df = pd.DataFrame()
42
+ genetic_df = pd.DataFrame()
43
+ else:
44
+ cohort_dir = os.path.join(tcga_root_dir, selected_dir)
45
+ # Find clinical and genetic file paths
46
+ clinical_file_path, genetic_file_path = tcga_get_relevant_filepaths(cohort_dir)
47
+
48
+ # Load dataframes
49
+ clinical_df = pd.read_csv(clinical_file_path, sep='\t', index_col=0, compression='infer', low_memory=False)
50
+ genetic_df = pd.read_csv(genetic_file_path, sep='\t', index_col=0, compression='infer', low_memory=False)
51
+
52
+ # Print clinical column names for inspection
53
+ print(clinical_df.columns.tolist())
54
+
55
+ # Step 2: Find Candidate Demographic Features
56
+ import os
57
+ import re
58
+ import pandas as pd
59
+
60
+ # Identify cohort directory (prefer LIHC for liver cancer)
61
+ cohort_dirs = [d for d in os.listdir(tcga_root_dir) if os.path.isdir(os.path.join(tcga_root_dir, d))]
62
+ preferred = [d for d in cohort_dirs if d.upper() == "LIHC"]
63
+ if preferred:
64
+ cohort_dir = os.path.join(tcga_root_dir, preferred[0])
65
+ else:
66
+ # fallback: pick first dir containing 'LIHC', else the first available dir
67
+ contains = [d for d in cohort_dirs if "LIHC" in d.upper()]
68
+ cohort_dir = os.path.join(tcga_root_dir, (contains[0] if contains else cohort_dirs[0]))
69
+
70
+ clinical_file_path, _ = tcga_get_relevant_filepaths(cohort_dir)
71
+
72
+ # Load clinical data (TCGA Xena clinicalMatrix is tab-delimited with samples as index)
73
+ clinical_df = pd.read_csv(clinical_file_path, sep='\t', header=0, index_col=0)
74
+
75
+ # Find candidate demographic columns with token-level matching to avoid false positives (e.g., "stage")
76
+ def tokenize(col_name: str):
77
+ return [tok for tok in re.split(r'[^a-z]+', col_name.lower()) if tok]
78
+
79
+ tokens_map = {col: tokenize(col) for col in clinical_df.columns}
80
+
81
+ candidate_age_cols = []
82
+ candidate_gender_cols = []
83
+
84
+ for col, toks in tokens_map.items():
85
+ if ('age' in toks) or ('birth' in toks):
86
+ candidate_age_cols.append(col)
87
+ if ('gender' in toks) or ('sex' in toks):
88
+ candidate_gender_cols.append(col)
89
+
90
+ # Deduplicate while preserving order
91
+ def dedup(seq):
92
+ seen = set()
93
+ out = []
94
+ for x in seq:
95
+ if x not in seen:
96
+ out.append(x)
97
+ seen.add(x)
98
+ return out
99
+
100
+ candidate_age_cols = dedup(candidate_age_cols)
101
+ candidate_gender_cols = dedup(candidate_gender_cols)
102
+
103
+ # Print required lists in strict format
104
+ print(f"candidate_age_cols = {candidate_age_cols}")
105
+ print(f"candidate_gender_cols = {candidate_gender_cols}")
106
+
107
+ # Preview extracted candidate columns
108
+ age_cols_present = [c for c in candidate_age_cols if c in clinical_df.columns]
109
+ gender_cols_present = [c for c in candidate_gender_cols if c in clinical_df.columns]
110
+
111
+ age_preview = preview_df(clinical_df[age_cols_present]) if age_cols_present else {}
112
+ gender_preview = preview_df(clinical_df[gender_cols_present]) if gender_cols_present else {}
113
+
114
+ print(age_preview)
115
+ print(gender_preview)
116
+
117
+ # Step 3: Select Demographic Features
118
+ # Select the most appropriate columns for age and gender based on candidate previews
119
+ age_col = None
120
+ gender_col = None
121
+
122
+ # Prefer age in years over days_to_birth
123
+ if 'age_at_initial_pathologic_diagnosis' in candidate_age_cols:
124
+ age_col = 'age_at_initial_pathologic_diagnosis'
125
+ elif candidate_age_cols:
126
+ # Fallback to the first available candidate if needed
127
+ age_col = candidate_age_cols[0]
128
+
129
+ # Gender column appears clean and meaningful
130
+ if 'gender' in candidate_gender_cols:
131
+ gender_col = 'gender'
132
+ elif candidate_gender_cols:
133
+ gender_col = candidate_gender_cols[0]
134
+
135
+ print(f"Selected age_col: {age_col}")
136
+ print(f"Selected gender_col: {gender_col}")
137
+
138
+ # Step 4: Feature Engineering and Validation
139
+ import os
140
+
141
+ # 1) Extract and standardize clinical features (trait, Age, Gender)
142
+ selected_clinical_df = tcga_select_clinical_features(
143
+ clinical_df=clinical_df,
144
+ trait=trait,
145
+ age_col=age_col,
146
+ gender_col=gender_col
147
+ )
148
+
149
+ # 2) Normalize gene symbols using NCBI synonym mapping and save
150
+ gene_df_norm = normalize_gene_symbols_in_index(genetic_df.copy())
151
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
152
+ gene_df_norm.to_csv(out_gene_data_file)
153
+
154
+ # 3) Link clinical and genetic data on sample IDs
155
+ linked_data = selected_clinical_df.join(gene_df_norm.T, how='inner')
156
+
157
+ # 4) Handle missing values systematically
158
+ linked_data_clean = handle_missing_values(linked_data, trait_col=trait)
159
+
160
+ # 5) Determine bias in trait and demographics; drop biased demographics
161
+ trait_biased, linked_data_clean = judge_and_remove_biased_features(linked_data_clean, trait)
162
+
163
+ # 6) Final validation and save cohort info
164
+ # Cast to native Python bool to avoid potential JSON serialization issues
165
+ is_gene_available = bool((gene_df_norm.shape[0] > 0) and (gene_df_norm.shape[1] > 0))
166
+ is_trait_available = bool((trait in linked_data_clean.columns) and linked_data_clean[trait].notna().any())
167
+
168
+ note = (
169
+ "INFO: TCGA LIHC cohort processed. Trait derived from TCGA sample barcode (tumor=01-09, normal=10-19). "
170
+ "Gene symbols normalized via NCBI synonyms; unmapped symbols removed; duplicates averaged."
171
+ )
172
+
173
+ try:
174
+ is_usable = validate_and_save_cohort_info(
175
+ is_final=True,
176
+ cohort="TCGA",
177
+ info_path=json_path,
178
+ is_gene_available=is_gene_available,
179
+ is_trait_available=is_trait_available,
180
+ is_biased=bool(trait_biased),
181
+ df=linked_data_clean,
182
+ note=note
183
+ )
184
+ except TypeError:
185
+ # If existing JSON contains non-serializable types from previous runs, reset and retry
186
+ if os.path.exists(json_path):
187
+ os.remove(json_path)
188
+ is_usable = validate_and_save_cohort_info(
189
+ is_final=True,
190
+ cohort="TCGA",
191
+ info_path=json_path,
192
+ is_gene_available=is_gene_available,
193
+ is_trait_available=is_trait_available,
194
+ is_biased=bool(trait_biased),
195
+ df=linked_data_clean,
196
+ note=note
197
+ )
198
+
199
+ # 7) Save linked data only if usable
200
+ if bool(is_usable):
201
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
202
+ linked_data_clean.to_csv(out_data_file)