Liu-Hy commited on
Commit
dc810d0
·
verified ·
1 Parent(s): d0e1f33

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +13 -0
  2. p1/preprocess/Pheochromocytoma_and_Paraganglioma/gene_data/TCGA.csv +3 -0
  3. p1/preprocess/Polycystic_Ovary_Syndrome/gene_data/TCGA.csv +3 -0
  4. p1/preprocess/Prostate_Cancer/gene_data/GSE201805.csv +3 -0
  5. p1/preprocess/Prostate_Cancer/gene_data/GSE209954.csv +3 -0
  6. p1/preprocess/Psoriatic_Arthritis/GSE57386.csv +3 -0
  7. p1/preprocess/Psoriatic_Arthritis/gene_data/GSE57383.csv +3 -0
  8. p1/preprocess/Psoriatic_Arthritis/gene_data/GSE57386.csv +3 -0
  9. p1/preprocess/Psoriatic_Arthritis/gene_data/GSE57405.csv +3 -0
  10. p1/preprocess/Psoriatic_Arthritis/gene_data/GSE61281.csv +3 -0
  11. p1/preprocess/Rectal_Cancer/GSE123390.csv +3 -0
  12. p1/preprocess/Rectal_Cancer/gene_data/GSE123390.csv +3 -0
  13. p1/preprocess/Rectal_Cancer/gene_data/TCGA.csv +3 -0
  14. p1/preprocess/Retinoblastoma/GSE208143.csv +0 -0
  15. p1/preprocess/Retinoblastoma/code/GSE63529.py +194 -0
  16. p1/preprocess/Retinoblastoma/code/GSE68950.py +67 -0
  17. p1/preprocess/Retinoblastoma/code/TCGA.py +72 -0
  18. p1/preprocess/Retinoblastoma/gene_data/GSE110811.csv +1 -0
  19. p1/preprocess/Retinoblastoma/gene_data/GSE208143.csv +0 -0
  20. p1/preprocess/Retinoblastoma/gene_data/GSE58780.csv +14 -0
  21. p1/preprocess/Rheumatoid_Arthritis/GSE121894.csv +0 -0
  22. p1/preprocess/Rheumatoid_Arthritis/clinical_data/GSE121894.csv +2 -0
  23. p1/preprocess/Rheumatoid_Arthritis/clinical_data/GSE236924.csv +2 -0
  24. p1/preprocess/Rheumatoid_Arthritis/code/GSE121894.py +171 -0
  25. p1/preprocess/Rheumatoid_Arthritis/code/GSE140161.py +96 -0
  26. p1/preprocess/Rheumatoid_Arthritis/code/GSE143153.py +167 -0
  27. p1/preprocess/Rheumatoid_Arthritis/code/GSE176440.py +126 -0
  28. p1/preprocess/Rheumatoid_Arthritis/code/GSE186963.py +69 -0
  29. p1/preprocess/Rheumatoid_Arthritis/code/GSE224330.py +107 -0
  30. p1/preprocess/Rheumatoid_Arthritis/code/GSE224842.py +157 -0
  31. p1/preprocess/Rheumatoid_Arthritis/code/GSE236924.py +165 -0
  32. p1/preprocess/Rheumatoid_Arthritis/code/GSE42842.py +158 -0
  33. p1/preprocess/Rheumatoid_Arthritis/code/GSE97475.py +159 -0
  34. p1/preprocess/Rheumatoid_Arthritis/code/TCGA.py +61 -0
  35. p1/preprocess/Rheumatoid_Arthritis/cohort_info.json +1 -0
  36. p1/preprocess/Rheumatoid_Arthritis/gene_data/GSE121894.csv +0 -0
  37. p1/preprocess/Rheumatoid_Arthritis/gene_data/GSE143153.csv +0 -0
  38. p1/preprocess/Rheumatoid_Arthritis/gene_data/GSE176440.csv +3 -0
  39. p1/preprocess/Rheumatoid_Arthritis/gene_data/GSE224842.csv +0 -0
  40. p1/preprocess/Rheumatoid_Arthritis/gene_data/GSE42842.csv +0 -0
  41. p1/preprocess/Sarcoma/clinical_data/GSE197147.csv +2 -0
  42. p1/preprocess/Sarcoma/code/GSE118336.py +251 -0
  43. p1/preprocess/Sarcoma/code/GSE133228.py +247 -0
  44. p1/preprocess/Sarcoma/code/GSE142162.py +235 -0
  45. p1/preprocess/Sarcoma/code/GSE159847.py +237 -0
  46. p1/preprocess/Sarcoma/code/GSE159848.py +234 -0
  47. p1/preprocess/Sarcoma/code/GSE162785.py +218 -0
  48. p1/preprocess/Sarcoma/code/GSE162789.py +245 -0
  49. p1/preprocess/Sarcoma/code/GSE197147.py +244 -0
  50. p1/preprocess/Sarcoma/code/GSE215265.py +218 -0
.gitattributes CHANGED
@@ -819,3 +819,16 @@ p1/preprocess/Post-Traumatic_Stress_Disorder/gene_data/GSE77164.csv filter=lfs d
819
  p1/preprocess/Psoriatic_Arthritis/gene_data/GSE142049.csv filter=lfs diff=lfs merge=lfs -text
820
  p1/preprocess/Psoriatic_Arthritis/GSE57405.csv filter=lfs diff=lfs merge=lfs -text
821
  p1/preprocess/Psoriatic_Arthritis/GSE57383.csv filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
819
  p1/preprocess/Psoriatic_Arthritis/gene_data/GSE142049.csv filter=lfs diff=lfs merge=lfs -text
820
  p1/preprocess/Psoriatic_Arthritis/GSE57405.csv filter=lfs diff=lfs merge=lfs -text
821
  p1/preprocess/Psoriatic_Arthritis/GSE57383.csv filter=lfs diff=lfs merge=lfs -text
822
+ p1/preprocess/Pheochromocytoma_and_Paraganglioma/gene_data/TCGA.csv filter=lfs diff=lfs merge=lfs -text
823
+ p1/preprocess/Prostate_Cancer/gene_data/GSE201805.csv filter=lfs diff=lfs merge=lfs -text
824
+ p1/preprocess/Psoriatic_Arthritis/gene_data/GSE61281.csv filter=lfs diff=lfs merge=lfs -text
825
+ p1/preprocess/Psoriatic_Arthritis/gene_data/GSE57383.csv filter=lfs diff=lfs merge=lfs -text
826
+ p1/preprocess/Rectal_Cancer/GSE123390.csv filter=lfs diff=lfs merge=lfs -text
827
+ p1/preprocess/Rectal_Cancer/gene_data/GSE123390.csv filter=lfs diff=lfs merge=lfs -text
828
+ p1/preprocess/Psoriatic_Arthritis/gene_data/GSE57405.csv filter=lfs diff=lfs merge=lfs -text
829
+ p1/preprocess/Psoriatic_Arthritis/GSE57386.csv filter=lfs diff=lfs merge=lfs -text
830
+ p1/preprocess/Prostate_Cancer/gene_data/GSE209954.csv filter=lfs diff=lfs merge=lfs -text
831
+ p1/preprocess/Rheumatoid_Arthritis/gene_data/GSE176440.csv filter=lfs diff=lfs merge=lfs -text
832
+ p1/preprocess/Psoriatic_Arthritis/gene_data/GSE57386.csv filter=lfs diff=lfs merge=lfs -text
833
+ p1/preprocess/Rectal_Cancer/gene_data/TCGA.csv filter=lfs diff=lfs merge=lfs -text
834
+ p1/preprocess/Polycystic_Ovary_Syndrome/gene_data/TCGA.csv filter=lfs diff=lfs merge=lfs -text
p1/preprocess/Pheochromocytoma_and_Paraganglioma/gene_data/TCGA.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:50743253caf86c00a769b96dfc543360e8b698cd87bf7a01f7003146b0905eb3
3
+ size 56096085
p1/preprocess/Polycystic_Ovary_Syndrome/gene_data/TCGA.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:87c7ae68cbb62da7726269fe4222c37575196fe8d616269cc193a4fe3a221faa
3
+ size 92186237
p1/preprocess/Prostate_Cancer/gene_data/GSE201805.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:19050cf97f73f9a2ce0ce19ddefe0bac2ba8a1748e81d90eab25f14c1820789d
3
+ size 46209433
p1/preprocess/Prostate_Cancer/gene_data/GSE209954.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:df6182c80734d527c4b65512074fb9a8c2cefe6cc380417a4c8b03cab839f53a
3
+ size 64018950
p1/preprocess/Psoriatic_Arthritis/GSE57386.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c9868fda17d369acce43f91d3eac7157f8f2ff4584f5b747837e615bf9b7a586
3
+ size 42400147
p1/preprocess/Psoriatic_Arthritis/gene_data/GSE57383.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6ec05d318d22b1d3f60ee19660c904b9954642af767206cc9dfa928cd63549b7
3
+ size 18661804
p1/preprocess/Psoriatic_Arthritis/gene_data/GSE57386.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9fc7e6c2a6f2d33555aaf0a8230da005ce80bb6674656e3b47a551c330d5c905
3
+ size 42399111
p1/preprocess/Psoriatic_Arthritis/gene_data/GSE57405.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b5765d69f9ced754d3f6d1541dea546c8823b21bcbbbff4382fd5f4e55f67333
3
+ size 18544472
p1/preprocess/Psoriatic_Arthritis/gene_data/GSE61281.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a1fdcb361e711da735fc7e9d1c933a95412fe72dde0d9dceeda3c0d6a2701f27
3
+ size 12822163
p1/preprocess/Rectal_Cancer/GSE123390.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:059ded7ae95b07075a29cd5abcfb7fe8e2795438abfea851edada3de43402185
3
+ size 14460677
p1/preprocess/Rectal_Cancer/gene_data/GSE123390.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d4aab6460ab0f5ca4f28b8501ec1576c49c45235596a4ecce96670e556e00137
3
+ size 14460535
p1/preprocess/Rectal_Cancer/gene_data/TCGA.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:059033ea0624004c8cdcef047178ee75a37b1bbf4e3c617cd8c70a7092e394a3
3
+ size 31724401
p1/preprocess/Retinoblastoma/GSE208143.csv ADDED
The diff for this file is too large to render. See raw diff
 
p1/preprocess/Retinoblastoma/code/GSE63529.py ADDED
@@ -0,0 +1,194 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Retinoblastoma"
6
+ cohort = "GSE63529"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Retinoblastoma"
10
+ in_cohort_dir = "../DATA/GEO/Retinoblastoma/GSE63529"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/preprocess/1/Retinoblastoma/GSE63529.csv"
14
+ out_gene_data_file = "./output/preprocess/1/Retinoblastoma/gene_data/GSE63529.csv"
15
+ out_clinical_data_file = "./output/preprocess/1/Retinoblastoma/clinical_data/GSE63529.csv"
16
+ json_path = "./output/preprocess/1/Retinoblastoma/cohort_info.json"
17
+
18
+ # STEP1
19
+ from tools.preprocess import *
20
+ # 1. Identify the paths to the SOFT file and the matrix file
21
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
22
+
23
+ # 2. Read the matrix file to obtain background information and sample characteristics data
24
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
25
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
26
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
27
+
28
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
29
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
30
+
31
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
32
+ print("Background Information:")
33
+ print(background_info)
34
+ print("Sample Characteristics Dictionary:")
35
+ print(sample_characteristics_dict)
36
+ # 1) Gene Expression Data Availability
37
+ is_gene_available = True # Based on the background info indicating actual gene expression profiling.
38
+
39
+ # 2) Variable Availability
40
+ # From the sample characteristics dictionary, there's no indication of:
41
+ # - Retinoblastoma trait status,
42
+ # - Age,
43
+ # - Gender.
44
+ # Hence we set all row indices to None.
45
+
46
+ trait_row = None
47
+ age_row = None
48
+ gender_row = None
49
+
50
+ # 2.2 Data Type Conversion Functions
51
+ def convert_trait(value: str):
52
+ # No actual trait data is available, return None
53
+ return None
54
+
55
+ def convert_age(value: str):
56
+ # No age data is available, return None
57
+ return None
58
+
59
+ def convert_gender(value: str):
60
+ # No gender data is available, return None
61
+ return None
62
+
63
+ # 3) Save Metadata (Initial Filtering)
64
+ # trait data availability can be determined by trait_row
65
+ is_trait_available = (trait_row is not None)
66
+
67
+ validate_and_save_cohort_info(
68
+ is_final=False,
69
+ cohort=cohort,
70
+ info_path=json_path,
71
+ is_gene_available=is_gene_available,
72
+ is_trait_available=is_trait_available
73
+ )
74
+
75
+ # 4) Clinical Feature Extraction
76
+ # Since trait_row is None, we skip this step.
77
+ # STEP3
78
+ import gzip
79
+ import pandas as pd
80
+
81
+ try:
82
+ # 1. Attempt to extract gene expression data using the library function
83
+ gene_data = get_genetic_data(matrix_file)
84
+ except KeyError:
85
+ # Fallback: the expected "ID_REF" column may be absent, so manually parse the file
86
+ # and rename the first column to "ID".
87
+ marker = "!series_matrix_table_begin"
88
+ skip_rows = None
89
+
90
+ # Determine how many rows to skip before the matrix data begins
91
+ with gzip.open(matrix_file, 'rt') as f:
92
+ for i, line in enumerate(f):
93
+ if marker in line:
94
+ skip_rows = i + 1
95
+ break
96
+ else:
97
+ raise ValueError(f"Marker '{marker}' not found in the file.")
98
+
99
+ # Read the data from the determined position
100
+ gene_data = pd.read_csv(
101
+ matrix_file,
102
+ compression='gzip',
103
+ skiprows=skip_rows,
104
+ comment='!',
105
+ delimiter='\t',
106
+ on_bad_lines='skip'
107
+ )
108
+
109
+ # If a different column name is used instead of 'ID_REF', rename appropriately
110
+ if 'ID_REF' in gene_data.columns:
111
+ gene_data.rename(columns={'ID_REF': 'ID'}, inplace=True)
112
+ else:
113
+ first_col = gene_data.columns[0]
114
+ gene_data.rename(columns={first_col: 'ID'}, inplace=True)
115
+
116
+ gene_data['ID'] = gene_data['ID'].astype(str)
117
+ gene_data.set_index('ID', inplace=True)
118
+
119
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
120
+ print(gene_data.index[:20])
121
+ print("Based on the presented identifiers (e.g. ILMN_1343291), they appear to be Illumina probe IDs.\nrequires_gene_mapping = True")
122
+ # STEP5
123
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
124
+ gene_annotation = get_gene_annotation(soft_file)
125
+
126
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
127
+ print("Gene annotation preview:")
128
+ print(preview_df(gene_annotation))
129
+ # STEP: Gene Identifier Mapping
130
+
131
+ # 1) Determine the matching columns in gene_annotation that map to the gene expression data's probe IDs ("ID")
132
+ # and the actual gene symbol ("Symbol").
133
+ mapping_df = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='Symbol')
134
+
135
+ # 2) Apply the mapping to convert probe-level expression data into gene-level data.
136
+ gene_data = apply_gene_mapping(gene_data, mapping_df)
137
+ import os
138
+ import pandas as pd
139
+
140
+ # STEP 7: Data Normalization and Linking
141
+
142
+ # First, check if the clinical CSV file exists. If it does not, we cannot proceed with trait-based linking.
143
+ if not os.path.exists(out_clinical_data_file):
144
+ # No trait data file => dataset is not usable for trait analysis
145
+ df_null = pd.DataFrame()
146
+ is_biased = True # Arbitrary boolean to satisfy function requirement
147
+ validate_and_save_cohort_info(
148
+ is_final=True,
149
+ cohort=cohort,
150
+ info_path=json_path,
151
+ is_gene_available=True,
152
+ is_trait_available=False,
153
+ is_biased=is_biased,
154
+ df=df_null,
155
+ note="No trait data file found; dataset not usable for trait analysis."
156
+ )
157
+
158
+ else:
159
+ # 1. Normalize the mapped gene expression data using known gene symbol synonyms, then save.
160
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
161
+ normalized_gene_data.to_csv(out_gene_data_file)
162
+
163
+ # 2. Load the previously extracted clinical CSV.
164
+ selected_clinical_df = pd.read_csv(out_clinical_data_file)
165
+ # If we had a single-row trait, rename row 0 to the trait name (example usage).
166
+ selected_clinical_df = selected_clinical_df.rename(index={0: trait})
167
+
168
+ # Combine these as our final clinical data; in this dataset, we only have trait info (if any).
169
+ combined_clinical_df = selected_clinical_df
170
+
171
+ # Link the clinical and genetic data by matching sample IDs in columns.
172
+ linked_data = geo_link_clinical_genetic_data(combined_clinical_df, normalized_gene_data)
173
+
174
+ # 3. Handle missing values in the linked data (drop incomplete rows/columns, then impute).
175
+ processed_data = handle_missing_values(linked_data, trait)
176
+
177
+ # 4. Check trait bias and remove any biased demographic features (if any).
178
+ trait_biased, processed_data = judge_and_remove_biased_features(processed_data, trait)
179
+
180
+ # 5. Final validation and metadata saving.
181
+ is_usable = validate_and_save_cohort_info(
182
+ is_final=True,
183
+ cohort=cohort,
184
+ info_path=json_path,
185
+ is_gene_available=True,
186
+ is_trait_available=True,
187
+ is_biased=trait_biased,
188
+ df=processed_data,
189
+ note="Completed trait-based preprocessing."
190
+ )
191
+
192
+ # 6. If final dataset is usable, save. Otherwise, skip.
193
+ if is_usable:
194
+ processed_data.to_csv(out_data_file)
p1/preprocess/Retinoblastoma/code/GSE68950.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Retinoblastoma"
6
+ cohort = "GSE68950"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Retinoblastoma"
10
+ in_cohort_dir = "../DATA/GEO/Retinoblastoma/GSE68950"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/preprocess/1/Retinoblastoma/GSE68950.csv"
14
+ out_gene_data_file = "./output/preprocess/1/Retinoblastoma/gene_data/GSE68950.csv"
15
+ out_clinical_data_file = "./output/preprocess/1/Retinoblastoma/clinical_data/GSE68950.csv"
16
+ json_path = "./output/preprocess/1/Retinoblastoma/cohort_info.json"
17
+
18
+ # STEP1
19
+ from tools.preprocess import *
20
+ # 1. Identify the paths to the SOFT file and the matrix file
21
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
22
+
23
+ # 2. Read the matrix file to obtain background information and sample characteristics data
24
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
25
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
26
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
27
+
28
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
29
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
30
+
31
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
32
+ print("Background Information:")
33
+ print(background_info)
34
+ print("Sample Characteristics Dictionary:")
35
+ print(sample_characteristics_dict)
36
+ # 1. Determine if the dataset likely contains gene expression data
37
+ is_gene_available = True # Based on "Assay Type: Gene Expression" and "Provider: Affymetrix"
38
+
39
+ # 2. Identify rows for trait, age, and gender in the sample characteristics dictionary
40
+ # Since "Retinoblastoma" is not found among the unique disease states, and no age/gender info is present, set them to None
41
+ trait_row = None
42
+ age_row = None
43
+ gender_row = None
44
+
45
+ # 2.2 Define data type conversion functions
46
+ def convert_trait(value: str) -> Optional[int]:
47
+ return None # Trait data is not available
48
+
49
+ def convert_age(value: str) -> Optional[float]:
50
+ return None # Age data is not available
51
+
52
+ def convert_gender(value: str) -> Optional[int]:
53
+ return None # Gender data is not available
54
+
55
+ # 3. Conduct initial filtering: trait data is considered unavailable if trait_row is None
56
+ is_trait_available = (trait_row is not None)
57
+
58
+ # Save metadata with the initial filtering
59
+ is_usable = validate_and_save_cohort_info(
60
+ is_final=False,
61
+ cohort=cohort,
62
+ info_path=json_path,
63
+ is_gene_available=is_gene_available,
64
+ is_trait_available=is_trait_available
65
+ )
66
+
67
+ # 4. Clinical feature extraction is skipped because trait_row is None
p1/preprocess/Retinoblastoma/code/TCGA.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Retinoblastoma"
6
+
7
+ # Input paths
8
+ tcga_root_dir = "../DATA/TCGA"
9
+
10
+ # Output paths
11
+ out_data_file = "./output/preprocess/1/Retinoblastoma/TCGA.csv"
12
+ out_gene_data_file = "./output/preprocess/1/Retinoblastoma/gene_data/TCGA.csv"
13
+ out_clinical_data_file = "./output/preprocess/1/Retinoblastoma/clinical_data/TCGA.csv"
14
+ json_path = "./output/preprocess/1/Retinoblastoma/cohort_info.json"
15
+
16
+ import os
17
+ import pandas as pd
18
+
19
+ # List of subdirectories provided in the instructions:
20
+ subdirectories = [
21
+ 'CrawlData.ipynb', '.DS_Store', 'TCGA_lower_grade_glioma_and_glioblastoma_(GBMLGG)',
22
+ 'TCGA_Uterine_Carcinosarcoma_(UCS)', 'TCGA_Thyroid_Cancer_(THCA)', 'TCGA_Thymoma_(THYM)',
23
+ 'TCGA_Testicular_Cancer_(TGCT)', 'TCGA_Stomach_Cancer_(STAD)', 'TCGA_Sarcoma_(SARC)',
24
+ 'TCGA_Rectal_Cancer_(READ)', 'TCGA_Prostate_Cancer_(PRAD)', 'TCGA_Pheochromocytoma_Paraganglioma_(PCPG)',
25
+ 'TCGA_Pancreatic_Cancer_(PAAD)', 'TCGA_Ovarian_Cancer_(OV)', 'TCGA_Ocular_melanomas_(UVM)',
26
+ 'TCGA_Mesothelioma_(MESO)', 'TCGA_Melanoma_(SKCM)', 'TCGA_Lung_Squamous_Cell_Carcinoma_(LUSC)',
27
+ 'TCGA_Lung_Cancer_(LUNG)', 'TCGA_Lung_Adenocarcinoma_(LUAD)', 'TCGA_Lower_Grade_Glioma_(LGG)',
28
+ 'TCGA_Liver_Cancer_(LIHC)', 'TCGA_Large_Bcell_Lymphoma_(DLBC)', 'TCGA_Kidney_Papillary_Cell_Carcinoma_(KIRP)',
29
+ 'TCGA_Kidney_Clear_Cell_Carcinoma_(KIRC)', 'TCGA_Kidney_Chromophobe_(KICH)', 'TCGA_Head_and_Neck_Cancer_(HNSC)',
30
+ 'TCGA_Glioblastoma_(GBM)', 'TCGA_Esophageal_Cancer_(ESCA)', 'TCGA_Endometrioid_Cancer_(UCEC)',
31
+ 'TCGA_Colon_and_Rectal_Cancer_(COADREAD)', 'TCGA_Colon_Cancer_(COAD)', 'TCGA_Cervical_Cancer_(CESC)',
32
+ 'TCGA_Breast_Cancer_(BRCA)', 'TCGA_Bladder_Cancer_(BLCA)', 'TCGA_Bile_Duct_Cancer_(CHOL)',
33
+ 'TCGA_Adrenocortical_Cancer_(ACC)', 'TCGA_Acute_Myeloid_Leukemia_(LAML)'
34
+ ]
35
+
36
+ # Synonyms for the trait "Retinoblastoma"
37
+ trait_synonyms = ["retinoblastoma", "rb"]
38
+
39
+ selected_subdirectory = None
40
+ for subdir in subdirectories:
41
+ if subdir.lower() in ['crawldata.ipynb', '.ds_store']:
42
+ continue
43
+ subdir_lower = subdir.lower()
44
+ if any(syn in subdir_lower for syn in trait_synonyms):
45
+ selected_subdirectory = subdir
46
+ break
47
+
48
+ if not selected_subdirectory:
49
+ # If no matching directory is found, mark dataset as unavailable
50
+ is_final = False
51
+ is_gene_available = False
52
+ is_trait_available = False
53
+ _ = validate_and_save_cohort_info(
54
+ is_final=is_final,
55
+ cohort="TCGA",
56
+ info_path=json_path,
57
+ is_gene_available=is_gene_available,
58
+ is_trait_available=is_trait_available
59
+ )
60
+ print(f"No suitable directory found for '{trait}'. Skipped this trait.")
61
+ else:
62
+ # Step 2: Identify clinicalMatrix file and PANCAN file
63
+ cohort_dir = os.path.join(tcga_root_dir, selected_subdirectory)
64
+ clinical_file_path, genetic_file_path = tcga_get_relevant_filepaths(cohort_dir)
65
+
66
+ # Step 3: Load both files as dataframes
67
+ clinical_df = pd.read_csv(clinical_file_path, index_col=0, sep='\t')
68
+ genetic_df = pd.read_csv(genetic_file_path, index_col=0, sep='\t')
69
+
70
+ # Step 4: Print the column names of the clinical data
71
+ print("Clinical data columns:")
72
+ print(list(clinical_df.columns))
p1/preprocess/Retinoblastoma/gene_data/GSE110811.csv ADDED
@@ -0,0 +1 @@
 
 
1
+ Gene,GSM3017123,GSM3017124,GSM3017125,GSM3017126,GSM3017127,GSM3017128,GSM3017129,GSM3017130,GSM3017131,GSM3017132,GSM3017133,GSM3017134,GSM3017135,GSM3017136,GSM3017137,GSM3017138,GSM3017139,GSM3017140,GSM3017141,GSM3017142,GSM3017143,GSM3017144,GSM3017145,GSM3017146,GSM3017147,GSM3017148,GSM3017149,GSM3017150,GSM3017151,GSM3017152,GSM3017153,GSM3017154,GSM3017155,GSM3017156
p1/preprocess/Retinoblastoma/gene_data/GSE208143.csv ADDED
The diff for this file is too large to render. See raw diff
 
p1/preprocess/Retinoblastoma/gene_data/GSE58780.csv ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Gene,GSM5121283,GSM5121284,GSM5121285,GSM5121286,GSM5121287,GSM5121288,GSM5121289,GSM5121290,GSM5121291,GSM5121292,GSM5121293,GSM5121294,GSM5121295,GSM5121296,GSM5121297,GSM5121298,GSM5121299,GSM5121300,GSM5121301,GSM5121302,GSM5121303,GSM5121304,GSM5121305,GSM5121306,GSM5121307,GSM5121308,GSM5121309,GSM5121310,GSM5121311,GSM5121312,GSM5121313,GSM5121314,GSM5121315,GSM5121316,GSM5121317,GSM5121318,GSM5121319,GSM5121320,GSM5121321,GSM5121322,GSM5121323,GSM5121324,GSM5121325,GSM5121326,GSM5121327,GSM5121328,GSM5121329,GSM5121330,GSM5121331,GSM5121332,GSM5121333,GSM5121334,GSM5121335,GSM5121336,GSM5121337,GSM5121338,GSM5121339,GSM5121340,GSM5121341,GSM5121342,GSM5121343,GSM5121344,GSM5121345,GSM5121346,GSM5121347,GSM5121348
2
+ ARHGEF15,1025906.713873315,1023109.2252259746,1024373.6386256578,1020378.2370327944,1014970.9691794246,1014390.2743304346,1010455.6931112942,1015023.9302813339,1017332.6594002885,1021095.4770704381,988622.1778226101,1010671.4139549216,1013034.7844051106,1013030.0988893397,1018552.2187664254,1013272.7299761884,1017061.1567727308,1014709.4187737909,1013872.0985935971,1020584.4278257567,1016484.7514095977,1017870.0972255162,1001510.8137217306,1008423.987992751,1023334.4366303028,1015082.3160771057,1014902.0541456684,1021377.3486559405,1022789.5755228159,1025022.184284791,1017674.0899442764,1014874.6347479641,1005070.2885402058,1012340.5816675044,1026790.0076490242,1011406.7766314573,1019805.542501082,1013790.3288290916,1012376.0825854043,1004110.3981636162,1015623.9064195845,1014036.8576425635,1012744.1816977242,1023461.5084349578,1003099.2056314398,1008288.396155771,1020101.6699152112,1020388.9772969631,1019528.0382052707,1010053.8995294508,992471.3968877683,1016074.8359334255,1013018.0652540576,1010084.5577778704,1019238.3189178862,1008702.5527493778,1008961.8138545615,1024851.9178553615,1008708.7876841516,1022005.5711834631,1019309.7317011043,1020226.8203911829,1014021.8381682868,1008625.9987155675,1015168.3875514315,1013946.5887658072
3
+ CST12P,681443.4441348393,689112.7318504807,689827.0492894253,693399.6832538449,689578.2074911633,693166.8931035304,698855.1394319956,696083.7266552993,679804.4470332565,698344.2336244725,733481.2279502876,697126.9381441531,693193.8061137494,699840.9489885231,686501.4503576666,701762.1436878766,693127.7784622244,691684.0194113518,697967.5566833266,700436.7808683405,685252.8696150522,690965.802720197,721724.5741799171,699851.8027669771,697629.1448930253,697290.7762408418,706736.7109689467,697249.7070466607,703570.3521987194,704434.0107346177,701283.3140123917,696134.1878512442,737959.6909246892,695622.275114851,688818.85633882,721399.8913170596,689099.4679320363,697399.7637791559,701153.713385665,712985.7837267038,696682.5506707042,697068.217168998,697179.9357684831,696363.957220718,740871.5647445526,689107.5684895689,691330.2928544534,690647.842771759,701638.8683058689,706773.4877122373,748018.566612207,693482.8741679395,701777.3194305447,701384.1792512671,703636.6174943126,711515.9491826907,709888.6122457593,685697.4804532132,700937.3378813585,683781.448796627,688751.1127575339,693829.8934870131,686453.1013415689,722892.5989449744,707190.9844913898,712324.1857921162
4
+ ELSPBP1,18411.95292708753,18800.005268603563,18595.912294212612,18651.19021649486,18657.967026070197,18572.392696473747,18567.517169768053,18539.032365686235,18744.125559644683,18809.621474142023,18859.699697733326,18916.083156819626,18702.58923087098,18482.6950740117,18885.813722125153,18744.775915673912,18627.2837015596,18892.872214173953,18954.74955400563,18775.95647578764,18411.121640822053,18517.36607209938,18339.258515768888,18635.940091299297,18693.95986057565,18636.299106619823,18878.70584407996,18638.9713001595,18723.53421438488,18794.247326020242,18747.430392650964,18624.987696307315,18673.01515405946,18702.69621914407,18750.403107256792,18699.05904669027,18859.09878284031,18848.73468340346,18539.442930298977,18612.30248968873,18779.300313594395,18677.739967797068,18847.600097018832,18705.277158843277,18704.977212081456,18974.321609627204,18691.06102388953,18469.71813468318,18738.66074660708,18533.486851246416,18803.209214950683,18606.520378171273,18406.78088176211,18692.684687411744,18625.111032864028,18820.712492427785,18348.72082783725,18926.43950069404,18759.916241192757,18685.798739097634,18837.18446720862,18653.526018971763,18697.29769176251,17621.359517526012,18144.59826313061,18424.6900659434
5
+ ENOPH1,533.1989995453134,524.9651094667383,507.96663017924834,534.6934977597057,532.6627807476902,492.0568453017254,526.4890076007707,536.3862678673116,521.8644468462174,531.8445231205559,541.8173230440352,502.8184911132732,534.2351729403229,508.85051348029253,515.9908450256341,509.90816038213535,509.5302155791706,496.9558686330555,495.2298432157767,541.4720758553717,493.8492426684181,528.1331990693056,530.3303004844,508.4540154346236,523.7269692331428,526.0082905777585,540.8772878854447,519.0435348962918,536.3759855471154,516.038832627092,527.638197491104,519.5263654265398,560.7086868769659,491.6538333377673,530.9405917542252,513.1899470608766,530.8305203517468,514.0070288204497,534.5716961336499,529.3490379494818,517.041272092648,520.0552690575374,532.0850817773385,535.262970278376,543.6643432207392,514.5664807844107,507.104499919243,532.6733080551537,537.9245344541231,511.8283034564236,563.7037518269448,495.84005231212706,525.1978307638162,516.9288854529077,525.9124363025094,531.3269127411022,554.4846047283467,513.838974253577,521.9639584381435,519.7500817446529,518.2091432842803,534.7984345098555,499.78164360686424,529.9298229480424,522.3724017878308,523.5231881763399
6
+ ITM2C,6.61939080338306,7.02452723787926,7.13563549104521,7.05875745442216,7.34607960386286,7.38140660479965,7.36469697838536,7.13877641839159,7.24823189779408,6.9140997891074,7.44100898713198,6.60464316647491,7.59984101638769,7.15156954121268,6.99706887671565,7.49828843569601,7.19098749378852,7.12730004677713,7.23592993482833,7.37845198595607,7.02246351255558,7.18376161529531,7.07441864387126,7.59334545301519,7.41057681293054,7.11932627468689,7.53157727999521,7.28263999985065,7.44548959762857,7.17381838842653,7.75180948110908,7.26973304437563,6.97557563666546,7.79159166164481,7.27099930134802,6.24707093626877,6.86375235388075,6.8447047002776,7.0972444904878,7.54639600663745,7.40838265206005,7.46953313536038,7.44536164077082,7.31539144409077,6.20887304732801,7.46291137912592,7.50866419265201,7.33355784967847,7.62398725587169,6.56747640661527,6.33276717131548,7.0894469926882,7.52789588310066,7.31530120088155,6.68795539189936,7.04453907556236,7.99440581529867,7.28461696404646,7.59651032741053,7.39956391733708,6.92819335114164,7.03925835503225,7.10080068386073,7.45237777301619,7.75217920151084,7.72534059079228
7
+ LOC105980073,4.15832664376132,3.93172576762742,4.12995327117712,3.47558631972733,4.38382609134184,4.24376177815382,3.67539851474685,4.29268943603102,4.44617348366656,4.05272043900334,3.76096475457578,4.12218909636266,4.45614869587539,3.63141199050967,3.85913859392334,3.50163469159835,3.93133630089429,3.7186653606595,4.21348503799797,4.27333397524867,3.92285275145299,3.90222934731526,3.92976585504632,3.48756771884484,3.700819917739,3.92682897345138,3.38582546862804,5.98356460696197,4.67355864561647,4.22389077315554,3.90559931396523,5.62634747931107,4.20630291552886,3.25915178943345,4.45938798889523,3.75705723894942,4.54241615333768,3.96097637337678,3.69792076504283,4.19635383391705,4.11034195878783,3.71935591943475,5.58620931138874,4.3567688507402,4.25631611122526,3.4582395060362,4.32987410352711,4.36648012738992,3.68397113929862,4.42936003038478,3.94969387114347,3.61271791274543,3.81602781554313,3.57931993464994,4.84301704690343,4.40080632778377,5.43389327910473,4.12145568461365,3.64700360911391,4.32423469908404,3.82681473746078,4.48328132407237,5.75871236068828,3.64137993422113,3.38387921154091,3.07133390751812
8
+ LOC111674475,51902.92997254326,52641.5557861857,52163.19673939594,52006.68457879176,52148.31004323445,52092.37863343312,51960.815598068184,51869.31645491753,52721.39771879604,52401.01645030702,52394.14724424576,52256.97016961257,52461.83941883028,51910.36580991578,53035.64579984774,51677.63775361062,52280.71661245519,52417.739116814766,52716.253923191456,52662.37473822959,51485.17051561321,52040.049356220115,50982.64699982317,51668.01649823755,51904.56282296915,52275.09099668668,52298.65066116348,52083.849466471125,52218.1247367348,52578.02681612778,52509.31329984809,51967.39181788128,52481.6840104521,52045.84871302396,52552.29060043629,52374.390072588125,52723.30052354862,52694.67534895362,52237.83681542457,52215.55550501247,52473.08752390553,52175.645610853666,52626.711412883444,52605.03932026138,51811.58844275657,52753.701227993,52321.323993457954,52248.124773502976,52056.109612248554,52206.45033728833,52768.73500261776,52348.45802271654,51443.92069750561,52201.198112426435,52076.09551310285,52269.66725058927,51612.197732449255,52251.7941710042,52130.85665676087,52198.94097966977,52633.992080948665,52178.973997200046,52158.46176556035,49238.81859297344,50056.6528351431,50582.41298288423
9
+ LY6D,5.94097759296838,5.81869928054528,5.68270200620443,5.84017901915232,5.9564493821746,6.05931313834019,5.49757288419343,5.78190829035639,6.64625296428486,5.40299728568853,5.88075465322932,5.90803937922093,5.90947565457833,5.66975567696506,5.8789892431877,5.79859352302658,5.92935069307516,5.64290972326301,6.0442312799457,5.80189819968397,6.18642446173504,5.9143628638101,5.68171885168377,5.29217498480138,5.45118305820263,5.79652922070956,5.55098293223042,6.72856613673552,5.7203931119382,5.76189551889388,6.10506725073559,6.34055446040168,5.87452875493829,5.88133192366397,5.7335535984012,6.01480464830615,6.18702569145643,5.93465470932498,5.8632062463553,5.99206489428185,5.87526498440302,5.5913044978546,6.16192641087576,6.26054870897471,5.33388300689144,5.74459607299515,6.09921826564003,6.61945950521303,5.91441728623084,5.86282931167222,5.64524301087107,5.76477796789561,6.40807828263626,5.78154827610026,6.01055856828123,6.46938557018418,5.77742470824269,5.65139295155647,5.79004359992011,6.01269416814394,5.76351815793929,5.70757824575143,6.79842810124112,5.85688522336554,5.90989322321618,6.57380199612475
10
+ NPAT,7.32740562269541,6.94359121874896,6.83661268246317,7.16447686997271,7.00569599947524,7.37770800492173,6.85032634829273,7.07333400840519,6.96752335997758,7.33476624441528,7.38087655948831,7.18897300471653,6.99464156064909,7.06633890051166,7.14289085670664,6.91146220645345,7.02135483658291,7.23088674054603,7.24591991213599,7.62448358835407,6.78230088411504,6.92354429124222,7.09726917357146,7.0283573304646,7.09100763167014,6.88896281447493,7.10713385821756,6.7803895140729,7.26775445128699,7.43058634823206,7.34293513158576,7.19023593762108,7.16047213725958,7.23268179204243,7.15529789376038,7.17202637301441,7.14395048006662,7.18788397287075,7.3695861059473,7.25258231827925,6.95999681865992,7.00079578354614,7.47050877084081,7.53000179366589,7.90030996691662,6.90780701694499,7.02583421611249,7.07920801030014,7.00310751827067,7.00198140623784,7.36761106920241,7.57729698020891,6.85930038600656,6.97791814540537,7.28966585730565,7.41027205850919,7.23345204530386,7.30555606087322,7.352032177611,7.11058026590386,7.00815123133131,6.69504375128451,6.94432883202499,7.00943679085161,7.01972167668906,6.93217018449226
11
+ SLC7A5,8.77529040766214,8.34704421156807,8.54646754858315,8.3130523665008,7.0822212887011,7.98741405537213,8.15186633372392,7.81385573805795,8.17886696139584,7.49194114429263,7.61703722797579,7.4877853634492,7.75145314204853,8.41856561556562,7.98711303885678,7.29937413245912,8.54203433898931,7.20969451132113,7.74765372857031,7.58442687480655,8.48261520855654,8.31559508322295,8.16649604866574,7.17242081691205,7.37471461450417,8.07704528795935,7.92121540411704,7.81794416075458,7.33793670802383,8.66648231350417,7.38994139807579,7.48247125326064,8.75671639563228,7.0911304437878,8.62466293278217,8.07771308060017,7.89877185846019,7.6717730206747,7.0390092355372,7.36237026757143,6.67416293160526,7.81245090439972,7.45379858647408,7.48220356105416,8.01205569789181,7.70384079691921,7.65287615961861,7.22762342463114,7.87376231992397,8.24027478929336,8.20079655928187,8.40631222958979,8.31049482765841,7.90960635548209,8.74224730024388,8.00619643385188,7.38846263064291,7.87856532797453,7.98021283647178,7.22336367607348,8.46938148613508,7.83208613237719,7.57528868866193,7.92787955871138,7.9879200026541,7.83428312198316
12
+ SNORD12C,1060248.403893682,1060975.6817942814,1065986.0498764347,1065872.866847611,1064007.6746350918,1089385.9720570277,1084192.624112445,1080523.9765355247,1055499.9290135154,1073574.9950726898,1130346.5573222612,1074144.509904194,1075815.8525940257,1088274.2665400573,1058223.6419469102,1074455.7922868985,1070361.552117384,1065973.2185157717,1078383.4297536672,1079316.1838340724,1069409.820932258,1066564.159935569,1114266.25683315,1079283.2979005896,1070128.2309383017,1058656.64995418,1082965.0247263166,1080528.9451579906,1071344.876131381,1073434.1648553603,1072347.8586901776,1069166.282330421,1113598.8971509968,1072787.760922459,1063287.93030405,1100883.9654007873,1060110.5725436555,1080312.8213100773,1073818.4819616738,1102105.9882531452,1072988.3011624236,1081639.2849530682,1073964.6439994562,1071647.2275264962,1136840.7524360514,1063849.1749886046,1071846.9505381067,1056636.150143229,1072404.7701220445,1079141.5432283003,1139603.8061659245,1089672.001505608,1096867.4851715164,1084368.3352814703,1095104.1343174977,1099621.8283465793,1084701.788817658,1065215.009323645,1086358.7334209029,1053339.3385393443,1069173.990922048,1070885.6240669736,1069398.801692196,1120470.5658872672,1090379.3817945677,1086734.865692007
13
+ TCF3,7.8277912788088,8.55443783183878,7.95947701090725,8.3324569048333,8.81789266590515,8.10121066017479,7.762048543752,8.09136521135471,8.57584987176763,8.25392517591663,8.23232047578322,8.87591321682236,8.32145816405039,7.89910148284506,8.29012031711875,8.66326357009635,8.19624541987564,8.92772919773815,8.21629957035244,8.64765376752483,7.95166764053703,8.14496062090454,8.57922883084337,8.85115779015788,8.95015785612472,8.28332392913984,8.46736304677153,7.83092813771755,8.41994613290198,8.63174114986381,8.72129658943073,8.18344372227565,8.15461787611179,8.59360044238905,8.01485217000844,8.39296435339603,8.62915002505544,8.33236271654801,8.90898978953121,8.63991194979359,9.10051130567638,8.1396950085192,8.69636861192782,9.49680451601521,8.96030815861423,8.62550104909787,8.04481934922379,8.49956617348781,8.01837421192959,8.33711024123485,8.28159634909021,8.26251429080143,7.45390188242999,8.14941841357191,8.11367950158728,8.76946945502065,8.64025110688866,8.03770231567335,8.5229539180667,9.01320949906287,7.93773403702973,8.11317518903452,8.10097949233264,7.63444980855312,7.98908293044251,8.13229217119588
14
+ UBE4B,948145.7939078866,941191.5226948174,946863.4992188354,944848.8806704659,939390.1180271794,957779.5219208451,948698.8540902779,949803.8791106448,937386.4486625536,947962.155864299,949810.7396272448,941541.8946555675,945966.1758844425,952738.5461002495,938513.2778213652,942348.1084377761,944281.1865420404,940034.6450480653,944050.1628435609,949007.8836282409,946500.0193200486,944219.5323076461,953974.010097689,943142.420012345,949003.816224108,936454.6495107318,947302.8204477996,953726.0846121883,947871.7910400954,949280.7996572376,942308.0270640028,942548.5543325385,953910.8694062509,939175.4627866357,945958.9734056981,953204.0454560246,940823.0998775121,948888.5101198156,940645.3134647415,951291.8101556831,944461.398200227,946858.7391683324,940622.7887002716,946307.0757994854,966368.3726489665,936213.3393743709,949300.7256881224,939081.8067971006,943759.1448590837,943689.6987393703,959960.2257917434,958995.5724470874,959058.0765147377,946234.5854938945,957710.2563378738,950616.8474377574,945470.6656165676,948177.10978815,946162.9486688733,939077.1061358387,946094.601779387,948605.5037060333,943490.3499661385,964837.6060586423,956593.7968188861,950552.8827307707
p1/preprocess/Rheumatoid_Arthritis/GSE121894.csv ADDED
The diff for this file is too large to render. See raw diff
 
p1/preprocess/Rheumatoid_Arthritis/clinical_data/GSE121894.csv ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ GSM3449621,GSM3449622,GSM3449623,GSM3449624,GSM3449625,GSM3449626,GSM3449627,GSM3449628,GSM3449629,GSM3449630,GSM3449631,GSM3449632,GSM3449633,GSM3449634,GSM3449635,GSM3449636,GSM3449637,GSM3449638,GSM3449639,GSM3449640,GSM3449641,GSM3449642,GSM3449643,GSM3449644,GSM3449645,GSM3449646,GSM3449647,GSM3449648,GSM3449649,GSM3449650,GSM3449651,GSM3449652,GSM3449653,GSM3449654,GSM3449655,GSM3449656,GSM3449657,GSM3449658,GSM3449659,GSM3449660,GSM3449661,GSM3449662,GSM3449663,GSM3449664,GSM3449665,GSM3449666,GSM3449667,GSM3449668,GSM3449669,GSM3449670,GSM3449671,GSM3449672,GSM3449673,GSM3449674,GSM3449675,GSM3449676,GSM3449677,GSM3449678
2
+ 1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0
p1/preprocess/Rheumatoid_Arthritis/clinical_data/GSE236924.csv ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ GSM7585682,GSM7585683,GSM7585684,GSM7585685,GSM7585686,GSM7585687,GSM7585688,GSM7585689,GSM7585690,GSM7585691,GSM7585692,GSM7585693,GSM7585694,GSM7585695,GSM7585696,GSM7585697,GSM7585698,GSM7585699,GSM7585700,GSM7585701,GSM7585702,GSM7585703,GSM7585704,GSM7585705,GSM7585706,GSM7585707,GSM7585708,GSM7585709,GSM7585710,GSM7585711,GSM7585712,GSM7585713,GSM7585714,GSM7585715,GSM7585716,GSM7585717,GSM7585718,GSM7585719,GSM7585720,GSM7585721,GSM7585722,GSM7585723,GSM7585724,GSM7585725,GSM7585726,GSM7585727,GSM7585728,GSM7585729,GSM7585730,GSM7585731,GSM7585732,GSM7585733,GSM7585734,GSM7585735,GSM7585736,GSM7585737,GSM7585738,GSM7585739,GSM7585740,GSM7585741,GSM7585742,GSM7585743,GSM7585744,GSM7585745,GSM7585746,GSM7585747,GSM7585748,GSM7585749,GSM7585750,GSM7585751,GSM7585752,GSM7585753,GSM7585754,GSM7585755,GSM7585756,GSM7585757,GSM7585758,GSM7585759,GSM7585760,GSM7585761,GSM7585762,GSM7585763,GSM7585764,GSM7585765,GSM7585766,GSM7585767,GSM7585768,GSM7585769,GSM7585770,GSM7585771,GSM7585772,GSM7585773,GSM7585774,GSM7585775,GSM7585776,GSM7585777,GSM7585778,GSM7585779,GSM7585780,GSM7585781,GSM7585782,GSM7585783,GSM7585784,GSM7585785,GSM7585786,GSM7585787,GSM7585788,GSM7585789,GSM7585790,GSM7585791,GSM7585792,GSM7585793,GSM7585794,GSM7585795,GSM7585796,GSM7585797,GSM7585798,GSM7585799,GSM7585800,GSM7585801,GSM7585802,GSM7585803,GSM7585804,GSM7585805,GSM7585806,GSM7585807,GSM7585808,GSM7585809,GSM7585810,GSM7585811,GSM7585812,GSM7585813
2
+ 0.0,0.0,0.0,0.0,1.0,0.0,0.0,0.0,0.0,1.0,0.0,1.0,0.0,0.0,0.0,1.0,1.0,0.0,0.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,0.0,0.0,0.0,1.0,0.0,0.0,1.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,0.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,0.0,0.0,0.0,1.0,0.0,0.0,0.0,0.0,1.0,0.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,0.0,0.0,0.0,1.0,1.0,0.0,0.0,0.0,0.0,1.0,0.0,0.0,0.0,1.0,1.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,1.0,0.0,0.0,0.0,0.0,0.0
p1/preprocess/Rheumatoid_Arthritis/code/GSE121894.py ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Rheumatoid_Arthritis"
6
+ cohort = "GSE121894"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Rheumatoid_Arthritis"
10
+ in_cohort_dir = "../DATA/GEO/Rheumatoid_Arthritis/GSE121894"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/preprocess/1/Rheumatoid_Arthritis/GSE121894.csv"
14
+ out_gene_data_file = "./output/preprocess/1/Rheumatoid_Arthritis/gene_data/GSE121894.csv"
15
+ out_clinical_data_file = "./output/preprocess/1/Rheumatoid_Arthritis/clinical_data/GSE121894.csv"
16
+ json_path = "./output/preprocess/1/Rheumatoid_Arthritis/cohort_info.json"
17
+
18
+ # STEP1
19
+ from tools.preprocess import *
20
+ # 1. Identify the paths to the SOFT file and the matrix file
21
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
22
+
23
+ # 2. Read the matrix file to obtain background information and sample characteristics data
24
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
25
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
26
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
27
+
28
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
29
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
30
+
31
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
32
+ print("Background Information:")
33
+ print(background_info)
34
+ print("Sample Characteristics Dictionary:")
35
+ print(sample_characteristics_dict)
36
+ # Step 1: Determine Gene Expression Data Availability
37
+ is_gene_available = True # Based on the series description mentioning "Gene expression profile"
38
+
39
+ # Step 2: Identify Variable Availability and Define Conversion Functions
40
+
41
+ # 2.1 Identify keys for trait, age, gender
42
+ # Observing the sample characteristics, row 0 has "subject status" with two unique values.
43
+ # That matches our trait of interest (RA vs. Healthy control), so we set trait_row=0.
44
+ trait_row = 0
45
+ # There's no mention of age or gender in the sample characteristics, set them to None.
46
+ age_row = None
47
+ gender_row = None
48
+
49
+ # 2.2 Define conversion functions
50
+
51
+ def convert_trait(value: str):
52
+ """
53
+ Convert subject status to a binary variable:
54
+ Rheumatoid arthritis -> 1
55
+ Healthy control -> 0
56
+ Unknown or Other -> None
57
+ """
58
+ parts = value.split(":")
59
+ val_str = parts[1].strip().lower() if len(parts) > 1 else value.lower()
60
+ if "rheumatoid" in val_str:
61
+ return 1
62
+ elif "healthy" in val_str:
63
+ return 0
64
+ return None
65
+
66
+ def convert_age(value: str):
67
+ """
68
+ No age data available, return None.
69
+ """
70
+ return None
71
+
72
+ def convert_gender(value: str):
73
+ """
74
+ No gender data available, return None.
75
+ """
76
+ return None
77
+
78
+ # Step 3: Initial Filtering and Metadata Saving
79
+ is_trait_available = (trait_row is not None)
80
+ is_usable = 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 not None)
89
+ if trait_row is not None:
90
+ # Assume 'clinical_data' DataFrame is available in this environment (previously loaded).
91
+ selected_clinical_df = geo_select_clinical_features(
92
+ clinical_data,
93
+ trait=trait,
94
+ trait_row=trait_row,
95
+ convert_trait=convert_trait,
96
+ age_row=age_row,
97
+ convert_age=convert_age,
98
+ gender_row=gender_row,
99
+ convert_gender=convert_gender
100
+ )
101
+ # Preview the extracted clinical features
102
+ print("Preview of selected clinical features:", preview_df(selected_clinical_df, n=5))
103
+ # Save to CSV
104
+ selected_clinical_df.to_csv(out_clinical_data_file, index=False)
105
+ # STEP3
106
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
107
+ gene_data = get_genetic_data(matrix_file)
108
+
109
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
110
+ print(gene_data.index[:20])
111
+ # Observing the given identifiers (e.g., '10000_at', '10001_at', etc.), these appear to be Affymetrix probe set IDs.
112
+ # They are not standard human gene symbols, so they need to be mapped to gene symbols.
113
+ print("requires_gene_mapping = True")
114
+ # STEP5
115
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
116
+ gene_annotation = get_gene_annotation(soft_file)
117
+
118
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
119
+ print("Gene annotation preview:")
120
+ print(preview_df(gene_annotation))
121
+ # STEP: Gene Identifier Mapping
122
+
123
+ # 1. Based on the preview of the annotation, the column "ID" matches the probe IDs in our gene expression data,
124
+ # and "Description" includes the gene information (which will be further parsed to extract gene symbols).
125
+ # 2. Extract the mapping data using these two columns.
126
+ mapping_df = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='Description')
127
+
128
+ # 3. Convert probe-level measurements to gene-level measurements by applying the mapping.
129
+ gene_data = apply_gene_mapping(gene_data, mapping_df)
130
+
131
+ # Print a small preview to verify the resulting gene_data.
132
+ print("Mapped gene_data shape:", gene_data.shape)
133
+ print("Mapped gene_data preview:\n", gene_data.head())
134
+ # STEP 7
135
+
136
+ import pandas as pd
137
+
138
+ # 1. Normalize the gene expression data to standard gene symbols.
139
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
140
+ normalized_gene_data.to_csv(out_gene_data_file)
141
+ print("Normalized gene expression data saved to:", out_gene_data_file)
142
+
143
+ # 2. Read back the clinical data, reassign its single row index to the trait name, and link with genetic data.
144
+ selected_clinical_df = pd.read_csv(out_clinical_data_file, header=0)
145
+ selected_clinical_df.index = [trait] # Ensure the clinical row is labeled by the trait
146
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
147
+
148
+ # 3. Handle missing values systematically.
149
+ df = handle_missing_values(linked_data, trait)
150
+
151
+ # 4. Determine whether the trait or demographic features are biased; remove biased demographic features.
152
+ trait_biased, df = judge_and_remove_biased_features(df, trait)
153
+
154
+ # 5. Perform final validation with full dataset information.
155
+ is_usable = validate_and_save_cohort_info(
156
+ is_final=True,
157
+ cohort=cohort,
158
+ info_path=json_path,
159
+ is_gene_available=True,
160
+ is_trait_available=True,
161
+ is_biased=trait_biased,
162
+ df=df,
163
+ note="Final step with linking, missing-value handling, bias checks."
164
+ )
165
+
166
+ # 6. If the data is usable, save the final linked data.
167
+ if is_usable:
168
+ df.to_csv(out_data_file)
169
+ print(f"Final linked data saved to: {out_data_file}")
170
+ else:
171
+ print("Dataset is not usable or severely biased. No final data saved.")
p1/preprocess/Rheumatoid_Arthritis/code/GSE140161.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Rheumatoid_Arthritis"
6
+ cohort = "GSE140161"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Rheumatoid_Arthritis"
10
+ in_cohort_dir = "../DATA/GEO/Rheumatoid_Arthritis/GSE140161"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/preprocess/1/Rheumatoid_Arthritis/GSE140161.csv"
14
+ out_gene_data_file = "./output/preprocess/1/Rheumatoid_Arthritis/gene_data/GSE140161.csv"
15
+ out_clinical_data_file = "./output/preprocess/1/Rheumatoid_Arthritis/clinical_data/GSE140161.csv"
16
+ json_path = "./output/preprocess/1/Rheumatoid_Arthritis/cohort_info.json"
17
+
18
+ # STEP1
19
+ from tools.preprocess import *
20
+ # 1. Identify the paths to the SOFT file and the matrix file
21
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
22
+
23
+ # 2. Read the matrix file to obtain background information and sample characteristics data
24
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
25
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
26
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
27
+
28
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
29
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
30
+
31
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
32
+ print("Background Information:")
33
+ print(background_info)
34
+ print("Sample Characteristics Dictionary:")
35
+ print(sample_characteristics_dict)
36
+ import pandas as pd
37
+ from typing import Optional, Any
38
+
39
+ # 1. Gene Expression Data Availability
40
+ # From the background, the dataset uses an Affymetrix chip for whole blood transcriptome,
41
+ # so it likely contains gene expression data.
42
+ is_gene_available = True
43
+
44
+ # 2. Variable Availability and Data Type Conversion
45
+
46
+ # Sample characteristics dictionary indicates:
47
+ # 0: [ 'tissue: Whole blood' ]
48
+ # 1: [ 'Sex: female', 'Sex: male' ]
49
+ # 2: [ 'antissa status: Positive', 'antissa status: Negative' ]
50
+ # 3: [ 'antissb status: Negative', 'antissb status: Positive' ]
51
+ # 4: [ 'disease state: Sjögren’s syndrome' ]
52
+ #
53
+ # We are interested in "Rheumatoid_Arthritis" (trait), "age", and "gender":
54
+ # - Trait: Not found (all have disease state: Sjögren’s). There's only one unique value,
55
+ # so treat it as not available.
56
+ # - Age: Not found in the dictionary.
57
+ # - Gender: Found in row 1 with two unique values ("female", "male").
58
+
59
+ trait_row = None
60
+ age_row = None
61
+ gender_row = 1
62
+
63
+ def convert_trait(value: Any) -> Optional[float]:
64
+ # No trait data is actually available, so this function is just a placeholder.
65
+ return None
66
+
67
+ def convert_age(value: Any) -> Optional[float]:
68
+ # Age data is not available, placeholder function.
69
+ return None
70
+
71
+ def convert_gender(value: str) -> Optional[int]:
72
+ # Extract the raw value after the colon
73
+ parts = value.split(':')
74
+ if len(parts) < 2:
75
+ return None
76
+ gender_str = parts[1].strip().lower() # e.g. "female", "male"
77
+ if gender_str == 'female':
78
+ return 0
79
+ elif gender_str == 'male':
80
+ return 1
81
+ return None
82
+
83
+ # 3. Save Metadata with initial filtering
84
+ # Trait data is not available (trait_row=None), so is_trait_available=False.
85
+ is_trait_available = False
86
+ is_usable = validate_and_save_cohort_info(
87
+ is_final=False,
88
+ cohort=cohort,
89
+ info_path=json_path,
90
+ is_gene_available=is_gene_available,
91
+ is_trait_available=is_trait_available
92
+ )
93
+
94
+ # 4. Clinical Feature Extraction
95
+ # Since trait_row is None, we skip the extraction step.
96
+ # (No code needed here for extraction, per instructions.)
p1/preprocess/Rheumatoid_Arthritis/code/GSE143153.py ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Rheumatoid_Arthritis"
6
+ cohort = "GSE143153"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Rheumatoid_Arthritis"
10
+ in_cohort_dir = "../DATA/GEO/Rheumatoid_Arthritis/GSE143153"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/preprocess/1/Rheumatoid_Arthritis/GSE143153.csv"
14
+ out_gene_data_file = "./output/preprocess/1/Rheumatoid_Arthritis/gene_data/GSE143153.csv"
15
+ out_clinical_data_file = "./output/preprocess/1/Rheumatoid_Arthritis/clinical_data/GSE143153.csv"
16
+ json_path = "./output/preprocess/1/Rheumatoid_Arthritis/cohort_info.json"
17
+
18
+ # STEP1
19
+ from tools.preprocess import *
20
+ # 1. Identify the paths to the SOFT file and the matrix file
21
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
22
+
23
+ # 2. Read the matrix file to obtain background information and sample characteristics data
24
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
25
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
26
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
27
+
28
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
29
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
30
+
31
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
32
+ print("Background Information:")
33
+ print(background_info)
34
+ print("Sample Characteristics Dictionary:")
35
+ print(sample_characteristics_dict)
36
+ # 1. Gene Expression Data Availability
37
+ # Based on the background info, this dataset uses Agilent Whole Human Genome arrays,
38
+ # so we set is_gene_available to True.
39
+ is_gene_available = True
40
+
41
+ # 2. Variable Availability and Data Type Conversion
42
+
43
+ # The dataset is about "Primary SS" vs "non-SS" and does not appear to provide data for "Rheumatoid_Arthritis".
44
+ # So we set the trait_row to None (trait not available).
45
+
46
+ trait_row = None
47
+
48
+ # For age, row 2 presents multiple unique age values like 'age: 56', 'age: 51', etc.
49
+ # => age is available at row 2
50
+ age_row = 2
51
+
52
+ # For gender (sex), row 3 presents 'Sex: M' and 'Sex: F'.
53
+ # => gender is available at row 3
54
+ gender_row = 3
55
+
56
+ # We define conversion functions to extract values from the string after the colon and convert to the desired type.
57
+
58
+ def convert_trait(x: str):
59
+ """
60
+ Since we don't have RA data in this dataset, the function will return None.
61
+ Provided here just for completeness.
62
+ """
63
+ return None
64
+
65
+ def convert_age(x: str):
66
+ """
67
+ Extract the substring after the colon and convert to float.
68
+ If conversion fails, return None.
69
+ """
70
+ parts = x.split(':', 1)
71
+ if len(parts) < 2:
72
+ return None
73
+ val_str = parts[1].strip()
74
+ try:
75
+ return float(val_str)
76
+ except ValueError:
77
+ return None
78
+
79
+ def convert_gender(x: str):
80
+ """
81
+ Extract the substring after the colon and convert to 0/1.
82
+ 'F' -> 0, 'M' -> 1. Otherwise return None.
83
+ """
84
+ parts = x.split(':', 1)
85
+ if len(parts) < 2:
86
+ return None
87
+ val_str = parts[1].strip().upper()
88
+ if val_str == 'F':
89
+ return 0
90
+ elif val_str == 'M':
91
+ return 1
92
+ else:
93
+ return None
94
+
95
+ # 3. Save Metadata
96
+ # Trait data availability is determined by whether trait_row is None.
97
+ is_trait_available = (trait_row is not None)
98
+
99
+ # Perform initial filtering and save info.
100
+ # If not is_final step, we do not need 'df' or 'is_biased'.
101
+ # This will return a boolean indicating whether the dataset passes the initial filter.
102
+ is_usable = 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
111
+ # Only proceed if trait_row is not None. Here, trait_row is None, so we skip.
112
+ # STEP3
113
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
114
+ gene_data = get_genetic_data(matrix_file)
115
+
116
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
117
+ print(gene_data.index[:20])
118
+ # Observing the given gene identifiers: "1", "2", ..., "20"
119
+ # These are purely numeric and not standard gene symbols.
120
+ print("\nrequires_gene_mapping = True")
121
+ # STEP5
122
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
123
+ gene_annotation = get_gene_annotation(soft_file)
124
+
125
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
126
+ print("Gene annotation preview:")
127
+ print(preview_df(gene_annotation))
128
+ # STEP: Gene Identifier Mapping
129
+
130
+ # 1. From the annotation preview, we see that both the gene expression DataFrame and the annotation DataFrame
131
+ # share the "ID" column. The "GeneName" column appears to store gene symbols.
132
+ # 2. Get a gene mapping DataFrame using 'ID' as the probe identifier column and 'GeneName' as the gene symbol column.
133
+ mapping_df = get_gene_mapping(gene_annotation, prob_col="ID", gene_col="GeneName")
134
+
135
+ # 3. Convert probe-level measurements to gene-level expression data.
136
+ gene_data = apply_gene_mapping(gene_data, mapping_df)
137
+
138
+ # For verification, we print the shape and a portion of the index.
139
+ print("Mapped gene_data shape:", gene_data.shape)
140
+ print("First 10 gene symbols in mapped gene_data index:")
141
+ print(gene_data.index[:10].tolist())
142
+ # STEP 7
143
+
144
+ import os
145
+ import pandas as pd
146
+
147
+ # 1. Normalize the gene expression data to standard gene symbols.
148
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
149
+ normalized_gene_data.to_csv(out_gene_data_file)
150
+ print("Normalized gene expression data saved to:", out_gene_data_file)
151
+
152
+ # Since in Step 2 we found trait_row = None, we determined there is no RA trait data available.
153
+ # Without trait data, we cannot proceed with final linking or downstream analysis.
154
+
155
+ # 2. Mark the dataset as not usable at the initial stage (is_final=False),
156
+ # because it fails the trait availability check.
157
+ is_usable = validate_and_save_cohort_info(
158
+ is_final=False,
159
+ cohort=cohort,
160
+ info_path=json_path,
161
+ is_gene_available=True,
162
+ is_trait_available=False
163
+ )
164
+
165
+ # 3. Since trait data is unavailable, we cannot do any final preprocessing or save final linked data.
166
+ if not is_usable:
167
+ print("Dataset lacks trait data; cannot proceed with linking or final analysis. No final data saved.")
p1/preprocess/Rheumatoid_Arthritis/code/GSE176440.py ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Rheumatoid_Arthritis"
6
+ cohort = "GSE176440"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Rheumatoid_Arthritis"
10
+ in_cohort_dir = "../DATA/GEO/Rheumatoid_Arthritis/GSE176440"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/preprocess/1/Rheumatoid_Arthritis/GSE176440.csv"
14
+ out_gene_data_file = "./output/preprocess/1/Rheumatoid_Arthritis/gene_data/GSE176440.csv"
15
+ out_clinical_data_file = "./output/preprocess/1/Rheumatoid_Arthritis/clinical_data/GSE176440.csv"
16
+ json_path = "./output/preprocess/1/Rheumatoid_Arthritis/cohort_info.json"
17
+
18
+ # STEP1
19
+ from tools.preprocess import *
20
+ # 1. Identify the paths to the SOFT file and the matrix file
21
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
22
+
23
+ # 2. Read the matrix file to obtain background information and sample characteristics data
24
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
25
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
26
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
27
+
28
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
29
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
30
+
31
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
32
+ print("Background Information:")
33
+ print(background_info)
34
+ print("Sample Characteristics Dictionary:")
35
+ print(sample_characteristics_dict)
36
+ # 1. Determine if gene expression data is available
37
+ is_gene_available = True # Based on the Microarray indication
38
+
39
+ # 2. Determine availability of trait, age, and gender data
40
+ # Inspecting the sample characteristics dictionary, it appears that:
41
+ # - Row 1 has only one unique value: "disease state: rheumatoid arthritis patient"
42
+ # which is constant (not varying). So it is considered not available for analysis.
43
+ # - No other rows seem to contain relevant trait, age, or gender data.
44
+ trait_row = None
45
+ age_row = None
46
+ gender_row = None
47
+
48
+ # 2.2 Define data type conversion functions
49
+ def convert_trait(x: str) -> int:
50
+ # Placeholder. This function won't be used since trait_row is None
51
+ return 1 if 'rheumatoid arthritis' in x.lower() else None
52
+
53
+ def convert_age(x: str) -> float:
54
+ # Placeholder. This function won't be used since age_row is None
55
+ return None
56
+
57
+ def convert_gender(x: str) -> int:
58
+ # Placeholder. This function won't be used since gender_row is None
59
+ # If data were available, we would convert female->0, male->1
60
+ return None
61
+
62
+ # 3. Conduct initial filtering and save metadata
63
+ is_trait_available = (trait_row is not None)
64
+ validate_and_save_cohort_info(
65
+ is_final=False,
66
+ cohort=cohort,
67
+ info_path=json_path,
68
+ is_gene_available=is_gene_available,
69
+ is_trait_available=is_trait_available
70
+ )
71
+
72
+ # 4. Since trait_row is None, skip clinical feature extraction
73
+ # (No code needed for extraction as per instructions)
74
+ # STEP3
75
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
76
+ gene_data = get_genetic_data(matrix_file)
77
+
78
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
79
+ print(gene_data.index[:20])
80
+ # Based on the provided identifiers (e.g. "A_23_P100001", "A_23_P100011"), these appear to be array probe IDs rather than standard human gene symbols.
81
+ # Therefore, gene mapping to standard gene symbols is required.
82
+
83
+ requires_gene_mapping = True
84
+ # STEP5
85
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
86
+ gene_annotation = get_gene_annotation(soft_file)
87
+
88
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
89
+ print("Gene annotation preview:")
90
+ print(preview_df(gene_annotation))
91
+ # STEP: Gene Identifier Mapping
92
+
93
+ # 1 & 2. Decide which columns store the probe IDs and which store the gene symbols, and obtain the mapping dataframe.
94
+ gene_mapping_df = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='GENE_SYMBOL')
95
+
96
+ # 3. Convert probe-level measurements to gene expression data by applying the gene mapping.
97
+ gene_data = apply_gene_mapping(gene_data, gene_mapping_df)
98
+ # STEP 7
99
+
100
+ import pandas as pd
101
+
102
+ # Since trait_row was None in a previous step, there is no trait data available.
103
+ # Hence, there's no clinical CSV to read or link. We'll finalize the dataset as not usable.
104
+ is_trait_available = False
105
+
106
+ # We do have gene data, so is_gene_available is True.
107
+ # With no trait data, the dataset is not usable for our analysis.
108
+
109
+ from tools.preprocess import validate_and_save_cohort_info
110
+ import os
111
+
112
+ # Final validation: mark dataset as unavailable for trait-based analysis.
113
+ # We pass an empty DataFrame for df just to complete the function's parameters.
114
+ # We must provide a boolean for is_biased when is_final=True:
115
+ is_usable = validate_and_save_cohort_info(
116
+ is_final=True,
117
+ cohort=cohort,
118
+ info_path=json_path,
119
+ is_gene_available=True,
120
+ is_trait_available=is_trait_available,
121
+ is_biased=False,
122
+ df=pd.DataFrame(),
123
+ note="No trait data available to support further analysis."
124
+ )
125
+
126
+ print("Dataset is not usable due to missing trait data. No final data saved.")
p1/preprocess/Rheumatoid_Arthritis/code/GSE186963.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Rheumatoid_Arthritis"
6
+ cohort = "GSE186963"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Rheumatoid_Arthritis"
10
+ in_cohort_dir = "../DATA/GEO/Rheumatoid_Arthritis/GSE186963"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/preprocess/1/Rheumatoid_Arthritis/GSE186963.csv"
14
+ out_gene_data_file = "./output/preprocess/1/Rheumatoid_Arthritis/gene_data/GSE186963.csv"
15
+ out_clinical_data_file = "./output/preprocess/1/Rheumatoid_Arthritis/clinical_data/GSE186963.csv"
16
+ json_path = "./output/preprocess/1/Rheumatoid_Arthritis/cohort_info.json"
17
+
18
+ # STEP1
19
+ from tools.preprocess import *
20
+ # 1. Identify the paths to the SOFT file and the matrix file
21
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
22
+
23
+ # 2. Read the matrix file to obtain background information and sample characteristics data
24
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
25
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
26
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
27
+
28
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
29
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
30
+
31
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
32
+ print("Background Information:")
33
+ print(background_info)
34
+ print("Sample Characteristics Dictionary:")
35
+ print(sample_characteristics_dict)
36
+ # Step 1: Determine if gene expression data is available
37
+ # "Whole blood gene expression" suggests this dataset indeed contains gene expression data.
38
+ is_gene_available = True
39
+
40
+ # Step 2: Determine data availability for trait, age, and gender
41
+ # The dataset is about Crohn's disease, not Rheumatoid_Arthritis. There's no mention of age or gender.
42
+ # Hence, all these rows are unavailable because they do not match our trait of interest
43
+ # ("Rheumatoid_Arthritis"), nor do we see valid age or gender columns.
44
+ trait_row = None
45
+ age_row = None
46
+ gender_row = None
47
+
48
+ # Define the data conversion functions
49
+ # Since the dataset does not provide corresponding fields, these functions will return None.
50
+ def convert_trait(value: str):
51
+ return None
52
+
53
+ def convert_age(value: str):
54
+ return None
55
+
56
+ def convert_gender(value: str):
57
+ return None
58
+
59
+ # Step 3: Conduct initial filtering and save metadata
60
+ is_trait_available = (trait_row is not None)
61
+ is_usable = validate_and_save_cohort_info(
62
+ is_final=False,
63
+ cohort=cohort,
64
+ info_path=json_path,
65
+ is_gene_available=is_gene_available,
66
+ is_trait_available=is_trait_available
67
+ )
68
+
69
+ # Step 4: Skip clinical feature extraction because trait_row is None
p1/preprocess/Rheumatoid_Arthritis/code/GSE224330.py ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Rheumatoid_Arthritis"
6
+ cohort = "GSE224330"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Rheumatoid_Arthritis"
10
+ in_cohort_dir = "../DATA/GEO/Rheumatoid_Arthritis/GSE224330"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/preprocess/1/Rheumatoid_Arthritis/GSE224330.csv"
14
+ out_gene_data_file = "./output/preprocess/1/Rheumatoid_Arthritis/gene_data/GSE224330.csv"
15
+ out_clinical_data_file = "./output/preprocess/1/Rheumatoid_Arthritis/clinical_data/GSE224330.csv"
16
+ json_path = "./output/preprocess/1/Rheumatoid_Arthritis/cohort_info.json"
17
+
18
+ # STEP1
19
+ from tools.preprocess import *
20
+ # 1. Identify the paths to the SOFT file and the matrix file
21
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
22
+
23
+ # 2. Read the matrix file to obtain background information and sample characteristics data
24
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
25
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
26
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
27
+
28
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
29
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
30
+
31
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
32
+ print("Background Information:")
33
+ print(background_info)
34
+ print("Sample Characteristics Dictionary:")
35
+ print(sample_characteristics_dict)
36
+ # 1. Gene Expression Data Availability
37
+ is_gene_available = True # Background info indicates "Gene expression" data.
38
+
39
+ # 2. Variable Availability and Conversion Setup
40
+ # 2.1 Identify rows for trait, age, gender
41
+ trait_row = None # No row with explicit or inferable RA/healthy data.
42
+ age_row = 1 # Row 1 contains multiple distinct age values.
43
+ gender_row = 2 # Row 2 contains female/male info.
44
+
45
+ # 2.2 Data Type Conversions
46
+ def convert_age(value: str) -> Optional[float]:
47
+ # Example string: "age: 63y"
48
+ try:
49
+ # Split at ":", take second part, strip, remove trailing 'y'
50
+ val = value.split(":", 1)[1].strip().replace("y", "")
51
+ return float(val)
52
+ except:
53
+ return None
54
+
55
+ def convert_gender(value: str) -> Optional[int]:
56
+ # Example string: "gender: female" or "gender: male"
57
+ try:
58
+ val = value.split(":", 1)[1].strip().lower()
59
+ if val == "female":
60
+ return 0
61
+ elif val == "male":
62
+ return 1
63
+ else:
64
+ return None
65
+ except:
66
+ return None
67
+
68
+ # 3. Save Metadata (initial filtering)
69
+ is_trait_available = (trait_row is not None)
70
+ is_usable = validate_and_save_cohort_info(
71
+ is_final=False,
72
+ cohort=cohort,
73
+ info_path=json_path,
74
+ is_gene_available=is_gene_available,
75
+ is_trait_available=is_trait_available
76
+ )
77
+
78
+ # 4. Clinical Feature Extraction (skip if trait_row is None)
79
+ # Since trait_row is None, we do not extract or save clinical data.
80
+ # STEP3
81
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
82
+ gene_data = get_genetic_data(matrix_file)
83
+
84
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
85
+ print(gene_data.index[:20])
86
+ # These IDs appear to be microarray probe identifiers (e.g., Agilent probes), not standard human gene symbols.
87
+ # Hence, gene mapping is required.
88
+
89
+ print("These identifiers are microarray probe IDs that need to be mapped to gene symbols.")
90
+ print("requires_gene_mapping = True")
91
+ # STEP5
92
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
93
+ gene_annotation = get_gene_annotation(soft_file)
94
+
95
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
96
+ print("Gene annotation preview:")
97
+ print(preview_df(gene_annotation))
98
+ # STEP: Gene Identifier Mapping
99
+
100
+ # 1. In the gene annotation, the "ID" column corresponds to the probe identifiers,
101
+ # and the "GENE_SYMBOL" column stores human gene symbols.
102
+
103
+ # 2. Extract the gene mapping dataframe from gene_annotation
104
+ mapping_df = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='GENE_SYMBOL')
105
+
106
+ # 3. Convert the probe-level data in gene_data to gene-level data
107
+ gene_data = apply_gene_mapping(gene_data, mapping_df)
p1/preprocess/Rheumatoid_Arthritis/code/GSE224842.py ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Rheumatoid_Arthritis"
6
+ cohort = "GSE224842"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Rheumatoid_Arthritis"
10
+ in_cohort_dir = "../DATA/GEO/Rheumatoid_Arthritis/GSE224842"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/preprocess/1/Rheumatoid_Arthritis/GSE224842.csv"
14
+ out_gene_data_file = "./output/preprocess/1/Rheumatoid_Arthritis/gene_data/GSE224842.csv"
15
+ out_clinical_data_file = "./output/preprocess/1/Rheumatoid_Arthritis/clinical_data/GSE224842.csv"
16
+ json_path = "./output/preprocess/1/Rheumatoid_Arthritis/cohort_info.json"
17
+
18
+ # STEP1
19
+ from tools.preprocess import *
20
+ # 1. Identify the paths to the SOFT file and the matrix file
21
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
22
+
23
+ # 2. Read the matrix file to obtain background information and sample characteristics data
24
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
25
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
26
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
27
+
28
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
29
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
30
+
31
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
32
+ print("Background Information:")
33
+ print(background_info)
34
+ print("Sample Characteristics Dictionary:")
35
+ print(sample_characteristics_dict)
36
+ # 1. Gene Expression Data Availability
37
+ # From the series title and summary, it indicates "DNA microarray analyses" for gene expression in PBMCs.
38
+ # Thus, we consider gene expression data is available.
39
+ is_gene_available = True
40
+
41
+ # 2. Variable Availability and Data Type Conversion
42
+
43
+ # From the sample characteristics dictionary:
44
+ # {0: ['disease state: rheumatoid arthritis'], 1: ['cell type: PBMC']}
45
+ # There is no variation for "disease state" (all are rheumatoid arthritis); age and gender are not provided.
46
+ # Hence, we treat all three as not available.
47
+ trait_row = None
48
+ age_row = None
49
+ gender_row = None
50
+
51
+ # Define conversion functions (though they won't be used here because all rows are None).
52
+ def convert_trait(value: str):
53
+ """
54
+ Convert trait string to binary/continuous value.
55
+ This function splits at the colon (if present) and tries to interpret the resulting value.
56
+ Unknown or non-matching values are converted to None.
57
+ """
58
+ parts = value.split(':', 1)
59
+ extracted = parts[1].strip().lower() if len(parts) > 1 else value.strip().lower()
60
+
61
+ if 'rheumatoid arthritis' in extracted:
62
+ return 1
63
+ elif 'healthy' in extracted:
64
+ return 0
65
+ return None
66
+
67
+ def convert_age(value: str):
68
+ """
69
+ Convert age string to a continuous value (float).
70
+ Splits at the colon, then tries to parse as float. Unknown values => None.
71
+ """
72
+ parts = value.split(':', 1)
73
+ extracted = parts[1].strip() if len(parts) > 1 else value.strip()
74
+ try:
75
+ return float(extracted)
76
+ except ValueError:
77
+ return None
78
+
79
+ def convert_gender(value: str):
80
+ """
81
+ Convert gender string to binary (female=0, male=1).
82
+ Splits at the colon, interprets the result, unknown => None.
83
+ """
84
+ parts = value.split(':', 1)
85
+ extracted = parts[1].strip().lower() if len(parts) > 1 else value.strip().lower()
86
+ if extracted in ['female', 'f']:
87
+ return 0
88
+ elif extracted in ['male', 'm']:
89
+ return 1
90
+ return None
91
+
92
+ # 3. Save Metadata (initial filtering)
93
+ is_trait_available = (trait_row is not None)
94
+ validate_and_save_cohort_info(
95
+ is_final=False,
96
+ cohort=cohort, # "GSE224842"
97
+ info_path=json_path, # "./output/preprocess/1/Rheumatoid_Arthritis/cohort_info.json"
98
+ is_gene_available=is_gene_available,
99
+ is_trait_available=is_trait_available
100
+ )
101
+
102
+ # 4. Clinical Feature Extraction
103
+ # Since trait_row is None, skip extracting clinical features.
104
+ # STEP3
105
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
106
+ gene_data = get_genetic_data(matrix_file)
107
+
108
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
109
+ print(gene_data.index[:20])
110
+ # Based on the observed identifiers (e.g., A_23_P100001), they appear to be microarray probe IDs (not standard gene symbols).
111
+ # Hence, gene mapping to standardized gene symbols is required.
112
+
113
+ print("requires_gene_mapping = True")
114
+ # STEP5
115
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
116
+ gene_annotation = get_gene_annotation(soft_file)
117
+
118
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
119
+ print("Gene annotation preview:")
120
+ print(preview_df(gene_annotation))
121
+ # STEP: Gene Identifier Mapping
122
+
123
+ # 1. Identify the columns in the gene annotation that correspond to the probe ID and the gene symbol
124
+ # From the preview, "ID" matches the probe identifiers in gene_data, and "GENE_SYMBOL" is the gene symbol.
125
+
126
+ # 2. Create a mapping dataframe from "ID" to "GENE_SYMBOL"
127
+ gene_mapping = get_gene_mapping(gene_annotation, prob_col="ID", gene_col="GENE_SYMBOL")
128
+
129
+ # 3. Apply the mapping to convert probe-level data to gene-level expression
130
+ gene_data = apply_gene_mapping(gene_data, gene_mapping)
131
+
132
+ # Quick check of the new gene_data structure
133
+ print("Gene expression data shape after mapping:", gene_data.shape)
134
+ print("First 5 gene symbols:", gene_data.index[:5])
135
+ # STEP 7
136
+
137
+ import os
138
+ import pandas as pd
139
+
140
+ # 1. Normalize the gene expression data to standard gene symbols.
141
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
142
+ normalized_gene_data.to_csv(out_gene_data_file)
143
+ print("Normalized gene expression data saved to:", out_gene_data_file)
144
+
145
+ # Since trait_row was determined to be None in Step 2 (indicating no clinical trait data),
146
+ # we cannot produce a final linked DataFrame or perform a final validation that requires df and is_biased.
147
+ # Instead, we perform partial validation to record that trait data is unavailable.
148
+
149
+ validate_and_save_cohort_info(
150
+ is_final=False,
151
+ cohort=cohort,
152
+ info_path=json_path,
153
+ is_gene_available=True, # We do have gene expression data
154
+ is_trait_available=False # No trait data
155
+ )
156
+
157
+ print("No trait data available. Skipping linking, missing-value handling, and final validation.")
p1/preprocess/Rheumatoid_Arthritis/code/GSE236924.py ADDED
@@ -0,0 +1,165 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Rheumatoid_Arthritis"
6
+ cohort = "GSE236924"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Rheumatoid_Arthritis"
10
+ in_cohort_dir = "../DATA/GEO/Rheumatoid_Arthritis/GSE236924"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/preprocess/1/Rheumatoid_Arthritis/GSE236924.csv"
14
+ out_gene_data_file = "./output/preprocess/1/Rheumatoid_Arthritis/gene_data/GSE236924.csv"
15
+ out_clinical_data_file = "./output/preprocess/1/Rheumatoid_Arthritis/clinical_data/GSE236924.csv"
16
+ json_path = "./output/preprocess/1/Rheumatoid_Arthritis/cohort_info.json"
17
+
18
+ # STEP1
19
+ from tools.preprocess import *
20
+ # 1. Identify the paths to the SOFT file and the matrix file
21
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
22
+
23
+ # 2. Read the matrix file to obtain background information and sample characteristics data
24
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
25
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
26
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
27
+
28
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
29
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
30
+
31
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
32
+ print("Background Information:")
33
+ print(background_info)
34
+ print("Sample Characteristics Dictionary:")
35
+ print(sample_characteristics_dict)
36
+ # Step 1: Gene expression data availability
37
+ is_gene_available = True # Based on "array" in the series title and summary, it's likely gene expression
38
+
39
+ # Step 2.1: Variable availability
40
+ # According to the sample characteristics dictionary,
41
+ # {0: ['disease: OA', 'disease: Control', 'disease: RA']}
42
+ # we see that row 0 records disease states, including RA. So that can be used for the trait.
43
+ trait_row = 0
44
+
45
+ # No information about age or gender is provided, so they are not available
46
+ age_row = None
47
+ gender_row = None
48
+
49
+ # Step 2.2: Data type conversion
50
+ def convert_trait(x: str):
51
+ # Extract the substring after the colon
52
+ parts = x.split(":")
53
+ val = parts[-1].strip().lower() if len(parts) > 1 else None
54
+ if val is None:
55
+ return None
56
+
57
+ # Convert "ra" to 1, else 0 (for OA or Control)
58
+ if val == 'ra':
59
+ return 1
60
+ elif val in ['oa', 'control']:
61
+ return 0
62
+ return None
63
+
64
+ def convert_age(x: str):
65
+ # No age data is available. Return None for all inputs.
66
+ return None
67
+
68
+ def convert_gender(x: str):
69
+ # No gender data is available. Return None for all inputs.
70
+ return None
71
+
72
+ # Step 3: Save metadata (initial filtering)
73
+ is_trait_available = (trait_row is not None)
74
+ validate_and_save_cohort_info(
75
+ is_final=False,
76
+ cohort=cohort,
77
+ info_path=json_path,
78
+ is_gene_available=is_gene_available,
79
+ is_trait_available=is_trait_available
80
+ )
81
+
82
+ # Step 4: Clinical feature extraction (only if trait_row is not None)
83
+ if trait_row is not None:
84
+ clinical_features_df = geo_select_clinical_features(
85
+ clinical_data,
86
+ trait=trait,
87
+ trait_row=trait_row,
88
+ convert_trait=convert_trait,
89
+ age_row=age_row,
90
+ convert_age=convert_age,
91
+ gender_row=gender_row,
92
+ convert_gender=convert_gender
93
+ )
94
+
95
+ # Preview the extracted clinical features
96
+ preview_data = preview_df(clinical_features_df)
97
+ print("Preview of clinical features:", preview_data)
98
+
99
+ # Save the clinical data
100
+ clinical_features_df.to_csv(out_clinical_data_file, index=False)
101
+ # STEP3
102
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
103
+ gene_data = get_genetic_data(matrix_file)
104
+
105
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
106
+ print(gene_data.index[:20])
107
+ # Observing the gene identifiers in the expression data, they appear to be Affymetrix probe set IDs.
108
+ # Hence, they are not standard gene symbols and require mapping.
109
+ requires_gene_mapping = True
110
+ # STEP5
111
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
112
+ gene_annotation = get_gene_annotation(soft_file)
113
+
114
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
115
+ print("Gene annotation preview:")
116
+ print(preview_df(gene_annotation))
117
+ # STEP: Gene Identifier Mapping
118
+
119
+ # 1. Identify the columns that match the gene expression identifiers and the gene symbols respectively.
120
+ # From the annotation preview, the "ID" column matches the probe identifiers in gene_data.
121
+ # And the "Gene Symbol" column stores the gene symbols.
122
+
123
+ # 2. Extract the mapping dataframe using the get_gene_mapping method.
124
+ mapping_df = get_gene_mapping(gene_annotation, prob_col="ID", gene_col="Gene Symbol")
125
+
126
+ # 3. Convert probe-level data to gene-level data by applying the mapping.
127
+ gene_data = apply_gene_mapping(gene_data, mapping_df)
128
+ # STEP 7
129
+
130
+ import pandas as pd
131
+
132
+ # 1. Normalize the gene expression data to standard gene symbols.
133
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
134
+ normalized_gene_data.to_csv(out_gene_data_file)
135
+ print("Normalized gene expression data saved to:", out_gene_data_file)
136
+
137
+ # 2. Read back the clinical data, reassign its single row index to the trait name, and link with genetic data.
138
+ selected_clinical_df = pd.read_csv(out_clinical_data_file, header=0)
139
+ selected_clinical_df.index = [trait] # Ensure the clinical row is labeled by the trait
140
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
141
+
142
+ # 3. Handle missing values systematically.
143
+ df = handle_missing_values(linked_data, trait)
144
+
145
+ # 4. Determine whether the trait or demographic features are biased; remove biased demographic features.
146
+ trait_biased, df = judge_and_remove_biased_features(df, trait)
147
+
148
+ # 5. Perform final validation with full dataset information.
149
+ is_usable = validate_and_save_cohort_info(
150
+ is_final=True,
151
+ cohort=cohort,
152
+ info_path=json_path,
153
+ is_gene_available=True,
154
+ is_trait_available=True,
155
+ is_biased=trait_biased,
156
+ df=df,
157
+ note="Final step with linking, missing-value handling, bias checks."
158
+ )
159
+
160
+ # 6. If the data is usable, save the final linked data.
161
+ if is_usable:
162
+ df.to_csv(out_data_file)
163
+ print(f"Final linked data saved to: {out_data_file}")
164
+ else:
165
+ print("Dataset is not usable or severely biased. No final data saved.")
p1/preprocess/Rheumatoid_Arthritis/code/GSE42842.py ADDED
@@ -0,0 +1,158 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Rheumatoid_Arthritis"
6
+ cohort = "GSE42842"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Rheumatoid_Arthritis"
10
+ in_cohort_dir = "../DATA/GEO/Rheumatoid_Arthritis/GSE42842"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/preprocess/1/Rheumatoid_Arthritis/GSE42842.csv"
14
+ out_gene_data_file = "./output/preprocess/1/Rheumatoid_Arthritis/gene_data/GSE42842.csv"
15
+ out_clinical_data_file = "./output/preprocess/1/Rheumatoid_Arthritis/clinical_data/GSE42842.csv"
16
+ json_path = "./output/preprocess/1/Rheumatoid_Arthritis/cohort_info.json"
17
+
18
+ # STEP1
19
+ from tools.preprocess import *
20
+ # 1. Identify the paths to the SOFT file and the matrix file
21
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
22
+
23
+ # 2. Read the matrix file to obtain background information and sample characteristics data
24
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
25
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
26
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
27
+
28
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
29
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
30
+
31
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
32
+ print("Background Information:")
33
+ print(background_info)
34
+ print("Sample Characteristics Dictionary:")
35
+ print(sample_characteristics_dict)
36
+ # 1) Determine if gene expression data is available
37
+ is_gene_available = True # Based on the background info, this dataset does use gene expression arrays.
38
+
39
+ # 2) Identify rows for trait, age, and gender in the sample characteristics
40
+ # and define their data-conversion functions.
41
+
42
+ # From the provided dictionary:
43
+ # 0 -> ['gender: M', 'gender: F']
44
+ # 1 -> ['cell type: PBMC']
45
+ # 2 -> ['disease state: rheumatoid arthritis']
46
+ # 3 -> ['treatment: methotrexate + adalimumab', 'treatment: methotrexate + etanercept']
47
+ # 4 -> ['efficacy: moderate response', 'efficacy: response']
48
+
49
+ # The "trait" here is rheumatoid arthritis, but the dictionary has only one unique value in row 2.
50
+ # This is not useful for association analysis, so we mark trait_row as None (not available).
51
+ trait_row = None
52
+
53
+ # No age data is found, so age_row is None.
54
+ age_row = None
55
+
56
+ # We do have gender data (M/F) in row 0, which varies, so gender_row = 0.
57
+ gender_row = 0
58
+
59
+ # Define conversion functions. Even if trait or age are not available, we still define them to keep consistent signatures.
60
+ def convert_trait(raw_value: str):
61
+ """
62
+ This function would convert RA data if we had it.
63
+ But trait_row = None, so this is unused here.
64
+ """
65
+ return None
66
+
67
+ def convert_age(raw_value: str):
68
+ """
69
+ Age not found in the dataset, so no actual conversion.
70
+ """
71
+ return None
72
+
73
+ def convert_gender(raw_value: str):
74
+ """
75
+ Convert 'gender' values to a binary variable: F -> 0, M -> 1.
76
+ If unknown, return None.
77
+ """
78
+ # Split at the colon, take the latter part, strip spaces.
79
+ parts = raw_value.split(':')
80
+ if len(parts) > 1:
81
+ val = parts[1].strip().upper()
82
+ if val in ['F', 'FEMALE']:
83
+ return 0
84
+ elif val in ['M', 'MALE']:
85
+ return 1
86
+ return None
87
+
88
+ # 3) Conduct initial filtering and save metadata using validate_and_save_cohort_info
89
+ # Trait availability depends on whether trait_row is None.
90
+ is_trait_available = (trait_row is not None)
91
+
92
+ is_usable = validate_and_save_cohort_info(
93
+ is_final=False,
94
+ cohort=cohort,
95
+ info_path=json_path,
96
+ is_gene_available=is_gene_available,
97
+ is_trait_available=is_trait_available
98
+ )
99
+
100
+ # 4) Because trait_row is None, we skip the clinical feature extraction step.
101
+ # (No code needed here, as there is no available trait data.)
102
+ # STEP3
103
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
104
+ gene_data = get_genetic_data(matrix_file)
105
+
106
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
107
+ print(gene_data.index[:20])
108
+ print("These gene identifiers are numeric, so they are not standard human gene symbols.")
109
+ print("requires_gene_mapping = True")
110
+ # STEP5
111
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
112
+ gene_annotation = get_gene_annotation(soft_file)
113
+
114
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
115
+ print("Gene annotation preview:")
116
+ print(preview_df(gene_annotation))
117
+ # STEP: Gene Identifier Mapping
118
+
119
+ # 1. We identified that the "ID" column in the gene annotation DataFrame corresponds to the numerically labeled
120
+ # probes in our gene_data, and "GENE_SYMBOL" holds the actual gene symbols (though not visible in the
121
+ # first few rows).
122
+
123
+ # 2. Extract the relevant columns for gene mapping
124
+ mapping_df = get_gene_mapping(gene_annotation, prob_col="ID", gene_col="GENE_SYMBOL")
125
+
126
+ # 3. Convert probe-level measurements to gene-level expression
127
+ gene_data = apply_gene_mapping(gene_data, mapping_df)
128
+ # STEP 7
129
+
130
+ import pandas as pd
131
+
132
+ # 1. Normalize the gene expression data to standard gene symbols.
133
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
134
+ normalized_gene_data.to_csv(out_gene_data_file)
135
+ print("Normalized gene expression data saved to:", out_gene_data_file)
136
+
137
+ # 2) Since the trait is not available (trait_row is None from Step 2),
138
+ # we skip linking or trait-based processing. However, we still need to
139
+ # finalize metadata to accurately record dataset status.
140
+ print("Trait data is not available. Skipping clinical linking, missing-value handling, and bias checks.")
141
+
142
+ # Prepare an empty placeholder DataFrame for final validation (required arguments).
143
+ dummy_df = pd.DataFrame()
144
+
145
+ # Final validation to mark that trait data is not available
146
+ is_biased = False # Arbitrarily set; won't matter since trait is unavailable
147
+ validate_and_save_cohort_info(
148
+ is_final=True,
149
+ cohort=cohort,
150
+ info_path=json_path,
151
+ is_gene_available=True,
152
+ is_trait_available=False,
153
+ is_biased=is_biased,
154
+ df=dummy_df,
155
+ note="No trait data available for this cohort."
156
+ )
157
+
158
+ print("Dataset status recorded. No final merged data saved due to missing trait.")
p1/preprocess/Rheumatoid_Arthritis/code/GSE97475.py ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Rheumatoid_Arthritis"
6
+ cohort = "GSE97475"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Rheumatoid_Arthritis"
10
+ in_cohort_dir = "../DATA/GEO/Rheumatoid_Arthritis/GSE97475"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/preprocess/1/Rheumatoid_Arthritis/GSE97475.csv"
14
+ out_gene_data_file = "./output/preprocess/1/Rheumatoid_Arthritis/gene_data/GSE97475.csv"
15
+ out_clinical_data_file = "./output/preprocess/1/Rheumatoid_Arthritis/clinical_data/GSE97475.csv"
16
+ json_path = "./output/preprocess/1/Rheumatoid_Arthritis/cohort_info.json"
17
+
18
+ # STEP1
19
+ from tools.preprocess import *
20
+ # 1. Identify the paths to the SOFT file and the matrix file
21
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
22
+
23
+ # 2. Read the matrix file to obtain background information and sample characteristics data
24
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
25
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
26
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
27
+
28
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
29
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
30
+
31
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
32
+ print("Background Information:")
33
+ print(background_info)
34
+ print("Sample Characteristics Dictionary:")
35
+ print(sample_characteristics_dict)
36
+ # 1. Gene Expression Data Availability
37
+ is_gene_available = True # The series summary explicitly mentions microarray (transcriptomic) data
38
+
39
+ # 2. Variable Availability and Data Type Conversion
40
+
41
+ # After reviewing the sample characteristics dictionary, there is no row
42
+ # indicating distinct Rheumatoid Arthritis vs. control status. Hence trait is unavailable.
43
+ trait_row = None
44
+
45
+ # For age, row 81 provides multiple distinct numeric entries.
46
+ age_row = 81
47
+
48
+ # For gender, row 118 provides 'Male' and 'Female'.
49
+ gender_row = 118
50
+
51
+ # 2.2 Define conversion functions
52
+
53
+ def convert_trait(x: str) -> int:
54
+ """
55
+ Since trait data is not found in this dataset,
56
+ this function is defined but won't be used.
57
+ """
58
+ return None
59
+
60
+ def convert_age(x: str) -> float:
61
+ """
62
+ Convert age string like 'subjects.demographics.age: 60' -> float(60).
63
+ If it fails, return None.
64
+ """
65
+ parts = x.split(':')
66
+ if len(parts) < 2:
67
+ return None
68
+ try:
69
+ return float(parts[1].strip())
70
+ except ValueError:
71
+ return None
72
+
73
+ def convert_gender(x: str) -> int:
74
+ """
75
+ Convert gender string like 'subjects.demographics.sex: Male' -> 1
76
+ and 'subjects.demographics.sex: Female' -> 0.
77
+ If it fails, return None.
78
+ """
79
+ parts = x.split(':')
80
+ if len(parts) < 2:
81
+ return None
82
+ val = parts[1].strip().lower()
83
+ if val == 'male':
84
+ return 1
85
+ elif val == 'female':
86
+ return 0
87
+ return None
88
+
89
+ # 3. Initial Filtering and Saving Metadata
90
+ # trait data availability depends on whether trait_row is None
91
+ is_trait_available = (trait_row is not None)
92
+
93
+ is_usable = validate_and_save_cohort_info(
94
+ is_final=False,
95
+ cohort=cohort,
96
+ info_path=json_path,
97
+ is_gene_available=is_gene_available,
98
+ is_trait_available=is_trait_available
99
+ )
100
+
101
+ # 4. Clinical Feature Extraction
102
+ # Since trait_row is None, we skip clinical feature extraction.
103
+ # STEP3
104
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
105
+ gene_data = get_genetic_data(matrix_file)
106
+
107
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
108
+ print(gene_data.index[:20])
109
+ print("The gene identifiers appear to be standard human gene symbols.")
110
+ print("requires_gene_mapping = False")
111
+ # STEP 5
112
+
113
+ import pandas as pd
114
+
115
+ # 1. Normalize the gene expression data to standard gene symbols.
116
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
117
+ normalized_gene_data.to_csv(out_gene_data_file)
118
+ print("Normalized gene expression data saved to:", out_gene_data_file)
119
+
120
+ # Since we determined trait_row is None earlier, trait data is unavailable (is_trait_available=False).
121
+ # We cannot do a final validation that requires df and is_biased.
122
+ # Instead, we record that the dataset fails due to missing trait data, and skip linking/analysis.
123
+
124
+ is_trait_available = False
125
+
126
+ if not is_trait_available:
127
+ # Record that the dataset is missing trait data without doing final validation.
128
+ validate_and_save_cohort_info(
129
+ is_final=False,
130
+ cohort=cohort,
131
+ info_path=json_path,
132
+ is_gene_available=True,
133
+ is_trait_available=False
134
+ )
135
+ print("Trait data not available => dataset not suitable for trait-based analysis. No final data saved.")
136
+ else:
137
+ # If, hypothetically, trait data existed, we'd link and finalize. Skipped here.
138
+ selected_clinical_df = pd.read_csv(out_clinical_data_file, index_col=0)
139
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
140
+
141
+ df = handle_missing_values(linked_data, trait)
142
+ trait_biased, df = judge_and_remove_biased_features(df, trait)
143
+
144
+ is_usable = validate_and_save_cohort_info(
145
+ is_final=True,
146
+ cohort=cohort,
147
+ info_path=json_path,
148
+ is_gene_available=True,
149
+ is_trait_available=True,
150
+ is_biased=trait_biased,
151
+ df=df,
152
+ note="Final step with linking, missing-value handling, bias checks."
153
+ )
154
+
155
+ if is_usable:
156
+ df.to_csv(out_data_file)
157
+ print(f"Final linked data saved to: {out_data_file}")
158
+ else:
159
+ print("Dataset is not usable or is severely biased. No final data saved.")
p1/preprocess/Rheumatoid_Arthritis/code/TCGA.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Rheumatoid_Arthritis"
6
+
7
+ # Input paths
8
+ tcga_root_dir = "../DATA/TCGA"
9
+
10
+ # Output paths
11
+ out_data_file = "./output/preprocess/1/Rheumatoid_Arthritis/TCGA.csv"
12
+ out_gene_data_file = "./output/preprocess/1/Rheumatoid_Arthritis/gene_data/TCGA.csv"
13
+ out_clinical_data_file = "./output/preprocess/1/Rheumatoid_Arthritis/clinical_data/TCGA.csv"
14
+ json_path = "./output/preprocess/1/Rheumatoid_Arthritis/cohort_info.json"
15
+
16
+ import os
17
+
18
+ # Step 1: Identify subdirectory that might relate to our trait "Rheumatoid_Arthritis"
19
+ subdirs = [
20
+ 'CrawlData.ipynb', '.DS_Store', 'TCGA_lower_grade_glioma_and_glioblastoma_(GBMLGG)',
21
+ 'TCGA_Uterine_Carcinosarcoma_(UCS)', 'TCGA_Thyroid_Cancer_(THCA)', 'TCGA_Thymoma_(THYM)',
22
+ 'TCGA_Testicular_Cancer_(TGCT)', 'TCGA_Stomach_Cancer_(STAD)', 'TCGA_Sarcoma_(SARC)',
23
+ 'TCGA_Rectal_Cancer_(READ)', 'TCGA_Prostate_Cancer_(PRAD)', 'TCGA_Pheochromocytoma_Paraganglioma_(PCPG)',
24
+ 'TCGA_Pancreatic_Cancer_(PAAD)', 'TCGA_Ovarian_Cancer_(OV)', 'TCGA_Ocular_melanomas_(UVM)',
25
+ 'TCGA_Mesothelioma_(MESO)', 'TCGA_Melanoma_(SKCM)', 'TCGA_Lung_Squamous_Cell_Carcinoma_(LUSC)',
26
+ 'TCGA_Lung_Cancer_(LUNG)', 'TCGA_Lung_Adenocarcinoma_(LUAD)', 'TCGA_Lower_Grade_Glioma_(LGG)',
27
+ 'TCGA_Liver_Cancer_(LIHC)', 'TCGA_Large_Bcell_Lymphoma_(DLBC)', 'TCGA_Kidney_Papillary_Cell_Carcinoma_(KIRP)',
28
+ 'TCGA_Kidney_Clear_Cell_Carcinoma_(KIRC)', 'TCGA_Kidney_Chromophobe_(KICH)', 'TCGA_Head_and_Neck_Cancer_(HNSC)',
29
+ 'TCGA_Glioblastoma_(GBM)', 'TCGA_Esophageal_Cancer_(ESCA)', 'TCGA_Endometrioid_Cancer_(UCEC)',
30
+ 'TCGA_Colon_and_Rectal_Cancer_(COADREAD)', 'TCGA_Colon_Cancer_(COAD)', 'TCGA_Cervical_Cancer_(CESC)',
31
+ 'TCGA_Breast_Cancer_(BRCA)', 'TCGA_Bladder_Cancer_(BLCA)', 'TCGA_Bile_Duct_Cancer_(CHOL)',
32
+ 'TCGA_Adrenocortical_Cancer_(ACC)', 'TCGA_Acute_Myeloid_Leukemia_(LAML)'
33
+ ]
34
+
35
+ suitable_subdir = None
36
+
37
+ # Look for "rheumatoid" in subdirectories
38
+ for sd in subdirs:
39
+ if "rheumatoid" in sd.lower():
40
+ suitable_subdir = sd
41
+ break
42
+
43
+ if not suitable_subdir:
44
+ print("No suitable subdirectory found for trait 'Rheumatoid_Arthritis'. Skipping this trait.")
45
+ validate_and_save_cohort_info(
46
+ is_final=False,
47
+ cohort="TCGA",
48
+ info_path=json_path,
49
+ is_gene_available=False,
50
+ is_trait_available=False
51
+ )
52
+ else:
53
+ # Step 2: Identify clinical and genetic file paths
54
+ clinical_path, genetic_path = tcga_get_relevant_filepaths(os.path.join(tcga_root_dir, suitable_subdir))
55
+
56
+ # Step 3: Load data into dataframes
57
+ clinical_df = pd.read_csv(clinical_path, index_col=0, sep='\t')
58
+ genetic_df = pd.read_csv(genetic_path, index_col=0, sep='\t')
59
+
60
+ # Step 4: Print clinical data columns
61
+ print("Clinical Data Columns:", clinical_df.columns.tolist())
p1/preprocess/Rheumatoid_Arthritis/cohort_info.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"GSE97475": {"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}, "GSE42842": {"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": "No trait data available for this cohort."}, "GSE236924": {"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": 132, "note": "Final step with linking, missing-value handling, bias checks."}, "GSE224842": {"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}, "GSE224330": {"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}, "GSE186963": {"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}, "GSE176440": {"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": "No trait data available to support further analysis."}, "GSE143153": {"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}, "GSE140161": {"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}, "GSE121894": {"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": 58, "note": "Final step with linking, missing-value handling, bias checks."}, "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}}
p1/preprocess/Rheumatoid_Arthritis/gene_data/GSE121894.csv ADDED
The diff for this file is too large to render. See raw diff
 
p1/preprocess/Rheumatoid_Arthritis/gene_data/GSE143153.csv ADDED
The diff for this file is too large to render. See raw diff
 
p1/preprocess/Rheumatoid_Arthritis/gene_data/GSE176440.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b3f50961527552fc1068262f086379dad753130d10b73cd5496018ede9f9fbc0
3
+ size 12288669
p1/preprocess/Rheumatoid_Arthritis/gene_data/GSE224842.csv ADDED
The diff for this file is too large to render. See raw diff
 
p1/preprocess/Rheumatoid_Arthritis/gene_data/GSE42842.csv ADDED
The diff for this file is too large to render. See raw diff
 
p1/preprocess/Sarcoma/clinical_data/GSE197147.csv ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ GSM5910186,GSM5910187,GSM5910188,GSM5910189,GSM5910190,GSM5910191,GSM5910192,GSM5910193,GSM5910194,GSM5910195,GSM5910196,GSM5910197,GSM5910198,GSM5910199,GSM5910200,GSM5910201,GSM5910202,GSM5910203,GSM5910204,GSM5910205,GSM5910206,GSM5910207,GSM5910208,GSM5910209,GSM5910210,GSM5910211,GSM5910212,GSM5910213,GSM5910214,GSM5910215,GSM5910216,GSM5910217,GSM5910218,GSM5910219,GSM5910220,GSM5910221,GSM5910222,GSM5910223,GSM5910224,GSM5910225,GSM5910226,GSM5910227,GSM5910228,GSM5910229,GSM5910230,GSM5910231,GSM5910232,GSM5910233,GSM5910234,GSM5910235,GSM5910236,GSM5910237,GSM5910238,GSM5910239,GSM5910240,GSM5910241,GSM5910242,GSM5910243,GSM5910244,GSM5910245,GSM5910246,GSM5910247,GSM5910248,GSM5910249,GSM5910250,GSM5910251,GSM5910252,GSM5910253,GSM5910254,GSM5910255,GSM5910256,GSM5910257,GSM5910258,GSM5910259,GSM5910260,GSM5910261,GSM5910262,GSM5910263,GSM5910264
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,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,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
p1/preprocess/Sarcoma/code/GSE118336.py ADDED
@@ -0,0 +1,251 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Sarcoma"
6
+ cohort = "GSE118336"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Sarcoma"
10
+ in_cohort_dir = "../DATA/GEO/Sarcoma/GSE118336"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/preprocess/1/Sarcoma/GSE118336.csv"
14
+ out_gene_data_file = "./output/preprocess/1/Sarcoma/gene_data/GSE118336.csv"
15
+ out_clinical_data_file = "./output/preprocess/1/Sarcoma/clinical_data/GSE118336.csv"
16
+ json_path = "./output/preprocess/1/Sarcoma/cohort_info.json"
17
+
18
+ # STEP1
19
+ from tools.preprocess import *
20
+ # 1. Identify the paths to the SOFT file and the matrix file
21
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
22
+
23
+ # 2. Read the matrix file to obtain background information and sample characteristics data
24
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
25
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
26
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
27
+
28
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
29
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
30
+
31
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
32
+ print("Background Information:")
33
+ print(background_info)
34
+ print("Sample Characteristics Dictionary:")
35
+ print(sample_characteristics_dict)
36
+ # Step: Dataset Analysis and Clinical Feature Extraction
37
+
38
+ # 1. Gene Expression Data Availability
39
+ # The Series title indicates "HTA2.0 (human transcriptome array) analysis", which suggests
40
+ # actual gene expression data is available (and not simply miRNA or methylation data).
41
+ is_gene_available = True
42
+
43
+ # 2. Variable Availability and Data Type Conversion
44
+
45
+ # 2.1 Identify keys in the sample characteristics for each variable:
46
+ trait_row = None # No mention of 'Sarcoma' or a relevant disease key in the dictionary.
47
+ age_row = None # No age information found.
48
+ gender_row = None # No gender information found.
49
+
50
+ # 2.2 Define data-type conversion functions. Even though data is not available,
51
+ # we provide them as placeholders.
52
+
53
+ def convert_trait(x: str) -> int:
54
+ # Not used because trait_row is None, but here's a placeholder function.
55
+ # Convert to 'binary' if used, or return None for unknown.
56
+ return None
57
+
58
+ def convert_age(x: str) -> float:
59
+ # Not used because age_row is None, placeholder function
60
+ return None
61
+
62
+ def convert_gender(x: str) -> int:
63
+ # Not used because gender_row is None, placeholder function
64
+ return None
65
+
66
+ # 3. Save Metadata (initial filtering).
67
+ # Trait data availability depends on trait_row. Since trait_row is None, is_trait_available=False.
68
+ is_trait_available = False
69
+
70
+ is_usable = validate_and_save_cohort_info(
71
+ is_final=False,
72
+ cohort=cohort,
73
+ info_path=json_path,
74
+ is_gene_available=is_gene_available,
75
+ is_trait_available=is_trait_available
76
+ )
77
+
78
+ # 4. Since trait_row is None, we skip clinical feature extraction and do not call geo_select_clinical_features.
79
+ # STEP3
80
+ import gzip
81
+ import pandas as pd
82
+
83
+ try:
84
+ # 1. Attempt to extract gene expression data using the library function
85
+ gene_data = get_genetic_data(matrix_file)
86
+ except KeyError:
87
+ # Fallback: the expected "ID_REF" column may be absent, so manually parse the file
88
+ # and rename the first column to "ID".
89
+ marker = "!series_matrix_table_begin"
90
+ skip_rows = None
91
+
92
+ # Determine how many rows to skip before the matrix data begins
93
+ with gzip.open(matrix_file, 'rt') as f:
94
+ for i, line in enumerate(f):
95
+ if marker in line:
96
+ skip_rows = i + 1
97
+ break
98
+ else:
99
+ raise ValueError(f"Marker '{marker}' not found in the file.")
100
+
101
+ # Read the data from the determined position
102
+ gene_data = pd.read_csv(
103
+ matrix_file,
104
+ compression='gzip',
105
+ skiprows=skip_rows,
106
+ comment='!',
107
+ delimiter='\t',
108
+ on_bad_lines='skip'
109
+ )
110
+
111
+ # If a different column name is used instead of 'ID_REF', rename appropriately
112
+ if 'ID_REF' in gene_data.columns:
113
+ gene_data.rename(columns={'ID_REF': 'ID'}, inplace=True)
114
+ else:
115
+ first_col = gene_data.columns[0]
116
+ gene_data.rename(columns={first_col: 'ID'}, inplace=True)
117
+
118
+ gene_data['ID'] = gene_data['ID'].astype(str)
119
+ gene_data.set_index('ID', inplace=True)
120
+
121
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
122
+ print(gene_data.index[:20])
123
+ requires_gene_mapping = True
124
+ # STEP5
125
+ # 1 & 2. Only extract and preview gene annotation data if the SOFT file exists, otherwise skip.
126
+ if soft_file is None:
127
+ print("No SOFT file found. Skipping gene annotation extraction.")
128
+ gene_annotation = pd.DataFrame()
129
+ else:
130
+ try:
131
+ # Attempt to extract gene annotation with the default method
132
+ gene_annotation = get_gene_annotation(soft_file)
133
+ except UnicodeDecodeError:
134
+ # Fallback if UTF-8 decoding fails: read with a more lenient encoding and pass the content as a string
135
+ import gzip
136
+ with gzip.open(soft_file, 'rt', encoding='latin-1', errors='replace') as f:
137
+ content = f.read()
138
+ gene_annotation = filter_content_by_prefix(
139
+ content,
140
+ prefixes_a=['^','!','#'],
141
+ unselect=True,
142
+ source_type='string',
143
+ return_df_a=True
144
+ )[0]
145
+
146
+ print("Gene annotation preview:")
147
+ print(preview_df(gene_annotation))
148
+ # STEP 6: Gene Identifier Mapping
149
+
150
+ # We'll attempt to map the probe-level data to gene symbols only if there's a genuine overlap
151
+ # between the expression data indices and the annotation IDs.
152
+
153
+ probe_column_candidates = ["ID", "probeset_id"]
154
+ gene_symbol_column_candidates = ["gene_assignment", "mrna_assignment"]
155
+
156
+ chosen_probe_col = None
157
+ chosen_symbol_col = None
158
+
159
+ # 1. Find a probe column with overlap
160
+ for col in probe_column_candidates:
161
+ if col in gene_annotation.columns:
162
+ overlap = set(gene_annotation[col]) & set(gene_data.index)
163
+ if len(overlap) > 0:
164
+ chosen_probe_col = col
165
+ break
166
+
167
+ # 2. Pick a gene symbol column
168
+ for col in gene_symbol_column_candidates:
169
+ if col in gene_annotation.columns:
170
+ chosen_symbol_col = col
171
+ break
172
+
173
+ # If none found, skip mapping
174
+ if not chosen_probe_col or not chosen_symbol_col:
175
+ print("No suitable probe or gene symbol columns found in the annotation. Skipping mapping.")
176
+ else:
177
+ # Build a preliminary mapping DataFrame
178
+ mapping_df = get_gene_mapping(
179
+ gene_annotation,
180
+ prob_col=chosen_probe_col,
181
+ gene_col=chosen_symbol_col
182
+ )
183
+
184
+ # 3. Check for genuine overlap after dropping invalid entries
185
+ mapped_ids = set(mapping_df["ID"].unique()) & set(gene_data.index)
186
+ if len(mapped_ids) == 0:
187
+ print("No overlapping probe IDs after cleaning. Skipping mapping.")
188
+ else:
189
+ # Proceed with the mapping since there is an actual overlap
190
+ gene_data = apply_gene_mapping(gene_data, mapping_df)
191
+ print("Gene-level mapping performed successfully.")
192
+ print("Mapped gene_data shape:", gene_data.shape)
193
+ print("First few gene symbols after mapping:", gene_data.index[:10].tolist())
194
+ import os
195
+ import pandas as pd
196
+
197
+ # STEP 7: Data Normalization and Linking
198
+
199
+ # First, check if the clinical CSV file exists. If it does not, we cannot proceed with trait-based linking.
200
+ if not os.path.exists(out_clinical_data_file):
201
+ # No trait data file => dataset is not usable for trait analysis
202
+ df_null = pd.DataFrame()
203
+ is_biased = True # Arbitrary boolean to satisfy function requirement
204
+ validate_and_save_cohort_info(
205
+ is_final=True,
206
+ cohort=cohort,
207
+ info_path=json_path,
208
+ is_gene_available=True,
209
+ is_trait_available=False,
210
+ is_biased=is_biased,
211
+ df=df_null,
212
+ note="No trait data file found; dataset not usable for trait analysis."
213
+ )
214
+
215
+ else:
216
+ # 1. Normalize the mapped gene expression data using known gene symbol synonyms, then save.
217
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
218
+ normalized_gene_data.to_csv(out_gene_data_file)
219
+
220
+ # 2. Load the previously extracted clinical CSV.
221
+ selected_clinical_df = pd.read_csv(out_clinical_data_file)
222
+ # If we had a single-row trait, rename row 0 to the trait name (example usage).
223
+ selected_clinical_df = selected_clinical_df.rename(index={0: trait})
224
+
225
+ # Combine these as our final clinical data; in this dataset, we only have trait info (if any).
226
+ combined_clinical_df = selected_clinical_df
227
+
228
+ # Link the clinical and genetic data by matching sample IDs in columns.
229
+ linked_data = geo_link_clinical_genetic_data(combined_clinical_df, normalized_gene_data)
230
+
231
+ # 3. Handle missing values in the linked data (drop incomplete rows/columns, then impute).
232
+ processed_data = handle_missing_values(linked_data, trait)
233
+
234
+ # 4. Check trait bias and remove any biased demographic features (if any).
235
+ trait_biased, processed_data = judge_and_remove_biased_features(processed_data, trait)
236
+
237
+ # 5. Final validation and metadata saving.
238
+ is_usable = validate_and_save_cohort_info(
239
+ is_final=True,
240
+ cohort=cohort,
241
+ info_path=json_path,
242
+ is_gene_available=True,
243
+ is_trait_available=True,
244
+ is_biased=trait_biased,
245
+ df=processed_data,
246
+ note="Completed trait-based preprocessing."
247
+ )
248
+
249
+ # 6. If final dataset is usable, save. Otherwise, skip.
250
+ if is_usable:
251
+ processed_data.to_csv(out_data_file)
p1/preprocess/Sarcoma/code/GSE133228.py ADDED
@@ -0,0 +1,247 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Sarcoma"
6
+ cohort = "GSE133228"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Sarcoma"
10
+ in_cohort_dir = "../DATA/GEO/Sarcoma/GSE133228"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/preprocess/1/Sarcoma/GSE133228.csv"
14
+ out_gene_data_file = "./output/preprocess/1/Sarcoma/gene_data/GSE133228.csv"
15
+ out_clinical_data_file = "./output/preprocess/1/Sarcoma/clinical_data/GSE133228.csv"
16
+ json_path = "./output/preprocess/1/Sarcoma/cohort_info.json"
17
+
18
+ # STEP1
19
+ from tools.preprocess import *
20
+ # 1. Identify the paths to the SOFT file and the matrix file
21
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
22
+
23
+ # 2. Read the matrix file to obtain background information and sample characteristics data
24
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
25
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
26
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
27
+
28
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
29
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
30
+
31
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
32
+ print("Background Information:")
33
+ print(background_info)
34
+ print("Sample Characteristics Dictionary:")
35
+ print(sample_characteristics_dict)
36
+ # 1) Gene Expression Data Availability
37
+ is_gene_available = True # Based on background info, we assume these data measure gene expression
38
+
39
+ # 2) Variable Availability and Data Type Conversion
40
+
41
+ # From the sample characteristics:
42
+ # 0 -> ['gender: Male', 'gender: Female']
43
+ # 1 -> ['age: 3', 'age: 11', 'age: 4', 'age: 25', ...] (multiple distinct ages)
44
+ # 2 -> ['tumor type: primary tumor'] (only one value)
45
+
46
+ # The trait "Sarcoma" is not explicitly found in any row, and row 2 has only one unique value.
47
+ # Hence, trait_row = None (not useful for a variation-based analysis).
48
+ trait_row = None
49
+
50
+ # Age data is in row=1 with multiple distinct values
51
+ age_row = 1
52
+
53
+ # Gender data is in row=0 with multiple distinct values
54
+ gender_row = 0
55
+
56
+ # 2.2) Define data type converters
57
+
58
+ def convert_trait(value: str) -> int:
59
+ # Not used because trait_row is None, but define for consistency.
60
+ # If we had data, we might extract part after the colon and map accordingly.
61
+ return None
62
+
63
+ def convert_age(value: str) -> float:
64
+ # Typical pattern: "age: 25"
65
+ # Split by colon and take the numeric part
66
+ parts = value.split(':')
67
+ if len(parts) == 2:
68
+ try:
69
+ return float(parts[1].strip())
70
+ except ValueError:
71
+ return None
72
+ return None
73
+
74
+ def convert_gender(value: str) -> int:
75
+ # Typical pattern: "gender: Male"/"gender: Female"
76
+ # Convert Female->0, Male->1, otherwise None
77
+ parts = value.split(':')
78
+ if len(parts) == 2:
79
+ g = parts[1].strip().lower()
80
+ if g == 'male':
81
+ return 1
82
+ elif g == 'female':
83
+ return 0
84
+ return None
85
+
86
+ # 3) Save Metadata (initial filtering)
87
+ # Trait data availability depends on whether trait_row is None
88
+ is_trait_available = (trait_row is not None)
89
+
90
+ is_usable = validate_and_save_cohort_info(
91
+ is_final=False,
92
+ cohort=cohort,
93
+ info_path=json_path,
94
+ is_gene_available=is_gene_available,
95
+ is_trait_available=is_trait_available
96
+ )
97
+
98
+ # 4) Clinical Feature Extraction
99
+ # Since trait_row is None, we skip extracting clinical features
100
+ # STEP3
101
+ import gzip
102
+ import pandas as pd
103
+
104
+ try:
105
+ # 1. Attempt to extract gene expression data using the library function
106
+ gene_data = get_genetic_data(matrix_file)
107
+ except KeyError:
108
+ # Fallback: the expected "ID_REF" column may be absent, so manually parse the file
109
+ # and rename the first column to "ID".
110
+ marker = "!series_matrix_table_begin"
111
+ skip_rows = None
112
+
113
+ # Determine how many rows to skip before the matrix data begins
114
+ with gzip.open(matrix_file, 'rt') as f:
115
+ for i, line in enumerate(f):
116
+ if marker in line:
117
+ skip_rows = i + 1
118
+ break
119
+ else:
120
+ raise ValueError(f"Marker '{marker}' not found in the file.")
121
+
122
+ # Read the data from the determined position
123
+ gene_data = pd.read_csv(
124
+ matrix_file,
125
+ compression='gzip',
126
+ skiprows=skip_rows,
127
+ comment='!',
128
+ delimiter='\t',
129
+ on_bad_lines='skip'
130
+ )
131
+
132
+ # If a different column name is used instead of 'ID_REF', rename appropriately
133
+ if 'ID_REF' in gene_data.columns:
134
+ gene_data.rename(columns={'ID_REF': 'ID'}, inplace=True)
135
+ else:
136
+ first_col = gene_data.columns[0]
137
+ gene_data.rename(columns={first_col: 'ID'}, inplace=True)
138
+
139
+ gene_data['ID'] = gene_data['ID'].astype(str)
140
+ gene_data.set_index('ID', inplace=True)
141
+
142
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
143
+ print(gene_data.index[:20])
144
+ # These identifiers (e.g., "100009676_at", "10000_at") appear to be microarray probe IDs, not standard human gene symbols.
145
+ # Typically, such probe IDs need to be mapped to the corresponding gene symbols.
146
+
147
+ print("requires_gene_mapping = True")
148
+ # STEP5
149
+ # 1 & 2. Only extract and preview gene annotation data if the SOFT file exists, otherwise skip.
150
+ if soft_file is None:
151
+ print("No SOFT file found. Skipping gene annotation extraction.")
152
+ gene_annotation = pd.DataFrame()
153
+ else:
154
+ try:
155
+ # Attempt to extract gene annotation with the default method
156
+ gene_annotation = get_gene_annotation(soft_file)
157
+ except UnicodeDecodeError:
158
+ # Fallback if UTF-8 decoding fails: read with a more lenient encoding and pass the content as a string
159
+ import gzip
160
+ with gzip.open(soft_file, 'rt', encoding='latin-1', errors='replace') as f:
161
+ content = f.read()
162
+ gene_annotation = filter_content_by_prefix(
163
+ content,
164
+ prefixes_a=['^','!','#'],
165
+ unselect=True,
166
+ source_type='string',
167
+ return_df_a=True
168
+ )[0]
169
+
170
+ print("Gene annotation preview:")
171
+ print(preview_df(gene_annotation))
172
+ # STEP: Gene Identifier Mapping
173
+
174
+ # 1) Decide which key in the gene annotation dataframe corresponds to the probe IDs
175
+ # (same as those in the gene expression data) and which key corresponds to the gene symbol.
176
+ # From our preview, "ID" in the annotation matches the probe IDs in the gene expression data,
177
+ # while "Description" appears to hold gene names/symbols (albeit as descriptive text).
178
+
179
+ prob_col = "ID"
180
+ gene_col = "Description"
181
+
182
+ # 2) Get a gene mapping dataframe using these columns.
183
+ mapping_df = get_gene_mapping(gene_annotation, prob_col, gene_col)
184
+
185
+ # 3) Convert probe-level measurements to gene-level data.
186
+ gene_data = apply_gene_mapping(gene_data, mapping_df)
187
+
188
+ # Optional: Inspect the resulting gene_data shape
189
+ print("Mapped gene expression data shape:", gene_data.shape)
190
+ import os
191
+ import pandas as pd
192
+
193
+ # STEP 7: Data Normalization and Linking
194
+
195
+ # First, check if the clinical CSV file exists. If it does not, we cannot proceed with trait-based linking.
196
+ if not os.path.exists(out_clinical_data_file):
197
+ # No trait data file => dataset is not usable for trait analysis
198
+ df_null = pd.DataFrame()
199
+ is_biased = True # Arbitrary boolean to satisfy function requirement
200
+ validate_and_save_cohort_info(
201
+ is_final=True,
202
+ cohort=cohort,
203
+ info_path=json_path,
204
+ is_gene_available=True,
205
+ is_trait_available=False,
206
+ is_biased=is_biased,
207
+ df=df_null,
208
+ note="No trait data file found; dataset not usable for trait analysis."
209
+ )
210
+
211
+ else:
212
+ # 1. Normalize the mapped gene expression data using known gene symbol synonyms, then save.
213
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
214
+ normalized_gene_data.to_csv(out_gene_data_file)
215
+
216
+ # 2. Load the previously extracted clinical CSV.
217
+ selected_clinical_df = pd.read_csv(out_clinical_data_file)
218
+ # If we had a single-row trait, rename row 0 to the trait name (example usage).
219
+ selected_clinical_df = selected_clinical_df.rename(index={0: trait})
220
+
221
+ # Combine these as our final clinical data; in this dataset, we only have trait info (if any).
222
+ combined_clinical_df = selected_clinical_df
223
+
224
+ # Link the clinical and genetic data by matching sample IDs in columns.
225
+ linked_data = geo_link_clinical_genetic_data(combined_clinical_df, normalized_gene_data)
226
+
227
+ # 3. Handle missing values in the linked data (drop incomplete rows/columns, then impute).
228
+ processed_data = handle_missing_values(linked_data, trait)
229
+
230
+ # 4. Check trait bias and remove any biased demographic features (if any).
231
+ trait_biased, processed_data = judge_and_remove_biased_features(processed_data, trait)
232
+
233
+ # 5. Final validation and metadata saving.
234
+ is_usable = validate_and_save_cohort_info(
235
+ is_final=True,
236
+ cohort=cohort,
237
+ info_path=json_path,
238
+ is_gene_available=True,
239
+ is_trait_available=True,
240
+ is_biased=trait_biased,
241
+ df=processed_data,
242
+ note="Completed trait-based preprocessing."
243
+ )
244
+
245
+ # 6. If final dataset is usable, save. Otherwise, skip.
246
+ if is_usable:
247
+ processed_data.to_csv(out_data_file)
p1/preprocess/Sarcoma/code/GSE142162.py ADDED
@@ -0,0 +1,235 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Sarcoma"
6
+ cohort = "GSE142162"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Sarcoma"
10
+ in_cohort_dir = "../DATA/GEO/Sarcoma/GSE142162"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/preprocess/1/Sarcoma/GSE142162.csv"
14
+ out_gene_data_file = "./output/preprocess/1/Sarcoma/gene_data/GSE142162.csv"
15
+ out_clinical_data_file = "./output/preprocess/1/Sarcoma/clinical_data/GSE142162.csv"
16
+ json_path = "./output/preprocess/1/Sarcoma/cohort_info.json"
17
+
18
+ # STEP1
19
+ from tools.preprocess import *
20
+ # 1. Identify the paths to the SOFT file and the matrix file
21
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
22
+
23
+ # 2. Read the matrix file to obtain background information and sample characteristics data
24
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
25
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
26
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
27
+
28
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
29
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
30
+
31
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
32
+ print("Background Information:")
33
+ print(background_info)
34
+ print("Sample Characteristics Dictionary:")
35
+ print(sample_characteristics_dict)
36
+ # 1) Determine gene expression availability
37
+ is_gene_available = True # Based on Affymetrix hgu133Plus2 arrays and "Expression profiling" indication
38
+
39
+ # 2) Identify data availability (rows) and define conversion functions
40
+
41
+ # For this dataset, the trait is effectively constant ("tumor type: primary tumor"), so it's not useful
42
+ # for an association study. Hence, trait_row is None.
43
+ trait_row = None
44
+
45
+ # Age is variable under key 1
46
+ age_row = 1
47
+
48
+ # Gender is variable under key 0
49
+ gender_row = 0
50
+
51
+ # 2.2) Data type conversion functions
52
+
53
+ def convert_trait(value: str):
54
+ """
55
+ This dataset does not contain meaningful variation for the primary trait 'Sarcoma'.
56
+ We'll return None for all inputs.
57
+ """
58
+ return None
59
+
60
+ def convert_age(value: str):
61
+ """
62
+ Converts age values after the colon to a continuous numeric type.
63
+ Unknown values are returned as None.
64
+ Example input: "age: 25"
65
+ """
66
+ parts = value.split(':')
67
+ if len(parts) < 2:
68
+ return None
69
+ raw_val = parts[1].strip()
70
+ if not raw_val.isdigit():
71
+ return None
72
+ return float(raw_val)
73
+
74
+ def convert_gender(value: str):
75
+ """
76
+ Converts gender to a binary variable:
77
+ Female -> 0
78
+ Male -> 1
79
+ Unknown values are returned as None.
80
+ Example input: "gender: Male"
81
+ """
82
+ parts = value.split(':')
83
+ if len(parts) < 2:
84
+ return None
85
+ raw_val = parts[1].strip().lower()
86
+ if raw_val == 'male':
87
+ return 1
88
+ elif raw_val == 'female':
89
+ return 0
90
+ return None
91
+
92
+ # 3) Conduct initial dataset filtering and save metadata
93
+ is_trait_available = (trait_row is not None)
94
+ is_usable = validate_and_save_cohort_info(
95
+ is_final=False,
96
+ cohort=cohort,
97
+ info_path=json_path,
98
+ is_gene_available=is_gene_available,
99
+ is_trait_available=is_trait_available
100
+ )
101
+
102
+ # 4) Since trait_row is None, we skip clinical feature extraction.
103
+ # STEP3
104
+ import gzip
105
+ import pandas as pd
106
+
107
+ try:
108
+ # 1. Attempt to extract gene expression data using the library function
109
+ gene_data = get_genetic_data(matrix_file)
110
+ except KeyError:
111
+ # Fallback: the expected "ID_REF" column may be absent, so manually parse the file
112
+ # and rename the first column to "ID".
113
+ marker = "!series_matrix_table_begin"
114
+ skip_rows = None
115
+
116
+ # Determine how many rows to skip before the matrix data begins
117
+ with gzip.open(matrix_file, 'rt') as f:
118
+ for i, line in enumerate(f):
119
+ if marker in line:
120
+ skip_rows = i + 1
121
+ break
122
+ else:
123
+ raise ValueError(f"Marker '{marker}' not found in the file.")
124
+
125
+ # Read the data from the determined position
126
+ gene_data = pd.read_csv(
127
+ matrix_file,
128
+ compression='gzip',
129
+ skiprows=skip_rows,
130
+ comment='!',
131
+ delimiter='\t',
132
+ on_bad_lines='skip'
133
+ )
134
+
135
+ # If a different column name is used instead of 'ID_REF', rename appropriately
136
+ if 'ID_REF' in gene_data.columns:
137
+ gene_data.rename(columns={'ID_REF': 'ID'}, inplace=True)
138
+ else:
139
+ first_col = gene_data.columns[0]
140
+ gene_data.rename(columns={first_col: 'ID'}, inplace=True)
141
+
142
+ gene_data['ID'] = gene_data['ID'].astype(str)
143
+ gene_data.set_index('ID', inplace=True)
144
+
145
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
146
+ print(gene_data.index[:20])
147
+ print("requires_gene_mapping = True")
148
+ # STEP5
149
+ # 1 & 2. Only extract and preview gene annotation data if the SOFT file exists, otherwise skip.
150
+ if soft_file is None:
151
+ print("No SOFT file found. Skipping gene annotation extraction.")
152
+ gene_annotation = pd.DataFrame()
153
+ else:
154
+ try:
155
+ # Attempt to extract gene annotation with the default method
156
+ gene_annotation = get_gene_annotation(soft_file)
157
+ except UnicodeDecodeError:
158
+ # Fallback if UTF-8 decoding fails: read with a more lenient encoding and pass the content as a string
159
+ import gzip
160
+ with gzip.open(soft_file, 'rt', encoding='latin-1', errors='replace') as f:
161
+ content = f.read()
162
+ gene_annotation = filter_content_by_prefix(
163
+ content,
164
+ prefixes_a=['^','!','#'],
165
+ unselect=True,
166
+ source_type='string',
167
+ return_df_a=True
168
+ )[0]
169
+
170
+ print("Gene annotation preview:")
171
+ print(preview_df(gene_annotation))
172
+ # Gene Identifier Mapping
173
+ probe_col = "ID" # column in gene_annotation that matches the probe IDs in gene_data
174
+ gene_symbol_col = "Description" # column in gene_annotation containing the gene symbol or descriptive info
175
+
176
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=probe_col, gene_col=gene_symbol_col)
177
+ gene_data = apply_gene_mapping(gene_data, mapping_df)
178
+ import os
179
+ import pandas as pd
180
+
181
+ # STEP 7: Data Normalization and Linking
182
+
183
+ # First, check if the clinical CSV file exists. If it does not, we cannot proceed with trait-based linking.
184
+ if not os.path.exists(out_clinical_data_file):
185
+ # No trait data file => dataset is not usable for trait analysis
186
+ df_null = pd.DataFrame()
187
+ is_biased = True # Arbitrary boolean to satisfy function requirement
188
+ validate_and_save_cohort_info(
189
+ is_final=True,
190
+ cohort=cohort,
191
+ info_path=json_path,
192
+ is_gene_available=True,
193
+ is_trait_available=False,
194
+ is_biased=is_biased,
195
+ df=df_null,
196
+ note="No trait data file found; dataset not usable for trait analysis."
197
+ )
198
+
199
+ else:
200
+ # 1. Normalize the mapped gene expression data using known gene symbol synonyms, then save.
201
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
202
+ normalized_gene_data.to_csv(out_gene_data_file)
203
+
204
+ # 2. Load the previously extracted clinical CSV.
205
+ selected_clinical_df = pd.read_csv(out_clinical_data_file)
206
+ # If we had a single-row trait, rename row 0 to the trait name (example usage).
207
+ selected_clinical_df = selected_clinical_df.rename(index={0: trait})
208
+
209
+ # Combine these as our final clinical data; in this dataset, we only have trait info (if any).
210
+ combined_clinical_df = selected_clinical_df
211
+
212
+ # Link the clinical and genetic data by matching sample IDs in columns.
213
+ linked_data = geo_link_clinical_genetic_data(combined_clinical_df, normalized_gene_data)
214
+
215
+ # 3. Handle missing values in the linked data (drop incomplete rows/columns, then impute).
216
+ processed_data = handle_missing_values(linked_data, trait)
217
+
218
+ # 4. Check trait bias and remove any biased demographic features (if any).
219
+ trait_biased, processed_data = judge_and_remove_biased_features(processed_data, trait)
220
+
221
+ # 5. Final validation and metadata saving.
222
+ is_usable = validate_and_save_cohort_info(
223
+ is_final=True,
224
+ cohort=cohort,
225
+ info_path=json_path,
226
+ is_gene_available=True,
227
+ is_trait_available=True,
228
+ is_biased=trait_biased,
229
+ df=processed_data,
230
+ note="Completed trait-based preprocessing."
231
+ )
232
+
233
+ # 6. If final dataset is usable, save. Otherwise, skip.
234
+ if is_usable:
235
+ processed_data.to_csv(out_data_file)
p1/preprocess/Sarcoma/code/GSE159847.py ADDED
@@ -0,0 +1,237 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Sarcoma"
6
+ cohort = "GSE159847"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Sarcoma"
10
+ in_cohort_dir = "../DATA/GEO/Sarcoma/GSE159847"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/preprocess/1/Sarcoma/GSE159847.csv"
14
+ out_gene_data_file = "./output/preprocess/1/Sarcoma/gene_data/GSE159847.csv"
15
+ out_clinical_data_file = "./output/preprocess/1/Sarcoma/clinical_data/GSE159847.csv"
16
+ json_path = "./output/preprocess/1/Sarcoma/cohort_info.json"
17
+
18
+ # STEP1
19
+ from tools.preprocess import *
20
+ # 1. Identify the paths to the SOFT file and the matrix file
21
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
22
+
23
+ # 2. Read the matrix file to obtain background information and sample characteristics data
24
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
25
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
26
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
27
+
28
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
29
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
30
+
31
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
32
+ print("Background Information:")
33
+ print(background_info)
34
+ print("Sample Characteristics Dictionary:")
35
+ print(sample_characteristics_dict)
36
+ # 1. Gene Expression Data Availability
37
+ is_gene_available = True # This dataset likely contains gene expression data (Affymetrix/Agilent transcriptome).
38
+
39
+ # 2. Variable Availability and Data Type Conversion
40
+
41
+ # Since all samples are "complex sarcomas" (one trait), there's effectively no variation in the trait.
42
+ trait_row = None
43
+
44
+ # We do see multiple ages under key=1, so age is available.
45
+ age_row = 1
46
+
47
+ # We see males and females under key=0, so gender is available.
48
+ gender_row = 0
49
+
50
+ # Conversion functions
51
+ def convert_trait(value: str):
52
+ # Not used since trait_row is None, but defined as per instructions
53
+ return None
54
+
55
+ def convert_age(value: str):
56
+ # Example value: "age: 73"
57
+ try:
58
+ val = value.split(":", 1)[1].strip()
59
+ return float(val)
60
+ except:
61
+ return None
62
+
63
+ def convert_gender(value: str):
64
+ # Example value: "Sex: M" or "Sex: F"
65
+ val = value.split(":", 1)[1].strip().lower()
66
+ if val == "m":
67
+ return 1
68
+ elif val == "f":
69
+ return 0
70
+ return None
71
+
72
+ # 3. Save Metadata (initial filtering)
73
+ is_trait_available = (trait_row is not None)
74
+ validate_and_save_cohort_info(
75
+ is_final=False,
76
+ cohort=cohort,
77
+ info_path=json_path,
78
+ is_gene_available=is_gene_available,
79
+ is_trait_available=is_trait_available
80
+ )
81
+
82
+ # 4. Clinical Feature Extraction
83
+ # Skip this step if trait_row is None
84
+ if trait_row is not None:
85
+ selected_clinical_df = geo_select_clinical_features(
86
+ clinical_df=clinical_data,
87
+ trait="Sarcoma",
88
+ trait_row=trait_row,
89
+ convert_trait=convert_trait,
90
+ age_row=age_row,
91
+ convert_age=convert_age,
92
+ gender_row=gender_row,
93
+ convert_gender=convert_gender
94
+ )
95
+ print("Preview of selected clinical features:", preview_df(selected_clinical_df))
96
+ selected_clinical_df.to_csv(out_clinical_data_file, index=False)
97
+ # STEP3
98
+ import gzip
99
+ import pandas as pd
100
+
101
+ try:
102
+ # 1. Attempt to extract gene expression data using the library function
103
+ gene_data = get_genetic_data(matrix_file)
104
+ except KeyError:
105
+ # Fallback: the expected "ID_REF" column may be absent, so manually parse the file
106
+ # and rename the first column to "ID".
107
+ marker = "!series_matrix_table_begin"
108
+ skip_rows = None
109
+
110
+ # Determine how many rows to skip before the matrix data begins
111
+ with gzip.open(matrix_file, 'rt') as f:
112
+ for i, line in enumerate(f):
113
+ if marker in line:
114
+ skip_rows = i + 1
115
+ break
116
+ else:
117
+ raise ValueError(f"Marker '{marker}' not found in the file.")
118
+
119
+ # Read the data from the determined position
120
+ gene_data = pd.read_csv(
121
+ matrix_file,
122
+ compression='gzip',
123
+ skiprows=skip_rows,
124
+ comment='!',
125
+ delimiter='\t',
126
+ on_bad_lines='skip'
127
+ )
128
+
129
+ # If a different column name is used instead of 'ID_REF', rename appropriately
130
+ if 'ID_REF' in gene_data.columns:
131
+ gene_data.rename(columns={'ID_REF': 'ID'}, inplace=True)
132
+ else:
133
+ first_col = gene_data.columns[0]
134
+ gene_data.rename(columns={first_col: 'ID'}, inplace=True)
135
+
136
+ gene_data['ID'] = gene_data['ID'].astype(str)
137
+ gene_data.set_index('ID', inplace=True)
138
+
139
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
140
+ print(gene_data.index[:20])
141
+ # These appear to be microarray probe IDs that are not standard human gene symbols.
142
+ print("requires_gene_mapping = True")
143
+ # STEP5
144
+ # 1 & 2. Only extract and preview gene annotation data if the SOFT file exists, otherwise skip.
145
+ if soft_file is None:
146
+ print("No SOFT file found. Skipping gene annotation extraction.")
147
+ gene_annotation = pd.DataFrame()
148
+ else:
149
+ try:
150
+ # Attempt to extract gene annotation with the default method
151
+ gene_annotation = get_gene_annotation(soft_file)
152
+ except UnicodeDecodeError:
153
+ # Fallback if UTF-8 decoding fails: read with a more lenient encoding and pass the content as a string
154
+ import gzip
155
+ with gzip.open(soft_file, 'rt', encoding='latin-1', errors='replace') as f:
156
+ content = f.read()
157
+ gene_annotation = filter_content_by_prefix(
158
+ content,
159
+ prefixes_a=['^','!','#'],
160
+ unselect=True,
161
+ source_type='string',
162
+ return_df_a=True
163
+ )[0]
164
+
165
+ print("Gene annotation preview:")
166
+ print(preview_df(gene_annotation))
167
+ # STEP6: Gene Identifier Mapping
168
+
169
+ # 1. Identify the matching columns in gene_annotation for probe ID and gene symbol
170
+ # Based on the preview, 'ID' corresponds to the probe IDs (e.g., A_23_P1000xx),
171
+ # and 'GENE_SYMBOL' holds the gene symbol.
172
+ mapping_df = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='GENE_SYMBOL')
173
+
174
+ # 2. Apply the mapping to convert probe-level data into gene-level data
175
+ gene_data = apply_gene_mapping(gene_data, mapping_df)
176
+
177
+ # 3. Check a small part of the resulting gene_data
178
+ print("Mapped gene expression data shape:", gene_data.shape)
179
+ print("First 5 genes in gene_data index:", gene_data.index[:5].tolist())
180
+ import os
181
+ import pandas as pd
182
+
183
+ # STEP 7: Data Normalization and Linking
184
+
185
+ # First, check if the clinical CSV file exists. If it does not, we cannot proceed with trait-based linking.
186
+ if not os.path.exists(out_clinical_data_file):
187
+ # No trait data file => dataset is not usable for trait analysis
188
+ df_null = pd.DataFrame()
189
+ is_biased = True # Arbitrary boolean to satisfy function requirement
190
+ 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=False,
196
+ is_biased=is_biased,
197
+ df=df_null,
198
+ note="No trait data file found; dataset not usable for trait analysis."
199
+ )
200
+
201
+ else:
202
+ # 1. Normalize the mapped gene expression data using known gene symbol synonyms, then save.
203
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
204
+ normalized_gene_data.to_csv(out_gene_data_file)
205
+
206
+ # 2. Load the previously extracted clinical CSV.
207
+ selected_clinical_df = pd.read_csv(out_clinical_data_file)
208
+ # If we had a single-row trait, rename row 0 to the trait name (example usage).
209
+ selected_clinical_df = selected_clinical_df.rename(index={0: trait})
210
+
211
+ # Combine these as our final clinical data; in this dataset, we only have trait info (if any).
212
+ combined_clinical_df = selected_clinical_df
213
+
214
+ # Link the clinical and genetic data by matching sample IDs in columns.
215
+ linked_data = geo_link_clinical_genetic_data(combined_clinical_df, normalized_gene_data)
216
+
217
+ # 3. Handle missing values in the linked data (drop incomplete rows/columns, then impute).
218
+ processed_data = handle_missing_values(linked_data, trait)
219
+
220
+ # 4. Check trait bias and remove any biased demographic features (if any).
221
+ trait_biased, processed_data = judge_and_remove_biased_features(processed_data, trait)
222
+
223
+ # 5. Final validation and metadata saving.
224
+ is_usable = validate_and_save_cohort_info(
225
+ is_final=True,
226
+ cohort=cohort,
227
+ info_path=json_path,
228
+ is_gene_available=True,
229
+ is_trait_available=True,
230
+ is_biased=trait_biased,
231
+ df=processed_data,
232
+ note="Completed trait-based preprocessing."
233
+ )
234
+
235
+ # 6. If final dataset is usable, save. Otherwise, skip.
236
+ if is_usable:
237
+ processed_data.to_csv(out_data_file)
p1/preprocess/Sarcoma/code/GSE159848.py ADDED
@@ -0,0 +1,234 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Sarcoma"
6
+ cohort = "GSE159848"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Sarcoma"
10
+ in_cohort_dir = "../DATA/GEO/Sarcoma/GSE159848"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/preprocess/1/Sarcoma/GSE159848.csv"
14
+ out_gene_data_file = "./output/preprocess/1/Sarcoma/gene_data/GSE159848.csv"
15
+ out_clinical_data_file = "./output/preprocess/1/Sarcoma/clinical_data/GSE159848.csv"
16
+ json_path = "./output/preprocess/1/Sarcoma/cohort_info.json"
17
+
18
+ # STEP1
19
+ from tools.preprocess import *
20
+ # 1. Identify the paths to the SOFT file and the matrix file
21
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
22
+
23
+ # 2. Read the matrix file to obtain background information and sample characteristics data
24
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
25
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
26
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
27
+
28
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
29
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
30
+
31
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
32
+ print("Background Information:")
33
+ print(background_info)
34
+ print("Sample Characteristics Dictionary:")
35
+ print(sample_characteristics_dict)
36
+ # 1. Determine if gene expression data is available
37
+ is_gene_available = True # The dataset is described as "Expression data from 50 mixoid liposarcomas"
38
+
39
+ # 2. Identify availability of variables and define their data-conversion functions
40
+ # According to the dictionary, row 0 has sex: M/F, and row 1 has age
41
+ # For the trait "Sarcoma," the dataset is entirely mixoid liposarcomas (no variation), so we consider it unavailable.
42
+ trait_row = None
43
+ age_row = 1
44
+ gender_row = 0
45
+
46
+ def convert_trait(value: str):
47
+ """
48
+ Since trait is not available/variable in this dataset, always return None.
49
+ """
50
+ return None
51
+
52
+ def convert_age(value: str):
53
+ """
54
+ Extract the age value after the colon, converting it to float if possible.
55
+ Return None for invalid or unknown values.
56
+ """
57
+ val = value.split(':')[-1].strip()
58
+ try:
59
+ return float(val)
60
+ except ValueError:
61
+ return None
62
+
63
+ def convert_gender(value: str):
64
+ """
65
+ Extract the gender value (M or F) after the colon and convert to binary:
66
+ M or male -> 1
67
+ F or female -> 0
68
+ Others -> None
69
+ """
70
+ val = value.split(':')[-1].strip().lower()
71
+ if val in ['m', 'male']:
72
+ return 1
73
+ elif val in ['f', 'female']:
74
+ return 0
75
+ else:
76
+ return None
77
+
78
+ # 3. Save metadata with initial filtering
79
+ is_trait_available = (trait_row is not None)
80
+ is_usable = 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
+ # 4. Since trait_row is None, skip extraction of clinical features
89
+ # STEP3
90
+ import gzip
91
+ import pandas as pd
92
+
93
+ try:
94
+ # 1. Attempt to extract gene expression data using the library function
95
+ gene_data = get_genetic_data(matrix_file)
96
+ except KeyError:
97
+ # Fallback: the expected "ID_REF" column may be absent, so manually parse the file
98
+ # and rename the first column to "ID".
99
+ marker = "!series_matrix_table_begin"
100
+ skip_rows = None
101
+
102
+ # Determine how many rows to skip before the matrix data begins
103
+ with gzip.open(matrix_file, 'rt') as f:
104
+ for i, line in enumerate(f):
105
+ if marker in line:
106
+ skip_rows = i + 1
107
+ break
108
+ else:
109
+ raise ValueError(f"Marker '{marker}' not found in the file.")
110
+
111
+ # Read the data from the determined position
112
+ gene_data = pd.read_csv(
113
+ matrix_file,
114
+ compression='gzip',
115
+ skiprows=skip_rows,
116
+ comment='!',
117
+ delimiter='\t',
118
+ on_bad_lines='skip'
119
+ )
120
+
121
+ # If a different column name is used instead of 'ID_REF', rename appropriately
122
+ if 'ID_REF' in gene_data.columns:
123
+ gene_data.rename(columns={'ID_REF': 'ID'}, inplace=True)
124
+ else:
125
+ first_col = gene_data.columns[0]
126
+ gene_data.rename(columns={first_col: 'ID'}, inplace=True)
127
+
128
+ gene_data['ID'] = gene_data['ID'].astype(str)
129
+ gene_data.set_index('ID', inplace=True)
130
+
131
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
132
+ print(gene_data.index[:20])
133
+ # Based on the observed probe IDs (e.g., "A_23_P100001"), these are not standard human gene symbols.
134
+ # Thus, gene-to-symbol mapping is required.
135
+
136
+ print("requires_gene_mapping = True")
137
+ # STEP5
138
+ # 1 & 2. Only extract and preview gene annotation data if the SOFT file exists, otherwise skip.
139
+ if soft_file is None:
140
+ print("No SOFT file found. Skipping gene annotation extraction.")
141
+ gene_annotation = pd.DataFrame()
142
+ else:
143
+ try:
144
+ # Attempt to extract gene annotation with the default method
145
+ gene_annotation = get_gene_annotation(soft_file)
146
+ except UnicodeDecodeError:
147
+ # Fallback if UTF-8 decoding fails: read with a more lenient encoding and pass the content as a string
148
+ import gzip
149
+ with gzip.open(soft_file, 'rt', encoding='latin-1', errors='replace') as f:
150
+ content = f.read()
151
+ gene_annotation = filter_content_by_prefix(
152
+ content,
153
+ prefixes_a=['^','!','#'],
154
+ unselect=True,
155
+ source_type='string',
156
+ return_df_a=True
157
+ )[0]
158
+
159
+ print("Gene annotation preview:")
160
+ print(preview_df(gene_annotation))
161
+ # STEP6: Gene Identifier Mapping
162
+
163
+ # 1. Identify the matching columns in the gene annotation dataframe.
164
+ # From the preview, the probe identifiers are under "ID" and the gene symbols are under "GENE_SYMBOL".
165
+ probe_col = "ID"
166
+ symbol_col = "GENE_SYMBOL"
167
+
168
+ # 2. Create the mapping dataframe from probe to gene symbol.
169
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=probe_col, gene_col=symbol_col)
170
+
171
+ # 3. Convert probe-level measurements into gene expression data using the mapping dataframe.
172
+ gene_data = apply_gene_mapping(gene_data, mapping_df)
173
+
174
+ # (Optional) Print the shape and a small index preview to verify successful mapping
175
+ print("Mapped gene_data shape:", gene_data.shape)
176
+ print("First 20 gene symbols in mapped gene_data:", list(gene_data.index[:20]))
177
+ import os
178
+ import pandas as pd
179
+
180
+ # STEP 7: Data Normalization and Linking
181
+
182
+ # First, check if the clinical CSV file exists. If it does not, we cannot proceed with trait-based linking.
183
+ if not os.path.exists(out_clinical_data_file):
184
+ # No trait data file => dataset is not usable for trait analysis
185
+ df_null = pd.DataFrame()
186
+ is_biased = True # Arbitrary boolean to satisfy function requirement
187
+ validate_and_save_cohort_info(
188
+ is_final=True,
189
+ cohort=cohort,
190
+ info_path=json_path,
191
+ is_gene_available=True,
192
+ is_trait_available=False,
193
+ is_biased=is_biased,
194
+ df=df_null,
195
+ note="No trait data file found; dataset not usable for trait analysis."
196
+ )
197
+
198
+ else:
199
+ # 1. Normalize the mapped gene expression data using known gene symbol synonyms, then save.
200
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
201
+ normalized_gene_data.to_csv(out_gene_data_file)
202
+
203
+ # 2. Load the previously extracted clinical CSV.
204
+ selected_clinical_df = pd.read_csv(out_clinical_data_file)
205
+ # If we had a single-row trait, rename row 0 to the trait name (example usage).
206
+ selected_clinical_df = selected_clinical_df.rename(index={0: trait})
207
+
208
+ # Combine these as our final clinical data; in this dataset, we only have trait info (if any).
209
+ combined_clinical_df = selected_clinical_df
210
+
211
+ # Link the clinical and genetic data by matching sample IDs in columns.
212
+ linked_data = geo_link_clinical_genetic_data(combined_clinical_df, normalized_gene_data)
213
+
214
+ # 3. Handle missing values in the linked data (drop incomplete rows/columns, then impute).
215
+ processed_data = handle_missing_values(linked_data, trait)
216
+
217
+ # 4. Check trait bias and remove any biased demographic features (if any).
218
+ trait_biased, processed_data = judge_and_remove_biased_features(processed_data, trait)
219
+
220
+ # 5. Final validation and metadata saving.
221
+ is_usable = validate_and_save_cohort_info(
222
+ is_final=True,
223
+ cohort=cohort,
224
+ info_path=json_path,
225
+ is_gene_available=True,
226
+ is_trait_available=True,
227
+ is_biased=trait_biased,
228
+ df=processed_data,
229
+ note="Completed trait-based preprocessing."
230
+ )
231
+
232
+ # 6. If final dataset is usable, save. Otherwise, skip.
233
+ if is_usable:
234
+ processed_data.to_csv(out_data_file)
p1/preprocess/Sarcoma/code/GSE162785.py ADDED
@@ -0,0 +1,218 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Sarcoma"
6
+ cohort = "GSE162785"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Sarcoma"
10
+ in_cohort_dir = "../DATA/GEO/Sarcoma/GSE162785"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/preprocess/1/Sarcoma/GSE162785.csv"
14
+ out_gene_data_file = "./output/preprocess/1/Sarcoma/gene_data/GSE162785.csv"
15
+ out_clinical_data_file = "./output/preprocess/1/Sarcoma/clinical_data/GSE162785.csv"
16
+ json_path = "./output/preprocess/1/Sarcoma/cohort_info.json"
17
+
18
+ # STEP1
19
+ from tools.preprocess import *
20
+ # 1. Identify the paths to the SOFT file and the matrix file
21
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
22
+
23
+ # 2. Read the matrix file to obtain background information and sample characteristics data
24
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
25
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
26
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
27
+
28
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
29
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
30
+
31
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
32
+ print("Background Information:")
33
+ print(background_info)
34
+ print("Sample Characteristics Dictionary:")
35
+ print(sample_characteristics_dict)
36
+ # 1) Determine gene expression data availability
37
+ is_gene_available = True # Microarray analysis suggests gene expression data is available
38
+
39
+ # 2) Variable availability and data type conversion
40
+
41
+ # From the sample characteristics dictionary:
42
+ # {0: ['cell line: A673', 'cell line: CHLA-10', 'cell line: EW7', 'cell line: SK-N-MC']}
43
+ # There is only one key (0), whose values all refer to Ewing sarcoma cell lines. For our trait of interest ("Sarcoma"),
44
+ # this dataset effectively has just one value for all samples (i.e., all are Ewing Sarcoma), so it is considered constant
45
+ # and therefore not available for association analysis.
46
+ trait_row = None # No variability in the trait
47
+ age_row = None # No age data available
48
+ gender_row = None # No gender data available
49
+
50
+ # Although the rows are None, we still define the conversion functions as requested.
51
+ def convert_trait(value: str):
52
+ # Not used here because trait_row is None
53
+ # Typically, we would parse the string after the colon and convert, but there's no relevant data to parse.
54
+ return None
55
+
56
+ def convert_age(value: str):
57
+ # Not used here because age_row is None
58
+ return None
59
+
60
+ def convert_gender(value: str):
61
+ # Not used here because gender_row is None
62
+ return None
63
+
64
+ # 3) Save metadata (initial filtering)
65
+ # Trait data is considered unavailable since trait_row is None.
66
+ is_trait_available = False
67
+ is_usable = validate_and_save_cohort_info(
68
+ is_final=False,
69
+ cohort=cohort,
70
+ info_path=json_path,
71
+ is_gene_available=is_gene_available,
72
+ is_trait_available=is_trait_available
73
+ )
74
+
75
+ # 4) Clinical feature extraction is skipped because trait_row is None (no clinical data for trait).
76
+ # STEP3
77
+ import gzip
78
+ import pandas as pd
79
+
80
+ try:
81
+ # 1. Attempt to extract gene expression data using the library function
82
+ gene_data = get_genetic_data(matrix_file)
83
+ except KeyError:
84
+ # Fallback: the expected "ID_REF" column may be absent, so manually parse the file
85
+ # and rename the first column to "ID".
86
+ marker = "!series_matrix_table_begin"
87
+ skip_rows = None
88
+
89
+ # Determine how many rows to skip before the matrix data begins
90
+ with gzip.open(matrix_file, 'rt') as f:
91
+ for i, line in enumerate(f):
92
+ if marker in line:
93
+ skip_rows = i + 1
94
+ break
95
+ else:
96
+ raise ValueError(f"Marker '{marker}' not found in the file.")
97
+
98
+ # Read the data from the determined position
99
+ gene_data = pd.read_csv(
100
+ matrix_file,
101
+ compression='gzip',
102
+ skiprows=skip_rows,
103
+ comment='!',
104
+ delimiter='\t',
105
+ on_bad_lines='skip'
106
+ )
107
+
108
+ # If a different column name is used instead of 'ID_REF', rename appropriately
109
+ if 'ID_REF' in gene_data.columns:
110
+ gene_data.rename(columns={'ID_REF': 'ID'}, inplace=True)
111
+ else:
112
+ first_col = gene_data.columns[0]
113
+ gene_data.rename(columns={first_col: 'ID'}, inplace=True)
114
+
115
+ gene_data['ID'] = gene_data['ID'].astype(str)
116
+ gene_data.set_index('ID', inplace=True)
117
+
118
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
119
+ print(gene_data.index[:20])
120
+ print("requires_gene_mapping = True")
121
+ # STEP5
122
+ # 1 & 2. Only extract and preview gene annotation data if the SOFT file exists, otherwise skip.
123
+ if soft_file is None:
124
+ print("No SOFT file found. Skipping gene annotation extraction.")
125
+ gene_annotation = pd.DataFrame()
126
+ else:
127
+ try:
128
+ # Attempt to extract gene annotation with the default method
129
+ gene_annotation = get_gene_annotation(soft_file)
130
+ except UnicodeDecodeError:
131
+ # Fallback if UTF-8 decoding fails: read with a more lenient encoding and pass the content as a string
132
+ import gzip
133
+ with gzip.open(soft_file, 'rt', encoding='latin-1', errors='replace') as f:
134
+ content = f.read()
135
+ gene_annotation = filter_content_by_prefix(
136
+ content,
137
+ prefixes_a=['^','!','#'],
138
+ unselect=True,
139
+ source_type='string',
140
+ return_df_a=True
141
+ )[0]
142
+
143
+ print("Gene annotation preview:")
144
+ print(preview_df(gene_annotation))
145
+ # STEP: Gene Identifier Mapping
146
+
147
+ # 1. Identify the columns in the annotation dataframe that match our probe IDs and contain gene symbols.
148
+ # From the preview, the "ID" column matches the numerical probe identifiers, and "gene_assignment" contains gene symbols.
149
+ prob_col = "ID"
150
+ gene_col = "gene_assignment"
151
+
152
+ # 2. Create a mapping dataframe with these two columns.
153
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=prob_col, gene_col=gene_col)
154
+
155
+ # 3. Convert the probe-level expression data to gene-level expression data using this mapping.
156
+ gene_data = apply_gene_mapping(gene_data, mapping_df)
157
+
158
+ # (Optional) Print shape and a small preview of the resulting mapped data
159
+ print("Mapped gene_data shape:", gene_data.shape)
160
+ print("Mapped gene_data preview:\n", gene_data.head())
161
+ import os
162
+ import pandas as pd
163
+
164
+ # STEP 7: Data Normalization and Linking
165
+
166
+ # First, check if the clinical CSV file exists. If it does not, we cannot proceed with trait-based linking.
167
+ if not os.path.exists(out_clinical_data_file):
168
+ # No trait data file => dataset is not usable for trait analysis
169
+ df_null = pd.DataFrame()
170
+ is_biased = True # Arbitrary boolean to satisfy function requirement
171
+ validate_and_save_cohort_info(
172
+ is_final=True,
173
+ cohort=cohort,
174
+ info_path=json_path,
175
+ is_gene_available=True,
176
+ is_trait_available=False,
177
+ is_biased=is_biased,
178
+ df=df_null,
179
+ note="No trait data file found; dataset not usable for trait analysis."
180
+ )
181
+
182
+ else:
183
+ # 1. Normalize the mapped gene expression data using known gene symbol synonyms, then save.
184
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
185
+ normalized_gene_data.to_csv(out_gene_data_file)
186
+
187
+ # 2. Load the previously extracted clinical CSV.
188
+ selected_clinical_df = pd.read_csv(out_clinical_data_file)
189
+ # If we had a single-row trait, rename row 0 to the trait name (example usage).
190
+ selected_clinical_df = selected_clinical_df.rename(index={0: trait})
191
+
192
+ # Combine these as our final clinical data; in this dataset, we only have trait info (if any).
193
+ combined_clinical_df = selected_clinical_df
194
+
195
+ # Link the clinical and genetic data by matching sample IDs in columns.
196
+ linked_data = geo_link_clinical_genetic_data(combined_clinical_df, normalized_gene_data)
197
+
198
+ # 3. Handle missing values in the linked data (drop incomplete rows/columns, then impute).
199
+ processed_data = handle_missing_values(linked_data, trait)
200
+
201
+ # 4. Check trait bias and remove any biased demographic features (if any).
202
+ trait_biased, processed_data = judge_and_remove_biased_features(processed_data, trait)
203
+
204
+ # 5. Final validation and metadata saving.
205
+ is_usable = validate_and_save_cohort_info(
206
+ is_final=True,
207
+ cohort=cohort,
208
+ info_path=json_path,
209
+ is_gene_available=True,
210
+ is_trait_available=True,
211
+ is_biased=trait_biased,
212
+ df=processed_data,
213
+ note="Completed trait-based preprocessing."
214
+ )
215
+
216
+ # 6. If final dataset is usable, save. Otherwise, skip.
217
+ if is_usable:
218
+ processed_data.to_csv(out_data_file)
p1/preprocess/Sarcoma/code/GSE162789.py ADDED
@@ -0,0 +1,245 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Sarcoma"
6
+ cohort = "GSE162789"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Sarcoma"
10
+ in_cohort_dir = "../DATA/GEO/Sarcoma/GSE162789"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/preprocess/1/Sarcoma/GSE162789.csv"
14
+ out_gene_data_file = "./output/preprocess/1/Sarcoma/gene_data/GSE162789.csv"
15
+ out_clinical_data_file = "./output/preprocess/1/Sarcoma/clinical_data/GSE162789.csv"
16
+ json_path = "./output/preprocess/1/Sarcoma/cohort_info.json"
17
+
18
+ # STEP1
19
+ from tools.preprocess import *
20
+ # 1. Identify the paths to the SOFT file and the matrix file
21
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
22
+
23
+ # 2. Read the matrix file to obtain background information and sample characteristics data
24
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
25
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
26
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
27
+
28
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
29
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
30
+
31
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
32
+ print("Background Information:")
33
+ print(background_info)
34
+ print("Sample Characteristics Dictionary:")
35
+ print(sample_characteristics_dict)
36
+ # 1) Determine if gene expression data is available
37
+ is_gene_available = True # Based on the dataset description focusing on Ewing sarcoma pathogenesis via HDAC
38
+
39
+ # 2) Identify and set availability of trait, age, and gender
40
+ # Inspecting the sample characteristics, we see only one key (0).
41
+ # All samples appear to have the same trait (Ewing sarcoma), so there's no variation -> trait not available
42
+ trait_row = None
43
+
44
+ # Age is available for 2 samples (14, 20). The other 4 do not mention age but we will treat them as missing
45
+ age_row = 0
46
+
47
+ # Gender is only explicitly "female" for 2 samples and unknown for the rest, so there's effectively only one unique known value
48
+ gender_row = None
49
+
50
+ # 2) Define converters for trait, age, and gender
51
+ def convert_trait(x: str) -> int:
52
+ """
53
+ Convert the trait from string to a binary or categorical label.
54
+ Not used here because trait_row is None, but defined for completeness.
55
+ """
56
+ # Example logic (convert to 1 if "Ewing sarcoma" appears, else None):
57
+ parts = x.split(":")
58
+ if len(parts) > 1:
59
+ val = parts[1].strip().lower()
60
+ if "ewing sarcoma" in val:
61
+ return 1
62
+ return None
63
+
64
+ def convert_age(x: str) -> float:
65
+ """
66
+ Convert the age from string to a continuous float.
67
+ If no age information is present, return None.
68
+ """
69
+ # Example logic to parse "14 year old"
70
+ match = re.search(r'(\d+)\s*year\s*old', x.lower())
71
+ if match:
72
+ return float(match.group(1))
73
+ return None
74
+
75
+ def convert_gender(x: str) -> int:
76
+ """
77
+ Convert the gender from string to binary (female -> 0, male -> 1).
78
+ If unknown, return None.
79
+ """
80
+ parts = x.split(":")
81
+ val = parts[-1].strip().lower() if len(parts) > 1 else x.lower()
82
+ if "female" in val:
83
+ return 0
84
+ elif "male" in val:
85
+ return 1
86
+ return None
87
+
88
+ # 3) Save metadata using initial filtering
89
+ is_trait_available = (trait_row is not None)
90
+
91
+ # Since this is just the initial filtering, set is_final=False
92
+ _ = validate_and_save_cohort_info(
93
+ is_final=False,
94
+ cohort=cohort,
95
+ info_path=json_path,
96
+ is_gene_available=is_gene_available,
97
+ is_trait_available=is_trait_available
98
+ )
99
+
100
+ # 4) Because trait_row is None, we skip clinical feature extraction
101
+ # (No further steps for clinical data since the trait is considered not available.)
102
+ # STEP3
103
+ import gzip
104
+ import pandas as pd
105
+
106
+ try:
107
+ # 1. Attempt to extract gene expression data using the library function
108
+ gene_data = get_genetic_data(matrix_file)
109
+ except KeyError:
110
+ # Fallback: the expected "ID_REF" column may be absent, so manually parse the file
111
+ # and rename the first column to "ID".
112
+ marker = "!series_matrix_table_begin"
113
+ skip_rows = None
114
+
115
+ # Determine how many rows to skip before the matrix data begins
116
+ with gzip.open(matrix_file, 'rt') as f:
117
+ for i, line in enumerate(f):
118
+ if marker in line:
119
+ skip_rows = i + 1
120
+ break
121
+ else:
122
+ raise ValueError(f"Marker '{marker}' not found in the file.")
123
+
124
+ # Read the data from the determined position
125
+ gene_data = pd.read_csv(
126
+ matrix_file,
127
+ compression='gzip',
128
+ skiprows=skip_rows,
129
+ comment='!',
130
+ delimiter='\t',
131
+ on_bad_lines='skip'
132
+ )
133
+
134
+ # If a different column name is used instead of 'ID_REF', rename appropriately
135
+ if 'ID_REF' in gene_data.columns:
136
+ gene_data.rename(columns={'ID_REF': 'ID'}, inplace=True)
137
+ else:
138
+ first_col = gene_data.columns[0]
139
+ gene_data.rename(columns={first_col: 'ID'}, inplace=True)
140
+
141
+ gene_data['ID'] = gene_data['ID'].astype(str)
142
+ gene_data.set_index('ID', inplace=True)
143
+
144
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
145
+ print(gene_data.index[:20])
146
+ # Based on the numeric identifiers (e.g., 7892501, 7892502, etc.), these look like probe IDs rather than official gene symbols.
147
+ # Therefore, they need to be mapped to standard human gene symbols.
148
+ print("requires_gene_mapping = True")
149
+ # STEP5
150
+ # 1 & 2. Only extract and preview gene annotation data if the SOFT file exists, otherwise skip.
151
+ if soft_file is None:
152
+ print("No SOFT file found. Skipping gene annotation extraction.")
153
+ gene_annotation = pd.DataFrame()
154
+ else:
155
+ try:
156
+ # Attempt to extract gene annotation with the default method
157
+ gene_annotation = get_gene_annotation(soft_file)
158
+ except UnicodeDecodeError:
159
+ # Fallback if UTF-8 decoding fails: read with a more lenient encoding and pass the content as a string
160
+ import gzip
161
+ with gzip.open(soft_file, 'rt', encoding='latin-1', errors='replace') as f:
162
+ content = f.read()
163
+ gene_annotation = filter_content_by_prefix(
164
+ content,
165
+ prefixes_a=['^','!','#'],
166
+ unselect=True,
167
+ source_type='string',
168
+ return_df_a=True
169
+ )[0]
170
+
171
+ print("Gene annotation preview:")
172
+ print(preview_df(gene_annotation))
173
+ # STEP 6: Gene Identifier Mapping
174
+
175
+ # 1. Identify the annotation columns that match the expression data IDs and the gene symbols.
176
+ # From inspection, "ID" corresponds to the probe ID (same format as gene_data.index),
177
+ # and "mrna_assignment" appears to have clearer references to actual gene symbols (e.g. "OR4F4", "SEPT14").
178
+
179
+ # 2. Get the gene mapping DataFrame using "mrna_assignment" as the gene symbol source
180
+ mapping_df = get_gene_mapping(gene_annotation, prob_col="ID", gene_col="mrna_assignment")
181
+
182
+ # 3. Convert probe-level measurements to gene-level expression
183
+ gene_data = apply_gene_mapping(gene_data, mapping_df)
184
+
185
+ # Let's see the result
186
+ print("Gene data shape after mapping:", gene_data.shape)
187
+ print("First 5 gene indices after mapping:", gene_data.index[:5].tolist())
188
+ import os
189
+ import pandas as pd
190
+
191
+ # STEP 7: Data Normalization and Linking
192
+
193
+ # First, check if the clinical CSV file exists. If it does not, we cannot proceed with trait-based linking.
194
+ if not os.path.exists(out_clinical_data_file):
195
+ # No trait data file => dataset is not usable for trait analysis
196
+ df_null = pd.DataFrame()
197
+ is_biased = True # Arbitrary boolean to satisfy function requirement
198
+ validate_and_save_cohort_info(
199
+ is_final=True,
200
+ cohort=cohort,
201
+ info_path=json_path,
202
+ is_gene_available=True,
203
+ is_trait_available=False,
204
+ is_biased=is_biased,
205
+ df=df_null,
206
+ note="No trait data file found; dataset not usable for trait analysis."
207
+ )
208
+
209
+ else:
210
+ # 1. Normalize the mapped gene expression data using known gene symbol synonyms, then save.
211
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
212
+ normalized_gene_data.to_csv(out_gene_data_file)
213
+
214
+ # 2. Load the previously extracted clinical CSV.
215
+ selected_clinical_df = pd.read_csv(out_clinical_data_file)
216
+ # If we had a single-row trait, rename row 0 to the trait name (example usage).
217
+ selected_clinical_df = selected_clinical_df.rename(index={0: trait})
218
+
219
+ # Combine these as our final clinical data; in this dataset, we only have trait info (if any).
220
+ combined_clinical_df = selected_clinical_df
221
+
222
+ # Link the clinical and genetic data by matching sample IDs in columns.
223
+ linked_data = geo_link_clinical_genetic_data(combined_clinical_df, normalized_gene_data)
224
+
225
+ # 3. Handle missing values in the linked data (drop incomplete rows/columns, then impute).
226
+ processed_data = handle_missing_values(linked_data, trait)
227
+
228
+ # 4. Check trait bias and remove any biased demographic features (if any).
229
+ trait_biased, processed_data = judge_and_remove_biased_features(processed_data, trait)
230
+
231
+ # 5. Final validation and metadata saving.
232
+ is_usable = validate_and_save_cohort_info(
233
+ is_final=True,
234
+ cohort=cohort,
235
+ info_path=json_path,
236
+ is_gene_available=True,
237
+ is_trait_available=True,
238
+ is_biased=trait_biased,
239
+ df=processed_data,
240
+ note="Completed trait-based preprocessing."
241
+ )
242
+
243
+ # 6. If final dataset is usable, save. Otherwise, skip.
244
+ if is_usable:
245
+ processed_data.to_csv(out_data_file)
p1/preprocess/Sarcoma/code/GSE197147.py ADDED
@@ -0,0 +1,244 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Sarcoma"
6
+ cohort = "GSE197147"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Sarcoma"
10
+ in_cohort_dir = "../DATA/GEO/Sarcoma/GSE197147"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/preprocess/1/Sarcoma/GSE197147.csv"
14
+ out_gene_data_file = "./output/preprocess/1/Sarcoma/gene_data/GSE197147.csv"
15
+ out_clinical_data_file = "./output/preprocess/1/Sarcoma/clinical_data/GSE197147.csv"
16
+ json_path = "./output/preprocess/1/Sarcoma/cohort_info.json"
17
+
18
+ # STEP1
19
+ from tools.preprocess import *
20
+ # 1. Identify the paths to the SOFT file and the matrix file
21
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
22
+
23
+ # 2. Read the matrix file to obtain background information and sample characteristics data
24
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
25
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
26
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
27
+
28
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
29
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
30
+
31
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
32
+ print("Background Information:")
33
+ print(background_info)
34
+ print("Sample Characteristics Dictionary:")
35
+ print(sample_characteristics_dict)
36
+ # 1. Determine if the dataset contains gene expression data
37
+ is_gene_available = True # The series description explicitly mentions "Gene expression profiling"
38
+
39
+ # 2. Identify variable availability and define row indices
40
+ # Only one key (0) is present with multiple histotypes ("HB","NB","RMS","WT").
41
+ # We'll map "RMS" to the trait of interest (Sarcoma=1) and others to 0.
42
+ trait_row = 0 # We can infer the Sarcoma trait from 'histotype: RMS' vs others
43
+ age_row = None # No age information in the sample dictionary
44
+ gender_row = None # No gender information in the sample dictionary
45
+
46
+ # 2.2 Define conversion functions
47
+ def convert_trait(value: str):
48
+ # Extract the part after the colon.
49
+ val = value.split(':')[-1].strip().lower()
50
+ # Map RMS => 1 (Sarcoma), others => 0
51
+ if val == 'rms':
52
+ return 1
53
+ elif val in ['hb', 'nb', 'wt']:
54
+ return 0
55
+ return None # For any unexpected values
56
+
57
+ def convert_age(value: str):
58
+ # No rows found for age, so no real conversion logic needed
59
+ return None
60
+
61
+ def convert_gender(value: str):
62
+ # No rows found for gender, so no real conversion logic needed
63
+ return None
64
+
65
+ # 2.1 Check if the trait data is available
66
+ is_trait_available = (trait_row is not None)
67
+
68
+ # 3. Save metadata with initial filtering
69
+ validate_and_save_cohort_info(
70
+ is_final=False,
71
+ cohort=cohort,
72
+ info_path=json_path,
73
+ is_gene_available=is_gene_available,
74
+ is_trait_available=is_trait_available
75
+ )
76
+
77
+ # 4. If trait data is available (trait_row != None), extract clinical features
78
+ if trait_row is not None:
79
+ selected_clinical = geo_select_clinical_features(
80
+ clinical_data,
81
+ trait=trait,
82
+ trait_row=trait_row,
83
+ convert_trait=convert_trait,
84
+ age_row=age_row,
85
+ convert_age=convert_age,
86
+ gender_row=gender_row,
87
+ convert_gender=convert_gender
88
+ )
89
+ # Preview the extracted clinical features
90
+ print(preview_df(selected_clinical, n=5))
91
+ # Save to CSV
92
+ selected_clinical.to_csv(out_clinical_data_file, index=False)
93
+ # STEP3
94
+ import gzip
95
+ import pandas as pd
96
+
97
+ try:
98
+ # 1. Attempt to extract gene expression data using the library function
99
+ gene_data = get_genetic_data(matrix_file)
100
+ except KeyError:
101
+ # Fallback: the expected "ID_REF" column may be absent, so manually parse the file
102
+ # and rename the first column to "ID".
103
+ marker = "!series_matrix_table_begin"
104
+ skip_rows = None
105
+
106
+ # Determine how many rows to skip before the matrix data begins
107
+ with gzip.open(matrix_file, 'rt') as f:
108
+ for i, line in enumerate(f):
109
+ if marker in line:
110
+ skip_rows = i + 1
111
+ break
112
+ else:
113
+ raise ValueError(f"Marker '{marker}' not found in the file.")
114
+
115
+ # Read the data from the determined position
116
+ gene_data = pd.read_csv(
117
+ matrix_file,
118
+ compression='gzip',
119
+ skiprows=skip_rows,
120
+ comment='!',
121
+ delimiter='\t',
122
+ on_bad_lines='skip'
123
+ )
124
+
125
+ # If a different column name is used instead of 'ID_REF', rename appropriately
126
+ if 'ID_REF' in gene_data.columns:
127
+ gene_data.rename(columns={'ID_REF': 'ID'}, inplace=True)
128
+ else:
129
+ first_col = gene_data.columns[0]
130
+ gene_data.rename(columns={first_col: 'ID'}, inplace=True)
131
+
132
+ gene_data['ID'] = gene_data['ID'].astype(str)
133
+ gene_data.set_index('ID', inplace=True)
134
+
135
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
136
+ print(gene_data.index[:20])
137
+ # Based on the provided gene expression data index (e.g., 'TC0100006437.hg.1'),
138
+ # these appear to be probe or platform-specific identifiers rather than standard human gene symbols.
139
+ # Therefore, we conclude that these IDs must be mapped to standard gene symbols for proper analysis.
140
+
141
+ print("requires_gene_mapping = True")
142
+ # STEP5
143
+ # 1 & 2. Only extract and preview gene annotation data if the SOFT file exists, otherwise skip.
144
+ if soft_file is None:
145
+ print("No SOFT file found. Skipping gene annotation extraction.")
146
+ gene_annotation = pd.DataFrame()
147
+ else:
148
+ try:
149
+ # Attempt to extract gene annotation with the default method
150
+ gene_annotation = get_gene_annotation(soft_file)
151
+ except UnicodeDecodeError:
152
+ # Fallback if UTF-8 decoding fails: read with a more lenient encoding and pass the content as a string
153
+ import gzip
154
+ with gzip.open(soft_file, 'rt', encoding='latin-1', errors='replace') as f:
155
+ content = f.read()
156
+ gene_annotation = filter_content_by_prefix(
157
+ content,
158
+ prefixes_a=['^','!','#'],
159
+ unselect=True,
160
+ source_type='string',
161
+ return_df_a=True
162
+ )[0]
163
+
164
+ print("Gene annotation preview:")
165
+ print(preview_df(gene_annotation))
166
+ # STEP: Gene Identifier Mapping
167
+
168
+ # 1. Identify which annotation columns store the gene IDs and gene symbol references.
169
+ # From the preview, it appears the column "ID" matches the row index of our gene expression data,
170
+ # and the column "SPOT_ID.1" contains gene symbol references.
171
+ probe_id_col = "ID"
172
+ gene_symbol_col = "SPOT_ID.1"
173
+
174
+ # 2. Get a gene mapping dataframe from the annotation dataframe.
175
+ mapping_df = get_gene_mapping(
176
+ annotation=gene_annotation,
177
+ prob_col=probe_id_col,
178
+ gene_col=gene_symbol_col
179
+ )
180
+
181
+ # 3. Convert probe-level measurements into gene-level expression.
182
+ gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
183
+
184
+ # Print a small preview to confirm the result
185
+ print("Mapped gene expression data preview:")
186
+ print(gene_data.head())
187
+ import os
188
+ import pandas as pd
189
+
190
+ # STEP 7: Data Normalization and Linking
191
+
192
+ # First, check if the clinical CSV file exists. If it does not, we cannot proceed with trait-based linking.
193
+ if not os.path.exists(out_clinical_data_file):
194
+ # No trait data file => dataset is not usable for trait analysis
195
+ df_null = pd.DataFrame()
196
+ is_biased = True # Arbitrary boolean to satisfy function requirement
197
+ validate_and_save_cohort_info(
198
+ is_final=True,
199
+ cohort=cohort,
200
+ info_path=json_path,
201
+ is_gene_available=True,
202
+ is_trait_available=False,
203
+ is_biased=is_biased,
204
+ df=df_null,
205
+ note="No trait data file found; dataset not usable for trait analysis."
206
+ )
207
+
208
+ else:
209
+ # 1. Normalize the mapped gene expression data using known gene symbol synonyms, then save.
210
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
211
+ normalized_gene_data.to_csv(out_gene_data_file)
212
+
213
+ # 2. Load the previously extracted clinical CSV.
214
+ selected_clinical_df = pd.read_csv(out_clinical_data_file)
215
+ # If we had a single-row trait, rename row 0 to the trait name (example usage).
216
+ selected_clinical_df = selected_clinical_df.rename(index={0: trait})
217
+
218
+ # Combine these as our final clinical data; in this dataset, we only have trait info (if any).
219
+ combined_clinical_df = selected_clinical_df
220
+
221
+ # Link the clinical and genetic data by matching sample IDs in columns.
222
+ linked_data = geo_link_clinical_genetic_data(combined_clinical_df, normalized_gene_data)
223
+
224
+ # 3. Handle missing values in the linked data (drop incomplete rows/columns, then impute).
225
+ processed_data = handle_missing_values(linked_data, trait)
226
+
227
+ # 4. Check trait bias and remove any biased demographic features (if any).
228
+ trait_biased, processed_data = judge_and_remove_biased_features(processed_data, trait)
229
+
230
+ # 5. Final validation and metadata saving.
231
+ is_usable = validate_and_save_cohort_info(
232
+ is_final=True,
233
+ cohort=cohort,
234
+ info_path=json_path,
235
+ is_gene_available=True,
236
+ is_trait_available=True,
237
+ is_biased=trait_biased,
238
+ df=processed_data,
239
+ note="Completed trait-based preprocessing."
240
+ )
241
+
242
+ # 6. If final dataset is usable, save. Otherwise, skip.
243
+ if is_usable:
244
+ processed_data.to_csv(out_data_file)
p1/preprocess/Sarcoma/code/GSE215265.py ADDED
@@ -0,0 +1,218 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Sarcoma"
6
+ cohort = "GSE215265"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Sarcoma"
10
+ in_cohort_dir = "../DATA/GEO/Sarcoma/GSE215265"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/preprocess/1/Sarcoma/GSE215265.csv"
14
+ out_gene_data_file = "./output/preprocess/1/Sarcoma/gene_data/GSE215265.csv"
15
+ out_clinical_data_file = "./output/preprocess/1/Sarcoma/clinical_data/GSE215265.csv"
16
+ json_path = "./output/preprocess/1/Sarcoma/cohort_info.json"
17
+
18
+ # STEP1
19
+ from tools.preprocess import *
20
+ # 1. Identify the paths to the SOFT file and the matrix file
21
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
22
+
23
+ # 2. Read the matrix file to obtain background information and sample characteristics data
24
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
25
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
26
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
27
+
28
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
29
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
30
+
31
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
32
+ print("Background Information:")
33
+ print(background_info)
34
+ print("Sample Characteristics Dictionary:")
35
+ print(sample_characteristics_dict)
36
+ # Step 1: Determine gene expression data availability
37
+ is_gene_available = True # Based on the background info, we assume it's gene expression, not miRNA/methylation.
38
+
39
+ # Step 2: Determine availability of variables (trait, age, gender) and define conversion functions
40
+ # From the sample characteristics dictionary, all samples have the same cell type "Alveolar soft part sarcoma",
41
+ # which is essentially constant. Therefore, trait_row is considered not available for our analysis.
42
+ trait_row = None
43
+ age_row = None
44
+ gender_row = None
45
+
46
+ def convert_trait(value: str) -> int:
47
+ # Not used because trait_row is None, but we define it as requested.
48
+ # Typically, you would parse out the portion after ':' and map to a numerical category.
49
+ return None
50
+
51
+ def convert_age(value: str) -> float:
52
+ # Not used because age_row is None, but we define it as requested.
53
+ return None
54
+
55
+ def convert_gender(value: str) -> int:
56
+ # Not used because gender_row is None, but we define it as requested.
57
+ return None
58
+
59
+ # Step 3: Initial filtering and save metadata
60
+ is_trait_available = (trait_row is not None)
61
+ is_usable = validate_and_save_cohort_info(
62
+ is_final=False,
63
+ cohort=cohort,
64
+ info_path=json_path,
65
+ is_gene_available=is_gene_available,
66
+ is_trait_available=is_trait_available
67
+ )
68
+
69
+ # Step 4: Since trait_row is None, we skip clinical feature extraction.
70
+ # STEP3
71
+ import gzip
72
+ import pandas as pd
73
+
74
+ try:
75
+ # 1. Attempt to extract gene expression data using the library function
76
+ gene_data = get_genetic_data(matrix_file)
77
+ except KeyError:
78
+ # Fallback: the expected "ID_REF" column may be absent, so manually parse the file
79
+ # and rename the first column to "ID".
80
+ marker = "!series_matrix_table_begin"
81
+ skip_rows = None
82
+
83
+ # Determine how many rows to skip before the matrix data begins
84
+ with gzip.open(matrix_file, 'rt') as f:
85
+ for i, line in enumerate(f):
86
+ if marker in line:
87
+ skip_rows = i + 1
88
+ break
89
+ else:
90
+ raise ValueError(f"Marker '{marker}' not found in the file.")
91
+
92
+ # Read the data from the determined position
93
+ gene_data = pd.read_csv(
94
+ matrix_file,
95
+ compression='gzip',
96
+ skiprows=skip_rows,
97
+ comment='!',
98
+ delimiter='\t',
99
+ on_bad_lines='skip'
100
+ )
101
+
102
+ # If a different column name is used instead of 'ID_REF', rename appropriately
103
+ if 'ID_REF' in gene_data.columns:
104
+ gene_data.rename(columns={'ID_REF': 'ID'}, inplace=True)
105
+ else:
106
+ first_col = gene_data.columns[0]
107
+ gene_data.rename(columns={first_col: 'ID'}, inplace=True)
108
+
109
+ gene_data['ID'] = gene_data['ID'].astype(str)
110
+ gene_data.set_index('ID', inplace=True)
111
+
112
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
113
+ print(gene_data.index[:20])
114
+ # The provided IDs appear to be Affymetrix probe set identifiers (e.g., "1007_PM_s_at"),
115
+ # which are not standard human gene symbols.
116
+ # Hence, they require mapping to gene symbols.
117
+
118
+ requires_gene_mapping = True
119
+ # STEP5
120
+ # 1 & 2. Only extract and preview gene annotation data if the SOFT file exists, otherwise skip.
121
+ if soft_file is None:
122
+ print("No SOFT file found. Skipping gene annotation extraction.")
123
+ gene_annotation = pd.DataFrame()
124
+ else:
125
+ try:
126
+ # Attempt to extract gene annotation with the default method
127
+ gene_annotation = get_gene_annotation(soft_file)
128
+ except UnicodeDecodeError:
129
+ # Fallback if UTF-8 decoding fails: read with a more lenient encoding and pass the content as a string
130
+ import gzip
131
+ with gzip.open(soft_file, 'rt', encoding='latin-1', errors='replace') as f:
132
+ content = f.read()
133
+ gene_annotation = filter_content_by_prefix(
134
+ content,
135
+ prefixes_a=['^','!','#'],
136
+ unselect=True,
137
+ source_type='string',
138
+ return_df_a=True
139
+ )[0]
140
+
141
+ print("Gene annotation preview:")
142
+ print(preview_df(gene_annotation))
143
+ # STEP: Gene Identifier Mapping
144
+
145
+ # 1. Identify the columns for gene identifier and gene symbol
146
+ # Based on the preview, "ID" matches our probe IDs (e.g., "1415670_PM_at"),
147
+ # and "Gene Symbol" contains the corresponding gene symbols.
148
+
149
+ probe_identifier_col = "ID"
150
+ gene_symbol_col = "Gene Symbol"
151
+
152
+ # 2. Extract gene mapping information
153
+ gene_mapping_df = get_gene_mapping(gene_annotation, prob_col=probe_identifier_col, gene_col=gene_symbol_col)
154
+
155
+ # 3. Convert probe-level measurements to gene expression data
156
+ gene_data = apply_gene_mapping(gene_data, gene_mapping_df)
157
+
158
+ # Optionally show a small preview of the resulting gene_data
159
+ print("Mapped gene_data shape:", gene_data.shape)
160
+ print("Mapped gene_data index sample:", gene_data.index[:10])
161
+ import os
162
+ import pandas as pd
163
+
164
+ # STEP 7: Data Normalization and Linking
165
+
166
+ # First, check if the clinical CSV file exists. If it does not, we cannot proceed with trait-based linking.
167
+ if not os.path.exists(out_clinical_data_file):
168
+ # No trait data file => dataset is not usable for trait analysis
169
+ df_null = pd.DataFrame()
170
+ is_biased = True # Arbitrary boolean to satisfy function requirement
171
+ validate_and_save_cohort_info(
172
+ is_final=True,
173
+ cohort=cohort,
174
+ info_path=json_path,
175
+ is_gene_available=True,
176
+ is_trait_available=False,
177
+ is_biased=is_biased,
178
+ df=df_null,
179
+ note="No trait data file found; dataset not usable for trait analysis."
180
+ )
181
+
182
+ else:
183
+ # 1. Normalize the mapped gene expression data using known gene symbol synonyms, then save.
184
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
185
+ normalized_gene_data.to_csv(out_gene_data_file)
186
+
187
+ # 2. Load the previously extracted clinical CSV.
188
+ selected_clinical_df = pd.read_csv(out_clinical_data_file)
189
+ # If we had a single-row trait, rename row 0 to the trait name (example usage).
190
+ selected_clinical_df = selected_clinical_df.rename(index={0: trait})
191
+
192
+ # Combine these as our final clinical data; in this dataset, we only have trait info (if any).
193
+ combined_clinical_df = selected_clinical_df
194
+
195
+ # Link the clinical and genetic data by matching sample IDs in columns.
196
+ linked_data = geo_link_clinical_genetic_data(combined_clinical_df, normalized_gene_data)
197
+
198
+ # 3. Handle missing values in the linked data (drop incomplete rows/columns, then impute).
199
+ processed_data = handle_missing_values(linked_data, trait)
200
+
201
+ # 4. Check trait bias and remove any biased demographic features (if any).
202
+ trait_biased, processed_data = judge_and_remove_biased_features(processed_data, trait)
203
+
204
+ # 5. Final validation and metadata saving.
205
+ is_usable = validate_and_save_cohort_info(
206
+ is_final=True,
207
+ cohort=cohort,
208
+ info_path=json_path,
209
+ is_gene_available=True,
210
+ is_trait_available=True,
211
+ is_biased=trait_biased,
212
+ df=processed_data,
213
+ note="Completed trait-based preprocessing."
214
+ )
215
+
216
+ # 6. If final dataset is usable, save. Otherwise, skip.
217
+ if is_usable:
218
+ processed_data.to_csv(out_data_file)