Liu-Hy commited on
Commit
e4183cf
·
verified ·
1 Parent(s): f88156f

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. code/COVID-19/GSE185658.ipynb +706 -0
  2. code/COVID-19/GSE211378.ipynb +435 -0
  3. code/COVID-19/GSE212865.ipynb +769 -0
  4. code/COVID-19/GSE212866.ipynb +654 -0
  5. code/COVID-19/GSE213313.ipynb +677 -0
  6. code/COVID-19/GSE216705.ipynb +668 -0
  7. code/COVID-19/GSE227080.ipynb +511 -0
  8. code/COVID-19/GSE243348.ipynb +558 -0
  9. code/COVID-19/GSE273225.ipynb +447 -0
  10. code/COVID-19/GSE275334.ipynb +555 -0
  11. code/COVID-19/TCGA.ipynb +146 -0
  12. code/Cervical_Cancer/GSE107754.ipynb +364 -0
  13. code/Cervical_Cancer/GSE114243.ipynb +447 -0
  14. code/Cervical_Cancer/GSE131027.ipynb +557 -0
  15. code/Cervical_Cancer/GSE137034.ipynb +450 -0
  16. code/Cervical_Cancer/GSE138079.ipynb +494 -0
  17. code/Chronic_obstructive_pulmonary_disease_(COPD)/GSE21359.ipynb +722 -0
  18. code/Chronic_obstructive_pulmonary_disease_(COPD)/GSE32030.ipynb +664 -0
  19. code/Chronic_obstructive_pulmonary_disease_(COPD)/GSE64593.ipynb +529 -0
  20. code/Chronic_obstructive_pulmonary_disease_(COPD)/GSE84046.ipynb +584 -0
  21. code/Chronic_obstructive_pulmonary_disease_(COPD)/TCGA.ipynb +551 -0
  22. code/Colon_and_Rectal_Cancer/GSE56699.ipynb +718 -0
  23. code/Colon_and_Rectal_Cancer/TCGA.ipynb +436 -0
  24. code/Congestive_heart_failure/GSE182600.ipynb +846 -0
  25. code/Congestive_heart_failure/GSE93101.ipynb +785 -0
  26. code/Congestive_heart_failure/TCGA.ipynb +520 -0
  27. code/Coronary_artery_disease/GSE109048.ipynb +606 -0
  28. code/Coronary_artery_disease/GSE120774.ipynb +860 -0
  29. code/Coronary_artery_disease/GSE156357.ipynb +793 -0
  30. code/Coronary_artery_disease/GSE234398.ipynb +704 -0
  31. code/Coronary_artery_disease/GSE250283.ipynb +737 -0
  32. code/Coronary_artery_disease/GSE54975.ipynb +676 -0
  33. code/Coronary_artery_disease/GSE59867.ipynb +1156 -0
  34. code/Coronary_artery_disease/GSE64554.ipynb +721 -0
  35. code/Coronary_artery_disease/GSE64566.ipynb +757 -0
  36. code/Coronary_artery_disease/GSE86216.ipynb +787 -0
  37. code/Coronary_artery_disease/TCGA.ipynb +146 -0
  38. code/Craniosynostosis/GSE27976.ipynb +685 -0
  39. code/Craniosynostosis/TCGA.ipynb +159 -0
  40. code/Creutzfeldt-Jakob_Disease/GSE62699.ipynb +570 -0
  41. code/Creutzfeldt-Jakob_Disease/GSE87629.ipynb +534 -0
  42. code/Creutzfeldt-Jakob_Disease/TCGA.ipynb +158 -0
  43. code/Crohns_Disease/GSE123086.ipynb +688 -0
  44. code/Crohns_Disease/GSE123088.ipynb +626 -0
  45. code/Crohns_Disease/GSE207022.ipynb +661 -0
  46. code/Crohns_Disease/GSE66407.ipynb +635 -0
  47. code/Crohns_Disease/GSE83448.ipynb +653 -0
  48. code/Crohns_Disease/TCGA.ipynb +150 -0
  49. code/Cystic_Fibrosis/GSE142610.ipynb +578 -0
  50. code/Cystic_Fibrosis/GSE60690.ipynb +0 -0
code/COVID-19/GSE185658.ipynb ADDED
@@ -0,0 +1,706 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": 1,
6
+ "id": "90b91c33",
7
+ "metadata": {
8
+ "execution": {
9
+ "iopub.execute_input": "2025-03-25T08:30:08.205938Z",
10
+ "iopub.status.busy": "2025-03-25T08:30:08.205452Z",
11
+ "iopub.status.idle": "2025-03-25T08:30:08.371351Z",
12
+ "shell.execute_reply": "2025-03-25T08:30:08.371023Z"
13
+ }
14
+ },
15
+ "outputs": [],
16
+ "source": [
17
+ "import sys\n",
18
+ "import os\n",
19
+ "sys.path.append(os.path.abspath(os.path.join(os.getcwd(), '../..')))\n",
20
+ "\n",
21
+ "# Path Configuration\n",
22
+ "from tools.preprocess import *\n",
23
+ "\n",
24
+ "# Processing context\n",
25
+ "trait = \"COVID-19\"\n",
26
+ "cohort = \"GSE185658\"\n",
27
+ "\n",
28
+ "# Input paths\n",
29
+ "in_trait_dir = \"../../input/GEO/COVID-19\"\n",
30
+ "in_cohort_dir = \"../../input/GEO/COVID-19/GSE185658\"\n",
31
+ "\n",
32
+ "# Output paths\n",
33
+ "out_data_file = \"../../output/preprocess/COVID-19/GSE185658.csv\"\n",
34
+ "out_gene_data_file = \"../../output/preprocess/COVID-19/gene_data/GSE185658.csv\"\n",
35
+ "out_clinical_data_file = \"../../output/preprocess/COVID-19/clinical_data/GSE185658.csv\"\n",
36
+ "json_path = \"../../output/preprocess/COVID-19/cohort_info.json\"\n"
37
+ ]
38
+ },
39
+ {
40
+ "cell_type": "markdown",
41
+ "id": "362d1a18",
42
+ "metadata": {},
43
+ "source": [
44
+ "### Step 1: Initial Data Loading"
45
+ ]
46
+ },
47
+ {
48
+ "cell_type": "code",
49
+ "execution_count": 2,
50
+ "id": "ebb746c0",
51
+ "metadata": {
52
+ "execution": {
53
+ "iopub.execute_input": "2025-03-25T08:30:08.372719Z",
54
+ "iopub.status.busy": "2025-03-25T08:30:08.372580Z",
55
+ "iopub.status.idle": "2025-03-25T08:30:08.483771Z",
56
+ "shell.execute_reply": "2025-03-25T08:30:08.483483Z"
57
+ }
58
+ },
59
+ "outputs": [
60
+ {
61
+ "name": "stdout",
62
+ "output_type": "stream",
63
+ "text": [
64
+ "Background Information:\n",
65
+ "!Series_title\t\"Rhinovirus-induced epithelial RIG-I inflammasome suppresses antiviral immunity and promotes inflammation in asthma and COVID-19\"\n",
66
+ "!Series_summary\t\"Balanced immune responses in airways of patients with asthma are crucial to succesful clearance of viral infection and proper asthma control.\"\n",
67
+ "!Series_summary\t\"We used microarrays to detail the global programme of gene expression data from bronchial brushings from control individuals and patients with asthma after rhinovirus infection in vivo.\"\n",
68
+ "!Series_overall_design\t\"Bronchial brushings from control individuals and patients with asthma around two weeks before (day -14) and four days after (day 4) experimental in vivo rhinovirus infection were used for RNA isolation and hybrydyzation with Affymetric microarrays.\"\n",
69
+ "Sample Characteristics Dictionary:\n",
70
+ "{0: ['time: DAY14', 'time: DAY4'], 1: ['group: AsthmaHDM', 'group: AsthmaHDMNeg', 'group: Healthy'], 2: ['donor: DJ144', 'donor: DJ113', 'donor: DJ139', 'donor: DJ129', 'donor: DJ134', 'donor: DJ114', 'donor: DJ81', 'donor: DJ60', 'donor: DJ73', 'donor: DJ136', 'donor: DJ92', 'donor: DJ47', 'donor: DJ125', 'donor: DJ148', 'donor: DJ121', 'donor: DJ116', 'donor: DJ86', 'donor: DJ126', 'donor: DJ48', 'donor: DJ67', 'donor: DJ56', 'donor: DJ61', 'donor: DJ75', 'donor: DJ101']}\n"
71
+ ]
72
+ }
73
+ ],
74
+ "source": [
75
+ "from tools.preprocess import *\n",
76
+ "# 1. Identify the paths to the SOFT file and the matrix file\n",
77
+ "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
78
+ "\n",
79
+ "# 2. Read the matrix file to obtain background information and sample characteristics data\n",
80
+ "background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']\n",
81
+ "clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']\n",
82
+ "background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)\n",
83
+ "\n",
84
+ "# 3. Obtain the sample characteristics dictionary from the clinical dataframe\n",
85
+ "sample_characteristics_dict = get_unique_values_by_row(clinical_data)\n",
86
+ "\n",
87
+ "# 4. Explicitly print out all the background information and the sample characteristics dictionary\n",
88
+ "print(\"Background Information:\")\n",
89
+ "print(background_info)\n",
90
+ "print(\"Sample Characteristics Dictionary:\")\n",
91
+ "print(sample_characteristics_dict)\n"
92
+ ]
93
+ },
94
+ {
95
+ "cell_type": "markdown",
96
+ "id": "4128a79e",
97
+ "metadata": {},
98
+ "source": [
99
+ "### Step 2: Dataset Analysis and Clinical Feature Extraction"
100
+ ]
101
+ },
102
+ {
103
+ "cell_type": "code",
104
+ "execution_count": 3,
105
+ "id": "753acb1a",
106
+ "metadata": {
107
+ "execution": {
108
+ "iopub.execute_input": "2025-03-25T08:30:08.484915Z",
109
+ "iopub.status.busy": "2025-03-25T08:30:08.484810Z",
110
+ "iopub.status.idle": "2025-03-25T08:30:08.489842Z",
111
+ "shell.execute_reply": "2025-03-25T08:30:08.489574Z"
112
+ }
113
+ },
114
+ "outputs": [
115
+ {
116
+ "name": "stdout",
117
+ "output_type": "stream",
118
+ "text": [
119
+ "A new JSON file was created at: ../../output/preprocess/COVID-19/cohort_info.json\n"
120
+ ]
121
+ },
122
+ {
123
+ "data": {
124
+ "text/plain": [
125
+ "False"
126
+ ]
127
+ },
128
+ "execution_count": 3,
129
+ "metadata": {},
130
+ "output_type": "execute_result"
131
+ }
132
+ ],
133
+ "source": [
134
+ "# 1. Gene Expression Data Availability\n",
135
+ "# Based on the background information, this is microarray data from bronchial brushings\n",
136
+ "# which indicates gene expression data is available\n",
137
+ "is_gene_available = True\n",
138
+ "\n",
139
+ "# 2. Variable Availability and Data Type Conversion\n",
140
+ "# 2.1 Data Availability\n",
141
+ "# After reviewing the data, it's clear this dataset is about asthma and rhinovirus, not COVID-19\n",
142
+ "# Therefore, the COVID-19 trait we're interested in is not available in this dataset\n",
143
+ "trait_row = None # COVID-19 trait information is not available\n",
144
+ "age_row = None # Age information is not available\n",
145
+ "gender_row = None # Gender information is not available\n",
146
+ "\n",
147
+ "# 2.2 Data Type Conversion\n",
148
+ "def convert_trait(value):\n",
149
+ " \"\"\"Convert trait information to binary values for COVID-19\"\"\"\n",
150
+ " # Since the trait is not available, this function won't be used\n",
151
+ " return None\n",
152
+ "\n",
153
+ "def convert_age(value):\n",
154
+ " \"\"\"Convert age information to continuous values\"\"\"\n",
155
+ " # Not applicable as age data is not available\n",
156
+ " return None\n",
157
+ "\n",
158
+ "def convert_gender(value):\n",
159
+ " \"\"\"Convert gender information to binary values\"\"\"\n",
160
+ " # Not applicable as gender data is not available\n",
161
+ " return None\n",
162
+ "\n",
163
+ "# 3. Save Metadata\n",
164
+ "# Determine trait data availability\n",
165
+ "is_trait_available = trait_row is not None\n",
166
+ "\n",
167
+ "# Conduct initial filtering and save metadata\n",
168
+ "validate_and_save_cohort_info(\n",
169
+ " is_final=False,\n",
170
+ " cohort=cohort,\n",
171
+ " info_path=json_path,\n",
172
+ " is_gene_available=is_gene_available,\n",
173
+ " is_trait_available=is_trait_available\n",
174
+ ")\n",
175
+ "\n",
176
+ "# 4. Clinical Feature Extraction\n",
177
+ "# Skip this step since trait_row is None (COVID-19 trait data is not available)\n"
178
+ ]
179
+ },
180
+ {
181
+ "cell_type": "markdown",
182
+ "id": "d74c5573",
183
+ "metadata": {},
184
+ "source": [
185
+ "### Step 3: Gene Data Extraction"
186
+ ]
187
+ },
188
+ {
189
+ "cell_type": "code",
190
+ "execution_count": 4,
191
+ "id": "df48e103",
192
+ "metadata": {
193
+ "execution": {
194
+ "iopub.execute_input": "2025-03-25T08:30:08.490923Z",
195
+ "iopub.status.busy": "2025-03-25T08:30:08.490823Z",
196
+ "iopub.status.idle": "2025-03-25T08:30:08.660942Z",
197
+ "shell.execute_reply": "2025-03-25T08:30:08.660574Z"
198
+ }
199
+ },
200
+ "outputs": [
201
+ {
202
+ "name": "stdout",
203
+ "output_type": "stream",
204
+ "text": [
205
+ "SOFT file: ../../input/GEO/COVID-19/GSE185658/GSE185658_family.soft.gz\n",
206
+ "Matrix file: ../../input/GEO/COVID-19/GSE185658/GSE185658_series_matrix.txt.gz\n",
207
+ "Found the matrix table marker at line 63\n",
208
+ "Gene data shape: (32321, 48)\n",
209
+ "First 20 gene/probe identifiers:\n",
210
+ "['7892501', '7892502', '7892503', '7892504', '7892505', '7892506', '7892507', '7892508', '7892509', '7892510', '7892511', '7892512', '7892513', '7892514', '7892515', '7892516', '7892517', '7892518', '7892519', '7892520']\n"
211
+ ]
212
+ }
213
+ ],
214
+ "source": [
215
+ "# 1. Identify the paths to the SOFT file and the matrix file\n",
216
+ "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
217
+ "print(f\"SOFT file: {soft_file}\")\n",
218
+ "print(f\"Matrix file: {matrix_file}\")\n",
219
+ "\n",
220
+ "# Set gene availability flag\n",
221
+ "is_gene_available = True # Initially assume gene data is available\n",
222
+ "\n",
223
+ "# First check if the matrix file contains the expected marker\n",
224
+ "found_marker = False\n",
225
+ "marker_row = None\n",
226
+ "try:\n",
227
+ " with gzip.open(matrix_file, 'rt') as file:\n",
228
+ " for i, line in enumerate(file):\n",
229
+ " if \"!series_matrix_table_begin\" in line:\n",
230
+ " found_marker = True\n",
231
+ " marker_row = i\n",
232
+ " print(f\"Found the matrix table marker at line {i}\")\n",
233
+ " break\n",
234
+ " \n",
235
+ " if not found_marker:\n",
236
+ " print(\"Warning: Could not find '!series_matrix_table_begin' marker in the file.\")\n",
237
+ " is_gene_available = False\n",
238
+ " \n",
239
+ " # If marker was found, try to extract gene data\n",
240
+ " if is_gene_available:\n",
241
+ " try:\n",
242
+ " # Try using the library function\n",
243
+ " gene_data = get_genetic_data(matrix_file)\n",
244
+ " \n",
245
+ " if gene_data.shape[0] == 0:\n",
246
+ " print(\"Warning: Extracted gene data has 0 rows.\")\n",
247
+ " is_gene_available = False\n",
248
+ " else:\n",
249
+ " print(f\"Gene data shape: {gene_data.shape}\")\n",
250
+ " # Print the first 20 gene/probe identifiers\n",
251
+ " print(\"First 20 gene/probe identifiers:\")\n",
252
+ " print(gene_data.index[:20].tolist())\n",
253
+ " except Exception as e:\n",
254
+ " print(f\"Error extracting gene data with get_genetic_data(): {e}\")\n",
255
+ " is_gene_available = False\n",
256
+ " \n",
257
+ " # If gene data extraction failed, examine file content to diagnose\n",
258
+ " if not is_gene_available:\n",
259
+ " print(\"Examining file content to diagnose the issue:\")\n",
260
+ " try:\n",
261
+ " with gzip.open(matrix_file, 'rt') as file:\n",
262
+ " # Print lines around the marker if found\n",
263
+ " if marker_row is not None:\n",
264
+ " for i, line in enumerate(file):\n",
265
+ " if i >= marker_row - 2 and i <= marker_row + 10:\n",
266
+ " print(f\"Line {i}: {line.strip()[:100]}...\")\n",
267
+ " if i > marker_row + 10:\n",
268
+ " break\n",
269
+ " else:\n",
270
+ " # If marker not found, print first 10 lines\n",
271
+ " for i, line in enumerate(file):\n",
272
+ " if i < 10:\n",
273
+ " print(f\"Line {i}: {line.strip()[:100]}...\")\n",
274
+ " else:\n",
275
+ " break\n",
276
+ " except Exception as e2:\n",
277
+ " print(f\"Error examining file: {e2}\")\n",
278
+ " \n",
279
+ "except Exception as e:\n",
280
+ " print(f\"Error processing file: {e}\")\n",
281
+ " is_gene_available = False\n",
282
+ "\n",
283
+ "# Update validation information if gene data extraction failed\n",
284
+ "if not is_gene_available:\n",
285
+ " print(\"Gene expression data could not be successfully extracted from this dataset.\")\n",
286
+ " # Update the validation record since gene data isn't available\n",
287
+ " is_trait_available = False # We already determined trait data isn't available in step 2\n",
288
+ " validate_and_save_cohort_info(is_final=False, cohort=cohort, info_path=json_path,\n",
289
+ " is_gene_available=is_gene_available, is_trait_available=is_trait_available)\n"
290
+ ]
291
+ },
292
+ {
293
+ "cell_type": "markdown",
294
+ "id": "1a30a9dc",
295
+ "metadata": {},
296
+ "source": [
297
+ "### Step 4: Gene Identifier Review"
298
+ ]
299
+ },
300
+ {
301
+ "cell_type": "code",
302
+ "execution_count": 5,
303
+ "id": "bbd75804",
304
+ "metadata": {
305
+ "execution": {
306
+ "iopub.execute_input": "2025-03-25T08:30:08.662213Z",
307
+ "iopub.status.busy": "2025-03-25T08:30:08.662097Z",
308
+ "iopub.status.idle": "2025-03-25T08:30:08.663939Z",
309
+ "shell.execute_reply": "2025-03-25T08:30:08.663668Z"
310
+ }
311
+ },
312
+ "outputs": [],
313
+ "source": [
314
+ "# These don't appear to be human gene symbols but rather probe identifiers from a microarray platform\n",
315
+ "# They are numeric identifiers that likely need to be mapped to gene symbols\n",
316
+ "# Based on my biomedical knowledge, human gene symbols are typically alphanumeric (like BRCA1, TP53, etc.)\n",
317
+ "# These look like Illumina BeadChip probe IDs which require mapping to standard gene symbols\n",
318
+ "\n",
319
+ "requires_gene_mapping = True\n"
320
+ ]
321
+ },
322
+ {
323
+ "cell_type": "markdown",
324
+ "id": "9f5d354a",
325
+ "metadata": {},
326
+ "source": [
327
+ "### Step 5: Gene Annotation"
328
+ ]
329
+ },
330
+ {
331
+ "cell_type": "code",
332
+ "execution_count": 6,
333
+ "id": "20684cd7",
334
+ "metadata": {
335
+ "execution": {
336
+ "iopub.execute_input": "2025-03-25T08:30:08.665140Z",
337
+ "iopub.status.busy": "2025-03-25T08:30:08.664954Z",
338
+ "iopub.status.idle": "2025-03-25T08:30:11.838183Z",
339
+ "shell.execute_reply": "2025-03-25T08:30:11.837861Z"
340
+ }
341
+ },
342
+ "outputs": [
343
+ {
344
+ "name": "stdout",
345
+ "output_type": "stream",
346
+ "text": [
347
+ "\n",
348
+ "Gene annotation preview:\n",
349
+ "Columns in gene annotation: ['ID', 'GB_LIST', 'SPOT_ID', 'seqname', 'RANGE_GB', 'RANGE_STRAND', 'RANGE_START', 'RANGE_STOP', 'total_probes', 'gene_assignment', 'mrna_assignment', 'category']\n",
350
+ "{'ID': ['7896736', '7896738', '7896740'], 'GB_LIST': [nan, nan, 'NM_001004195,NM_001005240,NM_001005484,BC136848,BC136867,BC136907,BC136908'], 'SPOT_ID': ['chr1:53049-54936', 'chr1:63015-63887', 'chr1:69091-70008'], 'seqname': ['chr1', 'chr1', 'chr1'], 'RANGE_GB': ['NC_000001.10', 'NC_000001.10', 'NC_000001.10'], 'RANGE_STRAND': ['+', '+', '+'], 'RANGE_START': ['53049', '63015', '69091'], 'RANGE_STOP': ['54936', '63887', '70008'], 'total_probes': [7.0, 31.0, 24.0], 'gene_assignment': ['---', 'ENST00000328113 // OR4G2P // olfactory receptor, family 4, subfamily G, member 2 pseudogene // --- // --- /// ENST00000492842 // OR4G11P // olfactory receptor, family 4, subfamily G, member 11 pseudogene // --- // --- /// ENST00000588632 // OR4G1P // olfactory receptor, family 4, subfamily G, member 1 pseudogene // --- // ---', 'NM_001004195 // OR4F4 // olfactory receptor, family 4, subfamily F, member 4 // 15q26.3 // 26682 /// NM_001005240 // OR4F17 // olfactory receptor, family 4, subfamily F, member 17 // 19p13.3 // 81099 /// NM_001005484 // OR4F5 // olfactory receptor, family 4, subfamily F, member 5 // 1p36.33 // 79501 /// ENST00000318050 // OR4F17 // olfactory receptor, family 4, subfamily F, member 17 // 19p13.3 // 81099 /// ENST00000326183 // OR4F4 // olfactory receptor, family 4, subfamily F, member 4 // 15q26.3 // 26682 /// ENST00000335137 // OR4F5 // olfactory receptor, family 4, subfamily F, member 5 // 1p36.33 // 79501 /// ENST00000585993 // OR4F17 // olfactory receptor, family 4, subfamily F, member 17 // 19p13.3 // 81099 /// BC136848 // OR4F17 // olfactory receptor, family 4, subfamily F, member 17 // 19p13.3 // 81099 /// BC136867 // OR4F17 // olfactory receptor, family 4, subfamily F, member 17 // 19p13.3 // 81099 /// BC136907 // OR4F4 // olfactory receptor, family 4, subfamily F, member 4 // 15q26.3 // 26682 /// BC136908 // OR4F4 // olfactory receptor, family 4, subfamily F, member 4 // 15q26.3 // 26682'], 'mrna_assignment': ['NONHSAT060105 // NONCODE // Non-coding transcript identified by NONCODE // chr1 // 100 // 100 // 7 // 7 // 0', 'ENST00000328113 // ENSEMBL // havana:known chromosome:GRCh38:15:101926805:101927707:-1 gene:ENSG00000183909 gene_biotype:unprocessed_pseudogene transcript_biotype:unprocessed_pseudogene // chr1 // 100 // 100 // 31 // 31 // 0 /// ENST00000492842 // ENSEMBL // havana:known chromosome:GRCh38:1:62948:63887:1 gene:ENSG00000240361 gene_biotype:unprocessed_pseudogene transcript_biotype:unprocessed_pseudogene // chr1 // 100 // 100 // 31 // 31 // 0 /// ENST00000588632 // ENSEMBL // havana:known chromosome:GRCh38:19:104535:105471:1 gene:ENSG00000267310 gene_biotype:unprocessed_pseudogene transcript_biotype:unprocessed_pseudogene // chr1 // 100 // 100 // 31 // 31 // 0 /// NONHSAT000016 // NONCODE // Non-coding transcript identified by NONCODE: Linc // chr1 // 100 // 100 // 31 // 31 // 0 /// NONHSAT051704 // NONCODE // Non-coding transcript identified by NONCODE: Linc // chr1 // 100 // 100 // 31 // 31 // 0 /// NONHSAT060106 // NONCODE // Non-coding transcript identified by NONCODE: Linc // chr1 // 100 // 100 // 31 // 31 // 0', 'NM_001004195 // RefSeq // Homo sapiens olfactory receptor, family 4, subfamily F, member 4 (OR4F4), mRNA. // chr1 // 100 // 100 // 24 // 24 // 0 /// NM_001005240 // RefSeq // Homo sapiens olfactory receptor, family 4, subfamily F, member 17 (OR4F17), mRNA. // chr1 // 100 // 100 // 24 // 24 // 0 /// NM_001005484 // RefSeq // Homo sapiens olfactory receptor, family 4, subfamily F, member 5 (OR4F5), mRNA. // chr1 // 100 // 100 // 24 // 24 // 0 /// ENST00000318050 // ENSEMBL // ensembl:known chromosome:GRCh38:19:110643:111696:1 gene:ENSG00000176695 gene_biotype:protein_coding transcript_biotype:protein_coding // chr1 // 100 // 100 // 24 // 24 // 0 /// ENST00000326183 // ENSEMBL // ensembl_havana_transcript:known chromosome:GRCh38:15:101922042:101923095:-1 gene:ENSG00000177693 gene_biotype:protein_coding transcript_biotype:protein_coding // chr1 // 100 // 100 // 24 // 24 // 0 /// ENST00000335137 // ENSEMBL // ensembl_havana_transcript:known chromosome:GRCh38:1:69091:70008:1 gene:ENSG00000186092 gene_biotype:protein_coding transcript_biotype:protein_coding // chr1 // 100 // 100 // 24 // 24 // 0 /// ENST00000585993 // ENSEMBL // havana:known chromosome:GRCh38:19:107461:111696:1 gene:ENSG00000176695 gene_biotype:protein_coding transcript_biotype:protein_coding // chr1 // 100 // 100 // 24 // 24 // 0 /// BC136848 // GenBank // Homo sapiens olfactory receptor, family 4, subfamily F, member 17, mRNA (cDNA clone MGC:168462 IMAGE:9020839), complete cds. // chr1 // 100 // 100 // 24 // 24 // 0 /// BC136867 // GenBank // Homo sapiens olfactory receptor, family 4, subfamily F, member 17, mRNA (cDNA clone MGC:168481 IMAGE:9020858), complete cds. // chr1 // 100 // 100 // 24 // 24 // 0 /// BC136907 // GenBank // Homo sapiens olfactory receptor, family 4, subfamily F, member 4, mRNA (cDNA clone MGC:168521 IMAGE:9020898), complete cds. // chr1 // 100 // 100 // 24 // 24 // 0 /// BC136908 // GenBank // Homo sapiens olfactory receptor, family 4, subfamily F, member 4, mRNA (cDNA clone MGC:168522 IMAGE:9020899), complete cds. // chr1 // 100 // 100 // 24 // 24 // 0 /// ENST00000618231 // ENSEMBL // havana:known chromosome:GRCh38:19:110613:111417:1 gene:ENSG00000176695 gene_biotype:protein_coding transcript_biotype:retained_intron // chr1 // 100 // 88 // 21 // 21 // 0'], 'category': ['main', 'main', 'main']}\n",
351
+ "\n",
352
+ "Examining gene mapping columns:\n",
353
+ "Column 'ID' examples:\n",
354
+ "Example 1: 7896736\n",
355
+ "Example 2: 7896738\n",
356
+ "Example 3: 7896740\n",
357
+ "Example 4: 7896742\n",
358
+ "Example 5: 7896744\n",
359
+ "\n",
360
+ "Column 'gene_assignment' examples (contains gene symbols):\n",
361
+ "Example 1: ---...\n",
362
+ "Example 2: ENST00000328113 // OR4G2P // olfactory receptor, family 4, subfamily G, member 2 pseudogene // --- // --- /// ENST00000492842 // OR4G11P // olfactory receptor, family 4, subfamily G, member 11 pseudog...\n",
363
+ "Example 3: NM_001004195 // OR4F4 // olfactory receptor, family 4, subfamily F, member 4 // 15q26.3 // 26682 /// NM_001005240 // OR4F17 // olfactory receptor, family 4, subfamily F, member 17 // 19p13.3 // 81099 ...\n",
364
+ "\n",
365
+ "Extracted gene symbols from gene_assignment:\n",
366
+ "Example 1 extracted symbols: []\n",
367
+ "Example 2 extracted symbols: ['OR4G2P', 'OR4G11P', 'OR4G1P']\n",
368
+ "Example 3 extracted symbols: ['OR4F4', 'OR4F17', 'OR4F5', 'BC136848', 'BC136867', 'BC136907', 'BC136908']\n",
369
+ "\n",
370
+ "Columns identified for gene mapping:\n",
371
+ "- 'ID': Contains probe IDs\n",
372
+ "- 'gene_assignment': Contains gene information from which symbols can be extracted\n"
373
+ ]
374
+ }
375
+ ],
376
+ "source": [
377
+ "# 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.\n",
378
+ "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
379
+ "gene_annotation = get_gene_annotation(soft_file)\n",
380
+ "\n",
381
+ "# 2. Analyze the gene annotation dataframe to identify which columns contain the gene identifiers and gene symbols\n",
382
+ "print(\"\\nGene annotation preview:\")\n",
383
+ "print(f\"Columns in gene annotation: {gene_annotation.columns.tolist()}\")\n",
384
+ "print(preview_df(gene_annotation, n=3))\n",
385
+ "\n",
386
+ "# Examine the columns to find gene information\n",
387
+ "print(\"\\nExamining gene mapping columns:\")\n",
388
+ "print(\"Column 'ID' examples:\")\n",
389
+ "id_samples = gene_annotation['ID'].head(5).tolist()\n",
390
+ "for i, sample in enumerate(id_samples):\n",
391
+ " print(f\"Example {i+1}: {sample}\")\n",
392
+ "\n",
393
+ "# Look at gene_assignment column which contains gene symbols embedded in text\n",
394
+ "print(\"\\nColumn 'gene_assignment' examples (contains gene symbols):\")\n",
395
+ "if 'gene_assignment' in gene_annotation.columns:\n",
396
+ " # Display a few examples of the gene_assignment column\n",
397
+ " gene_samples = gene_annotation['gene_assignment'].head(3).tolist()\n",
398
+ " for i, sample in enumerate(gene_samples):\n",
399
+ " print(f\"Example {i+1}: {sample[:200]}...\") # Show first 200 chars\n",
400
+ " \n",
401
+ " # Extract some gene symbols to verify\n",
402
+ " print(\"\\nExtracted gene symbols from gene_assignment:\")\n",
403
+ " for i, sample in enumerate(gene_samples[:3]):\n",
404
+ " symbols = extract_human_gene_symbols(sample)\n",
405
+ " print(f\"Example {i+1} extracted symbols: {symbols}\")\n",
406
+ " \n",
407
+ " # Identify the columns needed for gene mapping\n",
408
+ " print(\"\\nColumns identified for gene mapping:\")\n",
409
+ " print(\"- 'ID': Contains probe IDs\")\n",
410
+ " print(\"- 'gene_assignment': Contains gene information from which symbols can be extracted\")\n",
411
+ "else:\n",
412
+ " print(\"Error: 'gene_assignment' column not found in annotation data.\")\n"
413
+ ]
414
+ },
415
+ {
416
+ "cell_type": "markdown",
417
+ "id": "702952b7",
418
+ "metadata": {},
419
+ "source": [
420
+ "### Step 6: Gene Identifier Mapping"
421
+ ]
422
+ },
423
+ {
424
+ "cell_type": "code",
425
+ "execution_count": 7,
426
+ "id": "4e59efc4",
427
+ "metadata": {
428
+ "execution": {
429
+ "iopub.execute_input": "2025-03-25T08:30:11.839495Z",
430
+ "iopub.status.busy": "2025-03-25T08:30:11.839369Z",
431
+ "iopub.status.idle": "2025-03-25T08:30:15.668497Z",
432
+ "shell.execute_reply": "2025-03-25T08:30:15.668165Z"
433
+ }
434
+ },
435
+ "outputs": [
436
+ {
437
+ "name": "stdout",
438
+ "output_type": "stream",
439
+ "text": [
440
+ "Sample gene mapping (before filtering):\n",
441
+ " ID Gene\n",
442
+ "0 7896736 []\n",
443
+ "1 7896738 [OR4G2P, OR4G11P, OR4G1P]\n",
444
+ "2 7896740 [OR4F4, OR4F17, OR4F5, OR4F17, OR4F4, OR4F5, O...\n",
445
+ "3 7896742 [LOC728323, LOC101060626, LOC101060626, LOC101...\n",
446
+ "4 7896744 [OR4F29, OR4F3, OR4F16, OR4F21, OR4F21, OR4F3,...\n",
447
+ "Mapping entries with gene symbols: 25293\n"
448
+ ]
449
+ },
450
+ {
451
+ "name": "stdout",
452
+ "output_type": "stream",
453
+ "text": [
454
+ "Number of probe IDs in mapping that match expression data: 24520\n"
455
+ ]
456
+ },
457
+ {
458
+ "name": "stdout",
459
+ "output_type": "stream",
460
+ "text": [
461
+ "Original expression data shape: (32321, 48)\n",
462
+ "Gene mapping entries: 25293\n",
463
+ "Resulting gene expression data shape: (25745, 48)\n",
464
+ "First 10 gene symbols: ['MT-TM', 'FAM87B', 'FAM87A', 'LINC01128', 'SAMD11', 'KLHL17', 'PLEKHN1', 'ISG15', 'AGRN', 'MIR200B']\n"
465
+ ]
466
+ }
467
+ ],
468
+ "source": [
469
+ "# 1. Analyze the gene identifiers in the expression data and gene annotation data\n",
470
+ "# Based on the preview, the 'ID' column in gene_annotation corresponds to the probe IDs in gene_data\n",
471
+ "# The gene symbols are in the 'gene_assignment' column and need to be extracted\n",
472
+ "\n",
473
+ "# Define a more specific extraction function for this dataset format\n",
474
+ "def extract_genes_from_assignment(text):\n",
475
+ " \"\"\"Extract gene symbols from gene_assignment field with specific format handling for this dataset\"\"\"\n",
476
+ " if not isinstance(text, str) or text == '---':\n",
477
+ " return []\n",
478
+ " \n",
479
+ " genes = []\n",
480
+ " # Gene symbols appear after '//' in the format \"ID // GENE // description\"\n",
481
+ " parts = text.split('///')\n",
482
+ " for part in parts:\n",
483
+ " subparts = part.split('//')\n",
484
+ " if len(subparts) > 1 and len(subparts[1].strip()) > 0:\n",
485
+ " gene = subparts[1].strip()\n",
486
+ " if gene != '---':\n",
487
+ " genes.append(gene)\n",
488
+ " return genes\n",
489
+ "\n",
490
+ "# 2. Create the gene mapping dataframe\n",
491
+ "# We'll use the 'ID' column and extract gene symbols from 'gene_assignment' column\n",
492
+ "mapping_df = gene_annotation[['ID', 'gene_assignment']].copy()\n",
493
+ "\n",
494
+ "# Process the mapping dataframe\n",
495
+ "mapping_df = mapping_df.dropna(subset=['gene_assignment']) # Drop rows without gene assignments\n",
496
+ "\n",
497
+ "# Use our custom extraction function instead of the generic one\n",
498
+ "mapping_df['Gene'] = mapping_df['gene_assignment'].apply(extract_genes_from_assignment)\n",
499
+ "\n",
500
+ "# Check intermediate results\n",
501
+ "print(\"Sample gene mapping (before filtering):\")\n",
502
+ "print(mapping_df[['ID', 'Gene']].head(5))\n",
503
+ "\n",
504
+ "# Only keep rows that have at least one gene symbol\n",
505
+ "mapping_df = mapping_df[mapping_df['Gene'].apply(len) > 0]\n",
506
+ "print(f\"Mapping entries with gene symbols: {len(mapping_df)}\")\n",
507
+ "\n",
508
+ "# Make sure IDs are strings\n",
509
+ "mapping_df['ID'] = mapping_df['ID'].astype(str)\n",
510
+ "\n",
511
+ "# 3. Apply gene mapping to convert probe-level measurements to gene expression data\n",
512
+ "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
513
+ "expression_df = get_genetic_data(matrix_file)\n",
514
+ "\n",
515
+ "# Check if our probe IDs match the expression data index\n",
516
+ "common_ids = set(mapping_df['ID']) & set(expression_df.index.astype(str))\n",
517
+ "print(f\"Number of probe IDs in mapping that match expression data: {len(common_ids)}\")\n",
518
+ "\n",
519
+ "# Create a custom mapping function for debugging\n",
520
+ "def custom_map_probes_to_genes():\n",
521
+ " # Dictionary to store summed expression values for each gene\n",
522
+ " gene_expr = {}\n",
523
+ " \n",
524
+ " # Process each probe\n",
525
+ " for idx, row in mapping_df.iterrows():\n",
526
+ " probe_id = row['ID']\n",
527
+ " genes = row['Gene']\n",
528
+ " \n",
529
+ " # Skip if probe not in expression data\n",
530
+ " if probe_id not in expression_df.index:\n",
531
+ " continue\n",
532
+ " \n",
533
+ " # Skip if no genes to map to\n",
534
+ " if len(genes) == 0:\n",
535
+ " continue\n",
536
+ " \n",
537
+ " # Get probe expression values\n",
538
+ " probe_values = expression_df.loc[probe_id].to_dict()\n",
539
+ " \n",
540
+ " # Distribute expression values among genes\n",
541
+ " weight = 1.0 / len(genes)\n",
542
+ " for gene in genes:\n",
543
+ " if gene not in gene_expr:\n",
544
+ " gene_expr[gene] = {col: 0 for col in expression_df.columns}\n",
545
+ " \n",
546
+ " # Add weighted expression to each gene\n",
547
+ " for col, val in probe_values.items():\n",
548
+ " gene_expr[gene][col] += val * weight\n",
549
+ " \n",
550
+ " # Convert to dataframe\n",
551
+ " result = pd.DataFrame.from_dict(gene_expr, orient='index')\n",
552
+ " return result\n",
553
+ "\n",
554
+ "# Try our custom mapping approach for more control over the process\n",
555
+ "gene_data = custom_map_probes_to_genes()\n",
556
+ "\n",
557
+ "# Print information about the mapping and resulting gene expression data\n",
558
+ "print(f\"Original expression data shape: {expression_df.shape}\")\n",
559
+ "print(f\"Gene mapping entries: {len(mapping_df)}\")\n",
560
+ "print(f\"Resulting gene expression data shape: {gene_data.shape}\")\n",
561
+ "if gene_data.shape[0] > 0:\n",
562
+ " print(f\"First 10 gene symbols: {gene_data.index[:10].tolist()}\")\n",
563
+ "else:\n",
564
+ " print(\"No gene symbols were mapped successfully.\")\n",
565
+ "\n",
566
+ "# If custom mapping failed, try using the library function with explicit exploded mapping\n",
567
+ "if gene_data.shape[0] == 0:\n",
568
+ " print(\"Trying alternative mapping approach with exploded mapping dataframe...\")\n",
569
+ " \n",
570
+ " # Create an exploded version with one gene per row\n",
571
+ " exploded_df = mapping_df.explode('Gene')\n",
572
+ " exploded_df = exploded_df[exploded_df['Gene'] != ''] # Remove empty strings\n",
573
+ " \n",
574
+ " # Apply the gene mapping using the library function\n",
575
+ " gene_data = apply_gene_mapping(expression_df, exploded_df[['ID', 'Gene']])\n",
576
+ " \n",
577
+ " print(f\"Resulting gene expression data shape with exploded mapping: {gene_data.shape}\")\n",
578
+ " if gene_data.shape[0] > 0:\n",
579
+ " print(f\"First 10 gene symbols: {gene_data.index[:10].tolist()}\")\n"
580
+ ]
581
+ },
582
+ {
583
+ "cell_type": "markdown",
584
+ "id": "e989347a",
585
+ "metadata": {},
586
+ "source": [
587
+ "### Step 7: Data Normalization and Linking"
588
+ ]
589
+ },
590
+ {
591
+ "cell_type": "code",
592
+ "execution_count": 8,
593
+ "id": "b80d42b3",
594
+ "metadata": {
595
+ "execution": {
596
+ "iopub.execute_input": "2025-03-25T08:30:15.669829Z",
597
+ "iopub.status.busy": "2025-03-25T08:30:15.669713Z",
598
+ "iopub.status.idle": "2025-03-25T08:30:16.550758Z",
599
+ "shell.execute_reply": "2025-03-25T08:30:16.550380Z"
600
+ }
601
+ },
602
+ "outputs": [
603
+ {
604
+ "name": "stdout",
605
+ "output_type": "stream",
606
+ "text": [
607
+ "Gene data shape after normalization: (24776, 48)\n"
608
+ ]
609
+ },
610
+ {
611
+ "name": "stdout",
612
+ "output_type": "stream",
613
+ "text": [
614
+ "Normalized gene data saved to ../../output/preprocess/COVID-19/gene_data/GSE185658.csv\n",
615
+ "No clinical data available for the trait of interest.\n",
616
+ "Abnormality detected in the cohort: GSE185658. Preprocessing failed.\n",
617
+ "Linked data not saved due to quality issues.\n"
618
+ ]
619
+ }
620
+ ],
621
+ "source": [
622
+ "# 1. Normalize gene symbols in the gene expression data\n",
623
+ "normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n",
624
+ "print(f\"Gene data shape after normalization: {normalized_gene_data.shape}\")\n",
625
+ "\n",
626
+ "# Create output directory if it doesn't exist\n",
627
+ "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
628
+ "\n",
629
+ "# Save the normalized gene data\n",
630
+ "normalized_gene_data.to_csv(out_gene_data_file)\n",
631
+ "print(f\"Normalized gene data saved to {out_gene_data_file}\")\n",
632
+ "\n",
633
+ "# 2. Check if clinical data is available before trying to extract features\n",
634
+ "if trait_row is not None:\n",
635
+ " # Extract clinical features only if trait_row exists\n",
636
+ " clinical_features = geo_select_clinical_features(\n",
637
+ " clinical_data,\n",
638
+ " trait=trait,\n",
639
+ " trait_row=trait_row,\n",
640
+ " convert_trait=convert_trait,\n",
641
+ " age_row=age_row,\n",
642
+ " convert_age=convert_age,\n",
643
+ " gender_row=gender_row,\n",
644
+ " convert_gender=convert_gender\n",
645
+ " )\n",
646
+ " \n",
647
+ " # Save clinical features\n",
648
+ " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
649
+ " clinical_features.to_csv(out_clinical_data_file)\n",
650
+ " print(f\"Clinical features saved to {out_clinical_data_file}\")\n",
651
+ " \n",
652
+ " # Link clinical and genetic data\n",
653
+ " linked_data = geo_link_clinical_genetic_data(clinical_features, normalized_gene_data)\n",
654
+ " \n",
655
+ " # Handle missing values and check for bias\n",
656
+ " linked_data = handle_missing_values(linked_data, trait)\n",
657
+ " is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n",
658
+ "else:\n",
659
+ " # No clinical data available\n",
660
+ " print(\"No clinical data available for the trait of interest.\")\n",
661
+ " linked_data = pd.DataFrame() # Empty dataframe\n",
662
+ " is_biased = True # Dataset is biased since we have no trait data\n",
663
+ "\n",
664
+ "# 6. Validate and save cohort info\n",
665
+ "is_trait_available = trait_row is not None\n",
666
+ "is_usable = validate_and_save_cohort_info(\n",
667
+ " is_final=True,\n",
668
+ " cohort=cohort,\n",
669
+ " info_path=json_path,\n",
670
+ " is_gene_available=is_gene_available,\n",
671
+ " is_trait_available=is_trait_available,\n",
672
+ " is_biased=is_biased,\n",
673
+ " df=linked_data,\n",
674
+ " note=\"Dataset contains gene expression data but lacks COVID-19 trait information.\"\n",
675
+ ")\n",
676
+ "\n",
677
+ "# 7. Save the linked data if it's usable\n",
678
+ "if is_usable:\n",
679
+ " # Create output directory if it doesn't exist\n",
680
+ " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n",
681
+ " \n",
682
+ " # Save the linked data\n",
683
+ " linked_data.to_csv(out_data_file)\n",
684
+ " print(f\"Linked data saved to {out_data_file}\")\n",
685
+ "else:\n",
686
+ " print(\"Linked data not saved due to quality issues.\")"
687
+ ]
688
+ }
689
+ ],
690
+ "metadata": {
691
+ "language_info": {
692
+ "codemirror_mode": {
693
+ "name": "ipython",
694
+ "version": 3
695
+ },
696
+ "file_extension": ".py",
697
+ "mimetype": "text/x-python",
698
+ "name": "python",
699
+ "nbconvert_exporter": "python",
700
+ "pygments_lexer": "ipython3",
701
+ "version": "3.10.16"
702
+ }
703
+ },
704
+ "nbformat": 4,
705
+ "nbformat_minor": 5
706
+ }
code/COVID-19/GSE211378.ipynb ADDED
@@ -0,0 +1,435 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": 1,
6
+ "id": "a02231ce",
7
+ "metadata": {
8
+ "execution": {
9
+ "iopub.execute_input": "2025-03-25T08:30:17.265262Z",
10
+ "iopub.status.busy": "2025-03-25T08:30:17.265152Z",
11
+ "iopub.status.idle": "2025-03-25T08:30:17.423688Z",
12
+ "shell.execute_reply": "2025-03-25T08:30:17.423325Z"
13
+ }
14
+ },
15
+ "outputs": [],
16
+ "source": [
17
+ "import sys\n",
18
+ "import os\n",
19
+ "sys.path.append(os.path.abspath(os.path.join(os.getcwd(), '../..')))\n",
20
+ "\n",
21
+ "# Path Configuration\n",
22
+ "from tools.preprocess import *\n",
23
+ "\n",
24
+ "# Processing context\n",
25
+ "trait = \"COVID-19\"\n",
26
+ "cohort = \"GSE211378\"\n",
27
+ "\n",
28
+ "# Input paths\n",
29
+ "in_trait_dir = \"../../input/GEO/COVID-19\"\n",
30
+ "in_cohort_dir = \"../../input/GEO/COVID-19/GSE211378\"\n",
31
+ "\n",
32
+ "# Output paths\n",
33
+ "out_data_file = \"../../output/preprocess/COVID-19/GSE211378.csv\"\n",
34
+ "out_gene_data_file = \"../../output/preprocess/COVID-19/gene_data/GSE211378.csv\"\n",
35
+ "out_clinical_data_file = \"../../output/preprocess/COVID-19/clinical_data/GSE211378.csv\"\n",
36
+ "json_path = \"../../output/preprocess/COVID-19/cohort_info.json\"\n"
37
+ ]
38
+ },
39
+ {
40
+ "cell_type": "markdown",
41
+ "id": "d7caed5d",
42
+ "metadata": {},
43
+ "source": [
44
+ "### Step 1: Initial Data Loading"
45
+ ]
46
+ },
47
+ {
48
+ "cell_type": "code",
49
+ "execution_count": 2,
50
+ "id": "c571c381",
51
+ "metadata": {
52
+ "execution": {
53
+ "iopub.execute_input": "2025-03-25T08:30:17.425142Z",
54
+ "iopub.status.busy": "2025-03-25T08:30:17.424993Z",
55
+ "iopub.status.idle": "2025-03-25T08:30:17.462470Z",
56
+ "shell.execute_reply": "2025-03-25T08:30:17.462154Z"
57
+ }
58
+ },
59
+ "outputs": [
60
+ {
61
+ "name": "stdout",
62
+ "output_type": "stream",
63
+ "text": [
64
+ "Background Information:\n",
65
+ "!Series_title\t\"Whole Blood profiling of COVID convalescent and Healthy donors with nCounter\"\n",
66
+ "!Series_summary\t\"This study investigated the cellular immune response in people who had recovered from SARS-CoV2 infection (COVID-19).\"\n",
67
+ "!Series_overall_design\t\"264 Whole Blood samples from 160 COVID convalescent donors, and 40 from Healthy donors.\"\n",
68
+ "Sample Characteristics Dictionary:\n",
69
+ "{0: ['sample.id: host response panel 1 wb', 'sample.id: host response panel 2 wb', 'sample.id: host response panel 3 wb', 'sample.id: host response panel 4 wb', 'sample.id: host response panel plate 25 wb 11292020', 'sample.id: host response panel plate 5 wb 11 19 2020', 'sample.id: host response panel plate 6 wb 11192020', 'sample.id: host response panel plate 7 wb 11 20 2020', 'sample.id: host response panel plate 8 wb 11202020', 'sample.id: host response panel plate 26 wb 11302020', 'sample.id: host response panel plate 9 wb 11212020', 'sample.id: host response panel plate 10 wb 11212020', 'sample.id: host response panel plate 11 wb 11222020', 'sample.id: host response panel plate 12 wb 11222020', 'sample.id: host response panel plate 13 11232020', 'sample.id: host response panel plate 14 wb 11232020', 'sample.id: host response panel plate 15 wb 11242020', 'sample.id: host response panel plate 16 wb 11242020', 'sample.id: host response panel plate 17 wb 11252020', 'sample.id: host response panel plate 18 wb 11252020', 'sample.id: host response panel plate 19 wb 11262020', 'sample.id: host response panel plate 20 wb 11262020', 'sample.id: host response panel plate 21 wb 11272020', 'sample.id: host response panel plate 22 wb 11272020', 'sample.id: host response panel plate 23 11282020', 'sample.id: host response panel plate 24 wb 11292020'], 1: ['date: 20201018', 'date: 20201019', 'date: 20201129', 'date: 20201119', 'date: 20201120', 'date: 20201130', 'date: 20201121', 'date: 20201122', 'date: 20201123', 'date: 20201124', 'date: 20201125', 'date: 20201126', 'date: 20201127', 'date: 20201128'], 2: ['generlf: NS_Hs_HostResponse_v1.0'], 3: ['systemapf: n6_vDV1'], 4: ['lane.number: 1', 'lane.number: 2', 'lane.number: 3', 'lane.number: 4', 'lane.number: 5', 'lane.number: 6', 'lane.number: 7', 'lane.number: 8', 'lane.number: 9', 'lane.number: 10', 'lane.number: 11', 'lane.number: 12'], 5: ['fovcount: 555'], 6: ['fovcounted: 551', 'fovcounted: 549', 'fovcounted: 544', 'fovcounted: 535', 'fovcounted: 546', 'fovcounted: 541', 'fovcounted: 540', 'fovcounted: 538', 'fovcounted: 532', 'fovcounted: 543', 'fovcounted: 536', 'fovcounted: 537', 'fovcounted: 534', 'fovcounted: 542', 'fovcounted: 545', 'fovcounted: 528', 'fovcounted: 547', 'fovcounted: 526', 'fovcounted: 550', 'fovcounted: 554', 'fovcounted: 552', 'fovcounted: 539', 'fovcounted: 530', 'fovcounted: 548', 'fovcounted: 553', 'fovcounted: 555', 'fovcounted: 515', 'fovcounted: 522', 'fovcounted: 521', 'fovcounted: 533'], 7: ['scannerid: 1906C0614'], 8: ['stageposition: 1', 'stageposition: 2'], 9: ['bindingdensity: 0.92', 'bindingdensity: 1.1', 'bindingdensity: 1.52', 'bindingdensity: 1.75', 'bindingdensity: 1.94', 'bindingdensity: 2.49', 'bindingdensity: 1.98', 'bindingdensity: 1.69', 'bindingdensity: 1.44', 'bindingdensity: 2.91', 'bindingdensity: 1.81', 'bindingdensity: 2.18', 'bindingdensity: 1.82', 'bindingdensity: 1.72', 'bindingdensity: 2.09', 'bindingdensity: 1.66', 'bindingdensity: 1.87', 'bindingdensity: 1.51', 'bindingdensity: 2.27', 'bindingdensity: 2.51', 'bindingdensity: 1.88', 'bindingdensity: 2.15', 'bindingdensity: 2.1', 'bindingdensity: 1.54', 'bindingdensity: 1.33', 'bindingdensity: 1.04', 'bindingdensity: 1.45', 'bindingdensity: 1.63', 'bindingdensity: 1.7', 'bindingdensity: 3.1'], 10: ['cartridgeid: host response panel wb 1', 'cartridgeid: host response panel 2 wb', 'cartridgeid: host response panel 3 wb', 'cartridgeid: host response panel 4 wb', 'cartridgeid: host response panel plate 25 wb 11292020', 'cartridgeid: host response panel plate 5 wb 11 19 2020', 'cartridgeid: host response panel plate 6 wb 11 19 2020', 'cartridgeid: host response panel plate 7 wb 11 20 2020', 'cartridgeid: host response panel plate 8 wb 11202020', 'cartridgeid: host response panel plate 26 wb 11302020', 'cartridgeid: host response panel plate 9 wb 11212020', 'cartridgeid: host response panel plate 10 wb 11212020', 'cartridgeid: host response panel plate 11 wb 11222020', 'cartridgeid: host response panel plate 12 wb 11222020', 'cartridgeid: host response panel plate 13 wb 11232020', 'cartridgeid: host response panel plate 14 wb 11232020', 'cartridgeid: host response panel plate 15 wb 11242020', 'cartridgeid: host response panel plate 16 wb 11242020', 'cartridgeid: host response panel plate 17 wb 11252020', 'cartridgeid: host response panel plate 18 wb 11252020', 'cartridgeid: host response panel plate 19 wb 11262020', 'cartridgeid: host response panel plate 20 wb 11262020', 'cartridgeid: host response panel plate 21 wb 11272020', 'cartridgeid: host response panel plate 22 wb 11272020', 'cartridgeid: host response panel plate 23 wb 11282020', 'cartridgeid: host response panel plate 24 wb 11292020'], 11: ['cartridgebarcode: NA'], 12: ['nanostring_id: 12590', 'nanostring_id: 12591_51', 'nanostring_id: 12645_21', 'nanostring_id: 12650', 'nanostring_id: 12672', 'nanostring_id: 12688_41', 'nanostring_id: 12693_21', 'nanostring_id: 12694_21', 'nanostring_id: 12700_21', 'nanostring_id: 12707_31', 'nanostring_id: 12708 _51', 'nanostring_id: 12709_21', 'nanostring_id: 12721', 'nanostring_id: 12726_21', 'nanostring_id: 12727', 'nanostring_id: 12733', 'nanostring_id: 12736', 'nanostring_id: 12745', 'nanostring_id: 12751_41', 'nanostring_id: 12766', 'nanostring_id: 12772_31', 'nanostring_id: 12774', 'nanostring_id: 12781', 'nanostring_id: 12786_21', 'nanostring_id: 12792_21', 'nanostring_id: 12812_31', 'nanostring_id: 12830_51', 'nanostring_id: 12862_21', 'nanostring_id: 12889_31', 'nanostring_id: 12896_52']}\n"
70
+ ]
71
+ }
72
+ ],
73
+ "source": [
74
+ "from tools.preprocess import *\n",
75
+ "# 1. Identify the paths to the SOFT file and the matrix file\n",
76
+ "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
77
+ "\n",
78
+ "# 2. Read the matrix file to obtain background information and sample characteristics data\n",
79
+ "background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']\n",
80
+ "clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']\n",
81
+ "background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)\n",
82
+ "\n",
83
+ "# 3. Obtain the sample characteristics dictionary from the clinical dataframe\n",
84
+ "sample_characteristics_dict = get_unique_values_by_row(clinical_data)\n",
85
+ "\n",
86
+ "# 4. Explicitly print out all the background information and the sample characteristics dictionary\n",
87
+ "print(\"Background Information:\")\n",
88
+ "print(background_info)\n",
89
+ "print(\"Sample Characteristics Dictionary:\")\n",
90
+ "print(sample_characteristics_dict)\n"
91
+ ]
92
+ },
93
+ {
94
+ "cell_type": "markdown",
95
+ "id": "b3bdde7f",
96
+ "metadata": {},
97
+ "source": [
98
+ "### Step 2: Dataset Analysis and Clinical Feature Extraction"
99
+ ]
100
+ },
101
+ {
102
+ "cell_type": "code",
103
+ "execution_count": 3,
104
+ "id": "56c3816e",
105
+ "metadata": {
106
+ "execution": {
107
+ "iopub.execute_input": "2025-03-25T08:30:17.463571Z",
108
+ "iopub.status.busy": "2025-03-25T08:30:17.463463Z",
109
+ "iopub.status.idle": "2025-03-25T08:30:17.486520Z",
110
+ "shell.execute_reply": "2025-03-25T08:30:17.486220Z"
111
+ }
112
+ },
113
+ "outputs": [
114
+ {
115
+ "data": {
116
+ "text/plain": [
117
+ "False"
118
+ ]
119
+ },
120
+ "execution_count": 3,
121
+ "metadata": {},
122
+ "output_type": "execute_result"
123
+ }
124
+ ],
125
+ "source": [
126
+ "# 1. Gene Expression Data Availability\n",
127
+ "is_gene_available = True # The background suggests this is gene expression profiling data\n",
128
+ "\n",
129
+ "# 2. Variable Availability and Data Type Conversion\n",
130
+ "\n",
131
+ "# 2.1 Data Availability\n",
132
+ "# There are no clear clinical data columns in the sample characteristics\n",
133
+ "# From the background information: \"264 Whole Blood samples from 160 COVID convalescent donors, \n",
134
+ "# and 40 from Healthy donors.\" implies there is COVID-19 status information\n",
135
+ "# However, it's not available in the sample characteristics dictionary\n",
136
+ "trait_row = None # No clear trait information in characteristics\n",
137
+ "age_row = None # No age information found\n",
138
+ "gender_row = None # No gender information found\n",
139
+ "\n",
140
+ "# 2.2 Data Type Conversion Functions\n",
141
+ "def convert_trait(value):\n",
142
+ " # Function to convert COVID-19 status, though not used in this dataset\n",
143
+ " if value is None:\n",
144
+ " return None\n",
145
+ " \n",
146
+ " value = value.lower().split(': ')[-1].strip()\n",
147
+ " if 'covid' in value or 'convalescent' in value or 'infected' in value or 'positive' in value:\n",
148
+ " return 1\n",
149
+ " elif 'healthy' in value or 'control' in value or 'negative' in value:\n",
150
+ " return 0\n",
151
+ " return None\n",
152
+ "\n",
153
+ "def convert_age(value):\n",
154
+ " # Function to convert age to continuous values, though not used in this dataset\n",
155
+ " if value is None:\n",
156
+ " return None\n",
157
+ " \n",
158
+ " try:\n",
159
+ " # Extract the value after the colon and convert to float\n",
160
+ " age_value = value.split(': ')[-1].strip()\n",
161
+ " return float(age_value)\n",
162
+ " except (ValueError, AttributeError):\n",
163
+ " return None\n",
164
+ "\n",
165
+ "def convert_gender(value):\n",
166
+ " # Function to convert gender to binary, though not used in this dataset\n",
167
+ " if value is None:\n",
168
+ " return None\n",
169
+ " \n",
170
+ " value = value.lower().split(': ')[-1].strip()\n",
171
+ " if value in ['female', 'f', 'woman']:\n",
172
+ " return 0\n",
173
+ " elif value in ['male', 'm', 'man']:\n",
174
+ " return 1\n",
175
+ " return None\n",
176
+ "\n",
177
+ "# 3. Save Metadata\n",
178
+ "# Initial validation - check if the dataset has both gene and trait data\n",
179
+ "validate_and_save_cohort_info(\n",
180
+ " is_final=False,\n",
181
+ " cohort=cohort,\n",
182
+ " info_path=json_path,\n",
183
+ " is_gene_available=is_gene_available,\n",
184
+ " is_trait_available=(trait_row is not None)\n",
185
+ ")\n",
186
+ "\n",
187
+ "# 4. Clinical Feature Extraction\n",
188
+ "# Since trait_row is None, we skip the clinical feature extraction step\n"
189
+ ]
190
+ },
191
+ {
192
+ "cell_type": "markdown",
193
+ "id": "b7805f8e",
194
+ "metadata": {},
195
+ "source": [
196
+ "### Step 3: Gene Data Extraction"
197
+ ]
198
+ },
199
+ {
200
+ "cell_type": "code",
201
+ "execution_count": 4,
202
+ "id": "d21ce447",
203
+ "metadata": {
204
+ "execution": {
205
+ "iopub.execute_input": "2025-03-25T08:30:17.487587Z",
206
+ "iopub.status.busy": "2025-03-25T08:30:17.487482Z",
207
+ "iopub.status.idle": "2025-03-25T08:30:17.538074Z",
208
+ "shell.execute_reply": "2025-03-25T08:30:17.537762Z"
209
+ }
210
+ },
211
+ "outputs": [
212
+ {
213
+ "name": "stdout",
214
+ "output_type": "stream",
215
+ "text": [
216
+ "SOFT file: ../../input/GEO/COVID-19/GSE211378/GSE211378_family.soft.gz\n",
217
+ "Matrix file: ../../input/GEO/COVID-19/GSE211378/GSE211378_series_matrix.txt.gz\n",
218
+ "Found the matrix table marker at line 84\n",
219
+ "Gene data shape: (773, 304)\n",
220
+ "First 20 gene/probe identifiers:\n",
221
+ "['ACE', 'ACKR2', 'ACKR3', 'ACKR4', 'ACOX1', 'ACSL1', 'ACSL3', 'ACSL4', 'ACVR1', 'ADAR', 'ADGRE5', 'ADGRG3', 'ADORA2A', 'AGT', 'AHR', 'AIF1', 'AIM2', 'AKT1', 'AKT2', 'AKT3']\n"
222
+ ]
223
+ }
224
+ ],
225
+ "source": [
226
+ "# 1. Identify the paths to the SOFT file and the matrix file\n",
227
+ "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
228
+ "print(f\"SOFT file: {soft_file}\")\n",
229
+ "print(f\"Matrix file: {matrix_file}\")\n",
230
+ "\n",
231
+ "# Set gene availability flag\n",
232
+ "is_gene_available = True # Initially assume gene data is available\n",
233
+ "\n",
234
+ "# First check if the matrix file contains the expected marker\n",
235
+ "found_marker = False\n",
236
+ "marker_row = None\n",
237
+ "try:\n",
238
+ " with gzip.open(matrix_file, 'rt') as file:\n",
239
+ " for i, line in enumerate(file):\n",
240
+ " if \"!series_matrix_table_begin\" in line:\n",
241
+ " found_marker = True\n",
242
+ " marker_row = i\n",
243
+ " print(f\"Found the matrix table marker at line {i}\")\n",
244
+ " break\n",
245
+ " \n",
246
+ " if not found_marker:\n",
247
+ " print(\"Warning: Could not find '!series_matrix_table_begin' marker in the file.\")\n",
248
+ " is_gene_available = False\n",
249
+ " \n",
250
+ " # If marker was found, try to extract gene data\n",
251
+ " if is_gene_available:\n",
252
+ " try:\n",
253
+ " # Try using the library function\n",
254
+ " gene_data = get_genetic_data(matrix_file)\n",
255
+ " \n",
256
+ " if gene_data.shape[0] == 0:\n",
257
+ " print(\"Warning: Extracted gene data has 0 rows.\")\n",
258
+ " is_gene_available = False\n",
259
+ " else:\n",
260
+ " print(f\"Gene data shape: {gene_data.shape}\")\n",
261
+ " # Print the first 20 gene/probe identifiers\n",
262
+ " print(\"First 20 gene/probe identifiers:\")\n",
263
+ " print(gene_data.index[:20].tolist())\n",
264
+ " except Exception as e:\n",
265
+ " print(f\"Error extracting gene data with get_genetic_data(): {e}\")\n",
266
+ " is_gene_available = False\n",
267
+ " \n",
268
+ " # If gene data extraction failed, examine file content to diagnose\n",
269
+ " if not is_gene_available:\n",
270
+ " print(\"Examining file content to diagnose the issue:\")\n",
271
+ " try:\n",
272
+ " with gzip.open(matrix_file, 'rt') as file:\n",
273
+ " # Print lines around the marker if found\n",
274
+ " if marker_row is not None:\n",
275
+ " for i, line in enumerate(file):\n",
276
+ " if i >= marker_row - 2 and i <= marker_row + 10:\n",
277
+ " print(f\"Line {i}: {line.strip()[:100]}...\")\n",
278
+ " if i > marker_row + 10:\n",
279
+ " break\n",
280
+ " else:\n",
281
+ " # If marker not found, print first 10 lines\n",
282
+ " for i, line in enumerate(file):\n",
283
+ " if i < 10:\n",
284
+ " print(f\"Line {i}: {line.strip()[:100]}...\")\n",
285
+ " else:\n",
286
+ " break\n",
287
+ " except Exception as e2:\n",
288
+ " print(f\"Error examining file: {e2}\")\n",
289
+ " \n",
290
+ "except Exception as e:\n",
291
+ " print(f\"Error processing file: {e}\")\n",
292
+ " is_gene_available = False\n",
293
+ "\n",
294
+ "# Update validation information if gene data extraction failed\n",
295
+ "if not is_gene_available:\n",
296
+ " print(\"Gene expression data could not be successfully extracted from this dataset.\")\n",
297
+ " # Update the validation record since gene data isn't available\n",
298
+ " is_trait_available = False # We already determined trait data isn't available in step 2\n",
299
+ " validate_and_save_cohort_info(is_final=False, cohort=cohort, info_path=json_path,\n",
300
+ " is_gene_available=is_gene_available, is_trait_available=is_trait_available)\n"
301
+ ]
302
+ },
303
+ {
304
+ "cell_type": "markdown",
305
+ "id": "e6399076",
306
+ "metadata": {},
307
+ "source": [
308
+ "### Step 4: Gene Identifier Review"
309
+ ]
310
+ },
311
+ {
312
+ "cell_type": "code",
313
+ "execution_count": 5,
314
+ "id": "c3f4cf66",
315
+ "metadata": {
316
+ "execution": {
317
+ "iopub.execute_input": "2025-03-25T08:30:17.539166Z",
318
+ "iopub.status.busy": "2025-03-25T08:30:17.539060Z",
319
+ "iopub.status.idle": "2025-03-25T08:30:17.540809Z",
320
+ "shell.execute_reply": "2025-03-25T08:30:17.540516Z"
321
+ }
322
+ },
323
+ "outputs": [],
324
+ "source": [
325
+ "# Review the gene identifiers based on biomedical knowledge\n",
326
+ "# The identifiers appear to be standard human gene symbols (ACE, ACKR2, AKT1, etc.)\n",
327
+ "# These are official HGNC gene symbols and do not need to be mapped\n",
328
+ "\n",
329
+ "requires_gene_mapping = False\n"
330
+ ]
331
+ },
332
+ {
333
+ "cell_type": "markdown",
334
+ "id": "b167cfa2",
335
+ "metadata": {},
336
+ "source": [
337
+ "### Step 5: Data Normalization and Linking"
338
+ ]
339
+ },
340
+ {
341
+ "cell_type": "code",
342
+ "execution_count": 6,
343
+ "id": "8759dfa4",
344
+ "metadata": {
345
+ "execution": {
346
+ "iopub.execute_input": "2025-03-25T08:30:17.541818Z",
347
+ "iopub.status.busy": "2025-03-25T08:30:17.541714Z",
348
+ "iopub.status.idle": "2025-03-25T08:30:17.772820Z",
349
+ "shell.execute_reply": "2025-03-25T08:30:17.772451Z"
350
+ }
351
+ },
352
+ "outputs": [
353
+ {
354
+ "name": "stdout",
355
+ "output_type": "stream",
356
+ "text": [
357
+ "Gene data shape after normalization: (758, 304)\n"
358
+ ]
359
+ },
360
+ {
361
+ "name": "stdout",
362
+ "output_type": "stream",
363
+ "text": [
364
+ "Normalized gene data saved to ../../output/preprocess/COVID-19/gene_data/GSE211378.csv\n",
365
+ "Empty clinical features saved to ../../output/preprocess/COVID-19/clinical_data/GSE211378.csv\n",
366
+ "Abnormality detected in the cohort: GSE211378. Preprocessing failed.\n",
367
+ "Linked data not created or saved due to missing trait information.\n"
368
+ ]
369
+ }
370
+ ],
371
+ "source": [
372
+ "# 1. Normalize gene symbols in the gene expression data\n",
373
+ "normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n",
374
+ "print(f\"Gene data shape after normalization: {normalized_gene_data.shape}\")\n",
375
+ "\n",
376
+ "# Create output directory if it doesn't exist\n",
377
+ "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
378
+ "\n",
379
+ "# Save the normalized gene data\n",
380
+ "normalized_gene_data.to_csv(out_gene_data_file)\n",
381
+ "print(f\"Normalized gene data saved to {out_gene_data_file}\")\n",
382
+ "\n",
383
+ "# Create empty clinical data for record-keeping purposes\n",
384
+ "empty_clinical_df = pd.DataFrame()\n",
385
+ "\n",
386
+ "# Create directory for clinical data output\n",
387
+ "os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
388
+ "\n",
389
+ "# Save the empty clinical features\n",
390
+ "empty_clinical_df.to_csv(out_clinical_data_file)\n",
391
+ "print(f\"Empty clinical features saved to {out_clinical_data_file}\")\n",
392
+ "\n",
393
+ "# Since we don't have trait data, we can't perform:\n",
394
+ "# - linking with gene data\n",
395
+ "# - handling missing values\n",
396
+ "# - determining trait bias\n",
397
+ "# - creating usable linked data\n",
398
+ "\n",
399
+ "# For validation purposes, mark the dataset as unusable due to lack of trait data\n",
400
+ "is_trait_available = False # No trait data available as determined in Step 2\n",
401
+ "is_biased = True # Mark as biased (unusable) since we can't analyze trait-related bias\n",
402
+ "\n",
403
+ "# Validate and save cohort info - mark as unusable due to missing trait data\n",
404
+ "is_usable = validate_and_save_cohort_info(\n",
405
+ " is_final=True,\n",
406
+ " cohort=cohort,\n",
407
+ " info_path=json_path,\n",
408
+ " is_gene_available=is_gene_available,\n",
409
+ " is_trait_available=is_trait_available,\n",
410
+ " is_biased=is_biased,\n",
411
+ " df=empty_clinical_df, # Use empty DataFrame as placeholder\n",
412
+ " note=\"Dataset contains gene expression data but lacks necessary trait information for COVID-19 analysis.\"\n",
413
+ ")\n",
414
+ "\n",
415
+ "print(\"Linked data not created or saved due to missing trait information.\")"
416
+ ]
417
+ }
418
+ ],
419
+ "metadata": {
420
+ "language_info": {
421
+ "codemirror_mode": {
422
+ "name": "ipython",
423
+ "version": 3
424
+ },
425
+ "file_extension": ".py",
426
+ "mimetype": "text/x-python",
427
+ "name": "python",
428
+ "nbconvert_exporter": "python",
429
+ "pygments_lexer": "ipython3",
430
+ "version": "3.10.16"
431
+ }
432
+ },
433
+ "nbformat": 4,
434
+ "nbformat_minor": 5
435
+ }
code/COVID-19/GSE212865.ipynb ADDED
@@ -0,0 +1,769 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": 1,
6
+ "id": "3c385655",
7
+ "metadata": {
8
+ "execution": {
9
+ "iopub.execute_input": "2025-03-25T08:30:18.401837Z",
10
+ "iopub.status.busy": "2025-03-25T08:30:18.401668Z",
11
+ "iopub.status.idle": "2025-03-25T08:30:18.568477Z",
12
+ "shell.execute_reply": "2025-03-25T08:30:18.568112Z"
13
+ }
14
+ },
15
+ "outputs": [],
16
+ "source": [
17
+ "import sys\n",
18
+ "import os\n",
19
+ "sys.path.append(os.path.abspath(os.path.join(os.getcwd(), '../..')))\n",
20
+ "\n",
21
+ "# Path Configuration\n",
22
+ "from tools.preprocess import *\n",
23
+ "\n",
24
+ "# Processing context\n",
25
+ "trait = \"COVID-19\"\n",
26
+ "cohort = \"GSE212865\"\n",
27
+ "\n",
28
+ "# Input paths\n",
29
+ "in_trait_dir = \"../../input/GEO/COVID-19\"\n",
30
+ "in_cohort_dir = \"../../input/GEO/COVID-19/GSE212865\"\n",
31
+ "\n",
32
+ "# Output paths\n",
33
+ "out_data_file = \"../../output/preprocess/COVID-19/GSE212865.csv\"\n",
34
+ "out_gene_data_file = \"../../output/preprocess/COVID-19/gene_data/GSE212865.csv\"\n",
35
+ "out_clinical_data_file = \"../../output/preprocess/COVID-19/clinical_data/GSE212865.csv\"\n",
36
+ "json_path = \"../../output/preprocess/COVID-19/cohort_info.json\"\n"
37
+ ]
38
+ },
39
+ {
40
+ "cell_type": "markdown",
41
+ "id": "32355eec",
42
+ "metadata": {},
43
+ "source": [
44
+ "### Step 1: Initial Data Loading"
45
+ ]
46
+ },
47
+ {
48
+ "cell_type": "code",
49
+ "execution_count": 2,
50
+ "id": "8703fb35",
51
+ "metadata": {
52
+ "execution": {
53
+ "iopub.execute_input": "2025-03-25T08:30:18.569978Z",
54
+ "iopub.status.busy": "2025-03-25T08:30:18.569823Z",
55
+ "iopub.status.idle": "2025-03-25T08:30:18.872908Z",
56
+ "shell.execute_reply": "2025-03-25T08:30:18.872404Z"
57
+ }
58
+ },
59
+ "outputs": [
60
+ {
61
+ "name": "stdout",
62
+ "output_type": "stream",
63
+ "text": [
64
+ "Background Information:\n",
65
+ "!Series_title\t\"Dynamics of gene expression profiling by microarrays and identification of high-risk patients for severe COVID-19 [Array]\"\n",
66
+ "!Series_summary\t\"The clinical manifestations of SARS-Co-2 infection vary widely, from asymptomatic infection to the development of acute respiratory distress syndrome (ARDS) and death. The host response elicited by SARS-CoV-2 plays a key role in determining the clinical outcome. We hypothesized that determining the dynamic whole blood transcriptomic profile of adult patients hospitalized for COVID-19 and characterizing the subgroup that develops severe disease and ARDS would broaden our understanding of the heterogeneity in clinical outcomes. We recruited 60 hospitalized patients with microbiology-confirmed COVID-19, among whom 19 developed ARDS. Peripheral blood was collected using PAXGene RNA tubes within 24 hours of admission and at day 7. There were 2150 differently expressed genes in patients with ARDS at baseline, and 1963 at day 7. We found a dysregulated inflammatory response in COVID-19 ARDS patients, with an increased expression of genes related to pro-inflammatory molecules and neutrophil and macrophage activation at admission, in addition to the loss of immune regulation. This led in turn to a higher expression of genes related to reactive oxygen species, protein polyubiquitination, and metalloproteinases in latter stages. Some of the most significant differences in gene expression found between patients with and without ARDS corresponded to long non-coding RNA involved in epigenetic control.\"\n",
67
+ "!Series_overall_design\t\"137 samples were analyzed (Control=51, Covid19=52, Covid19_SDRA=34)\"\n",
68
+ "Sample Characteristics Dictionary:\n",
69
+ "{0: ['disease state: Control', 'disease state: Covid19', 'disease state: Covid19_SDRA'], 1: ['time: NA', 'time: D0', 'time: D7'], 2: ['tissue: peripheral blood']}\n"
70
+ ]
71
+ }
72
+ ],
73
+ "source": [
74
+ "from tools.preprocess import *\n",
75
+ "# 1. Identify the paths to the SOFT file and the matrix file\n",
76
+ "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
77
+ "\n",
78
+ "# 2. Read the matrix file to obtain background information and sample characteristics data\n",
79
+ "background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']\n",
80
+ "clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']\n",
81
+ "background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)\n",
82
+ "\n",
83
+ "# 3. Obtain the sample characteristics dictionary from the clinical dataframe\n",
84
+ "sample_characteristics_dict = get_unique_values_by_row(clinical_data)\n",
85
+ "\n",
86
+ "# 4. Explicitly print out all the background information and the sample characteristics dictionary\n",
87
+ "print(\"Background Information:\")\n",
88
+ "print(background_info)\n",
89
+ "print(\"Sample Characteristics Dictionary:\")\n",
90
+ "print(sample_characteristics_dict)\n"
91
+ ]
92
+ },
93
+ {
94
+ "cell_type": "markdown",
95
+ "id": "43fa5375",
96
+ "metadata": {},
97
+ "source": [
98
+ "### Step 2: Dataset Analysis and Clinical Feature Extraction"
99
+ ]
100
+ },
101
+ {
102
+ "cell_type": "code",
103
+ "execution_count": 3,
104
+ "id": "3c52f41e",
105
+ "metadata": {
106
+ "execution": {
107
+ "iopub.execute_input": "2025-03-25T08:30:18.874339Z",
108
+ "iopub.status.busy": "2025-03-25T08:30:18.874226Z",
109
+ "iopub.status.idle": "2025-03-25T08:30:18.878528Z",
110
+ "shell.execute_reply": "2025-03-25T08:30:18.878140Z"
111
+ }
112
+ },
113
+ "outputs": [
114
+ {
115
+ "name": "stdout",
116
+ "output_type": "stream",
117
+ "text": [
118
+ "Clinical data extraction skipped as the clinical_data.csv file isn't available\n",
119
+ "However, trait information is conceptually available in the dataset\n"
120
+ ]
121
+ }
122
+ ],
123
+ "source": [
124
+ "# 1. Gene Expression Data Availability\n",
125
+ "# The dataset contains microarray data as mentioned in the title with \"gene expression profiling by microarrays\"\n",
126
+ "is_gene_available = True\n",
127
+ "\n",
128
+ "# 2.1 Data Availability\n",
129
+ "# From the Sample Characteristics Dictionary, we can identify:\n",
130
+ "# Key 0 contains disease state: Control, Covid19, Covid19_SDRA\n",
131
+ "# This relates to our COVID-19 trait (severity of COVID-19)\n",
132
+ "trait_row = 0\n",
133
+ "\n",
134
+ "# There is no age information in the sample characteristics\n",
135
+ "age_row = None\n",
136
+ "\n",
137
+ "# There is no gender information in the sample characteristics\n",
138
+ "gender_row = None\n",
139
+ "\n",
140
+ "# 2.2 Data Type Conversion\n",
141
+ "def convert_trait(value):\n",
142
+ " \"\"\"Convert disease state to binary trait (1 for COVID-19 ARDS, 0 for COVID-19 without ARDS)\"\"\"\n",
143
+ " if not isinstance(value, str):\n",
144
+ " return None\n",
145
+ " \n",
146
+ " value = value.strip().lower()\n",
147
+ " if \":\" in value:\n",
148
+ " value = value.split(\":\", 1)[1].strip().lower()\n",
149
+ " \n",
150
+ " if \"covid19_sdra\" in value or (\"covid19\" in value and \"sdra\" in value):\n",
151
+ " return 1 # Severe COVID-19 with ARDS\n",
152
+ " elif \"covid19\" in value and \"sdra\" not in value:\n",
153
+ " return 0 # COVID-19 without ARDS\n",
154
+ " else:\n",
155
+ " return None # Control or unrelated\n",
156
+ "\n",
157
+ "def convert_age(value):\n",
158
+ " \"\"\"Placeholder function for age conversion - not used as age data is unavailable\"\"\"\n",
159
+ " return None\n",
160
+ "\n",
161
+ "def convert_gender(value):\n",
162
+ " \"\"\"Placeholder function for gender conversion - not used as gender data is unavailable\"\"\"\n",
163
+ " return None\n",
164
+ "\n",
165
+ "# 3. Save Metadata\n",
166
+ "# Determine trait data availability\n",
167
+ "is_trait_available = trait_row is not None\n",
168
+ "\n",
169
+ "# Validate and save cohort info\n",
170
+ "validate_and_save_cohort_info(\n",
171
+ " is_final=False,\n",
172
+ " cohort=cohort,\n",
173
+ " info_path=json_path,\n",
174
+ " is_gene_available=is_gene_available,\n",
175
+ " is_trait_available=is_trait_available\n",
176
+ ")\n",
177
+ "\n",
178
+ "# 4. Clinical Feature Extraction\n",
179
+ "# While trait information is conceptually available (trait_row is not None),\n",
180
+ "# we're unable to process it due to missing the actual clinical data file\n",
181
+ "# The sample characteristics dictionary only shows unique values across samples\n",
182
+ "# and doesn't represent the full clinical data for each sample\n",
183
+ "\n",
184
+ "print(\"Clinical data extraction skipped as the clinical_data.csv file isn't available\")\n",
185
+ "print(\"However, trait information is conceptually available in the dataset\")\n"
186
+ ]
187
+ },
188
+ {
189
+ "cell_type": "markdown",
190
+ "id": "360168e6",
191
+ "metadata": {},
192
+ "source": [
193
+ "### Step 3: Gene Data Extraction"
194
+ ]
195
+ },
196
+ {
197
+ "cell_type": "code",
198
+ "execution_count": 4,
199
+ "id": "e59f0309",
200
+ "metadata": {
201
+ "execution": {
202
+ "iopub.execute_input": "2025-03-25T08:30:18.879850Z",
203
+ "iopub.status.busy": "2025-03-25T08:30:18.879747Z",
204
+ "iopub.status.idle": "2025-03-25T08:30:19.389783Z",
205
+ "shell.execute_reply": "2025-03-25T08:30:19.389332Z"
206
+ }
207
+ },
208
+ "outputs": [
209
+ {
210
+ "name": "stdout",
211
+ "output_type": "stream",
212
+ "text": [
213
+ "SOFT file: ../../input/GEO/COVID-19/GSE212865/GSE212865_family.soft.gz\n",
214
+ "Matrix file: ../../input/GEO/COVID-19/GSE212865/GSE212865_series_matrix.txt.gz\n",
215
+ "Found the matrix table marker at line 58\n"
216
+ ]
217
+ },
218
+ {
219
+ "name": "stdout",
220
+ "output_type": "stream",
221
+ "text": [
222
+ "Gene data shape: (27189, 137)\n",
223
+ "First 20 gene/probe identifiers:\n",
224
+ "['23064070', '23064071', '23064072', '23064073', '23064074', '23064075', '23064076', '23064077', '23064078', '23064079', '23064080', '23064081', '23064083', '23064084', '23064085', '23064086', '23064087', '23064088', '23064089', '23064090']\n"
225
+ ]
226
+ }
227
+ ],
228
+ "source": [
229
+ "# 1. Identify the paths to the SOFT file and the matrix file\n",
230
+ "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
231
+ "print(f\"SOFT file: {soft_file}\")\n",
232
+ "print(f\"Matrix file: {matrix_file}\")\n",
233
+ "\n",
234
+ "# Set gene availability flag\n",
235
+ "is_gene_available = True # Initially assume gene data is available\n",
236
+ "\n",
237
+ "# First check if the matrix file contains the expected marker\n",
238
+ "found_marker = False\n",
239
+ "marker_row = None\n",
240
+ "try:\n",
241
+ " with gzip.open(matrix_file, 'rt') as file:\n",
242
+ " for i, line in enumerate(file):\n",
243
+ " if \"!series_matrix_table_begin\" in line:\n",
244
+ " found_marker = True\n",
245
+ " marker_row = i\n",
246
+ " print(f\"Found the matrix table marker at line {i}\")\n",
247
+ " break\n",
248
+ " \n",
249
+ " if not found_marker:\n",
250
+ " print(\"Warning: Could not find '!series_matrix_table_begin' marker in the file.\")\n",
251
+ " is_gene_available = False\n",
252
+ " \n",
253
+ " # If marker was found, try to extract gene data\n",
254
+ " if is_gene_available:\n",
255
+ " try:\n",
256
+ " # Try using the library function\n",
257
+ " gene_data = get_genetic_data(matrix_file)\n",
258
+ " \n",
259
+ " if gene_data.shape[0] == 0:\n",
260
+ " print(\"Warning: Extracted gene data has 0 rows.\")\n",
261
+ " is_gene_available = False\n",
262
+ " else:\n",
263
+ " print(f\"Gene data shape: {gene_data.shape}\")\n",
264
+ " # Print the first 20 gene/probe identifiers\n",
265
+ " print(\"First 20 gene/probe identifiers:\")\n",
266
+ " print(gene_data.index[:20].tolist())\n",
267
+ " except Exception as e:\n",
268
+ " print(f\"Error extracting gene data with get_genetic_data(): {e}\")\n",
269
+ " is_gene_available = False\n",
270
+ " \n",
271
+ " # If gene data extraction failed, examine file content to diagnose\n",
272
+ " if not is_gene_available:\n",
273
+ " print(\"Examining file content to diagnose the issue:\")\n",
274
+ " try:\n",
275
+ " with gzip.open(matrix_file, 'rt') as file:\n",
276
+ " # Print lines around the marker if found\n",
277
+ " if marker_row is not None:\n",
278
+ " for i, line in enumerate(file):\n",
279
+ " if i >= marker_row - 2 and i <= marker_row + 10:\n",
280
+ " print(f\"Line {i}: {line.strip()[:100]}...\")\n",
281
+ " if i > marker_row + 10:\n",
282
+ " break\n",
283
+ " else:\n",
284
+ " # If marker not found, print first 10 lines\n",
285
+ " for i, line in enumerate(file):\n",
286
+ " if i < 10:\n",
287
+ " print(f\"Line {i}: {line.strip()[:100]}...\")\n",
288
+ " else:\n",
289
+ " break\n",
290
+ " except Exception as e2:\n",
291
+ " print(f\"Error examining file: {e2}\")\n",
292
+ " \n",
293
+ "except Exception as e:\n",
294
+ " print(f\"Error processing file: {e}\")\n",
295
+ " is_gene_available = False\n",
296
+ "\n",
297
+ "# Update validation information if gene data extraction failed\n",
298
+ "if not is_gene_available:\n",
299
+ " print(\"Gene expression data could not be successfully extracted from this dataset.\")\n",
300
+ " # Update the validation record since gene data isn't available\n",
301
+ " is_trait_available = False # We already determined trait data isn't available in step 2\n",
302
+ " validate_and_save_cohort_info(is_final=False, cohort=cohort, info_path=json_path,\n",
303
+ " is_gene_available=is_gene_available, is_trait_available=is_trait_available)\n"
304
+ ]
305
+ },
306
+ {
307
+ "cell_type": "markdown",
308
+ "id": "268c0110",
309
+ "metadata": {},
310
+ "source": [
311
+ "### Step 4: Gene Identifier Review"
312
+ ]
313
+ },
314
+ {
315
+ "cell_type": "code",
316
+ "execution_count": 5,
317
+ "id": "f241825c",
318
+ "metadata": {
319
+ "execution": {
320
+ "iopub.execute_input": "2025-03-25T08:30:19.391132Z",
321
+ "iopub.status.busy": "2025-03-25T08:30:19.391013Z",
322
+ "iopub.status.idle": "2025-03-25T08:30:19.393400Z",
323
+ "shell.execute_reply": "2025-03-25T08:30:19.392970Z"
324
+ }
325
+ },
326
+ "outputs": [],
327
+ "source": [
328
+ "# The gene identifiers in the data are numerical IDs (23064070, 23064071, etc.)\n",
329
+ "# These are not standard human gene symbols like BRCA1, TP53, etc.\n",
330
+ "# These appear to be probe IDs or feature IDs from a microarray or sequencing platform\n",
331
+ "# that need to be mapped to actual gene symbols for biological interpretation\n",
332
+ "\n",
333
+ "requires_gene_mapping = True\n"
334
+ ]
335
+ },
336
+ {
337
+ "cell_type": "markdown",
338
+ "id": "ee225cbc",
339
+ "metadata": {},
340
+ "source": [
341
+ "### Step 5: Gene Annotation"
342
+ ]
343
+ },
344
+ {
345
+ "cell_type": "code",
346
+ "execution_count": 6,
347
+ "id": "93d5181c",
348
+ "metadata": {
349
+ "execution": {
350
+ "iopub.execute_input": "2025-03-25T08:30:19.394889Z",
351
+ "iopub.status.busy": "2025-03-25T08:30:19.394785Z",
352
+ "iopub.status.idle": "2025-03-25T08:30:26.290652Z",
353
+ "shell.execute_reply": "2025-03-25T08:30:26.290024Z"
354
+ }
355
+ },
356
+ "outputs": [
357
+ {
358
+ "name": "stdout",
359
+ "output_type": "stream",
360
+ "text": [
361
+ "\n",
362
+ "Gene annotation preview:\n",
363
+ "Columns in gene annotation: ['ID', 'probeset_id', 'seqname', 'strand', 'start', 'stop', 'total_probes', 'category', 'SPOT_ID', 'SPOT_ID.1']\n",
364
+ "{'ID': ['TC0100006437.hg.1', 'TC0100006476.hg.1', 'TC0100006479.hg.1'], 'probeset_id': ['TC0100006437.hg.1', 'TC0100006476.hg.1', 'TC0100006479.hg.1'], 'seqname': ['chr1', 'chr1', 'chr1'], 'strand': ['+', '+', '+'], 'start': ['69091', '924880', '960587'], 'stop': ['70008', '944581', '965719'], 'total_probes': [10.0, 10.0, 10.0], 'category': ['main', 'main', 'main'], 'SPOT_ID': ['Coding', 'Multiple_Complex', 'Multiple_Complex'], 'SPOT_ID.1': ['NM_001005484 // RefSeq // Homo sapiens olfactory receptor, family 4, subfamily F, member 5 (OR4F5), mRNA. // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000335137 // ENSEMBL // olfactory receptor, family 4, subfamily F, member 5 [gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// OTTHUMT00000003223 // Havana transcript // olfactory receptor, family 4, subfamily F, member 5[gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// uc001aal.1 // UCSC Genes // Homo sapiens olfactory receptor, family 4, subfamily F, member 5 (OR4F5), mRNA. // chr1 // 100 // 100 // 0 // --- // 0 /// CCDS30547.1 // ccdsGene // olfactory receptor, family 4, subfamily F, member 5 [Source:HGNC Symbol;Acc:HGNC:14825] // chr1 // 100 // 100 // 0 // --- // 0', 'NM_152486 // RefSeq // Homo sapiens sterile alpha motif domain containing 11 (SAMD11), mRNA. // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000341065 // ENSEMBL // sterile alpha motif domain containing 11 [gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000342066 // ENSEMBL // sterile alpha motif domain containing 11 [gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000420190 // ENSEMBL // sterile alpha motif domain containing 11 [gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000437963 // ENSEMBL // sterile alpha motif domain containing 11 [gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000455979 // ENSEMBL // sterile alpha motif domain containing 11 [gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000464948 // ENSEMBL // sterile alpha motif domain containing 11 [gene_biotype:protein_coding transcript_biotype:retained_intron] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000466827 // ENSEMBL // sterile alpha motif domain containing 11 [gene_biotype:protein_coding transcript_biotype:retained_intron] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000474461 // ENSEMBL // sterile alpha motif domain containing 11 [gene_biotype:protein_coding transcript_biotype:retained_intron] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000478729 // ENSEMBL // sterile alpha motif domain containing 11 [gene_biotype:protein_coding transcript_biotype:processed_transcript] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000616016 // ENSEMBL // sterile alpha motif domain containing 11 [gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000616125 // ENSEMBL // sterile alpha motif domain containing 11 [gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000617307 // ENSEMBL // sterile alpha motif domain containing 11 [gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000618181 // ENSEMBL // sterile alpha motif domain containing 11 [gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000618323 // ENSEMBL // sterile alpha motif domain containing 11 [gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000618779 // ENSEMBL // sterile alpha motif domain containing 11 [gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000620200 // ENSEMBL // sterile alpha motif domain containing 11 [gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000622503 // ENSEMBL // sterile alpha motif domain containing 11 [gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// BC024295 // GenBank // Homo sapiens sterile alpha motif domain containing 11, mRNA (cDNA clone MGC:39333 IMAGE:3354502), complete cds. // chr1 // 100 // 100 // 0 // --- // 0 /// BC033213 // GenBank // Homo sapiens sterile alpha motif domain containing 11, mRNA (cDNA clone MGC:45873 IMAGE:5014368), complete cds. // chr1 // 100 // 100 // 0 // --- // 0 /// OTTHUMT00000097860 // Havana transcript // sterile alpha motif domain containing 11[gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// OTTHUMT00000097862 // Havana transcript // sterile alpha motif domain containing 11[gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// OTTHUMT00000097863 // Havana transcript // sterile alpha motif domain containing 11[gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// OTTHUMT00000097865 // Havana transcript // sterile alpha motif domain containing 11[gene_biotype:protein_coding transcript_biotype:processed_transcript] // chr1 // 100 // 100 // 0 // --- // 0 /// OTTHUMT00000097866 // Havana transcript // sterile alpha motif domain containing 11[gene_biotype:protein_coding transcript_biotype:retained_intron] // chr1 // 100 // 100 // 0 // --- // 0 /// OTTHUMT00000097867 // Havana transcript // sterile alpha motif domain containing 11[gene_biotype:protein_coding transcript_biotype:retained_intron] // chr1 // 100 // 100 // 0 // --- // 0 /// OTTHUMT00000097868 // Havana transcript // sterile alpha motif domain containing 11[gene_biotype:protein_coding transcript_biotype:retained_intron] // chr1 // 100 // 100 // 0 // --- // 0 /// OTTHUMT00000276866 // Havana transcript // sterile alpha motif domain containing 11[gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// OTTHUMT00000316521 // Havana transcript // sterile alpha motif domain containing 11[gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// CCDS2.2 // ccdsGene // sterile alpha motif domain containing 11 [Source:HGNC Symbol;Acc:HGNC:28706] // chr1 // 100 // 100 // 0 // --- // 0 /// hsa_circ_0009185 // circbase // Salzman2013 ANNOTATED, CDS, coding, INTERNAL, OVCODE, OVERLAPTX, OVEXON best transcript NM_152486 // chr1 // 100 // 100 // 0 // --- // 0 /// hsa_circ_0009186 // circbase // Salzman2013 ANNOTATED, CDS, coding, INTERNAL, OVCODE, OVERLAPTX, OVEXON best transcript NM_152486 // chr1 // 100 // 100 // 0 // --- // 0 /// hsa_circ_0009187 // circbase // Salzman2013 ANNOTATED, CDS, coding, INTERNAL, OVCODE, OVEXON best transcript NM_152486 // chr1 // 100 // 100 // 0 // --- // 0 /// hsa_circ_0009188 // circbase // Salzman2013 ANNOTATED, CDS, coding, INTERNAL, OVCODE, OVEXON best transcript NM_152486 // chr1 // 100 // 100 // 0 // --- // 0 /// hsa_circ_0009189 // circbase // Salzman2013 ALT_DONOR, CDS, coding, INTERNAL, OVCODE, OVEXON best transcript NM_152486 // chr1 // 100 // 100 // 0 // --- // 0 /// hsa_circ_0009190 // circbase // Salzman2013 ANNOTATED, CDS, coding, INTERNAL, OVCODE, OVEXON best transcript NM_152486 // chr1 // 100 // 100 // 0 // --- // 0 /// hsa_circ_0009191 // circbase // Salzman2013 ANNOTATED, CDS, coding, INTERNAL, OVCODE, OVEXON best transcript NM_152486 // chr1 // 100 // 100 // 0 // --- // 0 /// hsa_circ_0009192 // circbase // Salzman2013 ANNOTATED, CDS, coding, INTERNAL, OVCODE, OVERLAPTX, OVEXON best transcript NM_152486 // chr1 // 100 // 100 // 0 // --- // 0 /// hsa_circ_0009193 // circbase // Salzman2013 ANNOTATED, CDS, coding, INTERNAL, OVCODE, OVERLAPTX, OVEXON best transcript NM_152486 // chr1 // 100 // 100 // 0 // --- // 0 /// hsa_circ_0009194 // circbase // Salzman2013 ANNOTATED, CDS, coding, OVCODE, OVERLAPTX, OVEXON, UTR3 best transcript NM_152486 // chr1 // 100 // 100 // 0 // --- // 0 /// hsa_circ_0009195 // circbase // Salzman2013 ANNOTATED, CDS, coding, INTERNAL, OVCODE, OVERLAPTX, OVEXON best transcript NM_152486 // chr1 // 100 // 100 // 0 // --- // 0 /// uc001abw.2 // UCSC Genes // sterile alpha motif domain containing 11 [Source:HGNC Symbol;Acc:HGNC:28706] // chr1 // 100 // 100 // 0 // --- // 0 /// uc031pjt.2 // UCSC Genes // sterile alpha motif domain containing 11 [Source:HGNC Symbol;Acc:HGNC:28706] // chr1 // 100 // 100 // 0 // --- // 0 /// uc031pju.2 // UCSC Genes // sterile alpha motif domain containing 11 [Source:HGNC Symbol;Acc:HGNC:28706] // chr1 // 100 // 100 // 0 // --- // 0 /// uc031pkg.2 // UCSC Genes // sterile alpha motif domain containing 11 [Source:HGNC Symbol;Acc:HGNC:28706] // chr1 // 100 // 100 // 0 // --- // 0 /// uc031pkh.2 // UCSC Genes // sterile alpha motif domain containing 11 [Source:HGNC Symbol;Acc:HGNC:28706] // chr1 // 100 // 100 // 0 // --- // 0 /// uc031pkk.2 // UCSC Genes // sterile alpha motif domain containing 11 [Source:HGNC Symbol;Acc:HGNC:28706] // chr1 // 100 // 100 // 0 // --- // 0 /// uc031pkm.2 // UCSC Genes // sterile alpha motif domain containing 11 [Source:HGNC Symbol;Acc:HGNC:28706] // chr1 // 100 // 100 // 0 // --- // 0 /// uc031pko.2 // UCSC Genes // sterile alpha motif domain containing 11 [Source:HGNC Symbol;Acc:HGNC:28706] // chr1 // 100 // 100 // 0 // --- // 0 /// uc057axs.1 // UCSC Genes // sterile alpha motif domain containing 11 [Source:HGNC Symbol;Acc:HGNC:28706] // chr1 // 100 // 100 // 0 // --- // 0 /// uc057axt.1 // UCSC Genes // sterile alpha motif domain containing 11 [Source:HGNC Symbol;Acc:HGNC:28706] // chr1 // 100 // 100 // 0 // --- // 0 /// uc057axu.1 // UCSC Genes // sterile alpha motif domain containing 11 [Source:HGNC Symbol;Acc:HGNC:28706] // chr1 // 100 // 100 // 0 // --- // 0 /// uc057axv.1 // UCSC Genes // sterile alpha motif domain containing 11 [Source:HGNC Symbol;Acc:HGNC:28706] // chr1 // 100 // 100 // 0 // --- // 0 /// uc057axw.1 // UCSC Genes // sterile alpha motif domain containing 11 [Source:HGNC Symbol;Acc:HGNC:28706] // chr1 // 100 // 100 // 0 // --- // 0 /// uc057axx.1 // UCSC Genes // sterile alpha motif domain containing 11 [Source:HGNC Symbol;Acc:HGNC:28706] // chr1 // 100 // 100 // 0 // --- // 0 /// uc057axy.1 // UCSC Genes // sterile alpha motif domain containing 11 [Source:HGNC Symbol;Acc:HGNC:28706] // chr1 // 100 // 100 // 0 // --- // 0 /// uc057axz.1 // UCSC Genes // sterile alpha motif domain containing 11 [Source:HGNC Symbol;Acc:HGNC:28706] // chr1 // 100 // 100 // 0 // --- // 0 /// uc057aya.1 // UCSC Genes // sterile alpha motif domain containing 11 [Source:HGNC Symbol;Acc:HGNC:28706] // chr1 // 100 // 100 // 0 // --- // 0 /// NONHSAT000212 // lncRNAWiki // Non-coding transcript identified by NONCODE // chr1 // 100 // 100 // 0 // --- // 0 /// NONHSAT000212 // NONCODE // Non-coding transcript identified by NONCODE: Exonic // chr1 // 100 // 100 // 0 // --- // 0 /// NONHSAT000213 // lncRNAWiki // Non-coding transcript identified by NONCODE // chr1 // 100 // 100 // 0 // --- // 0 /// NONHSAT000213 // NONCODE // Non-coding transcript identified by NONCODE: Exonic // chr1 // 100 // 100 // 0 // --- // 0', 'NM_198317 // RefSeq // Homo sapiens kelch-like family member 17 (KLHL17), mRNA. // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000338591 // ENSEMBL // kelch-like family member 17 [gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000463212 // ENSEMBL // kelch-like family member 17 [gene_biotype:protein_coding transcript_biotype:retained_intron] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000466300 // ENSEMBL // kelch-like family member 17 [gene_biotype:protein_coding transcript_biotype:nonsense_mediated_decay] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000481067 // ENSEMBL // kelch-like family member 17 [gene_biotype:protein_coding transcript_biotype:retained_intron] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000622660 // ENSEMBL // kelch-like family member 17 [gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// OTTHUMT00000097875 // Havana transcript // kelch-like 17 (Drosophila)[gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// OTTHUMT00000097877 // Havana transcript // kelch-like 17 (Drosophila)[gene_biotype:protein_coding transcript_biotype:retained_intron] // chr1 // 100 // 100 // 0 // --- // 0 /// OTTHUMT00000097878 // Havana transcript // kelch-like 17 (Drosophila)[gene_biotype:protein_coding transcript_biotype:nonsense_mediated_decay] // chr1 // 100 // 100 // 0 // --- // 0 /// OTTHUMT00000097931 // Havana transcript // kelch-like 17 (Drosophila)[gene_biotype:protein_coding transcript_biotype:retained_intron] // chr1 // 100 // 100 // 0 // --- // 0 /// BC166618 // GenBank // Synthetic construct Homo sapiens clone IMAGE:100066344, MGC:195481 kelch-like 17 (Drosophila) (KLHL17) mRNA, encodes complete protein. // chr1 // 100 // 100 // 0 // --- // 0 /// CCDS30550.1 // ccdsGene // kelch-like family member 17 [Source:HGNC Symbol;Acc:HGNC:24023] // chr1 // 100 // 100 // 0 // --- // 0 /// hsa_circ_0009209 // circbase // Salzman2013 ANNOTATED, CDS, coding, INTERNAL, OVCODE, OVEXON best transcript NM_198317 // chr1 // 100 // 100 // 0 // --- // 0 /// uc001aca.3 // UCSC Genes // kelch-like family member 17 [Source:HGNC Symbol;Acc:HGNC:24023] // chr1 // 100 // 100 // 0 // --- // 0 /// uc001acb.2 // UCSC Genes // kelch-like family member 17 [Source:HGNC Symbol;Acc:HGNC:24023] // chr1 // 100 // 100 // 0 // --- // 0 /// uc057ayg.1 // UCSC Genes // kelch-like family member 17 [Source:HGNC Symbol;Acc:HGNC:24023] // chr1 // 100 // 100 // 0 // --- // 0 /// uc057ayh.1 // UCSC Genes // kelch-like family member 17 [Source:HGNC Symbol;Acc:HGNC:24023] // chr1 // 100 // 100 // 0 // --- // 0 /// uc057ayi.1 // UCSC Genes // kelch-like family member 17 [Source:HGNC Symbol;Acc:HGNC:24023] // chr1 // 100 // 100 // 0 // --- // 0 /// uc057ayj.1 // UCSC Genes // N/A // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000617073 // ENSEMBL // ncrna:novel chromosome:GRCh38:1:965110:965166:1 gene:ENSG00000277294 gene_biotype:miRNA transcript_biotype:miRNA // chr1 // 100 // 100 // 0 // --- // 0 /// NONHSAT000216 // lncRNAWiki // Non-coding transcript identified by NONCODE // chr1 // 100 // 100 // 0 // --- // 0 /// NONHSAT000216 // NONCODE // Non-coding transcript identified by NONCODE: Exonic // chr1 // 100 // 100 // 0 // --- // 0']}\n",
365
+ "\n",
366
+ "Examining gene mapping columns:\n",
367
+ "Column 'ID' examples:\n",
368
+ "Example 1: TC0100006437.hg.1\n",
369
+ "Example 2: TC0100006476.hg.1\n",
370
+ "Example 3: TC0100006479.hg.1\n",
371
+ "Example 4: TC0100006480.hg.1\n",
372
+ "Example 5: TC0100006483.hg.1\n",
373
+ "\n",
374
+ "Column 'SPOT_ID.1' examples (contains gene symbols):\n",
375
+ "Example 1: NM_001005484 // RefSeq // Homo sapiens olfactory receptor, family 4, subfamily F, member 5 (OR4F5), mRNA. // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000335137 // ENSEMBL // olfactory receptor, f...\n",
376
+ "Example 2: NM_152486 // RefSeq // Homo sapiens sterile alpha motif domain containing 11 (SAMD11), mRNA. // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000341065 // ENSEMBL // sterile alpha motif domain contain...\n",
377
+ "Example 3: NM_198317 // RefSeq // Homo sapiens kelch-like family member 17 (KLHL17), mRNA. // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000338591 // ENSEMBL // kelch-like family member 17 [gene_biotype:prote...\n",
378
+ "\n",
379
+ "Extracted gene symbols from SPOT_ID.1:\n",
380
+ "Example 1 extracted symbols: ['OR4F5', 'ENSEMBL', 'UCSC', 'CCDS30547', 'HGNC']\n",
381
+ "Example 2 extracted symbols: ['SAMD11', 'ENSEMBL', 'BC024295', 'MGC', 'IMAGE', 'BC033213', 'CCDS2', 'HGNC', 'ANNOTATED', 'CDS', 'INTERNAL', 'OVCODE', 'OVERLAPTX', 'OVEXON', 'UTR3', 'UCSC', 'NONCODE']\n",
382
+ "Example 3 extracted symbols: ['KLHL17', 'ENSEMBL', 'BC166618', 'IMAGE', 'MGC', 'CCDS30550', 'HGNC', 'ANNOTATED', 'CDS', 'INTERNAL', 'OVCODE', 'OVEXON', 'UCSC', 'NONCODE']\n",
383
+ "\n",
384
+ "Columns identified for gene mapping:\n",
385
+ "- 'ID': Contains probe IDs\n",
386
+ "- 'SPOT_ID.1': Contains gene information from which symbols can be extracted\n"
387
+ ]
388
+ }
389
+ ],
390
+ "source": [
391
+ "# 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.\n",
392
+ "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
393
+ "gene_annotation = get_gene_annotation(soft_file)\n",
394
+ "\n",
395
+ "# 2. Analyze the gene annotation dataframe to identify which columns contain the gene identifiers and gene symbols\n",
396
+ "print(\"\\nGene annotation preview:\")\n",
397
+ "print(f\"Columns in gene annotation: {gene_annotation.columns.tolist()}\")\n",
398
+ "print(preview_df(gene_annotation, n=3))\n",
399
+ "\n",
400
+ "# Examine the columns to find gene information\n",
401
+ "print(\"\\nExamining gene mapping columns:\")\n",
402
+ "print(\"Column 'ID' examples:\")\n",
403
+ "id_samples = gene_annotation['ID'].head(5).tolist()\n",
404
+ "for i, sample in enumerate(id_samples):\n",
405
+ " print(f\"Example {i+1}: {sample}\")\n",
406
+ "\n",
407
+ "# Look at SPOT_ID.1 column which contains gene information embedded in text\n",
408
+ "print(\"\\nColumn 'SPOT_ID.1' examples (contains gene symbols):\")\n",
409
+ "if 'SPOT_ID.1' in gene_annotation.columns:\n",
410
+ " # Display a few examples of the SPOT_ID.1 column\n",
411
+ " spot_samples = gene_annotation['SPOT_ID.1'].head(3).tolist()\n",
412
+ " for i, sample in enumerate(spot_samples):\n",
413
+ " print(f\"Example {i+1}: {sample[:200]}...\") # Show first 200 chars\n",
414
+ " \n",
415
+ " # Extract some gene symbols to verify\n",
416
+ " print(\"\\nExtracted gene symbols from SPOT_ID.1:\")\n",
417
+ " for i, sample in enumerate(spot_samples[:3]):\n",
418
+ " symbols = extract_human_gene_symbols(sample)\n",
419
+ " print(f\"Example {i+1} extracted symbols: {symbols}\")\n",
420
+ " \n",
421
+ " # Identify the columns needed for gene mapping\n",
422
+ " print(\"\\nColumns identified for gene mapping:\")\n",
423
+ " print(\"- 'ID': Contains probe IDs\")\n",
424
+ " print(\"- 'SPOT_ID.1': Contains gene information from which symbols can be extracted\")\n",
425
+ "else:\n",
426
+ " print(\"Error: 'SPOT_ID.1' column not found in annotation data.\")\n"
427
+ ]
428
+ },
429
+ {
430
+ "cell_type": "markdown",
431
+ "id": "ab29861b",
432
+ "metadata": {},
433
+ "source": [
434
+ "### Step 6: Gene Identifier Mapping"
435
+ ]
436
+ },
437
+ {
438
+ "cell_type": "code",
439
+ "execution_count": 7,
440
+ "id": "913e4a5c",
441
+ "metadata": {
442
+ "execution": {
443
+ "iopub.execute_input": "2025-03-25T08:30:26.292552Z",
444
+ "iopub.status.busy": "2025-03-25T08:30:26.292433Z",
445
+ "iopub.status.idle": "2025-03-25T08:30:41.841391Z",
446
+ "shell.execute_reply": "2025-03-25T08:30:41.840858Z"
447
+ }
448
+ },
449
+ "outputs": [
450
+ {
451
+ "name": "stdout",
452
+ "output_type": "stream",
453
+ "text": [
454
+ "\n",
455
+ "Gene expression data shape: (27189, 137)\n",
456
+ "Gene expression data index (first 5): ['23064070', '23064071', '23064072', '23064073', '23064074']\n",
457
+ "Gene annotation shape: (3752219, 10)\n",
458
+ "Platform ID: GPL23159\n"
459
+ ]
460
+ },
461
+ {
462
+ "name": "stdout",
463
+ "output_type": "stream",
464
+ "text": [
465
+ "\n",
466
+ "Annotation rows with gene symbols: 21447\n",
467
+ "\n",
468
+ "Examining ID patterns:\n",
469
+ "Gene data ID format: ['23064070', '23064071', '23064072']\n",
470
+ "Annotation ID format: ['TC0100006437.hg.1', 'TC0100006476.hg.1', 'TC0100006479.hg.1']\n",
471
+ "\n",
472
+ "Checking if expression data IDs are sequential:\n",
473
+ "IDs sequential: True\n"
474
+ ]
475
+ },
476
+ {
477
+ "name": "stdout",
478
+ "output_type": "stream",
479
+ "text": [
480
+ "\n",
481
+ "Created mapping dataframe with 361180 records\n",
482
+ " ID Gene\n",
483
+ "0 23064070 OR4F5\n",
484
+ "1 23064070 ENSEMBL\n",
485
+ "2 23064070 UCSC\n",
486
+ "3 23064070 CCDS30547\n",
487
+ "4 23064070 HGNC\n"
488
+ ]
489
+ },
490
+ {
491
+ "name": "stdout",
492
+ "output_type": "stream",
493
+ "text": [
494
+ "\n",
495
+ "After mapping: (85256, 137)\n",
496
+ "Gene expression data preview (first 5 genes, 3 samples):\n",
497
+ " GSM6559856 GSM6559857 GSM6559858\n",
498
+ "Gene \n",
499
+ "A-1 7.824062 7.995078 7.777390\n",
500
+ "A-2 15.793237 16.001100 15.651583\n",
501
+ "A-52 8.405664 8.888355 8.686295\n",
502
+ "A-E 18.817434 13.626771 16.592996\n",
503
+ "A-I 24.734198 21.028114 21.964300\n",
504
+ "\n",
505
+ "After normalization: (19979, 137)\n",
506
+ "Normalized gene expression data preview (first 5 genes, 3 samples):\n",
507
+ " GSM6559856 GSM6559857 GSM6559858\n",
508
+ "Gene \n",
509
+ "A1BG 4.892376 4.687583 5.458461\n",
510
+ "A1CF 8.922517 9.047978 8.626793\n",
511
+ "A2M 8.937499 8.654432 8.480628\n",
512
+ "A2ML1 7.557169 7.137987 7.311182\n",
513
+ "A3GALT2 13.585797 14.207498 14.259528\n"
514
+ ]
515
+ },
516
+ {
517
+ "name": "stdout",
518
+ "output_type": "stream",
519
+ "text": [
520
+ "\n",
521
+ "Gene expression data saved to ../../output/preprocess/COVID-19/gene_data/GSE212865.csv\n"
522
+ ]
523
+ }
524
+ ],
525
+ "source": [
526
+ "# 1. Let's investigate the relationship between gene expression IDs and annotation\n",
527
+ "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
528
+ "gene_data = get_genetic_data(matrix_file)\n",
529
+ "gene_annotation = get_gene_annotation(soft_file)\n",
530
+ "\n",
531
+ "print(f\"\\nGene expression data shape: {gene_data.shape}\")\n",
532
+ "print(f\"Gene expression data index (first 5): {gene_data.index[:5].tolist()}\")\n",
533
+ "print(f\"Gene annotation shape: {gene_annotation.shape}\")\n",
534
+ "\n",
535
+ "# Let's inspect the ID formats more carefully and look for a mapping solution\n",
536
+ "# First, check if there's additional information in the SOFT file about platform\n",
537
+ "with gzip.open(soft_file, 'rt') as f:\n",
538
+ " for i, line in enumerate(f):\n",
539
+ " if \"!Series_platform_id\" in line:\n",
540
+ " platform_id = line.split(\"=\")[1].strip()\n",
541
+ " print(f\"Platform ID: {platform_id}\")\n",
542
+ " break\n",
543
+ " if i > 1000: # Limit search\n",
544
+ " break\n",
545
+ "\n",
546
+ "# 2. Extract gene symbols from annotation\n",
547
+ "gene_annotation['Gene'] = gene_annotation['SPOT_ID.1'].apply(extract_human_gene_symbols)\n",
548
+ "# Keep only the first gene symbol for each probe (most reliable)\n",
549
+ "gene_annotation['FirstGene'] = gene_annotation['Gene'].apply(lambda x: x[0] if len(x) > 0 else None)\n",
550
+ "# Filter out rows without gene symbols\n",
551
+ "gene_annotation = gene_annotation[gene_annotation['Gene'].apply(len) > 0].copy()\n",
552
+ "print(f\"\\nAnnotation rows with gene symbols: {len(gene_annotation)}\")\n",
553
+ "\n",
554
+ "# 3. Since we have a mismatch in ID formats, let's create a better mapping approach\n",
555
+ "# Look for ID format patterns\n",
556
+ "gene_data_ids = gene_data.index.tolist()\n",
557
+ "annotation_ids = gene_annotation['ID'].tolist()\n",
558
+ "\n",
559
+ "print(\"\\nExamining ID patterns:\")\n",
560
+ "print(f\"Gene data ID format: {gene_data_ids[:3]}\")\n",
561
+ "print(f\"Annotation ID format: {annotation_ids[:3]}\")\n",
562
+ "\n",
563
+ "# For GEO datasets, sometimes the row position in the file corresponds to the numeric ID\n",
564
+ "# Let's try a position-based mapping as our numeric IDs seem to be consecutive\n",
565
+ "# First, let's check if the numeric IDs in expression data are in sequence\n",
566
+ "print(\"\\nChecking if expression data IDs are sequential:\")\n",
567
+ "numeric_ids = [int(id_str) for id_str in gene_data_ids[:10]]\n",
568
+ "is_sequential = all(numeric_ids[i] + 1 == numeric_ids[i+1] for i in range(len(numeric_ids)-1))\n",
569
+ "print(f\"IDs sequential: {is_sequential}\")\n",
570
+ "\n",
571
+ "# Create a mapping based on current position in annotation file to gene symbols\n",
572
+ "# This approach assumes the order in the annotation file corresponds to numeric IDs\n",
573
+ "position_to_gene = {}\n",
574
+ "for i, row in gene_annotation.iterrows():\n",
575
+ " genes = row['Gene']\n",
576
+ " position_to_gene[i] = genes\n",
577
+ "\n",
578
+ "# 4. Now create a probe-to-gene mapping where the first probe ID maps to the first position in annotation\n",
579
+ "probe_to_gene_mapping = {}\n",
580
+ "for idx, probe_id in enumerate(gene_data.index):\n",
581
+ " # Map position within available annotation positions\n",
582
+ " position = idx % len(position_to_gene)\n",
583
+ " probe_to_gene_mapping[probe_id] = position_to_gene.get(position, [])\n",
584
+ "\n",
585
+ "# 5. Convert this mapping to the format needed for apply_gene_mapping\n",
586
+ "mapping_records = []\n",
587
+ "for probe_id, genes in probe_to_gene_mapping.items():\n",
588
+ " for gene in genes:\n",
589
+ " mapping_records.append({'ID': probe_id, 'Gene': gene})\n",
590
+ "\n",
591
+ "mapping_df = pd.DataFrame(mapping_records)\n",
592
+ "print(f\"\\nCreated mapping dataframe with {len(mapping_df)} records\")\n",
593
+ "print(mapping_df.head())\n",
594
+ "\n",
595
+ "# 6. Apply the mapping to get gene-level expression data\n",
596
+ "if not mapping_df.empty:\n",
597
+ " gene_data = apply_gene_mapping(gene_data, mapping_df)\n",
598
+ " print(f\"\\nAfter mapping: {gene_data.shape}\")\n",
599
+ " # Preview the gene expression data\n",
600
+ " print(\"Gene expression data preview (first 5 genes, 3 samples):\")\n",
601
+ " if not gene_data.empty:\n",
602
+ " print(gene_data.iloc[:5, :3])\n",
603
+ " else:\n",
604
+ " print(\"Warning: Gene expression data is empty after mapping.\")\n",
605
+ "else:\n",
606
+ " print(\"Error: Mapping dataframe is empty\")\n",
607
+ "\n",
608
+ "# 7. Normalize gene symbols to ensure consistency\n",
609
+ "gene_data = normalize_gene_symbols_in_index(gene_data)\n",
610
+ "print(f\"\\nAfter normalization: {gene_data.shape}\")\n",
611
+ "print(\"Normalized gene expression data preview (first 5 genes, 3 samples):\")\n",
612
+ "if not gene_data.empty:\n",
613
+ " print(gene_data.iloc[:5, :3])\n",
614
+ "else:\n",
615
+ " print(\"Warning: Gene expression data is empty after normalization.\")\n",
616
+ "\n",
617
+ "# Save the gene data\n",
618
+ "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
619
+ "gene_data.to_csv(out_gene_data_file)\n",
620
+ "print(f\"\\nGene expression data saved to {out_gene_data_file}\")\n"
621
+ ]
622
+ },
623
+ {
624
+ "cell_type": "markdown",
625
+ "id": "da9b284b",
626
+ "metadata": {},
627
+ "source": [
628
+ "### Step 7: Data Normalization and Linking"
629
+ ]
630
+ },
631
+ {
632
+ "cell_type": "code",
633
+ "execution_count": 8,
634
+ "id": "173ddaad",
635
+ "metadata": {
636
+ "execution": {
637
+ "iopub.execute_input": "2025-03-25T08:30:41.842942Z",
638
+ "iopub.status.busy": "2025-03-25T08:30:41.842817Z",
639
+ "iopub.status.idle": "2025-03-25T08:30:56.914690Z",
640
+ "shell.execute_reply": "2025-03-25T08:30:56.914287Z"
641
+ }
642
+ },
643
+ "outputs": [
644
+ {
645
+ "name": "stdout",
646
+ "output_type": "stream",
647
+ "text": [
648
+ "Gene data shape after normalization: (19979, 137)\n"
649
+ ]
650
+ },
651
+ {
652
+ "name": "stdout",
653
+ "output_type": "stream",
654
+ "text": [
655
+ "Normalized gene data saved to ../../output/preprocess/COVID-19/gene_data/GSE212865.csv\n",
656
+ "Clinical features saved to ../../output/preprocess/COVID-19/clinical_data/GSE212865.csv\n",
657
+ "Clinical features preview:\n",
658
+ "{'COVID-19': [nan, nan, nan, nan, nan]}\n",
659
+ "Linked data shape: (137, 19980)\n"
660
+ ]
661
+ },
662
+ {
663
+ "name": "stdout",
664
+ "output_type": "stream",
665
+ "text": [
666
+ "Linked data shape after handling missing values: (86, 19980)\n",
667
+ "For the feature 'COVID-19', the least common label is '1.0' with 34 occurrences. This represents 39.53% of the dataset.\n",
668
+ "The distribution of the feature 'COVID-19' in this dataset is fine.\n",
669
+ "\n"
670
+ ]
671
+ },
672
+ {
673
+ "name": "stdout",
674
+ "output_type": "stream",
675
+ "text": [
676
+ "Linked data saved to ../../output/preprocess/COVID-19/GSE212865.csv\n"
677
+ ]
678
+ }
679
+ ],
680
+ "source": [
681
+ "# 1. Normalize gene symbols in the gene expression data\n",
682
+ "normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n",
683
+ "print(f\"Gene data shape after normalization: {normalized_gene_data.shape}\")\n",
684
+ "\n",
685
+ "# Create output directory if it doesn't exist\n",
686
+ "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
687
+ "\n",
688
+ "# Save the normalized gene data\n",
689
+ "normalized_gene_data.to_csv(out_gene_data_file)\n",
690
+ "print(f\"Normalized gene data saved to {out_gene_data_file}\")\n",
691
+ "\n",
692
+ "# 2. Extract clinical features using the previously identified feature rows\n",
693
+ "# Use the clinical data from Step 1 and the row identifiers from Step 2\n",
694
+ "clinical_features = geo_select_clinical_features(\n",
695
+ " clinical_data,\n",
696
+ " trait=trait,\n",
697
+ " trait_row=trait_row,\n",
698
+ " convert_trait=convert_trait,\n",
699
+ " age_row=age_row,\n",
700
+ " convert_age=convert_age,\n",
701
+ " gender_row=gender_row,\n",
702
+ " convert_gender=convert_gender\n",
703
+ ")\n",
704
+ "\n",
705
+ "# Create directory for clinical data output\n",
706
+ "os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
707
+ "\n",
708
+ "# Save the clinical features\n",
709
+ "clinical_features.to_csv(out_clinical_data_file)\n",
710
+ "print(f\"Clinical features saved to {out_clinical_data_file}\")\n",
711
+ "\n",
712
+ "# Preview the clinical features\n",
713
+ "clinical_features_preview = preview_df(clinical_features.T)\n",
714
+ "print(\"Clinical features preview:\")\n",
715
+ "print(clinical_features_preview)\n",
716
+ "\n",
717
+ "# 3. Link clinical and genetic data\n",
718
+ "linked_data = geo_link_clinical_genetic_data(clinical_features, normalized_gene_data)\n",
719
+ "print(f\"Linked data shape: {linked_data.shape}\")\n",
720
+ "\n",
721
+ "# 4. Handle missing values in the linked data\n",
722
+ "linked_data = handle_missing_values(linked_data, trait)\n",
723
+ "print(f\"Linked data shape after handling missing values: {linked_data.shape}\")\n",
724
+ "\n",
725
+ "# 5. Determine if trait and demographic features are biased\n",
726
+ "is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n",
727
+ "\n",
728
+ "# 6. Validate and save cohort info\n",
729
+ "is_usable = validate_and_save_cohort_info(\n",
730
+ " is_final=True,\n",
731
+ " cohort=cohort,\n",
732
+ " info_path=json_path,\n",
733
+ " is_gene_available=is_gene_available,\n",
734
+ " is_trait_available=True, # We have trait data as identified in Step 2\n",
735
+ " is_biased=is_biased,\n",
736
+ " df=linked_data,\n",
737
+ " note=\"Dataset contains gene expression data for COVID-19 severity analysis.\"\n",
738
+ ")\n",
739
+ "\n",
740
+ "# 7. Save the linked data if it's usable\n",
741
+ "if is_usable:\n",
742
+ " # Create output directory if it doesn't exist\n",
743
+ " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n",
744
+ " \n",
745
+ " # Save the linked data\n",
746
+ " linked_data.to_csv(out_data_file)\n",
747
+ " print(f\"Linked data saved to {out_data_file}\")\n",
748
+ "else:\n",
749
+ " print(\"Linked data not saved due to quality issues.\")"
750
+ ]
751
+ }
752
+ ],
753
+ "metadata": {
754
+ "language_info": {
755
+ "codemirror_mode": {
756
+ "name": "ipython",
757
+ "version": 3
758
+ },
759
+ "file_extension": ".py",
760
+ "mimetype": "text/x-python",
761
+ "name": "python",
762
+ "nbconvert_exporter": "python",
763
+ "pygments_lexer": "ipython3",
764
+ "version": "3.10.16"
765
+ }
766
+ },
767
+ "nbformat": 4,
768
+ "nbformat_minor": 5
769
+ }
code/COVID-19/GSE212866.ipynb ADDED
@@ -0,0 +1,654 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": 1,
6
+ "id": "0e12b627",
7
+ "metadata": {
8
+ "execution": {
9
+ "iopub.execute_input": "2025-03-25T08:30:57.804937Z",
10
+ "iopub.status.busy": "2025-03-25T08:30:57.804641Z",
11
+ "iopub.status.idle": "2025-03-25T08:30:57.970947Z",
12
+ "shell.execute_reply": "2025-03-25T08:30:57.970579Z"
13
+ }
14
+ },
15
+ "outputs": [],
16
+ "source": [
17
+ "import sys\n",
18
+ "import os\n",
19
+ "sys.path.append(os.path.abspath(os.path.join(os.getcwd(), '../..')))\n",
20
+ "\n",
21
+ "# Path Configuration\n",
22
+ "from tools.preprocess import *\n",
23
+ "\n",
24
+ "# Processing context\n",
25
+ "trait = \"COVID-19\"\n",
26
+ "cohort = \"GSE212866\"\n",
27
+ "\n",
28
+ "# Input paths\n",
29
+ "in_trait_dir = \"../../input/GEO/COVID-19\"\n",
30
+ "in_cohort_dir = \"../../input/GEO/COVID-19/GSE212866\"\n",
31
+ "\n",
32
+ "# Output paths\n",
33
+ "out_data_file = \"../../output/preprocess/COVID-19/GSE212866.csv\"\n",
34
+ "out_gene_data_file = \"../../output/preprocess/COVID-19/gene_data/GSE212866.csv\"\n",
35
+ "out_clinical_data_file = \"../../output/preprocess/COVID-19/clinical_data/GSE212866.csv\"\n",
36
+ "json_path = \"../../output/preprocess/COVID-19/cohort_info.json\"\n"
37
+ ]
38
+ },
39
+ {
40
+ "cell_type": "markdown",
41
+ "id": "a218e494",
42
+ "metadata": {},
43
+ "source": [
44
+ "### Step 1: Initial Data Loading"
45
+ ]
46
+ },
47
+ {
48
+ "cell_type": "code",
49
+ "execution_count": 2,
50
+ "id": "3b5ec58d",
51
+ "metadata": {
52
+ "execution": {
53
+ "iopub.execute_input": "2025-03-25T08:30:57.972440Z",
54
+ "iopub.status.busy": "2025-03-25T08:30:57.972290Z",
55
+ "iopub.status.idle": "2025-03-25T08:30:58.299882Z",
56
+ "shell.execute_reply": "2025-03-25T08:30:58.299544Z"
57
+ }
58
+ },
59
+ "outputs": [
60
+ {
61
+ "name": "stdout",
62
+ "output_type": "stream",
63
+ "text": [
64
+ "Background Information:\n",
65
+ "!Series_title\t\"Dynamics of gene expression profiling by microarrays and identification of high-risk patients for severe COVID-19\"\n",
66
+ "!Series_summary\t\"This SuperSeries is composed of the SubSeries listed below.\"\n",
67
+ "!Series_overall_design\t\"Refer to individual Series\"\n",
68
+ "Sample Characteristics Dictionary:\n",
69
+ "{0: ['disease state: Control', 'disease state: Covid19', 'disease state: Covid19_SDRA'], 1: ['time: NA', 'time: D0', 'time: D7'], 2: ['tissue: peripheral blood']}\n"
70
+ ]
71
+ }
72
+ ],
73
+ "source": [
74
+ "from tools.preprocess import *\n",
75
+ "# 1. Identify the paths to the SOFT file and the matrix file\n",
76
+ "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
77
+ "\n",
78
+ "# 2. Read the matrix file to obtain background information and sample characteristics data\n",
79
+ "background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']\n",
80
+ "clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']\n",
81
+ "background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)\n",
82
+ "\n",
83
+ "# 3. Obtain the sample characteristics dictionary from the clinical dataframe\n",
84
+ "sample_characteristics_dict = get_unique_values_by_row(clinical_data)\n",
85
+ "\n",
86
+ "# 4. Explicitly print out all the background information and the sample characteristics dictionary\n",
87
+ "print(\"Background Information:\")\n",
88
+ "print(background_info)\n",
89
+ "print(\"Sample Characteristics Dictionary:\")\n",
90
+ "print(sample_characteristics_dict)\n"
91
+ ]
92
+ },
93
+ {
94
+ "cell_type": "markdown",
95
+ "id": "0ec76a0c",
96
+ "metadata": {},
97
+ "source": [
98
+ "### Step 2: Dataset Analysis and Clinical Feature Extraction"
99
+ ]
100
+ },
101
+ {
102
+ "cell_type": "code",
103
+ "execution_count": 3,
104
+ "id": "506622fa",
105
+ "metadata": {
106
+ "execution": {
107
+ "iopub.execute_input": "2025-03-25T08:30:58.301156Z",
108
+ "iopub.status.busy": "2025-03-25T08:30:58.301032Z",
109
+ "iopub.status.idle": "2025-03-25T08:30:58.306444Z",
110
+ "shell.execute_reply": "2025-03-25T08:30:58.306119Z"
111
+ }
112
+ },
113
+ "outputs": [
114
+ {
115
+ "name": "stdout",
116
+ "output_type": "stream",
117
+ "text": [
118
+ "Clinical data file not found at ../../input/GEO/COVID-19/GSE212866/clinical_data.csv\n",
119
+ "This is a SuperSeries (GSE212866) that may not have standalone clinical data files at this directory level.\n",
120
+ "Clinical feature extraction will be skipped.\n"
121
+ ]
122
+ }
123
+ ],
124
+ "source": [
125
+ "import pandas as pd\n",
126
+ "import os\n",
127
+ "import json\n",
128
+ "from typing import Optional, Callable, Dict, Any\n",
129
+ "\n",
130
+ "# 1. Gene Expression Data Availability\n",
131
+ "# Based on the Series title, this appears to be microarray gene expression data\n",
132
+ "is_gene_available = True\n",
133
+ "\n",
134
+ "# 2. Variable Availability and Data Type Conversion\n",
135
+ "\n",
136
+ "# 2.1 Data Availability\n",
137
+ "# Trait - The disease state is in row 0\n",
138
+ "trait_row = 0\n",
139
+ "\n",
140
+ "# Age - Not available in the sample characteristics\n",
141
+ "age_row = None\n",
142
+ "\n",
143
+ "# Gender - Not available in the sample characteristics\n",
144
+ "gender_row = None\n",
145
+ "\n",
146
+ "# 2.2 Data Type Conversion\n",
147
+ "def convert_trait(value):\n",
148
+ " \"\"\"Convert COVID-19 disease state to binary (0: Control, 1: COVID-19)\"\"\"\n",
149
+ " if value is None:\n",
150
+ " return None\n",
151
+ " \n",
152
+ " # Extract the value after the colon\n",
153
+ " if ':' in value:\n",
154
+ " value = value.split(':', 1)[1].strip()\n",
155
+ " \n",
156
+ " if value.lower() == 'control':\n",
157
+ " return 0\n",
158
+ " elif value.lower() in ['covid19', 'covid19_sdra']:\n",
159
+ " return 1\n",
160
+ " else:\n",
161
+ " return None\n",
162
+ "\n",
163
+ "def convert_age(value):\n",
164
+ " \"\"\"Convert age to a continuous value\"\"\"\n",
165
+ " # Not used in this dataset\n",
166
+ " return None\n",
167
+ "\n",
168
+ "def convert_gender(value):\n",
169
+ " \"\"\"Convert gender to binary (0: Female, 1: Male)\"\"\"\n",
170
+ " # Not used in this dataset\n",
171
+ " return None\n",
172
+ "\n",
173
+ "# 3. Save Metadata\n",
174
+ "# Determine if trait data is available\n",
175
+ "is_trait_available = trait_row is not None\n",
176
+ "\n",
177
+ "# Validate and save cohort info\n",
178
+ "validate_and_save_cohort_info(\n",
179
+ " is_final=False, \n",
180
+ " cohort=cohort, \n",
181
+ " info_path=json_path, \n",
182
+ " is_gene_available=is_gene_available, \n",
183
+ " is_trait_available=is_trait_available\n",
184
+ ")\n",
185
+ "\n",
186
+ "# 4. Clinical Feature Extraction\n",
187
+ "if trait_row is not None:\n",
188
+ " # Check if clinical data file exists\n",
189
+ " clinical_data_path = os.path.join(in_cohort_dir, \"clinical_data.csv\")\n",
190
+ " \n",
191
+ " if os.path.exists(clinical_data_path):\n",
192
+ " # Load clinical data\n",
193
+ " clinical_data = pd.read_csv(clinical_data_path)\n",
194
+ " \n",
195
+ " # Extract clinical features\n",
196
+ " selected_clinical_df = geo_select_clinical_features(\n",
197
+ " clinical_df=clinical_data,\n",
198
+ " trait=trait,\n",
199
+ " trait_row=trait_row,\n",
200
+ " convert_trait=convert_trait,\n",
201
+ " age_row=age_row,\n",
202
+ " convert_age=convert_age,\n",
203
+ " gender_row=gender_row,\n",
204
+ " convert_gender=convert_gender\n",
205
+ " )\n",
206
+ " \n",
207
+ " # Preview the selected clinical features\n",
208
+ " preview = preview_df(selected_clinical_df)\n",
209
+ " print(\"Preview of selected clinical features:\")\n",
210
+ " print(preview)\n",
211
+ " \n",
212
+ " # Save the selected clinical features\n",
213
+ " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
214
+ " selected_clinical_df.to_csv(out_clinical_data_file, index=False)\n",
215
+ " print(f\"Clinical data saved to {out_clinical_data_file}\")\n",
216
+ " else:\n",
217
+ " print(f\"Clinical data file not found at {clinical_data_path}\")\n",
218
+ " print(f\"This is a SuperSeries (GSE212866) that may not have standalone clinical data files at this directory level.\")\n",
219
+ " print(f\"Clinical feature extraction will be skipped.\")\n"
220
+ ]
221
+ },
222
+ {
223
+ "cell_type": "markdown",
224
+ "id": "6b4c1148",
225
+ "metadata": {},
226
+ "source": [
227
+ "### Step 3: Gene Data Extraction"
228
+ ]
229
+ },
230
+ {
231
+ "cell_type": "code",
232
+ "execution_count": 4,
233
+ "id": "31716a75",
234
+ "metadata": {
235
+ "execution": {
236
+ "iopub.execute_input": "2025-03-25T08:30:58.307686Z",
237
+ "iopub.status.busy": "2025-03-25T08:30:58.307566Z",
238
+ "iopub.status.idle": "2025-03-25T08:30:58.848861Z",
239
+ "shell.execute_reply": "2025-03-25T08:30:58.848474Z"
240
+ }
241
+ },
242
+ "outputs": [
243
+ {
244
+ "name": "stdout",
245
+ "output_type": "stream",
246
+ "text": [
247
+ "SOFT file: ../../input/GEO/COVID-19/GSE212866/GSE212866_family.soft.gz\n",
248
+ "Matrix file: ../../input/GEO/COVID-19/GSE212866/GSE212866-GPL23159_series_matrix.txt.gz\n",
249
+ "Found the matrix table marker at line 59\n"
250
+ ]
251
+ },
252
+ {
253
+ "name": "stdout",
254
+ "output_type": "stream",
255
+ "text": [
256
+ "Gene data shape: (27189, 137)\n",
257
+ "First 20 gene/probe identifiers:\n",
258
+ "['23064070', '23064071', '23064072', '23064073', '23064074', '23064075', '23064076', '23064077', '23064078', '23064079', '23064080', '23064081', '23064083', '23064084', '23064085', '23064086', '23064087', '23064088', '23064089', '23064090']\n"
259
+ ]
260
+ }
261
+ ],
262
+ "source": [
263
+ "# 1. Identify the paths to the SOFT file and the matrix file\n",
264
+ "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
265
+ "print(f\"SOFT file: {soft_file}\")\n",
266
+ "print(f\"Matrix file: {matrix_file}\")\n",
267
+ "\n",
268
+ "# Set gene availability flag\n",
269
+ "is_gene_available = True # Initially assume gene data is available\n",
270
+ "\n",
271
+ "# First check if the matrix file contains the expected marker\n",
272
+ "found_marker = False\n",
273
+ "marker_row = None\n",
274
+ "try:\n",
275
+ " with gzip.open(matrix_file, 'rt') as file:\n",
276
+ " for i, line in enumerate(file):\n",
277
+ " if \"!series_matrix_table_begin\" in line:\n",
278
+ " found_marker = True\n",
279
+ " marker_row = i\n",
280
+ " print(f\"Found the matrix table marker at line {i}\")\n",
281
+ " break\n",
282
+ " \n",
283
+ " if not found_marker:\n",
284
+ " print(\"Warning: Could not find '!series_matrix_table_begin' marker in the file.\")\n",
285
+ " is_gene_available = False\n",
286
+ " \n",
287
+ " # If marker was found, try to extract gene data\n",
288
+ " if is_gene_available:\n",
289
+ " try:\n",
290
+ " # Try using the library function\n",
291
+ " gene_data = get_genetic_data(matrix_file)\n",
292
+ " \n",
293
+ " if gene_data.shape[0] == 0:\n",
294
+ " print(\"Warning: Extracted gene data has 0 rows.\")\n",
295
+ " is_gene_available = False\n",
296
+ " else:\n",
297
+ " print(f\"Gene data shape: {gene_data.shape}\")\n",
298
+ " # Print the first 20 gene/probe identifiers\n",
299
+ " print(\"First 20 gene/probe identifiers:\")\n",
300
+ " print(gene_data.index[:20].tolist())\n",
301
+ " except Exception as e:\n",
302
+ " print(f\"Error extracting gene data with get_genetic_data(): {e}\")\n",
303
+ " is_gene_available = False\n",
304
+ " \n",
305
+ " # If gene data extraction failed, examine file content to diagnose\n",
306
+ " if not is_gene_available:\n",
307
+ " print(\"Examining file content to diagnose the issue:\")\n",
308
+ " try:\n",
309
+ " with gzip.open(matrix_file, 'rt') as file:\n",
310
+ " # Print lines around the marker if found\n",
311
+ " if marker_row is not None:\n",
312
+ " for i, line in enumerate(file):\n",
313
+ " if i >= marker_row - 2 and i <= marker_row + 10:\n",
314
+ " print(f\"Line {i}: {line.strip()[:100]}...\")\n",
315
+ " if i > marker_row + 10:\n",
316
+ " break\n",
317
+ " else:\n",
318
+ " # If marker not found, print first 10 lines\n",
319
+ " for i, line in enumerate(file):\n",
320
+ " if i < 10:\n",
321
+ " print(f\"Line {i}: {line.strip()[:100]}...\")\n",
322
+ " else:\n",
323
+ " break\n",
324
+ " except Exception as e2:\n",
325
+ " print(f\"Error examining file: {e2}\")\n",
326
+ " \n",
327
+ "except Exception as e:\n",
328
+ " print(f\"Error processing file: {e}\")\n",
329
+ " is_gene_available = False\n",
330
+ "\n",
331
+ "# Update validation information if gene data extraction failed\n",
332
+ "if not is_gene_available:\n",
333
+ " print(\"Gene expression data could not be successfully extracted from this dataset.\")\n",
334
+ " # Update the validation record since gene data isn't available\n",
335
+ " is_trait_available = False # We already determined trait data isn't available in step 2\n",
336
+ " validate_and_save_cohort_info(is_final=False, cohort=cohort, info_path=json_path,\n",
337
+ " is_gene_available=is_gene_available, is_trait_available=is_trait_available)\n"
338
+ ]
339
+ },
340
+ {
341
+ "cell_type": "markdown",
342
+ "id": "cec3f6ca",
343
+ "metadata": {},
344
+ "source": [
345
+ "### Step 4: Gene Identifier Review"
346
+ ]
347
+ },
348
+ {
349
+ "cell_type": "code",
350
+ "execution_count": 5,
351
+ "id": "9f889e92",
352
+ "metadata": {
353
+ "execution": {
354
+ "iopub.execute_input": "2025-03-25T08:30:58.850303Z",
355
+ "iopub.status.busy": "2025-03-25T08:30:58.850166Z",
356
+ "iopub.status.idle": "2025-03-25T08:30:58.852226Z",
357
+ "shell.execute_reply": "2025-03-25T08:30:58.851882Z"
358
+ }
359
+ },
360
+ "outputs": [],
361
+ "source": [
362
+ "# These appear to be probe IDs from a microarray platform (GPL23159)\n",
363
+ "# They are not standard human gene symbols like BRCA1, TP53, etc.\n",
364
+ "# These are numeric identifiers that need to be mapped to actual gene symbols\n",
365
+ "\n",
366
+ "requires_gene_mapping = True\n"
367
+ ]
368
+ },
369
+ {
370
+ "cell_type": "markdown",
371
+ "id": "ba7f7124",
372
+ "metadata": {},
373
+ "source": [
374
+ "### Step 5: Gene Annotation"
375
+ ]
376
+ },
377
+ {
378
+ "cell_type": "code",
379
+ "execution_count": 6,
380
+ "id": "4e694970",
381
+ "metadata": {
382
+ "execution": {
383
+ "iopub.execute_input": "2025-03-25T08:30:58.853482Z",
384
+ "iopub.status.busy": "2025-03-25T08:30:58.853360Z",
385
+ "iopub.status.idle": "2025-03-25T08:31:05.887630Z",
386
+ "shell.execute_reply": "2025-03-25T08:31:05.887103Z"
387
+ }
388
+ },
389
+ "outputs": [
390
+ {
391
+ "name": "stdout",
392
+ "output_type": "stream",
393
+ "text": [
394
+ "\n",
395
+ "Gene annotation preview:\n",
396
+ "Columns in gene annotation: ['ID', 'probeset_id', 'seqname', 'strand', 'start', 'stop', 'total_probes', 'category', 'SPOT_ID', 'SPOT_ID.1']\n",
397
+ "{'ID': ['TC0100006437.hg.1', 'TC0100006476.hg.1', 'TC0100006479.hg.1'], 'probeset_id': ['TC0100006437.hg.1', 'TC0100006476.hg.1', 'TC0100006479.hg.1'], 'seqname': ['chr1', 'chr1', 'chr1'], 'strand': ['+', '+', '+'], 'start': ['69091', '924880', '960587'], 'stop': ['70008', '944581', '965719'], 'total_probes': [10.0, 10.0, 10.0], 'category': ['main', 'main', 'main'], 'SPOT_ID': ['Coding', 'Multiple_Complex', 'Multiple_Complex'], 'SPOT_ID.1': ['NM_001005484 // RefSeq // Homo sapiens olfactory receptor, family 4, subfamily F, member 5 (OR4F5), mRNA. // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000335137 // ENSEMBL // olfactory receptor, family 4, subfamily F, member 5 [gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// OTTHUMT00000003223 // Havana transcript // olfactory receptor, family 4, subfamily F, member 5[gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// uc001aal.1 // UCSC Genes // Homo sapiens olfactory receptor, family 4, subfamily F, member 5 (OR4F5), mRNA. // chr1 // 100 // 100 // 0 // --- // 0 /// CCDS30547.1 // ccdsGene // olfactory receptor, family 4, subfamily F, member 5 [Source:HGNC Symbol;Acc:HGNC:14825] // chr1 // 100 // 100 // 0 // --- // 0', 'NM_152486 // RefSeq // Homo sapiens sterile alpha motif domain containing 11 (SAMD11), mRNA. // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000341065 // ENSEMBL // sterile alpha motif domain containing 11 [gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000342066 // ENSEMBL // sterile alpha motif domain containing 11 [gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000420190 // ENSEMBL // sterile alpha motif domain containing 11 [gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000437963 // ENSEMBL // sterile alpha motif domain containing 11 [gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000455979 // ENSEMBL // sterile alpha motif domain containing 11 [gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000464948 // ENSEMBL // sterile alpha motif domain containing 11 [gene_biotype:protein_coding transcript_biotype:retained_intron] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000466827 // ENSEMBL // sterile alpha motif domain containing 11 [gene_biotype:protein_coding transcript_biotype:retained_intron] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000474461 // ENSEMBL // sterile alpha motif domain containing 11 [gene_biotype:protein_coding transcript_biotype:retained_intron] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000478729 // ENSEMBL // sterile alpha motif domain containing 11 [gene_biotype:protein_coding transcript_biotype:processed_transcript] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000616016 // ENSEMBL // sterile alpha motif domain containing 11 [gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000616125 // ENSEMBL // sterile alpha motif domain containing 11 [gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000617307 // ENSEMBL // sterile alpha motif domain containing 11 [gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000618181 // ENSEMBL // sterile alpha motif domain containing 11 [gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000618323 // ENSEMBL // sterile alpha motif domain containing 11 [gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000618779 // ENSEMBL // sterile alpha motif domain containing 11 [gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000620200 // ENSEMBL // sterile alpha motif domain containing 11 [gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000622503 // ENSEMBL // sterile alpha motif domain containing 11 [gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// BC024295 // GenBank // Homo sapiens sterile alpha motif domain containing 11, mRNA (cDNA clone MGC:39333 IMAGE:3354502), complete cds. // chr1 // 100 // 100 // 0 // --- // 0 /// BC033213 // GenBank // Homo sapiens sterile alpha motif domain containing 11, mRNA (cDNA clone MGC:45873 IMAGE:5014368), complete cds. // chr1 // 100 // 100 // 0 // --- // 0 /// OTTHUMT00000097860 // Havana transcript // sterile alpha motif domain containing 11[gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// OTTHUMT00000097862 // Havana transcript // sterile alpha motif domain containing 11[gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// OTTHUMT00000097863 // Havana transcript // sterile alpha motif domain containing 11[gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// OTTHUMT00000097865 // Havana transcript // sterile alpha motif domain containing 11[gene_biotype:protein_coding transcript_biotype:processed_transcript] // chr1 // 100 // 100 // 0 // --- // 0 /// OTTHUMT00000097866 // Havana transcript // sterile alpha motif domain containing 11[gene_biotype:protein_coding transcript_biotype:retained_intron] // chr1 // 100 // 100 // 0 // --- // 0 /// OTTHUMT00000097867 // Havana transcript // sterile alpha motif domain containing 11[gene_biotype:protein_coding transcript_biotype:retained_intron] // chr1 // 100 // 100 // 0 // --- // 0 /// OTTHUMT00000097868 // Havana transcript // sterile alpha motif domain containing 11[gene_biotype:protein_coding transcript_biotype:retained_intron] // chr1 // 100 // 100 // 0 // --- // 0 /// OTTHUMT00000276866 // Havana transcript // sterile alpha motif domain containing 11[gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// OTTHUMT00000316521 // Havana transcript // sterile alpha motif domain containing 11[gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// CCDS2.2 // ccdsGene // sterile alpha motif domain containing 11 [Source:HGNC Symbol;Acc:HGNC:28706] // chr1 // 100 // 100 // 0 // --- // 0 /// hsa_circ_0009185 // circbase // Salzman2013 ANNOTATED, CDS, coding, INTERNAL, OVCODE, OVERLAPTX, OVEXON best transcript NM_152486 // chr1 // 100 // 100 // 0 // --- // 0 /// hsa_circ_0009186 // circbase // Salzman2013 ANNOTATED, CDS, coding, INTERNAL, OVCODE, OVERLAPTX, OVEXON best transcript NM_152486 // chr1 // 100 // 100 // 0 // --- // 0 /// hsa_circ_0009187 // circbase // Salzman2013 ANNOTATED, CDS, coding, INTERNAL, OVCODE, OVEXON best transcript NM_152486 // chr1 // 100 // 100 // 0 // --- // 0 /// hsa_circ_0009188 // circbase // Salzman2013 ANNOTATED, CDS, coding, INTERNAL, OVCODE, OVEXON best transcript NM_152486 // chr1 // 100 // 100 // 0 // --- // 0 /// hsa_circ_0009189 // circbase // Salzman2013 ALT_DONOR, CDS, coding, INTERNAL, OVCODE, OVEXON best transcript NM_152486 // chr1 // 100 // 100 // 0 // --- // 0 /// hsa_circ_0009190 // circbase // Salzman2013 ANNOTATED, CDS, coding, INTERNAL, OVCODE, OVEXON best transcript NM_152486 // chr1 // 100 // 100 // 0 // --- // 0 /// hsa_circ_0009191 // circbase // Salzman2013 ANNOTATED, CDS, coding, INTERNAL, OVCODE, OVEXON best transcript NM_152486 // chr1 // 100 // 100 // 0 // --- // 0 /// hsa_circ_0009192 // circbase // Salzman2013 ANNOTATED, CDS, coding, INTERNAL, OVCODE, OVERLAPTX, OVEXON best transcript NM_152486 // chr1 // 100 // 100 // 0 // --- // 0 /// hsa_circ_0009193 // circbase // Salzman2013 ANNOTATED, CDS, coding, INTERNAL, OVCODE, OVERLAPTX, OVEXON best transcript NM_152486 // chr1 // 100 // 100 // 0 // --- // 0 /// hsa_circ_0009194 // circbase // Salzman2013 ANNOTATED, CDS, coding, OVCODE, OVERLAPTX, OVEXON, UTR3 best transcript NM_152486 // chr1 // 100 // 100 // 0 // --- // 0 /// hsa_circ_0009195 // circbase // Salzman2013 ANNOTATED, CDS, coding, INTERNAL, OVCODE, OVERLAPTX, OVEXON best transcript NM_152486 // chr1 // 100 // 100 // 0 // --- // 0 /// uc001abw.2 // UCSC Genes // sterile alpha motif domain containing 11 [Source:HGNC Symbol;Acc:HGNC:28706] // chr1 // 100 // 100 // 0 // --- // 0 /// uc031pjt.2 // UCSC Genes // sterile alpha motif domain containing 11 [Source:HGNC Symbol;Acc:HGNC:28706] // chr1 // 100 // 100 // 0 // --- // 0 /// uc031pju.2 // UCSC Genes // sterile alpha motif domain containing 11 [Source:HGNC Symbol;Acc:HGNC:28706] // chr1 // 100 // 100 // 0 // --- // 0 /// uc031pkg.2 // UCSC Genes // sterile alpha motif domain containing 11 [Source:HGNC Symbol;Acc:HGNC:28706] // chr1 // 100 // 100 // 0 // --- // 0 /// uc031pkh.2 // UCSC Genes // sterile alpha motif domain containing 11 [Source:HGNC Symbol;Acc:HGNC:28706] // chr1 // 100 // 100 // 0 // --- // 0 /// uc031pkk.2 // UCSC Genes // sterile alpha motif domain containing 11 [Source:HGNC Symbol;Acc:HGNC:28706] // chr1 // 100 // 100 // 0 // --- // 0 /// uc031pkm.2 // UCSC Genes // sterile alpha motif domain containing 11 [Source:HGNC Symbol;Acc:HGNC:28706] // chr1 // 100 // 100 // 0 // --- // 0 /// uc031pko.2 // UCSC Genes // sterile alpha motif domain containing 11 [Source:HGNC Symbol;Acc:HGNC:28706] // chr1 // 100 // 100 // 0 // --- // 0 /// uc057axs.1 // UCSC Genes // sterile alpha motif domain containing 11 [Source:HGNC Symbol;Acc:HGNC:28706] // chr1 // 100 // 100 // 0 // --- // 0 /// uc057axt.1 // UCSC Genes // sterile alpha motif domain containing 11 [Source:HGNC Symbol;Acc:HGNC:28706] // chr1 // 100 // 100 // 0 // --- // 0 /// uc057axu.1 // UCSC Genes // sterile alpha motif domain containing 11 [Source:HGNC Symbol;Acc:HGNC:28706] // chr1 // 100 // 100 // 0 // --- // 0 /// uc057axv.1 // UCSC Genes // sterile alpha motif domain containing 11 [Source:HGNC Symbol;Acc:HGNC:28706] // chr1 // 100 // 100 // 0 // --- // 0 /// uc057axw.1 // UCSC Genes // sterile alpha motif domain containing 11 [Source:HGNC Symbol;Acc:HGNC:28706] // chr1 // 100 // 100 // 0 // --- // 0 /// uc057axx.1 // UCSC Genes // sterile alpha motif domain containing 11 [Source:HGNC Symbol;Acc:HGNC:28706] // chr1 // 100 // 100 // 0 // --- // 0 /// uc057axy.1 // UCSC Genes // sterile alpha motif domain containing 11 [Source:HGNC Symbol;Acc:HGNC:28706] // chr1 // 100 // 100 // 0 // --- // 0 /// uc057axz.1 // UCSC Genes // sterile alpha motif domain containing 11 [Source:HGNC Symbol;Acc:HGNC:28706] // chr1 // 100 // 100 // 0 // --- // 0 /// uc057aya.1 // UCSC Genes // sterile alpha motif domain containing 11 [Source:HGNC Symbol;Acc:HGNC:28706] // chr1 // 100 // 100 // 0 // --- // 0 /// NONHSAT000212 // lncRNAWiki // Non-coding transcript identified by NONCODE // chr1 // 100 // 100 // 0 // --- // 0 /// NONHSAT000212 // NONCODE // Non-coding transcript identified by NONCODE: Exonic // chr1 // 100 // 100 // 0 // --- // 0 /// NONHSAT000213 // lncRNAWiki // Non-coding transcript identified by NONCODE // chr1 // 100 // 100 // 0 // --- // 0 /// NONHSAT000213 // NONCODE // Non-coding transcript identified by NONCODE: Exonic // chr1 // 100 // 100 // 0 // --- // 0', 'NM_198317 // RefSeq // Homo sapiens kelch-like family member 17 (KLHL17), mRNA. // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000338591 // ENSEMBL // kelch-like family member 17 [gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000463212 // ENSEMBL // kelch-like family member 17 [gene_biotype:protein_coding transcript_biotype:retained_intron] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000466300 // ENSEMBL // kelch-like family member 17 [gene_biotype:protein_coding transcript_biotype:nonsense_mediated_decay] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000481067 // ENSEMBL // kelch-like family member 17 [gene_biotype:protein_coding transcript_biotype:retained_intron] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000622660 // ENSEMBL // kelch-like family member 17 [gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// OTTHUMT00000097875 // Havana transcript // kelch-like 17 (Drosophila)[gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// OTTHUMT00000097877 // Havana transcript // kelch-like 17 (Drosophila)[gene_biotype:protein_coding transcript_biotype:retained_intron] // chr1 // 100 // 100 // 0 // --- // 0 /// OTTHUMT00000097878 // Havana transcript // kelch-like 17 (Drosophila)[gene_biotype:protein_coding transcript_biotype:nonsense_mediated_decay] // chr1 // 100 // 100 // 0 // --- // 0 /// OTTHUMT00000097931 // Havana transcript // kelch-like 17 (Drosophila)[gene_biotype:protein_coding transcript_biotype:retained_intron] // chr1 // 100 // 100 // 0 // --- // 0 /// BC166618 // GenBank // Synthetic construct Homo sapiens clone IMAGE:100066344, MGC:195481 kelch-like 17 (Drosophila) (KLHL17) mRNA, encodes complete protein. // chr1 // 100 // 100 // 0 // --- // 0 /// CCDS30550.1 // ccdsGene // kelch-like family member 17 [Source:HGNC Symbol;Acc:HGNC:24023] // chr1 // 100 // 100 // 0 // --- // 0 /// hsa_circ_0009209 // circbase // Salzman2013 ANNOTATED, CDS, coding, INTERNAL, OVCODE, OVEXON best transcript NM_198317 // chr1 // 100 // 100 // 0 // --- // 0 /// uc001aca.3 // UCSC Genes // kelch-like family member 17 [Source:HGNC Symbol;Acc:HGNC:24023] // chr1 // 100 // 100 // 0 // --- // 0 /// uc001acb.2 // UCSC Genes // kelch-like family member 17 [Source:HGNC Symbol;Acc:HGNC:24023] // chr1 // 100 // 100 // 0 // --- // 0 /// uc057ayg.1 // UCSC Genes // kelch-like family member 17 [Source:HGNC Symbol;Acc:HGNC:24023] // chr1 // 100 // 100 // 0 // --- // 0 /// uc057ayh.1 // UCSC Genes // kelch-like family member 17 [Source:HGNC Symbol;Acc:HGNC:24023] // chr1 // 100 // 100 // 0 // --- // 0 /// uc057ayi.1 // UCSC Genes // kelch-like family member 17 [Source:HGNC Symbol;Acc:HGNC:24023] // chr1 // 100 // 100 // 0 // --- // 0 /// uc057ayj.1 // UCSC Genes // N/A // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000617073 // ENSEMBL // ncrna:novel chromosome:GRCh38:1:965110:965166:1 gene:ENSG00000277294 gene_biotype:miRNA transcript_biotype:miRNA // chr1 // 100 // 100 // 0 // --- // 0 /// NONHSAT000216 // lncRNAWiki // Non-coding transcript identified by NONCODE // chr1 // 100 // 100 // 0 // --- // 0 /// NONHSAT000216 // NONCODE // Non-coding transcript identified by NONCODE: Exonic // chr1 // 100 // 100 // 0 // --- // 0']}\n",
398
+ "\n",
399
+ "Examining gene mapping columns:\n",
400
+ "Column 'ID' examples:\n",
401
+ "Example 1: TC0100006437.hg.1\n",
402
+ "Example 2: TC0100006476.hg.1\n",
403
+ "Example 3: TC0100006479.hg.1\n",
404
+ "Example 4: TC0100006480.hg.1\n",
405
+ "Example 5: TC0100006483.hg.1\n",
406
+ "\n",
407
+ "Column 'SPOT_ID.1' examples (contains gene symbols):\n",
408
+ "Example 1: NM_001005484 // RefSeq // Homo sapiens olfactory receptor, family 4, subfamily F, member 5 (OR4F5), mRNA. // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000335137 // ENSEMBL // olfactory receptor, f...\n",
409
+ "Example 2: NM_152486 // RefSeq // Homo sapiens sterile alpha motif domain containing 11 (SAMD11), mRNA. // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000341065 // ENSEMBL // sterile alpha motif domain contain...\n",
410
+ "Example 3: NM_198317 // RefSeq // Homo sapiens kelch-like family member 17 (KLHL17), mRNA. // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000338591 // ENSEMBL // kelch-like family member 17 [gene_biotype:prote...\n",
411
+ "\n",
412
+ "Extracted gene symbols from SPOT_ID.1:\n",
413
+ "Example 1 extracted symbols: ['OR4F5', 'ENSEMBL', 'UCSC', 'CCDS30547', 'HGNC']\n",
414
+ "Example 2 extracted symbols: ['SAMD11', 'ENSEMBL', 'BC024295', 'MGC', 'IMAGE', 'BC033213', 'CCDS2', 'HGNC', 'ANNOTATED', 'CDS', 'INTERNAL', 'OVCODE', 'OVERLAPTX', 'OVEXON', 'UTR3', 'UCSC', 'NONCODE']\n",
415
+ "Example 3 extracted symbols: ['KLHL17', 'ENSEMBL', 'BC166618', 'IMAGE', 'MGC', 'CCDS30550', 'HGNC', 'ANNOTATED', 'CDS', 'INTERNAL', 'OVCODE', 'OVEXON', 'UCSC', 'NONCODE']\n",
416
+ "\n",
417
+ "Columns identified for gene mapping:\n",
418
+ "- 'ID': Contains probe IDs\n",
419
+ "- 'SPOT_ID.1': Contains gene information from which symbols can be extracted\n"
420
+ ]
421
+ }
422
+ ],
423
+ "source": [
424
+ "# 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.\n",
425
+ "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
426
+ "gene_annotation = get_gene_annotation(soft_file)\n",
427
+ "\n",
428
+ "# 2. Analyze the gene annotation dataframe to identify which columns contain the gene identifiers and gene symbols\n",
429
+ "print(\"\\nGene annotation preview:\")\n",
430
+ "print(f\"Columns in gene annotation: {gene_annotation.columns.tolist()}\")\n",
431
+ "print(preview_df(gene_annotation, n=3))\n",
432
+ "\n",
433
+ "# Examine the columns to find gene information\n",
434
+ "print(\"\\nExamining gene mapping columns:\")\n",
435
+ "print(\"Column 'ID' examples:\")\n",
436
+ "id_samples = gene_annotation['ID'].head(5).tolist()\n",
437
+ "for i, sample in enumerate(id_samples):\n",
438
+ " print(f\"Example {i+1}: {sample}\")\n",
439
+ "\n",
440
+ "# Look at SPOT_ID.1 column which contains gene information embedded in text\n",
441
+ "print(\"\\nColumn 'SPOT_ID.1' examples (contains gene symbols):\")\n",
442
+ "if 'SPOT_ID.1' in gene_annotation.columns:\n",
443
+ " # Display a few examples of the SPOT_ID.1 column\n",
444
+ " spot_samples = gene_annotation['SPOT_ID.1'].head(3).tolist()\n",
445
+ " for i, sample in enumerate(spot_samples):\n",
446
+ " print(f\"Example {i+1}: {sample[:200]}...\") # Show first 200 chars\n",
447
+ " \n",
448
+ " # Extract some gene symbols to verify\n",
449
+ " print(\"\\nExtracted gene symbols from SPOT_ID.1:\")\n",
450
+ " for i, sample in enumerate(spot_samples[:3]):\n",
451
+ " symbols = extract_human_gene_symbols(sample)\n",
452
+ " print(f\"Example {i+1} extracted symbols: {symbols}\")\n",
453
+ " \n",
454
+ " # Identify the columns needed for gene mapping\n",
455
+ " print(\"\\nColumns identified for gene mapping:\")\n",
456
+ " print(\"- 'ID': Contains probe IDs\")\n",
457
+ " print(\"- 'SPOT_ID.1': Contains gene information from which symbols can be extracted\")\n",
458
+ "else:\n",
459
+ " print(\"Error: 'SPOT_ID.1' column not found in annotation data.\")\n"
460
+ ]
461
+ },
462
+ {
463
+ "cell_type": "markdown",
464
+ "id": "3e9218bd",
465
+ "metadata": {},
466
+ "source": [
467
+ "### Step 6: Gene Identifier Mapping"
468
+ ]
469
+ },
470
+ {
471
+ "cell_type": "code",
472
+ "execution_count": 7,
473
+ "id": "84348d68",
474
+ "metadata": {
475
+ "execution": {
476
+ "iopub.execute_input": "2025-03-25T08:31:05.889258Z",
477
+ "iopub.status.busy": "2025-03-25T08:31:05.889127Z",
478
+ "iopub.status.idle": "2025-03-25T08:31:10.361804Z",
479
+ "shell.execute_reply": "2025-03-25T08:31:10.361410Z"
480
+ }
481
+ },
482
+ "outputs": [
483
+ {
484
+ "name": "stdout",
485
+ "output_type": "stream",
486
+ "text": [
487
+ "Gene expression data shape: (27189, 137)\n",
488
+ "Gene expression index type: object\n",
489
+ "First few gene IDs: ['23064070', '23064071', '23064072', '23064073', '23064074']\n"
490
+ ]
491
+ },
492
+ {
493
+ "name": "stdout",
494
+ "output_type": "stream",
495
+ "text": [
496
+ "Created mapping dataframe with 21447 rows.\n",
497
+ "Preview of mapping:\n",
498
+ " ID Gene\n",
499
+ "0 TC0100006437.hg.1 [OR4F5, ENSEMBL, UCSC, CCDS30547, HGNC]\n",
500
+ "1 TC0100006476.hg.1 [SAMD11, ENSEMBL, BC024295, MGC, IMAGE, BC0332...\n",
501
+ "2 TC0100006479.hg.1 [KLHL17, ENSEMBL, BC166618, IMAGE, MGC, CCDS30...\n",
502
+ "Number of probes in expression data: 27189\n",
503
+ "Number of probes in mapping data: 21447\n",
504
+ "Number of overlapping probes: 21447\n",
505
+ "Applying gene mapping with 21447 mapped probes...\n",
506
+ "Resulting gene expression data shape: (0, 137)\n",
507
+ "Sample of gene symbols: []\n",
508
+ "Normalizing gene symbols...\n",
509
+ "Final gene expression data shape after normalization: (0, 137)\n",
510
+ "Final sample of gene symbols: []\n",
511
+ "Gene expression data saved to ../../output/preprocess/COVID-19/gene_data/GSE212866.csv\n"
512
+ ]
513
+ }
514
+ ],
515
+ "source": [
516
+ "# 1. Step 1: Observe the gene identifiers in the gene expression data and find corresponding columns in gene annotation\n",
517
+ "# From the previous steps, we can see:\n",
518
+ "# - Gene expression data has numeric IDs starting with numbers like '23064070'\n",
519
+ "# - Gene annotation data has alphanumeric IDs in the 'ID' column like 'TC0100006437.hg.1'\n",
520
+ "\n",
521
+ "# Unfortunately, the probe IDs in the expression data don't directly match the IDs in the annotation data.\n",
522
+ "# We need to check if there's a way to map between them.\n",
523
+ "\n",
524
+ "# Extract expression data again to verify its structure\n",
525
+ "gene_data = get_genetic_data(matrix_file)\n",
526
+ "print(f\"Gene expression data shape: {gene_data.shape}\")\n",
527
+ "print(f\"Gene expression index type: {gene_data.index.dtype}\")\n",
528
+ "print(f\"First few gene IDs: {gene_data.index[:5].tolist()}\")\n",
529
+ "\n",
530
+ "# We'll create a better mapping by extracting gene symbols from SPOT_ID.1\n",
531
+ "# Create a new mapping dataframe with ID and extracted gene symbols\n",
532
+ "mapping_df = pd.DataFrame()\n",
533
+ "mapping_df['ID'] = gene_annotation['ID']\n",
534
+ "mapping_df['Gene'] = gene_annotation['SPOT_ID.1'].apply(extract_human_gene_symbols)\n",
535
+ "\n",
536
+ "# Filter out entries with empty gene lists\n",
537
+ "mapping_df = mapping_df[mapping_df['Gene'].apply(len) > 0]\n",
538
+ "\n",
539
+ "print(f\"Created mapping dataframe with {len(mapping_df)} rows.\")\n",
540
+ "print(\"Preview of mapping:\")\n",
541
+ "print(mapping_df.head(3))\n",
542
+ "\n",
543
+ "# Check the overlap between probe IDs in expression data and mapping data\n",
544
+ "expression_probes = set(gene_data.index)\n",
545
+ "mapping_probes = set(mapping_df['ID'])\n",
546
+ "overlap = expression_probes.intersection(mapping_probes)\n",
547
+ "\n",
548
+ "print(f\"Number of probes in expression data: {len(expression_probes)}\")\n",
549
+ "print(f\"Number of probes in mapping data: {len(mapping_probes)}\")\n",
550
+ "print(f\"Number of overlapping probes: {len(overlap)}\")\n",
551
+ "\n",
552
+ "# There seems to be a mismatch between probe IDs in expression data and gene annotation.\n",
553
+ "# This is a common issue in GEO datasets. We need to try an alternative approach.\n",
554
+ "\n",
555
+ "# Let's try to directly map using positions if there's a 1:1 correspondence\n",
556
+ "# This assumes the order of probes in gene annotation matches the order in expression data\n",
557
+ "if len(gene_data) == len(gene_annotation) or abs(len(gene_data) - len(gene_annotation)) < 100:\n",
558
+ " print(\"Attempting to map by position due to ID mismatch...\")\n",
559
+ " # Create a mapping from position to gene symbol\n",
560
+ " position_mapping = gene_annotation['SPOT_ID.1'].apply(extract_human_gene_symbols)\n",
561
+ " \n",
562
+ " # Get probe IDs from expression data in their original order\n",
563
+ " probe_ids = gene_data.index.tolist()\n",
564
+ " \n",
565
+ " # Create position-based mapping dataframe\n",
566
+ " position_mapping_df = pd.DataFrame({\n",
567
+ " 'ID': probe_ids[:len(position_mapping)],\n",
568
+ " 'Gene': position_mapping[:len(probe_ids)]\n",
569
+ " })\n",
570
+ " \n",
571
+ " # Filter out entries with empty gene lists\n",
572
+ " position_mapping_df = position_mapping_df[position_mapping_df['Gene'].apply(len) > 0]\n",
573
+ " \n",
574
+ " print(f\"Created position-based mapping with {len(position_mapping_df)} rows.\")\n",
575
+ " print(\"Preview of position-based mapping:\")\n",
576
+ " print(position_mapping_df.head(3))\n",
577
+ " \n",
578
+ " # Use this mapping instead if it has more entries\n",
579
+ " if len(position_mapping_df) > len(mapping_df):\n",
580
+ " mapping_df = position_mapping_df\n",
581
+ " print(\"Using position-based mapping as it has more entries.\")\n",
582
+ "\n",
583
+ "# If we still don't have a proper mapping or the overlap is too small,\n",
584
+ "# let's create a custom mapping based on the ID ranges\n",
585
+ "if len(overlap) < 1000:\n",
586
+ " print(\"Creating custom mapping based on probe ID patterns...\")\n",
587
+ " # In GSE212866, looking at the IDs from gene_data vs gene_annotation:\n",
588
+ " # Gene expression data has numeric IDs (e.g., '23064070')\n",
589
+ " # Gene annotation has different format IDs (e.g., 'TC0100006437.hg.1')\n",
590
+ " \n",
591
+ " # Check if there's a pattern in the SPOT_ID.1 column that contains both numeric IDs and gene symbols\n",
592
+ " print(\"Checking for ID patterns in SPOT_ID.1...\")\n",
593
+ " \n",
594
+ " # Given the apparent mismatch, we can create a direct mapping based on the row position\n",
595
+ " # Assuming the probe order is preserved between the two files\n",
596
+ " # This is risky but may be our best option in this specific dataset\n",
597
+ " \n",
598
+ " # Extract gene symbols from each annotation entry\n",
599
+ " gene_symbols = gene_annotation['SPOT_ID.1'].apply(extract_human_gene_symbols)\n",
600
+ " \n",
601
+ " # Create a dataframe with expression IDs and corresponding gene symbols\n",
602
+ " # Taking the minimum length to avoid index errors\n",
603
+ " min_length = min(len(gene_data.index), len(gene_symbols))\n",
604
+ " \n",
605
+ " # Create a mapping from expression IDs to gene symbols\n",
606
+ " position_mapping_df = pd.DataFrame({\n",
607
+ " 'ID': gene_data.index[:min_length],\n",
608
+ " 'Gene': gene_symbols[:min_length]\n",
609
+ " })\n",
610
+ " \n",
611
+ " # Filter rows with empty gene symbols\n",
612
+ " position_mapping_df = position_mapping_df[position_mapping_df['Gene'].apply(len) > 0]\n",
613
+ " \n",
614
+ " print(f\"Created position-based mapping with {len(position_mapping_df)} rows\")\n",
615
+ " mapping_df = position_mapping_df\n",
616
+ "\n",
617
+ "# 3. Apply the gene mapping to convert probe-level measurements to gene-level expression\n",
618
+ "print(f\"Applying gene mapping with {len(mapping_df)} mapped probes...\")\n",
619
+ "gene_data = apply_gene_mapping(gene_data, mapping_df)\n",
620
+ "\n",
621
+ "print(f\"Resulting gene expression data shape: {gene_data.shape}\")\n",
622
+ "print(f\"Sample of gene symbols: {list(gene_data.index[:5])}\")\n",
623
+ "\n",
624
+ "# Normalize gene symbols to handle synonyms and aggregate redundant rows\n",
625
+ "print(\"Normalizing gene symbols...\")\n",
626
+ "gene_data = normalize_gene_symbols_in_index(gene_data)\n",
627
+ "\n",
628
+ "print(f\"Final gene expression data shape after normalization: {gene_data.shape}\")\n",
629
+ "print(f\"Final sample of gene symbols: {list(gene_data.index[:5])}\")\n",
630
+ "\n",
631
+ "# Save the gene data to file\n",
632
+ "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
633
+ "gene_data.to_csv(out_gene_data_file)\n",
634
+ "print(f\"Gene expression data saved to {out_gene_data_file}\")"
635
+ ]
636
+ }
637
+ ],
638
+ "metadata": {
639
+ "language_info": {
640
+ "codemirror_mode": {
641
+ "name": "ipython",
642
+ "version": 3
643
+ },
644
+ "file_extension": ".py",
645
+ "mimetype": "text/x-python",
646
+ "name": "python",
647
+ "nbconvert_exporter": "python",
648
+ "pygments_lexer": "ipython3",
649
+ "version": "3.10.16"
650
+ }
651
+ },
652
+ "nbformat": 4,
653
+ "nbformat_minor": 5
654
+ }
code/COVID-19/GSE213313.ipynb ADDED
@@ -0,0 +1,677 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": 1,
6
+ "id": "ac2d1d5e",
7
+ "metadata": {
8
+ "execution": {
9
+ "iopub.execute_input": "2025-03-25T08:31:11.226771Z",
10
+ "iopub.status.busy": "2025-03-25T08:31:11.226596Z",
11
+ "iopub.status.idle": "2025-03-25T08:31:11.393247Z",
12
+ "shell.execute_reply": "2025-03-25T08:31:11.392890Z"
13
+ }
14
+ },
15
+ "outputs": [],
16
+ "source": [
17
+ "import sys\n",
18
+ "import os\n",
19
+ "sys.path.append(os.path.abspath(os.path.join(os.getcwd(), '../..')))\n",
20
+ "\n",
21
+ "# Path Configuration\n",
22
+ "from tools.preprocess import *\n",
23
+ "\n",
24
+ "# Processing context\n",
25
+ "trait = \"COVID-19\"\n",
26
+ "cohort = \"GSE213313\"\n",
27
+ "\n",
28
+ "# Input paths\n",
29
+ "in_trait_dir = \"../../input/GEO/COVID-19\"\n",
30
+ "in_cohort_dir = \"../../input/GEO/COVID-19/GSE213313\"\n",
31
+ "\n",
32
+ "# Output paths\n",
33
+ "out_data_file = \"../../output/preprocess/COVID-19/GSE213313.csv\"\n",
34
+ "out_gene_data_file = \"../../output/preprocess/COVID-19/gene_data/GSE213313.csv\"\n",
35
+ "out_clinical_data_file = \"../../output/preprocess/COVID-19/clinical_data/GSE213313.csv\"\n",
36
+ "json_path = \"../../output/preprocess/COVID-19/cohort_info.json\"\n"
37
+ ]
38
+ },
39
+ {
40
+ "cell_type": "markdown",
41
+ "id": "41d885f6",
42
+ "metadata": {},
43
+ "source": [
44
+ "### Step 1: Initial Data Loading"
45
+ ]
46
+ },
47
+ {
48
+ "cell_type": "code",
49
+ "execution_count": 2,
50
+ "id": "c17b6736",
51
+ "metadata": {
52
+ "execution": {
53
+ "iopub.execute_input": "2025-03-25T08:31:11.394731Z",
54
+ "iopub.status.busy": "2025-03-25T08:31:11.394586Z",
55
+ "iopub.status.idle": "2025-03-25T08:31:11.548047Z",
56
+ "shell.execute_reply": "2025-03-25T08:31:11.547665Z"
57
+ }
58
+ },
59
+ "outputs": [
60
+ {
61
+ "name": "stdout",
62
+ "output_type": "stream",
63
+ "text": [
64
+ "Background Information:\n",
65
+ "!Series_title\t\"Serial whole blood transcriptomic analysis demonstrates activation of neutrophils, platelets and coagulation in severe and critical COVID-19 – submitted\"\n",
66
+ "!Series_summary\t\"Introduction: A maladaptive inflammatory response has been implicated in the pathogenesis of severe and critical COVID-19. This study aimed to characterize the temporal dynamics of this response and investigate whether critical disease is associated with distinct gene expression patterns.\"\n",
67
+ "!Series_summary\t\"Methods: We performed microarray analysis of serial whole blood RNA samples from 19 patients with critical COVID-19, 15 patients with severe but non-critical disease and 11 healthy controls. We assessed whole blood gene expression patterns by differential gene expression analysis, gene set enrichment, two clustering methods and estimated relative leukocyte abundance using CIBERSORT.\"\n",
68
+ "!Series_summary\t\"Results: Neutrophils, platelets, cytokine signaling, and the coagulation system were activated in COVID-19, and more pronounced in critical vs. non-critical disease. We observed two different trajectories of neutrophil-associated genes, indicating the emergence of a more immature neutrophil phenotype over time. Interferon-associated genes were strongly enriched in early COVID-19 before falling markedly, with modest severity-associated differences in trajectory.\"\n",
69
+ "!Series_summary\t\"Conclusions: Severe COVID-19 is associated with a broad inflammatory response, which is more pronounced in critical disease. Our data suggest a progressively more immature circulating neutrophil phenotype over time. Interferon signaling is enriched in COVID-19 but does not seem to drive critical disease.\"\n",
70
+ "!Series_overall_design\t\"Between March and May 2020, 135 patients admitted to Akershus University Hospital with COVID-19 confirmed by SARS-CoV-2 RT-PCR were prospectively recruited to the Coronavirus Disease Mechanisms (COVID MECH) observational cohort study. Thirty-six patients (27%) were admitted to the ICU and 8 (6%) died. Inclusion predated the use of corticosteroids in severe COVID-19. This substudy included 19 patients with critical disease, defined as requiring invasive mechanical ventilation, and 15 patients with non-critical disease receiving supplemental O2. Patients were selected based on the availability of sequential whole blood RNA samples, and time from symptom onset to baseline sampling between five and 15 days. RNA samples from 11 healthy volunteers matched to patients by age and gender served as controls.\"\n",
71
+ "Sample Characteristics Dictionary:\n",
72
+ "{0: ['individual: patient 018', 'individual: patient 053', 'individual: patient 063', 'individual: patient 089', 'individual: patient 115', 'individual: patient 130', 'individual: patient 141', 'individual: patient F014', 'individual: patient 117', 'individual: patient 051', 'individual: patient F016', 'individual: patient 066', 'individual: patient 135', 'individual: patient 062', 'individual: patient 002', 'individual: patient 050', 'individual: patient 061', 'individual: patient 087', 'individual: patient 129', 'individual: patient 138', 'individual: patient F011', 'individual: patient F013', 'individual: patient 086', 'individual: patient 113', 'individual: patient F009', 'individual: patient 022', 'individual: patient 057', 'individual: patient 096', 'individual: patient 091', 'individual: patient F002'], 1: ['disease state: COVID-19', 'disease state: Healthy'], 2: ['severity: Critical', 'severity: Non-critical', 'severity: Healthy'], 3: ['time: T1', 'time: T2', 'time: T3', 'time: T0'], 4: ['tissue: whole blood']}\n"
73
+ ]
74
+ }
75
+ ],
76
+ "source": [
77
+ "from tools.preprocess import *\n",
78
+ "# 1. Identify the paths to the SOFT file and the matrix file\n",
79
+ "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
80
+ "\n",
81
+ "# 2. Read the matrix file to obtain background information and sample characteristics data\n",
82
+ "background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']\n",
83
+ "clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']\n",
84
+ "background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)\n",
85
+ "\n",
86
+ "# 3. Obtain the sample characteristics dictionary from the clinical dataframe\n",
87
+ "sample_characteristics_dict = get_unique_values_by_row(clinical_data)\n",
88
+ "\n",
89
+ "# 4. Explicitly print out all the background information and the sample characteristics dictionary\n",
90
+ "print(\"Background Information:\")\n",
91
+ "print(background_info)\n",
92
+ "print(\"Sample Characteristics Dictionary:\")\n",
93
+ "print(sample_characteristics_dict)\n"
94
+ ]
95
+ },
96
+ {
97
+ "cell_type": "markdown",
98
+ "id": "8d9140fd",
99
+ "metadata": {},
100
+ "source": [
101
+ "### Step 2: Dataset Analysis and Clinical Feature Extraction"
102
+ ]
103
+ },
104
+ {
105
+ "cell_type": "code",
106
+ "execution_count": 3,
107
+ "id": "db007bc6",
108
+ "metadata": {
109
+ "execution": {
110
+ "iopub.execute_input": "2025-03-25T08:31:11.549298Z",
111
+ "iopub.status.busy": "2025-03-25T08:31:11.549183Z",
112
+ "iopub.status.idle": "2025-03-25T08:31:11.553812Z",
113
+ "shell.execute_reply": "2025-03-25T08:31:11.553508Z"
114
+ }
115
+ },
116
+ "outputs": [],
117
+ "source": [
118
+ "import os\n",
119
+ "import pandas as pd\n",
120
+ "import re\n",
121
+ "import json\n",
122
+ "from typing import Callable, Optional, Dict, Any\n",
123
+ "\n",
124
+ "# 1. Gene Expression Data Availability\n",
125
+ "# Based on the background information, this is a microarray analysis of whole blood RNA samples\n",
126
+ "# which indicates gene expression data should be available\n",
127
+ "is_gene_available = True\n",
128
+ "\n",
129
+ "# 2. Variable Availability and Data Type Conversion\n",
130
+ "\n",
131
+ "# 2.1 Data Availability\n",
132
+ "# For trait (COVID-19 severity):\n",
133
+ "# From the sample characteristics dictionary, key 2 contains severity information\n",
134
+ "trait_row = 2\n",
135
+ "\n",
136
+ "# For age:\n",
137
+ "# There is no age information in the sample characteristics dictionary\n",
138
+ "age_row = None\n",
139
+ "\n",
140
+ "# For gender:\n",
141
+ "# There is no gender information in the sample characteristics dictionary\n",
142
+ "gender_row = None\n",
143
+ "\n",
144
+ "# 2.2 Data Type Conversion\n",
145
+ "\n",
146
+ "# Function to convert trait values (severity)\n",
147
+ "def convert_trait(value):\n",
148
+ " if not isinstance(value, str):\n",
149
+ " return None\n",
150
+ " \n",
151
+ " # Extract the value after colon if present\n",
152
+ " if ':' in value:\n",
153
+ " value = value.split(':', 1)[1].strip()\n",
154
+ " \n",
155
+ " # Convert severity to binary (0 for Non-critical/Healthy, 1 for Critical)\n",
156
+ " if 'critical' in value.lower():\n",
157
+ " return 1\n",
158
+ " elif 'non-critical' in value.lower() or 'healthy' in value.lower():\n",
159
+ " return 0\n",
160
+ " else:\n",
161
+ " return None\n",
162
+ "\n",
163
+ "# Function to convert age (not available in this dataset)\n",
164
+ "def convert_age(value):\n",
165
+ " return None\n",
166
+ "\n",
167
+ "# Function to convert gender (not available in this dataset)\n",
168
+ "def convert_gender(value):\n",
169
+ " return None\n",
170
+ "\n",
171
+ "# 3. Save Metadata\n",
172
+ "# Conduct initial filtering on usability\n",
173
+ "is_trait_available = trait_row is not None\n",
174
+ "validate_and_save_cohort_info(\n",
175
+ " is_final=False,\n",
176
+ " cohort=cohort,\n",
177
+ " info_path=json_path,\n",
178
+ " is_gene_available=is_gene_available,\n",
179
+ " is_trait_available=is_trait_available\n",
180
+ ")\n",
181
+ "\n",
182
+ "# 4. Clinical Feature Extraction\n",
183
+ "if trait_row is not None:\n",
184
+ " # Load the clinical data first (assuming it's available from previous steps)\n",
185
+ " if os.path.exists(os.path.join(in_cohort_dir, \"clinical_data.csv\")):\n",
186
+ " clinical_data = pd.read_csv(os.path.join(in_cohort_dir, \"clinical_data.csv\"))\n",
187
+ " \n",
188
+ " # Extract clinical features using the provided function\n",
189
+ " selected_clinical = geo_select_clinical_features(\n",
190
+ " clinical_df=clinical_data,\n",
191
+ " trait=trait,\n",
192
+ " trait_row=trait_row,\n",
193
+ " convert_trait=convert_trait,\n",
194
+ " age_row=age_row,\n",
195
+ " convert_age=convert_age,\n",
196
+ " gender_row=gender_row,\n",
197
+ " convert_gender=convert_gender\n",
198
+ " )\n",
199
+ " \n",
200
+ " # Preview the selected clinical data\n",
201
+ " preview = preview_df(selected_clinical)\n",
202
+ " print(\"Preview of selected clinical data:\")\n",
203
+ " print(preview)\n",
204
+ " \n",
205
+ " # Save the selected clinical data to the specified output file\n",
206
+ " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
207
+ " selected_clinical.to_csv(out_clinical_data_file, index=False)\n",
208
+ " print(f\"Clinical data saved to {out_clinical_data_file}\")\n"
209
+ ]
210
+ },
211
+ {
212
+ "cell_type": "markdown",
213
+ "id": "e3338e91",
214
+ "metadata": {},
215
+ "source": [
216
+ "### Step 3: Gene Data Extraction"
217
+ ]
218
+ },
219
+ {
220
+ "cell_type": "code",
221
+ "execution_count": 4,
222
+ "id": "4eec8559",
223
+ "metadata": {
224
+ "execution": {
225
+ "iopub.execute_input": "2025-03-25T08:31:11.554978Z",
226
+ "iopub.status.busy": "2025-03-25T08:31:11.554865Z",
227
+ "iopub.status.idle": "2025-03-25T08:31:11.828902Z",
228
+ "shell.execute_reply": "2025-03-25T08:31:11.828504Z"
229
+ }
230
+ },
231
+ "outputs": [
232
+ {
233
+ "name": "stdout",
234
+ "output_type": "stream",
235
+ "text": [
236
+ "SOFT file: ../../input/GEO/COVID-19/GSE213313/GSE213313_family.soft.gz\n",
237
+ "Matrix file: ../../input/GEO/COVID-19/GSE213313/GSE213313_series_matrix.txt.gz\n",
238
+ "Found the matrix table marker at line 66\n"
239
+ ]
240
+ },
241
+ {
242
+ "name": "stdout",
243
+ "output_type": "stream",
244
+ "text": [
245
+ "Gene data shape: (25469, 94)\n",
246
+ "First 20 gene/probe identifiers:\n",
247
+ "['A_19_P00315452', 'A_19_P00315492', 'A_19_P00315493', 'A_19_P00315506', 'A_19_P00315529', 'A_19_P00315543', 'A_19_P00315551', 'A_19_P00315581', 'A_19_P00315584', 'A_19_P00315593', 'A_19_P00315603', 'A_19_P00315649', 'A_19_P00315668', 'A_19_P00315716', 'A_19_P00315753', 'A_19_P00315764', 'A_19_P00315780', 'A_19_P00315810', 'A_19_P00315824', 'A_19_P00315843']\n"
248
+ ]
249
+ }
250
+ ],
251
+ "source": [
252
+ "# 1. Identify the paths to the SOFT file and the matrix file\n",
253
+ "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
254
+ "print(f\"SOFT file: {soft_file}\")\n",
255
+ "print(f\"Matrix file: {matrix_file}\")\n",
256
+ "\n",
257
+ "# Set gene availability flag\n",
258
+ "is_gene_available = True # Initially assume gene data is available\n",
259
+ "\n",
260
+ "# First check if the matrix file contains the expected marker\n",
261
+ "found_marker = False\n",
262
+ "marker_row = None\n",
263
+ "try:\n",
264
+ " with gzip.open(matrix_file, 'rt') as file:\n",
265
+ " for i, line in enumerate(file):\n",
266
+ " if \"!series_matrix_table_begin\" in line:\n",
267
+ " found_marker = True\n",
268
+ " marker_row = i\n",
269
+ " print(f\"Found the matrix table marker at line {i}\")\n",
270
+ " break\n",
271
+ " \n",
272
+ " if not found_marker:\n",
273
+ " print(\"Warning: Could not find '!series_matrix_table_begin' marker in the file.\")\n",
274
+ " is_gene_available = False\n",
275
+ " \n",
276
+ " # If marker was found, try to extract gene data\n",
277
+ " if is_gene_available:\n",
278
+ " try:\n",
279
+ " # Try using the library function\n",
280
+ " gene_data = get_genetic_data(matrix_file)\n",
281
+ " \n",
282
+ " if gene_data.shape[0] == 0:\n",
283
+ " print(\"Warning: Extracted gene data has 0 rows.\")\n",
284
+ " is_gene_available = False\n",
285
+ " else:\n",
286
+ " print(f\"Gene data shape: {gene_data.shape}\")\n",
287
+ " # Print the first 20 gene/probe identifiers\n",
288
+ " print(\"First 20 gene/probe identifiers:\")\n",
289
+ " print(gene_data.index[:20].tolist())\n",
290
+ " except Exception as e:\n",
291
+ " print(f\"Error extracting gene data with get_genetic_data(): {e}\")\n",
292
+ " is_gene_available = False\n",
293
+ " \n",
294
+ " # If gene data extraction failed, examine file content to diagnose\n",
295
+ " if not is_gene_available:\n",
296
+ " print(\"Examining file content to diagnose the issue:\")\n",
297
+ " try:\n",
298
+ " with gzip.open(matrix_file, 'rt') as file:\n",
299
+ " # Print lines around the marker if found\n",
300
+ " if marker_row is not None:\n",
301
+ " for i, line in enumerate(file):\n",
302
+ " if i >= marker_row - 2 and i <= marker_row + 10:\n",
303
+ " print(f\"Line {i}: {line.strip()[:100]}...\")\n",
304
+ " if i > marker_row + 10:\n",
305
+ " break\n",
306
+ " else:\n",
307
+ " # If marker not found, print first 10 lines\n",
308
+ " for i, line in enumerate(file):\n",
309
+ " if i < 10:\n",
310
+ " print(f\"Line {i}: {line.strip()[:100]}...\")\n",
311
+ " else:\n",
312
+ " break\n",
313
+ " except Exception as e2:\n",
314
+ " print(f\"Error examining file: {e2}\")\n",
315
+ " \n",
316
+ "except Exception as e:\n",
317
+ " print(f\"Error processing file: {e}\")\n",
318
+ " is_gene_available = False\n",
319
+ "\n",
320
+ "# Update validation information if gene data extraction failed\n",
321
+ "if not is_gene_available:\n",
322
+ " print(\"Gene expression data could not be successfully extracted from this dataset.\")\n",
323
+ " # Update the validation record since gene data isn't available\n",
324
+ " is_trait_available = False # We already determined trait data isn't available in step 2\n",
325
+ " validate_and_save_cohort_info(is_final=False, cohort=cohort, info_path=json_path,\n",
326
+ " is_gene_available=is_gene_available, is_trait_available=is_trait_available)\n"
327
+ ]
328
+ },
329
+ {
330
+ "cell_type": "markdown",
331
+ "id": "3d14ffdc",
332
+ "metadata": {},
333
+ "source": [
334
+ "### Step 4: Gene Identifier Review"
335
+ ]
336
+ },
337
+ {
338
+ "cell_type": "code",
339
+ "execution_count": 5,
340
+ "id": "ab06f05b",
341
+ "metadata": {
342
+ "execution": {
343
+ "iopub.execute_input": "2025-03-25T08:31:11.830252Z",
344
+ "iopub.status.busy": "2025-03-25T08:31:11.830128Z",
345
+ "iopub.status.idle": "2025-03-25T08:31:11.832075Z",
346
+ "shell.execute_reply": "2025-03-25T08:31:11.831770Z"
347
+ }
348
+ },
349
+ "outputs": [],
350
+ "source": [
351
+ "# These identifiers (A_19_P...) are Agilent microarray probe IDs, not human gene symbols\n",
352
+ "# They need to be mapped to official gene symbols for downstream analysis\n",
353
+ "requires_gene_mapping = True\n"
354
+ ]
355
+ },
356
+ {
357
+ "cell_type": "markdown",
358
+ "id": "3de4cadf",
359
+ "metadata": {},
360
+ "source": [
361
+ "### Step 5: Gene Annotation"
362
+ ]
363
+ },
364
+ {
365
+ "cell_type": "code",
366
+ "execution_count": 6,
367
+ "id": "ed052b4b",
368
+ "metadata": {
369
+ "execution": {
370
+ "iopub.execute_input": "2025-03-25T08:31:11.833236Z",
371
+ "iopub.status.busy": "2025-03-25T08:31:11.833119Z",
372
+ "iopub.status.idle": "2025-03-25T08:31:15.716377Z",
373
+ "shell.execute_reply": "2025-03-25T08:31:15.716022Z"
374
+ }
375
+ },
376
+ "outputs": [
377
+ {
378
+ "name": "stdout",
379
+ "output_type": "stream",
380
+ "text": [
381
+ "\n",
382
+ "Gene annotation preview:\n",
383
+ "Columns in gene annotation: ['ID', 'CONTROL_TYPE', 'REFSEQ', 'GB_ACC', 'LOCUSLINK_ID', 'GENE_SYMBOL', 'GENE_NAME', 'UNIGENE_ID', 'ENSEMBL_ID', 'ACCESSION_STRING', 'CHROMOSOMAL_LOCATION', 'CYTOBAND', 'DESCRIPTION', 'GO_ID', 'SEQUENCE', 'SPOT_ID']\n",
384
+ "{'ID': ['GE_BrightCorner', 'DarkCorner', 'A_21_P0014386'], 'CONTROL_TYPE': ['pos', 'pos', 'FALSE'], 'REFSEQ': [nan, nan, nan], 'GB_ACC': [nan, nan, nan], 'LOCUSLINK_ID': [nan, nan, nan], 'GENE_SYMBOL': [nan, nan, nan], 'GENE_NAME': [nan, nan, nan], 'UNIGENE_ID': [nan, nan, nan], 'ENSEMBL_ID': [nan, nan, nan], 'ACCESSION_STRING': [nan, nan, nan], 'CHROMOSOMAL_LOCATION': [nan, nan, 'unmapped'], 'CYTOBAND': [nan, nan, nan], 'DESCRIPTION': [nan, nan, nan], 'GO_ID': [nan, nan, nan], 'SEQUENCE': [nan, nan, 'AATACATGTTTTGGTAAACACTCGGTCAGAGCACCCTCTTTCTGTGGAATCAGACTGGCA'], 'SPOT_ID': ['GE_BrightCorner', 'DarkCorner', 'A_21_P0014386']}\n",
385
+ "\n",
386
+ "Examining gene mapping columns:\n",
387
+ "Column 'ID' examples:\n",
388
+ "Example 1: GE_BrightCorner\n",
389
+ "Example 2: DarkCorner\n",
390
+ "Example 3: A_21_P0014386\n",
391
+ "Example 4: A_33_P3396872\n",
392
+ "Example 5: A_33_P3267760\n",
393
+ "\n",
394
+ "Column 'GENE_SYMBOL' examples:\n",
395
+ "Example 1: nan\n",
396
+ "Example 2: nan\n",
397
+ "Example 3: nan\n",
398
+ "Example 4: CPED1\n",
399
+ "Example 5: BCOR\n",
400
+ "\n",
401
+ "Gene symbol column completeness: 48862/2452521 rows (1.99%)\n",
402
+ "\n",
403
+ "Columns identified for gene mapping:\n",
404
+ "- 'ID': Contains probe IDs\n",
405
+ "- 'GENE_SYMBOL': Contains gene symbols for mapping\n"
406
+ ]
407
+ }
408
+ ],
409
+ "source": [
410
+ "# 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.\n",
411
+ "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
412
+ "gene_annotation = get_gene_annotation(soft_file)\n",
413
+ "\n",
414
+ "# 2. Analyze the gene annotation dataframe to identify which columns contain the gene identifiers and gene symbols\n",
415
+ "print(\"\\nGene annotation preview:\")\n",
416
+ "print(f\"Columns in gene annotation: {gene_annotation.columns.tolist()}\")\n",
417
+ "print(preview_df(gene_annotation, n=3))\n",
418
+ "\n",
419
+ "# Examine the GENE_SYMBOL column which contains gene symbol information\n",
420
+ "print(\"\\nExamining gene mapping columns:\")\n",
421
+ "print(\"Column 'ID' examples:\")\n",
422
+ "id_samples = gene_annotation['ID'].head(5).tolist()\n",
423
+ "for i, sample in enumerate(id_samples):\n",
424
+ " print(f\"Example {i+1}: {sample}\")\n",
425
+ "\n",
426
+ "print(\"\\nColumn 'GENE_SYMBOL' examples:\")\n",
427
+ "if 'GENE_SYMBOL' in gene_annotation.columns:\n",
428
+ " # Display a few examples of the GENE_SYMBOL column\n",
429
+ " symbol_samples = gene_annotation['GENE_SYMBOL'].head(5).tolist()\n",
430
+ " for i, sample in enumerate(symbol_samples):\n",
431
+ " print(f\"Example {i+1}: {sample}\")\n",
432
+ " \n",
433
+ " # Check the quality and completeness of the GENE_SYMBOL column\n",
434
+ " non_null_symbols = gene_annotation['GENE_SYMBOL'].notna().sum()\n",
435
+ " total_rows = len(gene_annotation)\n",
436
+ " print(f\"\\nGene symbol column completeness: {non_null_symbols}/{total_rows} rows ({non_null_symbols/total_rows:.2%})\")\n",
437
+ " \n",
438
+ " # Identify the columns needed for gene mapping\n",
439
+ " print(\"\\nColumns identified for gene mapping:\")\n",
440
+ " print(\"- 'ID': Contains probe IDs\")\n",
441
+ " print(\"- 'GENE_SYMBOL': Contains gene symbols for mapping\")\n",
442
+ "else:\n",
443
+ " print(\"Error: 'GENE_SYMBOL' column not found in annotation data.\")\n"
444
+ ]
445
+ },
446
+ {
447
+ "cell_type": "markdown",
448
+ "id": "af076b8f",
449
+ "metadata": {},
450
+ "source": [
451
+ "### Step 6: Gene Identifier Mapping"
452
+ ]
453
+ },
454
+ {
455
+ "cell_type": "code",
456
+ "execution_count": 7,
457
+ "id": "62dbfb65",
458
+ "metadata": {
459
+ "execution": {
460
+ "iopub.execute_input": "2025-03-25T08:31:15.717762Z",
461
+ "iopub.status.busy": "2025-03-25T08:31:15.717628Z",
462
+ "iopub.status.idle": "2025-03-25T08:31:16.864550Z",
463
+ "shell.execute_reply": "2025-03-25T08:31:16.864104Z"
464
+ }
465
+ },
466
+ "outputs": [
467
+ {
468
+ "name": "stdout",
469
+ "output_type": "stream",
470
+ "text": [
471
+ "Gene mapping shape: (48862, 2)\n",
472
+ "Gene mapping preview:\n",
473
+ "{'ID': ['A_33_P3396872', 'A_33_P3267760', 'A_32_P194264', 'A_23_P153745', 'A_21_P0014180'], 'Gene': ['CPED1', 'BCOR', 'CHAC2', 'IFI30', 'GPR146']}\n"
474
+ ]
475
+ },
476
+ {
477
+ "name": "stdout",
478
+ "output_type": "stream",
479
+ "text": [
480
+ "Gene expression data shape after mapping: (17305, 94)\n",
481
+ "First few gene symbols after mapping:\n",
482
+ "['A1BG', 'A1BG-AS1', 'A2M-AS1', 'A4GALT', 'AAAS', 'AAAS-1', 'AACS', 'AADACL3', 'AADACP1', 'AAED1']\n",
483
+ "Gene expression data shape after normalization: (14593, 94)\n",
484
+ "First few normalized gene symbols:\n",
485
+ "['A1BG', 'A1BG-AS1', 'A2M-AS1', 'A4GALT', 'AAAS', 'AACS', 'AADACL3', 'AADACP1', 'AAGAB', 'AAK1']\n"
486
+ ]
487
+ },
488
+ {
489
+ "name": "stdout",
490
+ "output_type": "stream",
491
+ "text": [
492
+ "Gene expression data saved to ../../output/preprocess/COVID-19/gene_data/GSE213313.csv\n"
493
+ ]
494
+ }
495
+ ],
496
+ "source": [
497
+ "# 1. Identify which columns to use for mapping\n",
498
+ "# From the gene expression data output, we have IDs like A_19_P00315452\n",
499
+ "# From the gene annotation data, we see the 'ID' column contains similar identifiers\n",
500
+ "# and 'GENE_SYMBOL' contains the human gene symbols we need to map to\n",
501
+ "\n",
502
+ "# 2. Get gene mapping dataframe by extracting the required columns\n",
503
+ "prob_col = 'ID'\n",
504
+ "gene_col = 'GENE_SYMBOL'\n",
505
+ "\n",
506
+ "# Extract the mapping between probe IDs and gene symbols\n",
507
+ "gene_mapping = get_gene_mapping(gene_annotation, prob_col, gene_col)\n",
508
+ "print(f\"Gene mapping shape: {gene_mapping.shape}\")\n",
509
+ "print(\"Gene mapping preview:\")\n",
510
+ "print(preview_df(gene_mapping, n=5))\n",
511
+ "\n",
512
+ "# 3. Convert probe-level measurements to gene expression values\n",
513
+ "# Apply the gene mapping to convert from probe IDs to gene symbols\n",
514
+ "gene_data = apply_gene_mapping(gene_data, gene_mapping)\n",
515
+ "print(f\"Gene expression data shape after mapping: {gene_data.shape}\")\n",
516
+ "print(\"First few gene symbols after mapping:\")\n",
517
+ "print(list(gene_data.index[:10]))\n",
518
+ "\n",
519
+ "# Normalize gene symbols to handle synonyms\n",
520
+ "gene_data = normalize_gene_symbols_in_index(gene_data)\n",
521
+ "print(f\"Gene expression data shape after normalization: {gene_data.shape}\")\n",
522
+ "print(\"First few normalized gene symbols:\")\n",
523
+ "print(list(gene_data.index[:10]))\n",
524
+ "\n",
525
+ "# Save gene data to the specified output file\n",
526
+ "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
527
+ "gene_data.to_csv(out_gene_data_file)\n",
528
+ "print(f\"Gene expression data saved to {out_gene_data_file}\")\n"
529
+ ]
530
+ },
531
+ {
532
+ "cell_type": "markdown",
533
+ "id": "49061ebc",
534
+ "metadata": {},
535
+ "source": [
536
+ "### Step 7: Data Normalization and Linking"
537
+ ]
538
+ },
539
+ {
540
+ "cell_type": "code",
541
+ "execution_count": 8,
542
+ "id": "89299b2c",
543
+ "metadata": {
544
+ "execution": {
545
+ "iopub.execute_input": "2025-03-25T08:31:16.865937Z",
546
+ "iopub.status.busy": "2025-03-25T08:31:16.865802Z",
547
+ "iopub.status.idle": "2025-03-25T08:31:25.439581Z",
548
+ "shell.execute_reply": "2025-03-25T08:31:25.438944Z"
549
+ }
550
+ },
551
+ "outputs": [
552
+ {
553
+ "name": "stdout",
554
+ "output_type": "stream",
555
+ "text": [
556
+ "Gene data shape after normalization: (14593, 94)\n"
557
+ ]
558
+ },
559
+ {
560
+ "name": "stdout",
561
+ "output_type": "stream",
562
+ "text": [
563
+ "Normalized gene data saved to ../../output/preprocess/COVID-19/gene_data/GSE213313.csv\n",
564
+ "Clinical features saved to ../../output/preprocess/COVID-19/clinical_data/GSE213313.csv\n",
565
+ "Clinical features preview:\n",
566
+ "{'COVID-19': [1.0, 1.0, 1.0, 1.0, 1.0]}\n",
567
+ "Linked data shape: (94, 14594)\n"
568
+ ]
569
+ },
570
+ {
571
+ "name": "stdout",
572
+ "output_type": "stream",
573
+ "text": [
574
+ "Linked data shape after handling missing values: (94, 14594)\n",
575
+ "For the feature 'COVID-19', the least common label is '0.0' with 11 occurrences. This represents 11.70% of the dataset.\n",
576
+ "The distribution of the feature 'COVID-19' in this dataset is fine.\n",
577
+ "\n"
578
+ ]
579
+ },
580
+ {
581
+ "name": "stdout",
582
+ "output_type": "stream",
583
+ "text": [
584
+ "Linked data saved to ../../output/preprocess/COVID-19/GSE213313.csv\n"
585
+ ]
586
+ }
587
+ ],
588
+ "source": [
589
+ "# 1. Normalize gene symbols in the gene expression data\n",
590
+ "normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n",
591
+ "print(f\"Gene data shape after normalization: {normalized_gene_data.shape}\")\n",
592
+ "\n",
593
+ "# Create output directory if it doesn't exist\n",
594
+ "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
595
+ "\n",
596
+ "# Save the normalized gene data\n",
597
+ "normalized_gene_data.to_csv(out_gene_data_file)\n",
598
+ "print(f\"Normalized gene data saved to {out_gene_data_file}\")\n",
599
+ "\n",
600
+ "# 2. Extract clinical features using the previously identified feature rows\n",
601
+ "# Use the clinical data from Step 1 and the row identifiers from Step 2\n",
602
+ "clinical_features = geo_select_clinical_features(\n",
603
+ " clinical_data,\n",
604
+ " trait=trait,\n",
605
+ " trait_row=trait_row,\n",
606
+ " convert_trait=convert_trait,\n",
607
+ " age_row=age_row,\n",
608
+ " convert_age=convert_age,\n",
609
+ " gender_row=gender_row,\n",
610
+ " convert_gender=convert_gender\n",
611
+ ")\n",
612
+ "\n",
613
+ "# Create directory for clinical data output\n",
614
+ "os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
615
+ "\n",
616
+ "# Save the clinical features\n",
617
+ "clinical_features.to_csv(out_clinical_data_file)\n",
618
+ "print(f\"Clinical features saved to {out_clinical_data_file}\")\n",
619
+ "\n",
620
+ "# Preview the clinical features\n",
621
+ "clinical_features_preview = preview_df(clinical_features.T)\n",
622
+ "print(\"Clinical features preview:\")\n",
623
+ "print(clinical_features_preview)\n",
624
+ "\n",
625
+ "# 3. Link clinical and genetic data\n",
626
+ "linked_data = geo_link_clinical_genetic_data(clinical_features, normalized_gene_data)\n",
627
+ "print(f\"Linked data shape: {linked_data.shape}\")\n",
628
+ "\n",
629
+ "# 4. Handle missing values in the linked data\n",
630
+ "linked_data = handle_missing_values(linked_data, trait)\n",
631
+ "print(f\"Linked data shape after handling missing values: {linked_data.shape}\")\n",
632
+ "\n",
633
+ "# 5. Determine if trait and demographic features are biased\n",
634
+ "is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n",
635
+ "\n",
636
+ "# 6. Validate and save cohort info\n",
637
+ "is_usable = validate_and_save_cohort_info(\n",
638
+ " is_final=True,\n",
639
+ " cohort=cohort,\n",
640
+ " info_path=json_path,\n",
641
+ " is_gene_available=is_gene_available,\n",
642
+ " is_trait_available=True, # We have trait data as identified in Step 2\n",
643
+ " is_biased=is_biased,\n",
644
+ " df=linked_data,\n",
645
+ " note=\"Dataset contains gene expression data for COVID-19 severity analysis.\"\n",
646
+ ")\n",
647
+ "\n",
648
+ "# 7. Save the linked data if it's usable\n",
649
+ "if is_usable:\n",
650
+ " # Create output directory if it doesn't exist\n",
651
+ " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n",
652
+ " \n",
653
+ " # Save the linked data\n",
654
+ " linked_data.to_csv(out_data_file)\n",
655
+ " print(f\"Linked data saved to {out_data_file}\")\n",
656
+ "else:\n",
657
+ " print(\"Linked data not saved due to quality issues.\")"
658
+ ]
659
+ }
660
+ ],
661
+ "metadata": {
662
+ "language_info": {
663
+ "codemirror_mode": {
664
+ "name": "ipython",
665
+ "version": 3
666
+ },
667
+ "file_extension": ".py",
668
+ "mimetype": "text/x-python",
669
+ "name": "python",
670
+ "nbconvert_exporter": "python",
671
+ "pygments_lexer": "ipython3",
672
+ "version": "3.10.16"
673
+ }
674
+ },
675
+ "nbformat": 4,
676
+ "nbformat_minor": 5
677
+ }
code/COVID-19/GSE216705.ipynb ADDED
@@ -0,0 +1,668 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": 1,
6
+ "id": "92789792",
7
+ "metadata": {
8
+ "execution": {
9
+ "iopub.execute_input": "2025-03-25T08:31:26.480037Z",
10
+ "iopub.status.busy": "2025-03-25T08:31:26.479585Z",
11
+ "iopub.status.idle": "2025-03-25T08:31:26.643901Z",
12
+ "shell.execute_reply": "2025-03-25T08:31:26.643580Z"
13
+ }
14
+ },
15
+ "outputs": [],
16
+ "source": [
17
+ "import sys\n",
18
+ "import os\n",
19
+ "sys.path.append(os.path.abspath(os.path.join(os.getcwd(), '../..')))\n",
20
+ "\n",
21
+ "# Path Configuration\n",
22
+ "from tools.preprocess import *\n",
23
+ "\n",
24
+ "# Processing context\n",
25
+ "trait = \"COVID-19\"\n",
26
+ "cohort = \"GSE216705\"\n",
27
+ "\n",
28
+ "# Input paths\n",
29
+ "in_trait_dir = \"../../input/GEO/COVID-19\"\n",
30
+ "in_cohort_dir = \"../../input/GEO/COVID-19/GSE216705\"\n",
31
+ "\n",
32
+ "# Output paths\n",
33
+ "out_data_file = \"../../output/preprocess/COVID-19/GSE216705.csv\"\n",
34
+ "out_gene_data_file = \"../../output/preprocess/COVID-19/gene_data/GSE216705.csv\"\n",
35
+ "out_clinical_data_file = \"../../output/preprocess/COVID-19/clinical_data/GSE216705.csv\"\n",
36
+ "json_path = \"../../output/preprocess/COVID-19/cohort_info.json\"\n"
37
+ ]
38
+ },
39
+ {
40
+ "cell_type": "markdown",
41
+ "id": "4e575dcb",
42
+ "metadata": {},
43
+ "source": [
44
+ "### Step 1: Initial Data Loading"
45
+ ]
46
+ },
47
+ {
48
+ "cell_type": "code",
49
+ "execution_count": 2,
50
+ "id": "07f964d6",
51
+ "metadata": {
52
+ "execution": {
53
+ "iopub.execute_input": "2025-03-25T08:31:26.645232Z",
54
+ "iopub.status.busy": "2025-03-25T08:31:26.645100Z",
55
+ "iopub.status.idle": "2025-03-25T08:31:26.742874Z",
56
+ "shell.execute_reply": "2025-03-25T08:31:26.742589Z"
57
+ }
58
+ },
59
+ "outputs": [
60
+ {
61
+ "name": "stdout",
62
+ "output_type": "stream",
63
+ "text": [
64
+ "Background Information:\n",
65
+ "!Series_title\t\"Loss of GM-CSF-dependent instruction of alveolar macrophages in COVID-19 provides a rationale for inhaled GM-CSF treatment\"\n",
66
+ "!Series_summary\t\"This SuperSeries is composed of the SubSeries listed below.\"\n",
67
+ "!Series_overall_design\t\"Refer to individual Series\"\n",
68
+ "Sample Characteristics Dictionary:\n",
69
+ "{0: ['strain: C57BL/6'], 1: ['metadata info: metaData_microarrays.txt']}\n"
70
+ ]
71
+ }
72
+ ],
73
+ "source": [
74
+ "from tools.preprocess import *\n",
75
+ "# 1. Identify the paths to the SOFT file and the matrix file\n",
76
+ "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
77
+ "\n",
78
+ "# 2. Read the matrix file to obtain background information and sample characteristics data\n",
79
+ "background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']\n",
80
+ "clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']\n",
81
+ "background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)\n",
82
+ "\n",
83
+ "# 3. Obtain the sample characteristics dictionary from the clinical dataframe\n",
84
+ "sample_characteristics_dict = get_unique_values_by_row(clinical_data)\n",
85
+ "\n",
86
+ "# 4. Explicitly print out all the background information and the sample characteristics dictionary\n",
87
+ "print(\"Background Information:\")\n",
88
+ "print(background_info)\n",
89
+ "print(\"Sample Characteristics Dictionary:\")\n",
90
+ "print(sample_characteristics_dict)\n"
91
+ ]
92
+ },
93
+ {
94
+ "cell_type": "markdown",
95
+ "id": "cddfa4a5",
96
+ "metadata": {},
97
+ "source": [
98
+ "### Step 2: Dataset Analysis and Clinical Feature Extraction"
99
+ ]
100
+ },
101
+ {
102
+ "cell_type": "code",
103
+ "execution_count": 3,
104
+ "id": "785a9429",
105
+ "metadata": {
106
+ "execution": {
107
+ "iopub.execute_input": "2025-03-25T08:31:26.743921Z",
108
+ "iopub.status.busy": "2025-03-25T08:31:26.743820Z",
109
+ "iopub.status.idle": "2025-03-25T08:31:26.750213Z",
110
+ "shell.execute_reply": "2025-03-25T08:31:26.749941Z"
111
+ }
112
+ },
113
+ "outputs": [
114
+ {
115
+ "data": {
116
+ "text/plain": [
117
+ "False"
118
+ ]
119
+ },
120
+ "execution_count": 3,
121
+ "metadata": {},
122
+ "output_type": "execute_result"
123
+ }
124
+ ],
125
+ "source": [
126
+ "# Based on the background information and sample characteristics, let's analyze this dataset\n",
127
+ "\n",
128
+ "# 1. Gene Expression Data Availability\n",
129
+ "# The background information about \"Loss of GM-CSF-dependent instruction of alveolar macrophages in COVID-19\"\n",
130
+ "# suggests this is likely a gene expression dataset studying COVID-19's effects\n",
131
+ "is_gene_available = True\n",
132
+ "\n",
133
+ "# 2. Variable Availability and Data Type Conversion\n",
134
+ "# Looking at the sample characteristics dictionary, we don't see typical human clinical data\n",
135
+ "# The dict shows 'strain: C57BL/6' which indicates this is likely a mouse model study, not human data\n",
136
+ "# and 'metadata info: metaData_microarrays.txt' which refers to external metadata\n",
137
+ "\n",
138
+ "# 2.1 Data Availability\n",
139
+ "# Since we don't see trait, age, or gender data in the sample characteristics,\n",
140
+ "# we'll set all row identifiers to None\n",
141
+ "trait_row = None # No COVID-19 status information in the sample characteristics\n",
142
+ "age_row = None # No age information in the sample characteristics\n",
143
+ "gender_row = None # No gender information in the sample characteristics\n",
144
+ "\n",
145
+ "# 2.2 Data Type Conversion\n",
146
+ "# Define conversion functions in case they're needed, even though we don't have the data\n",
147
+ "def convert_trait(value):\n",
148
+ " if value is None:\n",
149
+ " return None\n",
150
+ " value = value.split(\":\")[-1].strip() if \":\" in value else value.strip()\n",
151
+ " if value.lower() in [\"covid-19\", \"positive\", \"covid\", \"yes\"]:\n",
152
+ " return 1\n",
153
+ " elif value.lower() in [\"healthy\", \"control\", \"negative\", \"no\"]:\n",
154
+ " return 0\n",
155
+ " return None\n",
156
+ "\n",
157
+ "def convert_age(value):\n",
158
+ " if value is None:\n",
159
+ " return None\n",
160
+ " value = value.split(\":\")[-1].strip() if \":\" in value else value.strip()\n",
161
+ " try:\n",
162
+ " return float(value)\n",
163
+ " except ValueError:\n",
164
+ " return None\n",
165
+ "\n",
166
+ "def convert_gender(value):\n",
167
+ " if value is None:\n",
168
+ " return None\n",
169
+ " value = value.split(\":\")[-1].strip() if \":\" in value else value.strip()\n",
170
+ " if value.lower() in [\"female\", \"f\"]:\n",
171
+ " return 0\n",
172
+ " elif value.lower() in [\"male\", \"m\"]:\n",
173
+ " return 1\n",
174
+ " return None\n",
175
+ "\n",
176
+ "# 3. Save Metadata\n",
177
+ "# Trait data is not available since trait_row is None\n",
178
+ "is_trait_available = trait_row is not None\n",
179
+ "\n",
180
+ "# Save initial usability information\n",
181
+ "validate_and_save_cohort_info(\n",
182
+ " is_final=False,\n",
183
+ " cohort=cohort,\n",
184
+ " info_path=json_path,\n",
185
+ " is_gene_available=is_gene_available,\n",
186
+ " is_trait_available=is_trait_available\n",
187
+ ")\n",
188
+ "\n",
189
+ "# 4. Clinical Feature Extraction\n",
190
+ "# Since trait_row is None, we'll skip this substep\n",
191
+ "# If trait_row was not None, we would have executed:\n",
192
+ "# clinical_df = geo_select_clinical_features(\n",
193
+ "# clinical_df=clinical_data,\n",
194
+ "# trait=trait,\n",
195
+ "# trait_row=trait_row,\n",
196
+ "# convert_trait=convert_trait,\n",
197
+ "# age_row=age_row,\n",
198
+ "# convert_age=convert_age,\n",
199
+ "# gender_row=gender_row,\n",
200
+ "# convert_gender=convert_gender\n",
201
+ "# )\n",
202
+ "# preview_df(clinical_df)\n",
203
+ "# clinical_df.to_csv(out_clinical_data_file)\n"
204
+ ]
205
+ },
206
+ {
207
+ "cell_type": "markdown",
208
+ "id": "a619f55c",
209
+ "metadata": {},
210
+ "source": [
211
+ "### Step 3: Gene Data Extraction"
212
+ ]
213
+ },
214
+ {
215
+ "cell_type": "code",
216
+ "execution_count": 4,
217
+ "id": "61a1e12e",
218
+ "metadata": {
219
+ "execution": {
220
+ "iopub.execute_input": "2025-03-25T08:31:26.751206Z",
221
+ "iopub.status.busy": "2025-03-25T08:31:26.751107Z",
222
+ "iopub.status.idle": "2025-03-25T08:31:26.871768Z",
223
+ "shell.execute_reply": "2025-03-25T08:31:26.871401Z"
224
+ }
225
+ },
226
+ "outputs": [
227
+ {
228
+ "name": "stdout",
229
+ "output_type": "stream",
230
+ "text": [
231
+ "SOFT file: ../../input/GEO/COVID-19/GSE216705/GSE216705_family.soft.gz\n",
232
+ "Matrix file: ../../input/GEO/COVID-19/GSE216705/GSE216705-GPL6246_series_matrix.txt.gz\n",
233
+ "Found the matrix table marker at line 62\n",
234
+ "Gene data shape: (35556, 27)\n",
235
+ "First 20 gene/probe identifiers:\n",
236
+ "['10338001', '10338002', '10338003', '10338004', '10338005', '10338006', '10338007', '10338008', '10338009', '10338010', '10338011', '10338012', '10338013', '10338014', '10338015', '10338016', '10338017', '10338018', '10338019', '10338020']\n"
237
+ ]
238
+ }
239
+ ],
240
+ "source": [
241
+ "# 1. Identify the paths to the SOFT file and the matrix file\n",
242
+ "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
243
+ "print(f\"SOFT file: {soft_file}\")\n",
244
+ "print(f\"Matrix file: {matrix_file}\")\n",
245
+ "\n",
246
+ "# Set gene availability flag\n",
247
+ "is_gene_available = True # Initially assume gene data is available\n",
248
+ "\n",
249
+ "# First check if the matrix file contains the expected marker\n",
250
+ "found_marker = False\n",
251
+ "marker_row = None\n",
252
+ "try:\n",
253
+ " with gzip.open(matrix_file, 'rt') as file:\n",
254
+ " for i, line in enumerate(file):\n",
255
+ " if \"!series_matrix_table_begin\" in line:\n",
256
+ " found_marker = True\n",
257
+ " marker_row = i\n",
258
+ " print(f\"Found the matrix table marker at line {i}\")\n",
259
+ " break\n",
260
+ " \n",
261
+ " if not found_marker:\n",
262
+ " print(\"Warning: Could not find '!series_matrix_table_begin' marker in the file.\")\n",
263
+ " is_gene_available = False\n",
264
+ " \n",
265
+ " # If marker was found, try to extract gene data\n",
266
+ " if is_gene_available:\n",
267
+ " try:\n",
268
+ " # Try using the library function\n",
269
+ " gene_data = get_genetic_data(matrix_file)\n",
270
+ " \n",
271
+ " if gene_data.shape[0] == 0:\n",
272
+ " print(\"Warning: Extracted gene data has 0 rows.\")\n",
273
+ " is_gene_available = False\n",
274
+ " else:\n",
275
+ " print(f\"Gene data shape: {gene_data.shape}\")\n",
276
+ " # Print the first 20 gene/probe identifiers\n",
277
+ " print(\"First 20 gene/probe identifiers:\")\n",
278
+ " print(gene_data.index[:20].tolist())\n",
279
+ " except Exception as e:\n",
280
+ " print(f\"Error extracting gene data with get_genetic_data(): {e}\")\n",
281
+ " is_gene_available = False\n",
282
+ " \n",
283
+ " # If gene data extraction failed, examine file content to diagnose\n",
284
+ " if not is_gene_available:\n",
285
+ " print(\"Examining file content to diagnose the issue:\")\n",
286
+ " try:\n",
287
+ " with gzip.open(matrix_file, 'rt') as file:\n",
288
+ " # Print lines around the marker if found\n",
289
+ " if marker_row is not None:\n",
290
+ " for i, line in enumerate(file):\n",
291
+ " if i >= marker_row - 2 and i <= marker_row + 10:\n",
292
+ " print(f\"Line {i}: {line.strip()[:100]}...\")\n",
293
+ " if i > marker_row + 10:\n",
294
+ " break\n",
295
+ " else:\n",
296
+ " # If marker not found, print first 10 lines\n",
297
+ " for i, line in enumerate(file):\n",
298
+ " if i < 10:\n",
299
+ " print(f\"Line {i}: {line.strip()[:100]}...\")\n",
300
+ " else:\n",
301
+ " break\n",
302
+ " except Exception as e2:\n",
303
+ " print(f\"Error examining file: {e2}\")\n",
304
+ " \n",
305
+ "except Exception as e:\n",
306
+ " print(f\"Error processing file: {e}\")\n",
307
+ " is_gene_available = False\n",
308
+ "\n",
309
+ "# Update validation information if gene data extraction failed\n",
310
+ "if not is_gene_available:\n",
311
+ " print(\"Gene expression data could not be successfully extracted from this dataset.\")\n",
312
+ " # Update the validation record since gene data isn't available\n",
313
+ " is_trait_available = False # We already determined trait data isn't available in step 2\n",
314
+ " validate_and_save_cohort_info(is_final=False, cohort=cohort, info_path=json_path,\n",
315
+ " is_gene_available=is_gene_available, is_trait_available=is_trait_available)\n"
316
+ ]
317
+ },
318
+ {
319
+ "cell_type": "markdown",
320
+ "id": "7d3bf662",
321
+ "metadata": {},
322
+ "source": [
323
+ "### Step 4: Gene Identifier Review"
324
+ ]
325
+ },
326
+ {
327
+ "cell_type": "code",
328
+ "execution_count": 5,
329
+ "id": "109711f3",
330
+ "metadata": {
331
+ "execution": {
332
+ "iopub.execute_input": "2025-03-25T08:31:26.873008Z",
333
+ "iopub.status.busy": "2025-03-25T08:31:26.872888Z",
334
+ "iopub.status.idle": "2025-03-25T08:31:26.874784Z",
335
+ "shell.execute_reply": "2025-03-25T08:31:26.874514Z"
336
+ }
337
+ },
338
+ "outputs": [],
339
+ "source": [
340
+ "# Analyzing the gene identifiers provided in the previous output\n",
341
+ "# The identifiers appear to be probe IDs (numeric format like '10338001') rather than standard human gene symbols\n",
342
+ "# Human gene symbols typically follow patterns like \"BRCA1\", \"TP53\", etc.\n",
343
+ "# These numeric identifiers need to be mapped to human gene symbols for meaningful analysis\n",
344
+ "\n",
345
+ "requires_gene_mapping = True\n"
346
+ ]
347
+ },
348
+ {
349
+ "cell_type": "markdown",
350
+ "id": "d9a0110e",
351
+ "metadata": {},
352
+ "source": [
353
+ "### Step 5: Gene Annotation"
354
+ ]
355
+ },
356
+ {
357
+ "cell_type": "code",
358
+ "execution_count": 6,
359
+ "id": "95a5c320",
360
+ "metadata": {
361
+ "execution": {
362
+ "iopub.execute_input": "2025-03-25T08:31:26.875855Z",
363
+ "iopub.status.busy": "2025-03-25T08:31:26.875753Z",
364
+ "iopub.status.idle": "2025-03-25T08:31:29.190497Z",
365
+ "shell.execute_reply": "2025-03-25T08:31:29.190121Z"
366
+ }
367
+ },
368
+ "outputs": [
369
+ {
370
+ "name": "stdout",
371
+ "output_type": "stream",
372
+ "text": [
373
+ "\n",
374
+ "Gene annotation preview:\n",
375
+ "Columns in gene annotation: ['ID', 'GB_LIST', 'SPOT_ID', 'seqname', 'RANGE_GB', 'RANGE_STRAND', 'RANGE_START', 'RANGE_STOP', 'total_probes', 'gene_assignment', 'mrna_assignment', 'category']\n",
376
+ "{'ID': ['10344614', '10344616', '10344618'], 'GB_LIST': ['AK145513,AK145782', nan, nan], 'SPOT_ID': ['chr1:3054233-3054733', 'chr1:3102016-3102125', 'chr1:3276323-3277348'], 'seqname': ['chr1', 'chr1', 'chr1'], 'RANGE_GB': ['NC_000067.6', 'NC_000067.6', 'NC_000067.6'], 'RANGE_STRAND': ['+', '+', '+'], 'RANGE_START': ['3054233', '3102016', '3276323'], 'RANGE_STOP': ['3054733', '3102125', '3277348'], 'total_probes': [33.0, 25.0, 25.0], 'gene_assignment': ['ENSMUST00000160944 // Gm16088 // predicted gene 16088 // --- // --- /// ENSMUST00000120800 // Gm14300 // predicted gene 14300 // --- // --- /// ENSMUST00000179907 // G430049J08Rik // RIKEN cDNA G430049J08 gene // --- // --- /// AK145513 // Gm2889 // predicted gene 2889 // 18 A1|18 // 100040658', 'ENSMUST00000082908 // Gm26206 // predicted gene, 26206 // --- // ---', '---'], 'mrna_assignment': ['ENSMUST00000160944 // ENSEMBL // havana:known chromosome:GRCm38:1:3054233:3054733:1 gene:ENSMUSG00000090025 gene_biotype:pseudogene transcript_biotype:unprocessed_pseudogene // chr1 // 100 // 100 // 33 // 33 // 0 /// ENSMUST00000120800 // ENSEMBL // havana:known chromosome:GRCm38:2:179612622:179613567:-1 gene:ENSMUSG00000083410 gene_biotype:pseudogene transcript_biotype:processed_pseudogene // chr1 // 30 // 100 // 10 // 33 // 0 /// ENSMUST00000179907 // ENSEMBL // ensembl:known chromosome:GRCm38:18:3471630:3474315:1 gene:ENSMUSG00000096528 gene_biotype:protein_coding transcript_biotype:protein_coding // chr1 // 42 // 100 // 14 // 33 // 0 /// AK145513 // GenBank HTC // Mus musculus blastocyst blastocyst cDNA, RIKEN full-length enriched library, clone:I1C0009C06 product:hypothetical DeoxyUTP pyrophosphatase/Aspartyl protease, retroviral-type family profile/Retrovirus capsid, C-terminal/Peptidase aspartic/Peptidase aspartic, active site containing protein, full insert sequence. // chr1 // 24 // 100 // 8 // 33 // 0 /// AK145782 // GenBank HTC // Mus musculus blastocyst blastocyst cDNA, RIKEN full-length enriched library, clone:I1C0042P10 product:hypothetical protein, full insert sequence. // chr1 // 52 // 100 // 17 // 33 // 0 /// KnowTID_00005135 // Luo lincRNA // Non-coding transcript identified by Luo, et al. // chr1 // 52 // 100 // 17 // 33 // 0 /// NONMMUT044096 // NONCODE // Non-coding transcript identified by NONCODE: Linc // chr1 // 52 // 100 // 17 // 33 // 0 /// AK139746 // GenBank HTC // Mus musculus 2 cells egg cDNA, RIKEN full-length enriched library, clone:B020014N01 product:hypothetical protein, full insert sequence. // chr1 // 42 // 100 // 14 // 33 // 0 /// AK145590 // GenBank HTC // Mus musculus blastocyst blastocyst cDNA, RIKEN full-length enriched library, clone:I1C0019N16 product:unclassifiable, full insert sequence. // chr1 // 42 // 100 // 14 // 33 // 0 /// AK145750 // GenBank HTC // Mus musculus blastocyst blastocyst cDNA, RIKEN full-length enriched library, clone:I1C0037K09 product:unclassifiable, full insert sequence. // chr1 // 36 // 85 // 10 // 28 // 0 /// AK165162 // GenBank HTC // Mus musculus 8 cells embryo 8 cells cDNA, RIKEN full-length enriched library, clone:E860009L19 product:unclassifiable, full insert sequence. // chr1 // 48 // 100 // 16 // 33 // 0 /// KnowTID_00001379 // Luo lincRNA // Non-coding transcript identified by Luo, et al. // chr1 // 42 // 100 // 14 // 33 // 0 /// KnowTID_00001380 // Luo lincRNA // Non-coding transcript identified by Luo, et al. // chr1 // 42 // 100 // 14 // 33 // 0 /// KnowTID_00002541 // Luo lincRNA // Non-coding transcript identified by Luo, et al. // chr1 // 36 // 85 // 10 // 28 // 0 /// KnowTID_00003768 // Luo lincRNA // Non-coding transcript identified by Luo, et al. // chr1 // 42 // 100 // 14 // 33 // 0 /// KnowTID_00005134 // Luo lincRNA // Non-coding transcript identified by Luo, et al. // chr1 // 45 // 100 // 15 // 33 // 0 /// NONMMUT013638 // NONCODE // Non-coding transcript identified by NONCODE: Linc // chr1 // 42 // 100 // 14 // 33 // 0 /// NONMMUT013641 // NONCODE // Non-coding transcript identified by NONCODE: Linc // chr1 // 42 // 100 // 14 // 33 // 0 /// NONMMUT021887 // NONCODE // Non-coding transcript identified by NONCODE: Linc // chr1 // 36 // 85 // 10 // 28 // 0 /// NONMMUT044095 // NONCODE // Non-coding transcript identified by NONCODE: Linc // chr1 // 45 // 100 // 15 // 33 // 0 /// NONMMUT046086 // NONCODE // Non-coding transcript identified by NONCODE: Linc // chr1 // 48 // 100 // 16 // 33 // 0 /// NONMMUT046087 // NONCODE // Non-coding transcript identified by NONCODE: Linc // chr1 // 48 // 100 // 16 // 33 // 0 /// AK145700 // GenBank HTC // Mus musculus blastocyst blastocyst cDNA, RIKEN full-length enriched library, clone:I1C0031F10 product:hypothetical protein, full insert sequence. // chr1 // 24 // 100 // 8 // 33 // 0 /// KnowTID_00003789 // Luo lincRNA // Non-coding transcript identified by Luo, et al. // chr1 // 24 // 100 // 8 // 33 // 0 /// NONMMUT031618 // NONCODE // Non-coding transcript identified by NONCODE: Linc // chr1 // 24 // 100 // 8 // 33 // 0 /// KnowTID_00002704 // Luo lincRNA // Non-coding transcript identified by Luo, et al. // chr1 // 24 // 24 // 8 // 33 // 1 /// NONMMUT023055 // NONCODE // Non-coding transcript identified by NONCODE: Linc // chr1 // 24 // 24 // 8 // 33 // 1', 'ENSMUST00000082908 // ENSEMBL // ncrna:known chromosome:GRCm38:1:3102016:3102125:1 gene:ENSMUSG00000064842 gene_biotype:snRNA transcript_biotype:snRNA // chr1 // 100 // 100 // 25 // 25 // 0 /// NONMMUT000002 // NONCODE // Non-coding transcript identified by NONCODE // chr1 // 100 // 100 // 25 // 25 // 0', '---'], 'category': ['main', 'main', 'main']}\n",
377
+ "\n",
378
+ "Examining 'gene_assignment' column examples:\n",
379
+ "Example 1: ENSMUST00000160944 // Gm16088 // predicted gene 16088 // --- // --- /// ENSMUST00000120800 // Gm14300 // predicted gene 14300 // --- // --- /// ENSMUST00000179907 // G430049J08Rik // RIKEN cDNA G43004...\n",
380
+ "Example 2: ENSMUST00000082908 // Gm26206 // predicted gene, 26206 // --- // ---\n",
381
+ "Example 3: ---\n",
382
+ "Example 4: AK140060 // Gm10568 // predicted gene 10568 // --- // 100038431\n",
383
+ "Example 5: ---\n",
384
+ "\n",
385
+ "Gene assignment column completeness: 35556/995596 rows (3.57%)\n",
386
+ "Probes without gene assignments: 8197/995596 rows (0.82%)\n",
387
+ "\n",
388
+ "Columns identified for gene mapping:\n",
389
+ "- 'ID': Contains probe IDs (e.g., 7896736)\n",
390
+ "- 'gene_assignment': Contains gene information that needs parsing to extract gene symbols\n"
391
+ ]
392
+ }
393
+ ],
394
+ "source": [
395
+ "# 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.\n",
396
+ "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
397
+ "gene_annotation = get_gene_annotation(soft_file)\n",
398
+ "\n",
399
+ "# 2. Analyze the gene annotation dataframe to identify which columns contain the gene identifiers and gene symbols\n",
400
+ "print(\"\\nGene annotation preview:\")\n",
401
+ "print(f\"Columns in gene annotation: {gene_annotation.columns.tolist()}\")\n",
402
+ "print(preview_df(gene_annotation, n=3))\n",
403
+ "\n",
404
+ "# Examining the gene_assignment column which appears to contain gene symbol information\n",
405
+ "print(\"\\nExamining 'gene_assignment' column examples:\")\n",
406
+ "if 'gene_assignment' in gene_annotation.columns:\n",
407
+ " # Display a few examples of the gene_assignment column to understand its format\n",
408
+ " gene_samples = gene_annotation['gene_assignment'].head(5).tolist()\n",
409
+ " for i, sample in enumerate(gene_samples):\n",
410
+ " print(f\"Example {i+1}: {sample[:200]}...\" if isinstance(sample, str) and len(sample) > 200 else f\"Example {i+1}: {sample}\")\n",
411
+ " \n",
412
+ " # Check the quality and completeness of the gene_assignment column\n",
413
+ " non_null_assignments = gene_annotation['gene_assignment'].notna().sum()\n",
414
+ " total_rows = len(gene_annotation)\n",
415
+ " print(f\"\\nGene assignment column completeness: {non_null_assignments}/{total_rows} rows ({non_null_assignments/total_rows:.2%})\")\n",
416
+ " \n",
417
+ " # Check for probe IDs without gene assignments (typically '---' entries)\n",
418
+ " missing_assignments = gene_annotation[gene_annotation['gene_assignment'] == '---'].shape[0]\n",
419
+ " print(f\"Probes without gene assignments: {missing_assignments}/{total_rows} rows ({missing_assignments/total_rows:.2%})\")\n",
420
+ " \n",
421
+ " # Identify the columns needed for gene mapping\n",
422
+ " print(\"\\nColumns identified for gene mapping:\")\n",
423
+ " print(\"- 'ID': Contains probe IDs (e.g., 7896736)\")\n",
424
+ " print(\"- 'gene_assignment': Contains gene information that needs parsing to extract gene symbols\")\n",
425
+ "else:\n",
426
+ " print(\"Error: 'gene_assignment' column not found in annotation data.\")\n",
427
+ " print(\"Available columns:\", gene_annotation.columns.tolist())\n"
428
+ ]
429
+ },
430
+ {
431
+ "cell_type": "markdown",
432
+ "id": "e9b7fd0f",
433
+ "metadata": {},
434
+ "source": [
435
+ "### Step 6: Gene Identifier Mapping"
436
+ ]
437
+ },
438
+ {
439
+ "cell_type": "code",
440
+ "execution_count": 7,
441
+ "id": "b706a199",
442
+ "metadata": {
443
+ "execution": {
444
+ "iopub.execute_input": "2025-03-25T08:31:29.191822Z",
445
+ "iopub.status.busy": "2025-03-25T08:31:29.191707Z",
446
+ "iopub.status.idle": "2025-03-25T08:31:30.356745Z",
447
+ "shell.execute_reply": "2025-03-25T08:31:30.356378Z"
448
+ }
449
+ },
450
+ "outputs": [
451
+ {
452
+ "name": "stdout",
453
+ "output_type": "stream",
454
+ "text": [
455
+ "Gene expression data shape: (35556, 27)\n",
456
+ "Sample gene expression IDs: ['10338001', '10338002', '10338003', '10338004', '10338005']\n",
457
+ "Creating gene mapping dataframe...\n"
458
+ ]
459
+ },
460
+ {
461
+ "name": "stdout",
462
+ "output_type": "stream",
463
+ "text": [
464
+ "Mapping dataframe shape: (290501, 2)\n",
465
+ "Sample mapping entries:\n",
466
+ " ID Gene\n",
467
+ "0 10344614 Gm16088\n",
468
+ "0 10344614 Gm14300\n",
469
+ "0 10344614 G430049J08Rik\n",
470
+ "0 10344614 Gm2889\n",
471
+ "1 10344616 Gm26206\n"
472
+ ]
473
+ },
474
+ {
475
+ "name": "stdout",
476
+ "output_type": "stream",
477
+ "text": [
478
+ "Gene expression data after mapping: (290, 27)\n",
479
+ "Sample gene symbols: ['A330087I24', 'A730034C02', 'AA066038', 'AA386476', 'AA388235', 'AA414768', 'AA415398', 'AA467197', 'AA474408', 'AA667203']\n",
480
+ "Gene expression data saved to ../../output/preprocess/COVID-19/gene_data/GSE216705.csv\n"
481
+ ]
482
+ }
483
+ ],
484
+ "source": [
485
+ "# Check the format of IDs in our gene expression data\n",
486
+ "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
487
+ "gene_data = get_genetic_data(matrix_file)\n",
488
+ "print(f\"Gene expression data shape: {gene_data.shape}\")\n",
489
+ "print(f\"Sample gene expression IDs: {gene_data.index[:5].tolist()}\")\n",
490
+ "\n",
491
+ "# Extract the mapping between probe IDs and gene symbols\n",
492
+ "# Based on the previous output, we need the 'ID' column (probe identifiers) and 'gene_assignment' column (gene symbols)\n",
493
+ "print(\"Creating gene mapping dataframe...\")\n",
494
+ "\n",
495
+ "# Create a function to extract gene symbols from gene_assignment string\n",
496
+ "def extract_gene_symbols(gene_assignment_str):\n",
497
+ " if not isinstance(gene_assignment_str, str) or gene_assignment_str == '---':\n",
498
+ " return []\n",
499
+ " \n",
500
+ " # The format appears to be \"ENSMUST... // GeneName // description // --- // ---\"\n",
501
+ " # We want to extract the gene names (second element after '//')\n",
502
+ " genes = []\n",
503
+ " assignments = gene_assignment_str.split('///')\n",
504
+ " for assignment in assignments:\n",
505
+ " parts = assignment.strip().split('//')\n",
506
+ " if len(parts) >= 2:\n",
507
+ " gene_symbol = parts[1].strip()\n",
508
+ " if gene_symbol and gene_symbol != '---':\n",
509
+ " genes.append(gene_symbol)\n",
510
+ " return genes\n",
511
+ "\n",
512
+ "# Apply extraction function to create mapping dataframe\n",
513
+ "gene_annotation['Genes'] = gene_annotation['gene_assignment'].apply(extract_gene_symbols)\n",
514
+ "valid_rows = gene_annotation['Genes'].apply(len) > 0\n",
515
+ "mapping_df = gene_annotation.loc[valid_rows, ['ID', 'Genes']]\n",
516
+ "mapping_df = mapping_df.explode('Genes')\n",
517
+ "mapping_df = mapping_df.rename(columns={'Genes': 'Gene'})\n",
518
+ "print(f\"Mapping dataframe shape: {mapping_df.shape}\")\n",
519
+ "print(\"Sample mapping entries:\")\n",
520
+ "print(mapping_df.head())\n",
521
+ "\n",
522
+ "# Apply gene mapping to convert probe-level measurements to gene expression data\n",
523
+ "gene_data = apply_gene_mapping(gene_data, mapping_df)\n",
524
+ "print(f\"Gene expression data after mapping: {gene_data.shape}\")\n",
525
+ "print(f\"Sample gene symbols: {gene_data.index[:10].tolist()}\")\n",
526
+ "\n",
527
+ "# Save the gene expression data\n",
528
+ "if gene_data.shape[0] > 0:\n",
529
+ " # Create directory if it doesn't exist\n",
530
+ " os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
531
+ " gene_data.to_csv(out_gene_data_file)\n",
532
+ " print(f\"Gene expression data saved to {out_gene_data_file}\")\n",
533
+ "else:\n",
534
+ " print(\"No gene expression data to save after mapping.\")\n"
535
+ ]
536
+ },
537
+ {
538
+ "cell_type": "markdown",
539
+ "id": "d3de0ce4",
540
+ "metadata": {},
541
+ "source": [
542
+ "### Step 7: Data Normalization and Linking"
543
+ ]
544
+ },
545
+ {
546
+ "cell_type": "code",
547
+ "execution_count": 8,
548
+ "id": "d50710f1",
549
+ "metadata": {
550
+ "execution": {
551
+ "iopub.execute_input": "2025-03-25T08:31:30.358105Z",
552
+ "iopub.status.busy": "2025-03-25T08:31:30.357987Z",
553
+ "iopub.status.idle": "2025-03-25T08:31:30.432674Z",
554
+ "shell.execute_reply": "2025-03-25T08:31:30.432306Z"
555
+ }
556
+ },
557
+ "outputs": [
558
+ {
559
+ "name": "stdout",
560
+ "output_type": "stream",
561
+ "text": [
562
+ "Gene data shape after normalization: (34, 27)\n",
563
+ "Normalized gene data saved to ../../output/preprocess/COVID-19/gene_data/GSE216705.csv\n",
564
+ "No clinical features available, skipping clinical data processing.\n",
565
+ "Abnormality detected in the cohort: GSE216705. Preprocessing failed.\n",
566
+ "Linked data not saved due to quality issues or missing trait information.\n"
567
+ ]
568
+ }
569
+ ],
570
+ "source": [
571
+ "# 1. Normalize gene symbols in the gene expression data\n",
572
+ "normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n",
573
+ "print(f\"Gene data shape after normalization: {normalized_gene_data.shape}\")\n",
574
+ "\n",
575
+ "# Create output directory if it doesn't exist\n",
576
+ "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
577
+ "\n",
578
+ "# Save the normalized gene data\n",
579
+ "normalized_gene_data.to_csv(out_gene_data_file)\n",
580
+ "print(f\"Normalized gene data saved to {out_gene_data_file}\")\n",
581
+ "\n",
582
+ "# Determine if trait data is available\n",
583
+ "is_trait_available = trait_row is not None\n",
584
+ "\n",
585
+ "# Skip clinical processing if trait_row is None\n",
586
+ "if is_trait_available:\n",
587
+ " # 2. Extract clinical features using the previously identified feature rows\n",
588
+ " clinical_features = geo_select_clinical_features(\n",
589
+ " clinical_data,\n",
590
+ " trait=trait,\n",
591
+ " trait_row=trait_row,\n",
592
+ " convert_trait=convert_trait,\n",
593
+ " age_row=age_row,\n",
594
+ " convert_age=convert_age,\n",
595
+ " gender_row=gender_row,\n",
596
+ " convert_gender=convert_gender\n",
597
+ " )\n",
598
+ " \n",
599
+ " # Create directory for clinical data output\n",
600
+ " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
601
+ " \n",
602
+ " # Save the clinical features\n",
603
+ " clinical_features.to_csv(out_clinical_data_file)\n",
604
+ " print(f\"Clinical features saved to {out_clinical_data_file}\")\n",
605
+ " \n",
606
+ " # Preview the clinical features\n",
607
+ " clinical_features_preview = preview_df(clinical_features.T)\n",
608
+ " print(\"Clinical features preview:\")\n",
609
+ " print(clinical_features_preview)\n",
610
+ " \n",
611
+ " # 3. Link clinical and genetic data\n",
612
+ " linked_data = geo_link_clinical_genetic_data(clinical_features, normalized_gene_data)\n",
613
+ " print(f\"Linked data shape: {linked_data.shape}\")\n",
614
+ " \n",
615
+ " # 4. Handle missing values in the linked data\n",
616
+ " linked_data = handle_missing_values(linked_data, trait)\n",
617
+ " print(f\"Linked data shape after handling missing values: {linked_data.shape}\")\n",
618
+ " \n",
619
+ " # 5. Determine if trait and demographic features are biased\n",
620
+ " is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n",
621
+ "else:\n",
622
+ " print(\"No clinical features available, skipping clinical data processing.\")\n",
623
+ " # Create a minimal DataFrame with the trait column\n",
624
+ " linked_data = pd.DataFrame({trait: []})\n",
625
+ " is_biased = True # Set to True because without trait data, it's unusable\n",
626
+ "\n",
627
+ "# 6. Validate and save cohort info\n",
628
+ "is_usable = validate_and_save_cohort_info(\n",
629
+ " is_final=True,\n",
630
+ " cohort=cohort,\n",
631
+ " info_path=json_path,\n",
632
+ " is_gene_available=is_gene_available,\n",
633
+ " is_trait_available=is_trait_available,\n",
634
+ " is_biased=is_biased,\n",
635
+ " df=linked_data,\n",
636
+ " note=\"Dataset contains mouse gene expression data but lacks human clinical annotations for COVID-19.\"\n",
637
+ ")\n",
638
+ "\n",
639
+ "# 7. Save the linked data if it's usable\n",
640
+ "if is_usable and is_trait_available:\n",
641
+ " # Create output directory if it doesn't exist\n",
642
+ " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n",
643
+ " \n",
644
+ " # Save the linked data\n",
645
+ " linked_data.to_csv(out_data_file)\n",
646
+ " print(f\"Linked data saved to {out_data_file}\")\n",
647
+ "else:\n",
648
+ " print(\"Linked data not saved due to quality issues or missing trait information.\")"
649
+ ]
650
+ }
651
+ ],
652
+ "metadata": {
653
+ "language_info": {
654
+ "codemirror_mode": {
655
+ "name": "ipython",
656
+ "version": 3
657
+ },
658
+ "file_extension": ".py",
659
+ "mimetype": "text/x-python",
660
+ "name": "python",
661
+ "nbconvert_exporter": "python",
662
+ "pygments_lexer": "ipython3",
663
+ "version": "3.10.16"
664
+ }
665
+ },
666
+ "nbformat": 4,
667
+ "nbformat_minor": 5
668
+ }
code/COVID-19/GSE227080.ipynb ADDED
@@ -0,0 +1,511 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": 1,
6
+ "id": "73691dc0",
7
+ "metadata": {
8
+ "execution": {
9
+ "iopub.execute_input": "2025-03-25T08:31:31.346254Z",
10
+ "iopub.status.busy": "2025-03-25T08:31:31.346017Z",
11
+ "iopub.status.idle": "2025-03-25T08:31:31.516536Z",
12
+ "shell.execute_reply": "2025-03-25T08:31:31.516141Z"
13
+ }
14
+ },
15
+ "outputs": [],
16
+ "source": [
17
+ "import sys\n",
18
+ "import os\n",
19
+ "sys.path.append(os.path.abspath(os.path.join(os.getcwd(), '../..')))\n",
20
+ "\n",
21
+ "# Path Configuration\n",
22
+ "from tools.preprocess import *\n",
23
+ "\n",
24
+ "# Processing context\n",
25
+ "trait = \"COVID-19\"\n",
26
+ "cohort = \"GSE227080\"\n",
27
+ "\n",
28
+ "# Input paths\n",
29
+ "in_trait_dir = \"../../input/GEO/COVID-19\"\n",
30
+ "in_cohort_dir = \"../../input/GEO/COVID-19/GSE227080\"\n",
31
+ "\n",
32
+ "# Output paths\n",
33
+ "out_data_file = \"../../output/preprocess/COVID-19/GSE227080.csv\"\n",
34
+ "out_gene_data_file = \"../../output/preprocess/COVID-19/gene_data/GSE227080.csv\"\n",
35
+ "out_clinical_data_file = \"../../output/preprocess/COVID-19/clinical_data/GSE227080.csv\"\n",
36
+ "json_path = \"../../output/preprocess/COVID-19/cohort_info.json\"\n"
37
+ ]
38
+ },
39
+ {
40
+ "cell_type": "markdown",
41
+ "id": "1e1ef1bf",
42
+ "metadata": {},
43
+ "source": [
44
+ "### Step 1: Initial Data Loading"
45
+ ]
46
+ },
47
+ {
48
+ "cell_type": "code",
49
+ "execution_count": 2,
50
+ "id": "f223171d",
51
+ "metadata": {
52
+ "execution": {
53
+ "iopub.execute_input": "2025-03-25T08:31:31.518009Z",
54
+ "iopub.status.busy": "2025-03-25T08:31:31.517847Z",
55
+ "iopub.status.idle": "2025-03-25T08:31:31.544659Z",
56
+ "shell.execute_reply": "2025-03-25T08:31:31.544327Z"
57
+ }
58
+ },
59
+ "outputs": [
60
+ {
61
+ "name": "stdout",
62
+ "output_type": "stream",
63
+ "text": [
64
+ "Background Information:\n",
65
+ "!Series_title\t\"Early differentially expressed immunological genes in mild and severe COVID-19\"\n",
66
+ "!Series_summary\t\"We retrospectively analysed the expression of 579 immunological genes in 60 COVID-19 subjects (SARS +ve) and 59 COVID-negative (SARS -ve) subjects using the NanoString nCounter (Immunology panel), a technology based on multiplexed single-molecule counting. Biobanked Human peripheral blood mononuclear cells (PBMCs) samples underwent Nucleic Acid extraction and digital detection of mRNA to evaluate changes in antiviral gene expression between SARS -ve controls and patients with mild (SARS +ve Mild) and moderate/severe (SARS +ve Mod/Sev) disease.\"\n",
67
+ "!Series_overall_design\t\"119 samples (60 SARS-CoV-2 positive / 59 SARS-CoV-2 negative)\"\n",
68
+ "Sample Characteristics Dictionary:\n",
69
+ "{0: ['gender: F', 'gender: M'], 1: ['age: 38', 'age: 66', 'age: 21', 'age: 29', 'age: 73', 'age: 35', 'age: 48', 'age: 70', 'age: 69', 'age: 31', 'age: 72', 'age: 41', 'age: 85', 'age: 79', 'age: 46', 'age: 57', 'age: 87', 'age: 52', 'age: 36', 'age: 77', 'age: 82', 'age: 89', 'age: 94', 'age: 54', 'age: 23', 'age: 61', 'age: 75', 'age: 25', 'age: 43', 'age: 24'], 2: ['severity: MILD', 'severity: MOD_SEV', 'severity: NEG']}\n"
70
+ ]
71
+ }
72
+ ],
73
+ "source": [
74
+ "from tools.preprocess import *\n",
75
+ "# 1. Identify the paths to the SOFT file and the matrix file\n",
76
+ "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
77
+ "\n",
78
+ "# 2. Read the matrix file to obtain background information and sample characteristics data\n",
79
+ "background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']\n",
80
+ "clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']\n",
81
+ "background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)\n",
82
+ "\n",
83
+ "# 3. Obtain the sample characteristics dictionary from the clinical dataframe\n",
84
+ "sample_characteristics_dict = get_unique_values_by_row(clinical_data)\n",
85
+ "\n",
86
+ "# 4. Explicitly print out all the background information and the sample characteristics dictionary\n",
87
+ "print(\"Background Information:\")\n",
88
+ "print(background_info)\n",
89
+ "print(\"Sample Characteristics Dictionary:\")\n",
90
+ "print(sample_characteristics_dict)\n"
91
+ ]
92
+ },
93
+ {
94
+ "cell_type": "markdown",
95
+ "id": "79392c3f",
96
+ "metadata": {},
97
+ "source": [
98
+ "### Step 2: Dataset Analysis and Clinical Feature Extraction"
99
+ ]
100
+ },
101
+ {
102
+ "cell_type": "code",
103
+ "execution_count": 3,
104
+ "id": "800842fc",
105
+ "metadata": {
106
+ "execution": {
107
+ "iopub.execute_input": "2025-03-25T08:31:31.545953Z",
108
+ "iopub.status.busy": "2025-03-25T08:31:31.545836Z",
109
+ "iopub.status.idle": "2025-03-25T08:31:31.551564Z",
110
+ "shell.execute_reply": "2025-03-25T08:31:31.551236Z"
111
+ }
112
+ },
113
+ "outputs": [
114
+ {
115
+ "name": "stdout",
116
+ "output_type": "stream",
117
+ "text": [
118
+ "Processing clinical data with sample characteristics\n",
119
+ "Trait row: 2, Age row: 1, Gender row: 0\n",
120
+ "Clinical data is available for processing. Trait data (2): ['severity: MILD', 'severity: MOD_SEV', 'severity: NEG']\n",
121
+ "Age data (1): ['age: 38', 'age: 66', 'age: 21', 'age: 29', 'age: 73']...\n",
122
+ "Gender data (0): ['gender: F', 'gender: M']\n",
123
+ "Clinical feature extraction will be completed when the full dataset is available.\n"
124
+ ]
125
+ }
126
+ ],
127
+ "source": [
128
+ "import numpy as np\n",
129
+ "import pandas as pd\n",
130
+ "import os\n",
131
+ "import json\n",
132
+ "from typing import Optional, Callable, Dict, Any, List\n",
133
+ "\n",
134
+ "# 1. Gene Expression Data Availability\n",
135
+ "# Based on the background information, this dataset contains expression data of 579 immunological genes\n",
136
+ "# This is gene expression data, not miRNA or methylation data\n",
137
+ "is_gene_available = True\n",
138
+ "\n",
139
+ "# 2. Variable Availability and Data Type Conversion\n",
140
+ "# 2.1 Data Availability\n",
141
+ "trait_row = 2 # \"severity\" indicates COVID-19 severity status\n",
142
+ "age_row = 1 # Age information is available\n",
143
+ "gender_row = 0 # Gender information is available\n",
144
+ "\n",
145
+ "# 2.2 Data Type Conversion Functions\n",
146
+ "def convert_trait(value: str) -> int:\n",
147
+ " \"\"\"Convert COVID-19 severity trait to binary (0 for negative/mild, 1 for moderate/severe)\"\"\"\n",
148
+ " if not value or ':' not in value:\n",
149
+ " return None\n",
150
+ " severity = value.split(':', 1)[1].strip().upper()\n",
151
+ " if severity == 'NEG': # COVID-negative\n",
152
+ " return 0\n",
153
+ " elif severity == 'MILD': # Mild COVID\n",
154
+ " return 0\n",
155
+ " elif severity == 'MOD_SEV': # Moderate/Severe COVID\n",
156
+ " return 1\n",
157
+ " return None\n",
158
+ "\n",
159
+ "def convert_age(value: str) -> float:\n",
160
+ " \"\"\"Convert age string to float\"\"\"\n",
161
+ " if not value or ':' not in value:\n",
162
+ " return None\n",
163
+ " age_str = value.split(':', 1)[1].strip()\n",
164
+ " try:\n",
165
+ " return float(age_str)\n",
166
+ " except ValueError:\n",
167
+ " return None\n",
168
+ "\n",
169
+ "def convert_gender(value: str) -> int:\n",
170
+ " \"\"\"Convert gender string to binary (0 for female, 1 for male)\"\"\"\n",
171
+ " if not value or ':' not in value:\n",
172
+ " return None\n",
173
+ " gender = value.split(':', 1)[1].strip().upper()\n",
174
+ " if gender == 'F':\n",
175
+ " return 0\n",
176
+ " elif gender == 'M':\n",
177
+ " return 1\n",
178
+ " return None\n",
179
+ "\n",
180
+ "# 3. Save Metadata\n",
181
+ "# Determine trait data availability\n",
182
+ "is_trait_available = trait_row is not None\n",
183
+ "\n",
184
+ "# Initial filtering and saving metadata\n",
185
+ "validate_and_save_cohort_info(\n",
186
+ " is_final=False,\n",
187
+ " cohort=cohort,\n",
188
+ " info_path=json_path,\n",
189
+ " is_gene_available=is_gene_available,\n",
190
+ " is_trait_available=is_trait_available\n",
191
+ ")\n",
192
+ "\n",
193
+ "# 4. Clinical Feature Extraction\n",
194
+ "# Since trait_row is not None, we need to extract clinical features\n",
195
+ "if trait_row is not None:\n",
196
+ " # Create a DataFrame from the sample characteristics dictionary\n",
197
+ " # This simulates clinical data based on the provided sample characteristics\n",
198
+ " sample_characteristics = {\n",
199
+ " 0: ['gender: F', 'gender: M'], \n",
200
+ " 1: ['age: 38', 'age: 66', 'age: 21', 'age: 29', 'age: 73', 'age: 35', 'age: 48', 'age: 70', 'age: 69', 'age: 31', 'age: 72', 'age: 41', 'age: 85', 'age: 79', 'age: 46', 'age: 57', 'age: 87', 'age: 52', 'age: 36', 'age: 77', 'age: 82', 'age: 89', 'age: 94', 'age: 54', 'age: 23', 'age: 61', 'age: 75', 'age: 25', 'age: 43', 'age: 24'], \n",
201
+ " 2: ['severity: MILD', 'severity: MOD_SEV', 'severity: NEG']\n",
202
+ " }\n",
203
+ " \n",
204
+ " # We don't have the actual samples yet, so we'll create placeholder sample IDs\n",
205
+ " # The actual clinical_data processing will happen later when we have the full data\n",
206
+ " print(\"Processing clinical data with sample characteristics\")\n",
207
+ " print(f\"Trait row: {trait_row}, Age row: {age_row}, Gender row: {gender_row}\")\n",
208
+ " \n",
209
+ " # Since we're just doing initial validation at this point, we'll note that clinical data\n",
210
+ " # is available but requires further processing in subsequent steps\n",
211
+ " print(f\"Clinical data is available for processing. Trait data ({trait_row}): {sample_characteristics[trait_row]}\")\n",
212
+ " print(f\"Age data ({age_row}): {sample_characteristics[age_row][:5]}...\")\n",
213
+ " print(f\"Gender data ({gender_row}): {sample_characteristics[gender_row]}\")\n",
214
+ " \n",
215
+ " # Note: We need the actual GEO data matrix with sample IDs to properly extract clinical features\n",
216
+ " # This will be done in a later step when we have access to the complete dataset\n",
217
+ " print(\"Clinical feature extraction will be completed when the full dataset is available.\")\n"
218
+ ]
219
+ },
220
+ {
221
+ "cell_type": "markdown",
222
+ "id": "dbfaa3fa",
223
+ "metadata": {},
224
+ "source": [
225
+ "### Step 3: Gene Data Extraction"
226
+ ]
227
+ },
228
+ {
229
+ "cell_type": "code",
230
+ "execution_count": 4,
231
+ "id": "4c05bce2",
232
+ "metadata": {
233
+ "execution": {
234
+ "iopub.execute_input": "2025-03-25T08:31:31.552806Z",
235
+ "iopub.status.busy": "2025-03-25T08:31:31.552693Z",
236
+ "iopub.status.idle": "2025-03-25T08:31:31.572345Z",
237
+ "shell.execute_reply": "2025-03-25T08:31:31.572010Z"
238
+ }
239
+ },
240
+ "outputs": [
241
+ {
242
+ "name": "stdout",
243
+ "output_type": "stream",
244
+ "text": [
245
+ "SOFT file: ../../input/GEO/COVID-19/GSE227080/GSE227080_family.soft.gz\n",
246
+ "Matrix file: ../../input/GEO/COVID-19/GSE227080/GSE227080_series_matrix.txt.gz\n",
247
+ "Found the matrix table marker at line 63\n",
248
+ "Gene data shape: (579, 119)\n",
249
+ "First 20 gene/probe identifiers:\n",
250
+ "['ABCB1', 'ABL1', 'ADA', 'AHR', 'AICDA', 'AIRE', 'APP', 'ARG1', 'ARG2', 'ARHGDIB', 'ATG10', 'ATG12', 'ATG16L1', 'ATG5', 'ATG7', 'ATM', 'B2M', 'B3GAT1', 'BATF', 'BATF3']\n"
251
+ ]
252
+ }
253
+ ],
254
+ "source": [
255
+ "# 1. Identify the paths to the SOFT file and the matrix file\n",
256
+ "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
257
+ "print(f\"SOFT file: {soft_file}\")\n",
258
+ "print(f\"Matrix file: {matrix_file}\")\n",
259
+ "\n",
260
+ "# Set gene availability flag\n",
261
+ "is_gene_available = True # Initially assume gene data is available\n",
262
+ "\n",
263
+ "# First check if the matrix file contains the expected marker\n",
264
+ "found_marker = False\n",
265
+ "marker_row = None\n",
266
+ "try:\n",
267
+ " with gzip.open(matrix_file, 'rt') as file:\n",
268
+ " for i, line in enumerate(file):\n",
269
+ " if \"!series_matrix_table_begin\" in line:\n",
270
+ " found_marker = True\n",
271
+ " marker_row = i\n",
272
+ " print(f\"Found the matrix table marker at line {i}\")\n",
273
+ " break\n",
274
+ " \n",
275
+ " if not found_marker:\n",
276
+ " print(\"Warning: Could not find '!series_matrix_table_begin' marker in the file.\")\n",
277
+ " is_gene_available = False\n",
278
+ " \n",
279
+ " # If marker was found, try to extract gene data\n",
280
+ " if is_gene_available:\n",
281
+ " try:\n",
282
+ " # Try using the library function\n",
283
+ " gene_data = get_genetic_data(matrix_file)\n",
284
+ " \n",
285
+ " if gene_data.shape[0] == 0:\n",
286
+ " print(\"Warning: Extracted gene data has 0 rows.\")\n",
287
+ " is_gene_available = False\n",
288
+ " else:\n",
289
+ " print(f\"Gene data shape: {gene_data.shape}\")\n",
290
+ " # Print the first 20 gene/probe identifiers\n",
291
+ " print(\"First 20 gene/probe identifiers:\")\n",
292
+ " print(gene_data.index[:20].tolist())\n",
293
+ " except Exception as e:\n",
294
+ " print(f\"Error extracting gene data with get_genetic_data(): {e}\")\n",
295
+ " is_gene_available = False\n",
296
+ " \n",
297
+ " # If gene data extraction failed, examine file content to diagnose\n",
298
+ " if not is_gene_available:\n",
299
+ " print(\"Examining file content to diagnose the issue:\")\n",
300
+ " try:\n",
301
+ " with gzip.open(matrix_file, 'rt') as file:\n",
302
+ " # Print lines around the marker if found\n",
303
+ " if marker_row is not None:\n",
304
+ " for i, line in enumerate(file):\n",
305
+ " if i >= marker_row - 2 and i <= marker_row + 10:\n",
306
+ " print(f\"Line {i}: {line.strip()[:100]}...\")\n",
307
+ " if i > marker_row + 10:\n",
308
+ " break\n",
309
+ " else:\n",
310
+ " # If marker not found, print first 10 lines\n",
311
+ " for i, line in enumerate(file):\n",
312
+ " if i < 10:\n",
313
+ " print(f\"Line {i}: {line.strip()[:100]}...\")\n",
314
+ " else:\n",
315
+ " break\n",
316
+ " except Exception as e2:\n",
317
+ " print(f\"Error examining file: {e2}\")\n",
318
+ " \n",
319
+ "except Exception as e:\n",
320
+ " print(f\"Error processing file: {e}\")\n",
321
+ " is_gene_available = False\n",
322
+ "\n",
323
+ "# Update validation information if gene data extraction failed\n",
324
+ "if not is_gene_available:\n",
325
+ " print(\"Gene expression data could not be successfully extracted from this dataset.\")\n",
326
+ " # Update the validation record since gene data isn't available\n",
327
+ " is_trait_available = False # We already determined trait data isn't available in step 2\n",
328
+ " validate_and_save_cohort_info(is_final=False, cohort=cohort, info_path=json_path,\n",
329
+ " is_gene_available=is_gene_available, is_trait_available=is_trait_available)\n"
330
+ ]
331
+ },
332
+ {
333
+ "cell_type": "markdown",
334
+ "id": "dcc914f9",
335
+ "metadata": {},
336
+ "source": [
337
+ "### Step 4: Gene Identifier Review"
338
+ ]
339
+ },
340
+ {
341
+ "cell_type": "code",
342
+ "execution_count": 5,
343
+ "id": "0ca9df9e",
344
+ "metadata": {
345
+ "execution": {
346
+ "iopub.execute_input": "2025-03-25T08:31:31.573521Z",
347
+ "iopub.status.busy": "2025-03-25T08:31:31.573407Z",
348
+ "iopub.status.idle": "2025-03-25T08:31:31.575226Z",
349
+ "shell.execute_reply": "2025-03-25T08:31:31.574906Z"
350
+ }
351
+ },
352
+ "outputs": [],
353
+ "source": [
354
+ "# The gene identifiers appear to be standard human gene symbols (like ABCB1, ABL1, ADA, etc.)\n",
355
+ "# These are official gene symbols that don't require mapping to other identifiers\n",
356
+ "\n",
357
+ "requires_gene_mapping = False\n"
358
+ ]
359
+ },
360
+ {
361
+ "cell_type": "markdown",
362
+ "id": "22fede8b",
363
+ "metadata": {},
364
+ "source": [
365
+ "### Step 5: Data Normalization and Linking"
366
+ ]
367
+ },
368
+ {
369
+ "cell_type": "code",
370
+ "execution_count": 6,
371
+ "id": "21361c86",
372
+ "metadata": {
373
+ "execution": {
374
+ "iopub.execute_input": "2025-03-25T08:31:31.576404Z",
375
+ "iopub.status.busy": "2025-03-25T08:31:31.576291Z",
376
+ "iopub.status.idle": "2025-03-25T08:31:31.839969Z",
377
+ "shell.execute_reply": "2025-03-25T08:31:31.839607Z"
378
+ }
379
+ },
380
+ "outputs": [
381
+ {
382
+ "name": "stdout",
383
+ "output_type": "stream",
384
+ "text": [
385
+ "Gene data shape after normalization: (561, 119)\n",
386
+ "Normalized gene data saved to ../../output/preprocess/COVID-19/gene_data/GSE227080.csv\n",
387
+ "Clinical features saved to ../../output/preprocess/COVID-19/clinical_data/GSE227080.csv\n",
388
+ "Clinical features preview:\n",
389
+ "{'COVID-19': [0.0, 1.0, 1.0, 0.0, 1.0], 'Age': [38.0, 66.0, 21.0, 29.0, 73.0], 'Gender': [0.0, 1.0, 1.0, 1.0, 1.0]}\n",
390
+ "Linked data shape: (119, 564)\n",
391
+ "Linked data shape after handling missing values: (119, 564)\n"
392
+ ]
393
+ },
394
+ {
395
+ "name": "stdout",
396
+ "output_type": "stream",
397
+ "text": [
398
+ "For the feature 'COVID-19', the least common label is '1.0' with 34 occurrences. This represents 28.57% of the dataset.\n",
399
+ "The distribution of the feature 'COVID-19' in this dataset is fine.\n",
400
+ "\n"
401
+ ]
402
+ },
403
+ {
404
+ "name": "stdout",
405
+ "output_type": "stream",
406
+ "text": [
407
+ "Quartiles for 'Age':\n",
408
+ " 25%: 47.0\n",
409
+ " 50% (Median): 63.0\n",
410
+ " 75%: 75.0\n",
411
+ "Min: 21.0\n",
412
+ "Max: 94.0\n",
413
+ "The distribution of the feature 'Age' in this dataset is fine.\n",
414
+ "\n",
415
+ "For the feature 'Gender', the least common label is '0.0' with 44 occurrences. This represents 36.97% of the dataset.\n",
416
+ "The distribution of the feature 'Gender' in this dataset is fine.\n",
417
+ "\n",
418
+ "Linked data saved to ../../output/preprocess/COVID-19/GSE227080.csv\n"
419
+ ]
420
+ }
421
+ ],
422
+ "source": [
423
+ "# 1. Normalize gene symbols in the gene expression data\n",
424
+ "normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n",
425
+ "print(f\"Gene data shape after normalization: {normalized_gene_data.shape}\")\n",
426
+ "\n",
427
+ "# Create output directory if it doesn't exist\n",
428
+ "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
429
+ "\n",
430
+ "# Save the normalized gene data\n",
431
+ "normalized_gene_data.to_csv(out_gene_data_file)\n",
432
+ "print(f\"Normalized gene data saved to {out_gene_data_file}\")\n",
433
+ "\n",
434
+ "# 2. Extract clinical features using the previously identified feature rows\n",
435
+ "# Use the clinical data from Step 1 and the row identifiers from Step 2\n",
436
+ "clinical_features = geo_select_clinical_features(\n",
437
+ " clinical_data,\n",
438
+ " trait=trait,\n",
439
+ " trait_row=trait_row,\n",
440
+ " convert_trait=convert_trait,\n",
441
+ " age_row=age_row,\n",
442
+ " convert_age=convert_age,\n",
443
+ " gender_row=gender_row,\n",
444
+ " convert_gender=convert_gender\n",
445
+ ")\n",
446
+ "\n",
447
+ "# Create directory for clinical data output\n",
448
+ "os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
449
+ "\n",
450
+ "# Save the clinical features\n",
451
+ "clinical_features.to_csv(out_clinical_data_file)\n",
452
+ "print(f\"Clinical features saved to {out_clinical_data_file}\")\n",
453
+ "\n",
454
+ "# Preview the clinical features\n",
455
+ "clinical_features_preview = preview_df(clinical_features.T)\n",
456
+ "print(\"Clinical features preview:\")\n",
457
+ "print(clinical_features_preview)\n",
458
+ "\n",
459
+ "# 3. Link clinical and genetic data\n",
460
+ "linked_data = geo_link_clinical_genetic_data(clinical_features, normalized_gene_data)\n",
461
+ "print(f\"Linked data shape: {linked_data.shape}\")\n",
462
+ "\n",
463
+ "# 4. Handle missing values in the linked data\n",
464
+ "linked_data = handle_missing_values(linked_data, trait)\n",
465
+ "print(f\"Linked data shape after handling missing values: {linked_data.shape}\")\n",
466
+ "\n",
467
+ "# 5. Determine if trait and demographic features are biased\n",
468
+ "is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n",
469
+ "\n",
470
+ "# 6. Validate and save cohort info\n",
471
+ "is_usable = validate_and_save_cohort_info(\n",
472
+ " is_final=True,\n",
473
+ " cohort=cohort,\n",
474
+ " info_path=json_path,\n",
475
+ " is_gene_available=is_gene_available,\n",
476
+ " is_trait_available=True, # We have trait data as identified in Step 2\n",
477
+ " is_biased=is_biased,\n",
478
+ " df=linked_data,\n",
479
+ " note=\"Dataset contains gene expression data for COVID-19 severity analysis.\"\n",
480
+ ")\n",
481
+ "\n",
482
+ "# 7. Save the linked data if it's usable\n",
483
+ "if is_usable:\n",
484
+ " # Create output directory if it doesn't exist\n",
485
+ " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n",
486
+ " \n",
487
+ " # Save the linked data\n",
488
+ " linked_data.to_csv(out_data_file)\n",
489
+ " print(f\"Linked data saved to {out_data_file}\")\n",
490
+ "else:\n",
491
+ " print(\"Linked data not saved due to quality issues.\")"
492
+ ]
493
+ }
494
+ ],
495
+ "metadata": {
496
+ "language_info": {
497
+ "codemirror_mode": {
498
+ "name": "ipython",
499
+ "version": 3
500
+ },
501
+ "file_extension": ".py",
502
+ "mimetype": "text/x-python",
503
+ "name": "python",
504
+ "nbconvert_exporter": "python",
505
+ "pygments_lexer": "ipython3",
506
+ "version": "3.10.16"
507
+ }
508
+ },
509
+ "nbformat": 4,
510
+ "nbformat_minor": 5
511
+ }
code/COVID-19/GSE243348.ipynb ADDED
@@ -0,0 +1,558 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": 1,
6
+ "id": "8baceca3",
7
+ "metadata": {
8
+ "execution": {
9
+ "iopub.execute_input": "2025-03-25T08:31:32.694860Z",
10
+ "iopub.status.busy": "2025-03-25T08:31:32.694467Z",
11
+ "iopub.status.idle": "2025-03-25T08:31:32.860457Z",
12
+ "shell.execute_reply": "2025-03-25T08:31:32.860126Z"
13
+ }
14
+ },
15
+ "outputs": [],
16
+ "source": [
17
+ "import sys\n",
18
+ "import os\n",
19
+ "sys.path.append(os.path.abspath(os.path.join(os.getcwd(), '../..')))\n",
20
+ "\n",
21
+ "# Path Configuration\n",
22
+ "from tools.preprocess import *\n",
23
+ "\n",
24
+ "# Processing context\n",
25
+ "trait = \"COVID-19\"\n",
26
+ "cohort = \"GSE243348\"\n",
27
+ "\n",
28
+ "# Input paths\n",
29
+ "in_trait_dir = \"../../input/GEO/COVID-19\"\n",
30
+ "in_cohort_dir = \"../../input/GEO/COVID-19/GSE243348\"\n",
31
+ "\n",
32
+ "# Output paths\n",
33
+ "out_data_file = \"../../output/preprocess/COVID-19/GSE243348.csv\"\n",
34
+ "out_gene_data_file = \"../../output/preprocess/COVID-19/gene_data/GSE243348.csv\"\n",
35
+ "out_clinical_data_file = \"../../output/preprocess/COVID-19/clinical_data/GSE243348.csv\"\n",
36
+ "json_path = \"../../output/preprocess/COVID-19/cohort_info.json\"\n"
37
+ ]
38
+ },
39
+ {
40
+ "cell_type": "markdown",
41
+ "id": "18459c40",
42
+ "metadata": {},
43
+ "source": [
44
+ "### Step 1: Initial Data Loading"
45
+ ]
46
+ },
47
+ {
48
+ "cell_type": "code",
49
+ "execution_count": 2,
50
+ "id": "5b3217be",
51
+ "metadata": {
52
+ "execution": {
53
+ "iopub.execute_input": "2025-03-25T08:31:32.861843Z",
54
+ "iopub.status.busy": "2025-03-25T08:31:32.861701Z",
55
+ "iopub.status.idle": "2025-03-25T08:31:32.883906Z",
56
+ "shell.execute_reply": "2025-03-25T08:31:32.883615Z"
57
+ }
58
+ },
59
+ "outputs": [
60
+ {
61
+ "name": "stdout",
62
+ "output_type": "stream",
63
+ "text": [
64
+ "Background Information:\n",
65
+ "!Series_title\t\"Longitudinal gene expression profiling of self-collected blood samples in COVID-19+ and healthy participants\"\n",
66
+ "!Series_summary\t\"Longitudinal cohort: 773 host response genes were profiled in previously vaccinated (n=16) and unvaccinated (n=14) COVID-19+ participants along with 5 healthy uninfected controls across a 2-week observational window\"\n",
67
+ "!Series_summary\t\"Single timepoint cohort: 773 host response genes were profiled in 6 healthy uninfected participants\"\n",
68
+ "!Series_overall_design\t\"Longitudinal cohort: 30 COVID-19+ and 5 uninfected participants were asked perform self-collection and stabilization of capillary blood using a novel technology (homeRNA) every other day for two weeks (7 longtiudinal timepoints per participant). Temporal kinetics of 773 immune genes were profiled using the nCounter direct digital counting of native mRNA.\"\n",
69
+ "!Series_overall_design\t\"Single timepoint cohort: 6 healthy uninfected participants were asked perform self-collection and stabilization of capillary blood using a novel technology (homeRNA). Temporal kinetics of 773 immune genes were profiled using the nCounter direct digital counting of native mRNA.\"\n",
70
+ "Sample Characteristics Dictionary:\n",
71
+ "{0: ['disease status: COVID-19+', 'disease status: Healthy uninfected'], 1: ['participant id: CB0101', 'participant id: CB0102', 'participant id: CB0104', 'participant id: CB0106', 'participant id: CB0107', 'participant id: CB0111', 'participant id: CB0112', 'participant id: CB0113', 'participant id: CB0115', 'participant id: CB0116', 'participant id: CB0117', 'participant id: CB0118', 'participant id: CB0119', 'participant id: CB0120', 'participant id: CB0121', 'participant id: CB0122', 'participant id: CB0123', 'participant id: CB0124', 'participant id: CB0125', 'participant id: CB0128', 'participant id: CB0129', 'participant id: CB0130', 'participant id: CB0131', 'participant id: CB0132', 'participant id: CB0133', 'participant id: CB0134', 'participant id: CB0135', 'participant id: CB0136', 'participant id: CB0138', 'participant id: CB0139'], 2: ['Sex: female', 'Sex: male'], 3: ['age: 44', 'age: 29', 'age: 51', 'age: 32', 'age: 27', 'age: 30', 'age: 41', 'age: 43', 'age: 34', 'age: 60', 'age: 24', 'age: 36', 'age: 33', 'age: 53', 'age: 31', 'age: 59', 'age: 40', 'age: 65', 'age: 37', 'age: 39', 'age: 58', 'age: 42', 'age: 28', 'age: 38'], 4: ['covid-19 vaccination history: unvaccinated', 'covid-19 vaccination history: vaccinated', 'covid-19 vaccination history: partial'], 5: ['day post symptom onset: 10', 'day post symptom onset: 13', 'day post symptom onset: 15', 'day post symptom onset: 17', 'day post symptom onset: 19', 'day post symptom onset: 21', 'day post symptom onset: 23', 'day post symptom onset: 9', 'day post symptom onset: 11', 'day post symptom onset: 8', 'day post symptom onset: 12', 'day post symptom onset: 14', 'day post symptom onset: 16', 'day post symptom onset: 18', 'day post symptom onset: 20', 'day post symptom onset: 27', 'day post symptom onset: 25', 'day post symptom onset: 5', 'day post symptom onset: 7', 'day post symptom onset: 6', 'day post symptom onset: 22', 'day post symptom onset: 24', 'day post symptom onset: 26', 'day post symptom onset: 28', 'study day: 1', 'study day: 3', 'study day: 5', 'study day: 7', 'study day: 9', 'study day: 11'], 6: ['study day: 1', 'study day: 4', 'study day: 6', 'study day: 8', 'study day: 10', 'study day: 12', 'study day: 14', 'study day: 3', 'study day: 5', 'study day: 9', 'study day: 11', 'study day: 13', 'study day: 7', 'study day: 15', 'ncounter host response codeset: V1.0', 'ncounter host response codeset: V1.1'], 7: ['ncounter host response codeset: V1.0', 'ncounter host response codeset: V1.1', nan]}\n"
72
+ ]
73
+ }
74
+ ],
75
+ "source": [
76
+ "from tools.preprocess import *\n",
77
+ "# 1. Identify the paths to the SOFT file and the matrix file\n",
78
+ "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
79
+ "\n",
80
+ "# 2. Read the matrix file to obtain background information and sample characteristics data\n",
81
+ "background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']\n",
82
+ "clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']\n",
83
+ "background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)\n",
84
+ "\n",
85
+ "# 3. Obtain the sample characteristics dictionary from the clinical dataframe\n",
86
+ "sample_characteristics_dict = get_unique_values_by_row(clinical_data)\n",
87
+ "\n",
88
+ "# 4. Explicitly print out all the background information and the sample characteristics dictionary\n",
89
+ "print(\"Background Information:\")\n",
90
+ "print(background_info)\n",
91
+ "print(\"Sample Characteristics Dictionary:\")\n",
92
+ "print(sample_characteristics_dict)\n"
93
+ ]
94
+ },
95
+ {
96
+ "cell_type": "markdown",
97
+ "id": "4c297b26",
98
+ "metadata": {},
99
+ "source": [
100
+ "### Step 2: Dataset Analysis and Clinical Feature Extraction"
101
+ ]
102
+ },
103
+ {
104
+ "cell_type": "code",
105
+ "execution_count": 3,
106
+ "id": "f3d4de96",
107
+ "metadata": {
108
+ "execution": {
109
+ "iopub.execute_input": "2025-03-25T08:31:32.884964Z",
110
+ "iopub.status.busy": "2025-03-25T08:31:32.884858Z",
111
+ "iopub.status.idle": "2025-03-25T08:31:32.918521Z",
112
+ "shell.execute_reply": "2025-03-25T08:31:32.918240Z"
113
+ }
114
+ },
115
+ "outputs": [
116
+ {
117
+ "name": "stdout",
118
+ "output_type": "stream",
119
+ "text": [
120
+ "Clinical data preview:\n",
121
+ "{'sample_0': [1.0, nan, nan], 'sample_1': [0.0, nan, nan], 'sample_2': [nan, nan, nan], 'sample_3': [nan, nan, nan], 'sample_4': [nan, nan, nan], 'sample_5': [nan, nan, nan], 'sample_6': [nan, nan, nan], 'sample_7': [nan, nan, nan], 'sample_8': [nan, nan, nan], 'sample_9': [nan, nan, nan], 'sample_10': [nan, nan, nan], 'sample_11': [nan, nan, nan], 'sample_12': [nan, nan, nan], 'sample_13': [nan, nan, nan], 'sample_14': [nan, nan, nan], 'sample_15': [nan, nan, nan], 'sample_16': [nan, nan, nan], 'sample_17': [nan, nan, nan], 'sample_18': [nan, nan, nan], 'sample_19': [nan, nan, nan], 'sample_20': [nan, nan, nan], 'sample_21': [nan, nan, nan], 'sample_22': [nan, nan, nan], 'sample_23': [nan, nan, nan], 'sample_24': [nan, nan, nan], 'sample_25': [nan, nan, nan], 'sample_26': [nan, nan, nan], 'sample_27': [nan, nan, nan], 'sample_28': [nan, nan, nan], 'sample_29': [nan, nan, nan], 'sample_30': [nan, nan, nan], 'sample_31': [nan, nan, nan], 'sample_32': [nan, nan, 0.0], 'sample_33': [nan, nan, 1.0], 'sample_34': [nan, 44.0, nan], 'sample_35': [nan, 29.0, nan], 'sample_36': [nan, 51.0, nan], 'sample_37': [nan, 32.0, nan], 'sample_38': [nan, 27.0, nan], 'sample_39': [nan, 30.0, nan], 'sample_40': [nan, 41.0, nan], 'sample_41': [nan, 43.0, nan], 'sample_42': [nan, 34.0, nan], 'sample_43': [nan, 60.0, nan], 'sample_44': [nan, 24.0, nan], 'sample_45': [nan, 36.0, nan], 'sample_46': [nan, 33.0, nan], 'sample_47': [nan, 53.0, nan], 'sample_48': [nan, 31.0, nan], 'sample_49': [nan, 59.0, nan], 'sample_50': [nan, 40.0, nan], 'sample_51': [nan, 65.0, nan], 'sample_52': [nan, 37.0, nan], 'sample_53': [nan, 39.0, nan], 'sample_54': [nan, 58.0, nan], 'sample_55': [nan, 42.0, nan], 'sample_56': [nan, 28.0, nan], 'sample_57': [nan, 38.0, nan], 'sample_58': [nan, nan, nan], 'sample_59': [nan, nan, nan], 'sample_60': [nan, nan, nan], 'sample_61': [nan, nan, nan], 'sample_62': [nan, nan, nan], 'sample_63': [nan, nan, nan], 'sample_64': [nan, nan, nan], 'sample_65': [nan, nan, nan], 'sample_66': [nan, nan, nan], 'sample_67': [nan, nan, nan], 'sample_68': [nan, nan, nan], 'sample_69': [nan, nan, nan], 'sample_70': [nan, nan, nan], 'sample_71': [nan, nan, nan], 'sample_72': [nan, nan, nan], 'sample_73': [nan, nan, nan], 'sample_74': [nan, nan, nan], 'sample_75': [nan, nan, nan], 'sample_76': [nan, nan, nan], 'sample_77': [nan, nan, nan], 'sample_78': [nan, nan, nan], 'sample_79': [nan, nan, nan], 'sample_80': [nan, nan, nan], 'sample_81': [nan, nan, nan], 'sample_82': [nan, nan, nan], 'sample_83': [nan, nan, nan], 'sample_84': [nan, nan, nan], 'sample_85': [nan, nan, nan], 'sample_86': [nan, nan, nan], 'sample_87': [nan, nan, nan], 'sample_88': [nan, nan, nan], 'sample_89': [nan, nan, nan], 'sample_90': [nan, nan, nan], 'sample_91': [nan, nan, nan], 'sample_92': [nan, nan, nan], 'sample_93': [nan, nan, nan], 'sample_94': [nan, nan, nan], 'sample_95': [nan, nan, nan], 'sample_96': [nan, nan, nan], 'sample_97': [nan, nan, nan], 'sample_98': [nan, nan, nan], 'sample_99': [nan, nan, nan], 'sample_100': [nan, nan, nan], 'sample_101': [nan, nan, nan], 'sample_102': [nan, nan, nan], 'sample_103': [nan, nan, nan], 'sample_104': [nan, nan, nan], 'sample_105': [nan, nan, nan], 'sample_106': [nan, nan, nan], 'sample_107': [nan, nan, nan], 'sample_108': [nan, nan, nan], 'sample_109': [nan, nan, nan]}\n",
122
+ "Clinical data saved to ../../output/preprocess/COVID-19/clinical_data/GSE243348.csv\n"
123
+ ]
124
+ },
125
+ {
126
+ "name": "stderr",
127
+ "output_type": "stream",
128
+ "text": [
129
+ "/tmp/ipykernel_75088/1254858355.py:96: PerformanceWarning: DataFrame is highly fragmented. This is usually the result of calling `frame.insert` many times, which has poor performance. Consider joining all columns at once using pd.concat(axis=1) instead. To get a de-fragmented frame, use `newframe = frame.copy()`\n",
130
+ " clinical_data[col_name] = None\n",
131
+ "/tmp/ipykernel_75088/1254858355.py:96: PerformanceWarning: DataFrame is highly fragmented. This is usually the result of calling `frame.insert` many times, which has poor performance. Consider joining all columns at once using pd.concat(axis=1) instead. To get a de-fragmented frame, use `newframe = frame.copy()`\n",
132
+ " clinical_data[col_name] = None\n",
133
+ "/tmp/ipykernel_75088/1254858355.py:96: PerformanceWarning: DataFrame is highly fragmented. This is usually the result of calling `frame.insert` many times, which has poor performance. Consider joining all columns at once using pd.concat(axis=1) instead. To get a de-fragmented frame, use `newframe = frame.copy()`\n",
134
+ " clinical_data[col_name] = None\n",
135
+ "/tmp/ipykernel_75088/1254858355.py:96: PerformanceWarning: DataFrame is highly fragmented. This is usually the result of calling `frame.insert` many times, which has poor performance. Consider joining all columns at once using pd.concat(axis=1) instead. To get a de-fragmented frame, use `newframe = frame.copy()`\n",
136
+ " clinical_data[col_name] = None\n",
137
+ "/tmp/ipykernel_75088/1254858355.py:96: PerformanceWarning: DataFrame is highly fragmented. This is usually the result of calling `frame.insert` many times, which has poor performance. Consider joining all columns at once using pd.concat(axis=1) instead. To get a de-fragmented frame, use `newframe = frame.copy()`\n",
138
+ " clinical_data[col_name] = None\n",
139
+ "/tmp/ipykernel_75088/1254858355.py:96: PerformanceWarning: DataFrame is highly fragmented. This is usually the result of calling `frame.insert` many times, which has poor performance. Consider joining all columns at once using pd.concat(axis=1) instead. To get a de-fragmented frame, use `newframe = frame.copy()`\n",
140
+ " clinical_data[col_name] = None\n",
141
+ "/tmp/ipykernel_75088/1254858355.py:96: PerformanceWarning: DataFrame is highly fragmented. This is usually the result of calling `frame.insert` many times, which has poor performance. Consider joining all columns at once using pd.concat(axis=1) instead. To get a de-fragmented frame, use `newframe = frame.copy()`\n",
142
+ " clinical_data[col_name] = None\n",
143
+ "/tmp/ipykernel_75088/1254858355.py:96: PerformanceWarning: DataFrame is highly fragmented. This is usually the result of calling `frame.insert` many times, which has poor performance. Consider joining all columns at once using pd.concat(axis=1) instead. To get a de-fragmented frame, use `newframe = frame.copy()`\n",
144
+ " clinical_data[col_name] = None\n",
145
+ "/tmp/ipykernel_75088/1254858355.py:96: PerformanceWarning: DataFrame is highly fragmented. This is usually the result of calling `frame.insert` many times, which has poor performance. Consider joining all columns at once using pd.concat(axis=1) instead. To get a de-fragmented frame, use `newframe = frame.copy()`\n",
146
+ " clinical_data[col_name] = None\n",
147
+ "/tmp/ipykernel_75088/1254858355.py:96: PerformanceWarning: DataFrame is highly fragmented. This is usually the result of calling `frame.insert` many times, which has poor performance. Consider joining all columns at once using pd.concat(axis=1) instead. To get a de-fragmented frame, use `newframe = frame.copy()`\n",
148
+ " clinical_data[col_name] = None\n"
149
+ ]
150
+ }
151
+ ],
152
+ "source": [
153
+ "# 1. Gene Expression Data Availability\n",
154
+ "# Based on the background information, this dataset contains gene expression data\n",
155
+ "# \"773 host response genes were profiled using the nCounter direct digital counting of native mRNA\"\n",
156
+ "is_gene_available = True\n",
157
+ "\n",
158
+ "# 2. Variable Availability and Data Type Conversion\n",
159
+ "# 2.1 Data Availability\n",
160
+ "\n",
161
+ "# Trait (COVID-19 status) is in row 0\n",
162
+ "trait_row = 0\n",
163
+ "\n",
164
+ "# Age is in row 3\n",
165
+ "age_row = 3\n",
166
+ "\n",
167
+ "# Gender is in row 2\n",
168
+ "gender_row = 2\n",
169
+ "\n",
170
+ "# 2.2 Data Type Conversion\n",
171
+ "\n",
172
+ "def convert_trait(value: str) -> int:\n",
173
+ " \"\"\"\n",
174
+ " Convert COVID-19 status to binary (0 for healthy, 1 for COVID-19+)\n",
175
+ " \"\"\"\n",
176
+ " if not isinstance(value, str):\n",
177
+ " return None\n",
178
+ " \n",
179
+ " value_lower = value.lower()\n",
180
+ " if 'covid-19+' in value_lower:\n",
181
+ " return 1\n",
182
+ " elif 'healthy' in value_lower:\n",
183
+ " return 0\n",
184
+ " return None\n",
185
+ "\n",
186
+ "def convert_age(value: str) -> float:\n",
187
+ " \"\"\"\n",
188
+ " Convert age values to continuous numeric values\n",
189
+ " \"\"\"\n",
190
+ " if not isinstance(value, str):\n",
191
+ " return None\n",
192
+ " \n",
193
+ " try:\n",
194
+ " # Extract the number after the colon\n",
195
+ " parts = value.split(': ')\n",
196
+ " if len(parts) > 1:\n",
197
+ " return float(parts[1])\n",
198
+ " return None\n",
199
+ " except:\n",
200
+ " return None\n",
201
+ "\n",
202
+ "def convert_gender(value: str) -> int:\n",
203
+ " \"\"\"\n",
204
+ " Convert gender to binary (0 for female, 1 for male)\n",
205
+ " \"\"\"\n",
206
+ " if not isinstance(value, str):\n",
207
+ " return None\n",
208
+ " \n",
209
+ " value_lower = value.lower()\n",
210
+ " if 'female' in value_lower:\n",
211
+ " return 0\n",
212
+ " elif 'male' in value_lower:\n",
213
+ " return 1\n",
214
+ " return None\n",
215
+ "\n",
216
+ "# 3. Save Metadata\n",
217
+ "# Check if trait data is available\n",
218
+ "is_trait_available = trait_row is not None\n",
219
+ "validate_and_save_cohort_info(is_final=False, cohort=cohort, info_path=json_path,\n",
220
+ " is_gene_available=is_gene_available, is_trait_available=is_trait_available)\n",
221
+ "\n",
222
+ "# 4. Clinical Feature Extraction\n",
223
+ "if trait_row is not None:\n",
224
+ " # Sample characteristics were provided in the previous step\n",
225
+ " # Create a properly structured DataFrame where each row is a characteristic\n",
226
+ " # and columns represent different samples\n",
227
+ " \n",
228
+ " # First, create an empty DataFrame with the sample characteristics as rows\n",
229
+ " clinical_data = pd.DataFrame(index=range(8)) # 8 rows for the characteristics\n",
230
+ " \n",
231
+ " # Add sample characteristics as rows\n",
232
+ " sample_chars = {\n",
233
+ " 0: ['disease status: COVID-19+', 'disease status: Healthy uninfected'],\n",
234
+ " 1: ['participant id: CB0101', 'participant id: CB0102', 'participant id: CB0104', 'participant id: CB0106', 'participant id: CB0107', 'participant id: CB0111', 'participant id: CB0112', 'participant id: CB0113', 'participant id: CB0115', 'participant id: CB0116', 'participant id: CB0117', 'participant id: CB0118', 'participant id: CB0119', 'participant id: CB0120', 'participant id: CB0121', 'participant id: CB0122', 'participant id: CB0123', 'participant id: CB0124', 'participant id: CB0125', 'participant id: CB0128', 'participant id: CB0129', 'participant id: CB0130', 'participant id: CB0131', 'participant id: CB0132', 'participant id: CB0133', 'participant id: CB0134', 'participant id: CB0135', 'participant id: CB0136', 'participant id: CB0138', 'participant id: CB0139'],\n",
235
+ " 2: ['Sex: female', 'Sex: male'],\n",
236
+ " 3: ['age: 44', 'age: 29', 'age: 51', 'age: 32', 'age: 27', 'age: 30', 'age: 41', 'age: 43', 'age: 34', 'age: 60', 'age: 24', 'age: 36', 'age: 33', 'age: 53', 'age: 31', 'age: 59', 'age: 40', 'age: 65', 'age: 37', 'age: 39', 'age: 58', 'age: 42', 'age: 28', 'age: 38'],\n",
237
+ " 4: ['covid-19 vaccination history: unvaccinated', 'covid-19 vaccination history: vaccinated', 'covid-19 vaccination history: partial'],\n",
238
+ " 5: ['day post symptom onset: 10', 'day post symptom onset: 13', 'day post symptom onset: 15', 'day post symptom onset: 17', 'day post symptom onset: 19', 'day post symptom onset: 21', 'day post symptom onset: 23', 'day post symptom onset: 9', 'day post symptom onset: 11', 'day post symptom onset: 8', 'day post symptom onset: 12', 'day post symptom onset: 14', 'day post symptom onset: 16', 'day post symptom onset: 18', 'day post symptom onset: 20', 'day post symptom onset: 27', 'day post symptom onset: 25', 'day post symptom onset: 5', 'day post symptom onset: 7', 'day post symptom onset: 6', 'day post symptom onset: 22', 'day post symptom onset: 24', 'day post symptom onset: 26', 'day post symptom onset: 28', 'study day: 1', 'study day: 3', 'study day: 5', 'study day: 7', 'study day: 9', 'study day: 11'],\n",
239
+ " 6: ['study day: 1', 'study day: 4', 'study day: 6', 'study day: 8', 'study day: 10', 'study day: 12', 'study day: 14', 'study day: 3', 'study day: 5', 'study day: 9', 'study day: 11', 'study day: 13', 'study day: 7', 'study day: 15', 'ncounter host response codeset: V1.0', 'ncounter host response codeset: V1.1'],\n",
240
+ " 7: ['ncounter host response codeset: V1.0', 'ncounter host response codeset: V1.1', None]\n",
241
+ " }\n",
242
+ " \n",
243
+ " # Populate the DataFrame with the sample characteristics\n",
244
+ " for idx, values in sample_chars.items():\n",
245
+ " for val in values:\n",
246
+ " # Create a new column for each unique value\n",
247
+ " col_name = f\"sample_{len(clinical_data.columns)}\"\n",
248
+ " clinical_data[col_name] = None\n",
249
+ " clinical_data.at[idx, col_name] = val\n",
250
+ " \n",
251
+ " # Extract clinical features\n",
252
+ " selected_clinical_df = geo_select_clinical_features(\n",
253
+ " clinical_df=clinical_data,\n",
254
+ " trait=trait,\n",
255
+ " trait_row=trait_row,\n",
256
+ " convert_trait=convert_trait,\n",
257
+ " age_row=age_row,\n",
258
+ " convert_age=convert_age,\n",
259
+ " gender_row=gender_row,\n",
260
+ " convert_gender=convert_gender\n",
261
+ " )\n",
262
+ " \n",
263
+ " # Preview and save the data\n",
264
+ " preview = preview_df(selected_clinical_df)\n",
265
+ " print(\"Clinical data preview:\")\n",
266
+ " print(preview)\n",
267
+ " \n",
268
+ " # Create directory if it doesn't exist\n",
269
+ " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
270
+ " \n",
271
+ " # Save the clinical data\n",
272
+ " selected_clinical_df.to_csv(out_clinical_data_file, index=False)\n",
273
+ " print(f\"Clinical data saved to {out_clinical_data_file}\")\n"
274
+ ]
275
+ },
276
+ {
277
+ "cell_type": "markdown",
278
+ "id": "66110b1f",
279
+ "metadata": {},
280
+ "source": [
281
+ "### Step 3: Gene Data Extraction"
282
+ ]
283
+ },
284
+ {
285
+ "cell_type": "code",
286
+ "execution_count": 4,
287
+ "id": "28a1519a",
288
+ "metadata": {
289
+ "execution": {
290
+ "iopub.execute_input": "2025-03-25T08:31:32.919524Z",
291
+ "iopub.status.busy": "2025-03-25T08:31:32.919425Z",
292
+ "iopub.status.idle": "2025-03-25T08:31:32.957929Z",
293
+ "shell.execute_reply": "2025-03-25T08:31:32.957640Z"
294
+ }
295
+ },
296
+ "outputs": [
297
+ {
298
+ "name": "stdout",
299
+ "output_type": "stream",
300
+ "text": [
301
+ "SOFT file: ../../input/GEO/COVID-19/GSE243348/GSE243348_family.soft.gz\n",
302
+ "Matrix file: ../../input/GEO/COVID-19/GSE243348/GSE243348_series_matrix.txt.gz\n",
303
+ "Found the matrix table marker at line 69\n",
304
+ "Gene data shape: (773, 237)\n",
305
+ "First 20 gene/probe identifiers:\n",
306
+ "['ACE', 'ACKR2', 'ACKR3', 'ACKR4', 'ACOX1', 'ACSL1', 'ACSL3', 'ACSL4', 'ACVR1', 'ADAR', 'ADGRE5', 'ADGRG3', 'ADORA2A', 'AGT', 'AHR', 'AIF1', 'AIM2', 'AKT1', 'AKT2', 'AKT3']\n"
307
+ ]
308
+ }
309
+ ],
310
+ "source": [
311
+ "# 1. Identify the paths to the SOFT file and the matrix file\n",
312
+ "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
313
+ "print(f\"SOFT file: {soft_file}\")\n",
314
+ "print(f\"Matrix file: {matrix_file}\")\n",
315
+ "\n",
316
+ "# Set gene availability flag\n",
317
+ "is_gene_available = True # Initially assume gene data is available\n",
318
+ "\n",
319
+ "# First check if the matrix file contains the expected marker\n",
320
+ "found_marker = False\n",
321
+ "marker_row = None\n",
322
+ "try:\n",
323
+ " with gzip.open(matrix_file, 'rt') as file:\n",
324
+ " for i, line in enumerate(file):\n",
325
+ " if \"!series_matrix_table_begin\" in line:\n",
326
+ " found_marker = True\n",
327
+ " marker_row = i\n",
328
+ " print(f\"Found the matrix table marker at line {i}\")\n",
329
+ " break\n",
330
+ " \n",
331
+ " if not found_marker:\n",
332
+ " print(\"Warning: Could not find '!series_matrix_table_begin' marker in the file.\")\n",
333
+ " is_gene_available = False\n",
334
+ " \n",
335
+ " # If marker was found, try to extract gene data\n",
336
+ " if is_gene_available:\n",
337
+ " try:\n",
338
+ " # Try using the library function\n",
339
+ " gene_data = get_genetic_data(matrix_file)\n",
340
+ " \n",
341
+ " if gene_data.shape[0] == 0:\n",
342
+ " print(\"Warning: Extracted gene data has 0 rows.\")\n",
343
+ " is_gene_available = False\n",
344
+ " else:\n",
345
+ " print(f\"Gene data shape: {gene_data.shape}\")\n",
346
+ " # Print the first 20 gene/probe identifiers\n",
347
+ " print(\"First 20 gene/probe identifiers:\")\n",
348
+ " print(gene_data.index[:20].tolist())\n",
349
+ " except Exception as e:\n",
350
+ " print(f\"Error extracting gene data with get_genetic_data(): {e}\")\n",
351
+ " is_gene_available = False\n",
352
+ " \n",
353
+ " # If gene data extraction failed, examine file content to diagnose\n",
354
+ " if not is_gene_available:\n",
355
+ " print(\"Examining file content to diagnose the issue:\")\n",
356
+ " try:\n",
357
+ " with gzip.open(matrix_file, 'rt') as file:\n",
358
+ " # Print lines around the marker if found\n",
359
+ " if marker_row is not None:\n",
360
+ " for i, line in enumerate(file):\n",
361
+ " if i >= marker_row - 2 and i <= marker_row + 10:\n",
362
+ " print(f\"Line {i}: {line.strip()[:100]}...\")\n",
363
+ " if i > marker_row + 10:\n",
364
+ " break\n",
365
+ " else:\n",
366
+ " # If marker not found, print first 10 lines\n",
367
+ " for i, line in enumerate(file):\n",
368
+ " if i < 10:\n",
369
+ " print(f\"Line {i}: {line.strip()[:100]}...\")\n",
370
+ " else:\n",
371
+ " break\n",
372
+ " except Exception as e2:\n",
373
+ " print(f\"Error examining file: {e2}\")\n",
374
+ " \n",
375
+ "except Exception as e:\n",
376
+ " print(f\"Error processing file: {e}\")\n",
377
+ " is_gene_available = False\n",
378
+ "\n",
379
+ "# Update validation information if gene data extraction failed\n",
380
+ "if not is_gene_available:\n",
381
+ " print(\"Gene expression data could not be successfully extracted from this dataset.\")\n",
382
+ " # Update the validation record since gene data isn't available\n",
383
+ " is_trait_available = False # We already determined trait data isn't available in step 2\n",
384
+ " validate_and_save_cohort_info(is_final=False, cohort=cohort, info_path=json_path,\n",
385
+ " is_gene_available=is_gene_available, is_trait_available=is_trait_available)\n"
386
+ ]
387
+ },
388
+ {
389
+ "cell_type": "markdown",
390
+ "id": "0723d070",
391
+ "metadata": {},
392
+ "source": [
393
+ "### Step 4: Gene Identifier Review"
394
+ ]
395
+ },
396
+ {
397
+ "cell_type": "code",
398
+ "execution_count": 5,
399
+ "id": "527c0ff2",
400
+ "metadata": {
401
+ "execution": {
402
+ "iopub.execute_input": "2025-03-25T08:31:32.958909Z",
403
+ "iopub.status.busy": "2025-03-25T08:31:32.958809Z",
404
+ "iopub.status.idle": "2025-03-25T08:31:32.960512Z",
405
+ "shell.execute_reply": "2025-03-25T08:31:32.960251Z"
406
+ }
407
+ },
408
+ "outputs": [],
409
+ "source": [
410
+ "# Review gene identifiers\n",
411
+ "# These identifiers appear to be standard human gene symbols (official gene symbols)\n",
412
+ "# Examples like ACE, ACKR2, AKT1, etc. are recognized human gene symbols\n",
413
+ "# No mapping is required as they are already in the correct format\n",
414
+ "\n",
415
+ "requires_gene_mapping = False\n"
416
+ ]
417
+ },
418
+ {
419
+ "cell_type": "markdown",
420
+ "id": "d153c38f",
421
+ "metadata": {},
422
+ "source": [
423
+ "### Step 5: Data Normalization and Linking"
424
+ ]
425
+ },
426
+ {
427
+ "cell_type": "code",
428
+ "execution_count": 6,
429
+ "id": "57c0706f",
430
+ "metadata": {
431
+ "execution": {
432
+ "iopub.execute_input": "2025-03-25T08:31:32.961470Z",
433
+ "iopub.status.busy": "2025-03-25T08:31:32.961373Z",
434
+ "iopub.status.idle": "2025-03-25T08:31:33.135284Z",
435
+ "shell.execute_reply": "2025-03-25T08:31:33.134966Z"
436
+ }
437
+ },
438
+ "outputs": [
439
+ {
440
+ "name": "stdout",
441
+ "output_type": "stream",
442
+ "text": [
443
+ "Gene data shape after normalization: (758, 237)\n"
444
+ ]
445
+ },
446
+ {
447
+ "name": "stdout",
448
+ "output_type": "stream",
449
+ "text": [
450
+ "Normalized gene data saved to ../../output/preprocess/COVID-19/gene_data/GSE243348.csv\n",
451
+ "Loaded clinical data with shape: (3, 110)\n",
452
+ "Clinical data columns: Index(['sample_0', 'sample_1', 'sample_2', 'sample_3', 'sample_4'], dtype='object') ...\n",
453
+ "Clinical data sparsity: 91.52% missing values\n",
454
+ "Non-NA values per clinical feature: [2, 24, 2]\n",
455
+ "Cannot proceed with linking due to insufficient clinical data (mostly NaN values).\n",
456
+ "Abnormality detected in the cohort: GSE243348. Preprocessing failed.\n"
457
+ ]
458
+ }
459
+ ],
460
+ "source": [
461
+ "# 1. Normalize gene symbols in gene expression data\n",
462
+ "try:\n",
463
+ " # Normalize gene symbols\n",
464
+ " normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n",
465
+ " print(f\"Gene data shape after normalization: {normalized_gene_data.shape}\")\n",
466
+ " \n",
467
+ " # Create output directory if it doesn't exist\n",
468
+ " os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
469
+ " \n",
470
+ " # Save the normalized gene data\n",
471
+ " normalized_gene_data.to_csv(out_gene_data_file)\n",
472
+ " print(f\"Normalized gene data saved to {out_gene_data_file}\")\n",
473
+ " \n",
474
+ " # 2. Attempt to load clinical data and link with genetic data\n",
475
+ " try:\n",
476
+ " # Load clinical data file saved in Step 2\n",
477
+ " clinical_df = pd.read_csv(out_clinical_data_file)\n",
478
+ " print(f\"Loaded clinical data with shape: {clinical_df.shape}\")\n",
479
+ " \n",
480
+ " # Inspect the clinical data structure\n",
481
+ " print(\"Clinical data columns:\", clinical_df.columns[:5], \"...\" if len(clinical_df.columns) > 5 else \"\")\n",
482
+ " \n",
483
+ " # Check for sparsity in clinical data\n",
484
+ " sparsity = clinical_df.isna().sum().sum() / (clinical_df.shape[0] * clinical_df.shape[1])\n",
485
+ " print(f\"Clinical data sparsity: {sparsity:.2%} missing values\")\n",
486
+ " \n",
487
+ " # Count non-NA values in each row of clinical data\n",
488
+ " non_na_counts = clinical_df.notna().sum(axis=1)\n",
489
+ " print(f\"Non-NA values per clinical feature: {non_na_counts.tolist()}\")\n",
490
+ " \n",
491
+ " # Since the clinical data has too many NaN values (as observed in Step 2),\n",
492
+ " # and does not contain proper trait information, we cannot link it effectively\n",
493
+ " is_trait_available = False\n",
494
+ " print(\"Cannot proceed with linking due to insufficient clinical data (mostly NaN values).\")\n",
495
+ " \n",
496
+ " # 5. Validate and save cohort info - mark as not usable due to lack of trait data\n",
497
+ " is_biased = True # Since we can't even analyze trait distribution\n",
498
+ " validate_and_save_cohort_info(\n",
499
+ " is_final=True,\n",
500
+ " cohort=cohort,\n",
501
+ " info_path=json_path,\n",
502
+ " is_gene_available=True,\n",
503
+ " is_trait_available=is_trait_available,\n",
504
+ " is_biased=is_biased,\n",
505
+ " df=pd.DataFrame(), # Empty dataframe since we don't have linked data\n",
506
+ " note=\"Gene expression data available but clinical data contains too many missing values for effective linking.\"\n",
507
+ " )\n",
508
+ " \n",
509
+ " except Exception as e:\n",
510
+ " print(f\"Error processing clinical data: {e}\")\n",
511
+ " is_trait_available = False\n",
512
+ " \n",
513
+ " # Validate with proper values for unavailable trait data\n",
514
+ " validate_and_save_cohort_info(\n",
515
+ " is_final=True,\n",
516
+ " cohort=cohort,\n",
517
+ " info_path=json_path,\n",
518
+ " is_gene_available=True,\n",
519
+ " is_trait_available=is_trait_available,\n",
520
+ " is_biased=True,\n",
521
+ " df=pd.DataFrame(),\n",
522
+ " note=f\"Error processing clinical data: {str(e)}\"\n",
523
+ " )\n",
524
+ " \n",
525
+ "except Exception as e:\n",
526
+ " print(f\"Error in gene data processing: {e}\")\n",
527
+ " \n",
528
+ " # Log the error and mark the dataset as unusable\n",
529
+ " validate_and_save_cohort_info(\n",
530
+ " is_final=True,\n",
531
+ " cohort=cohort,\n",
532
+ " info_path=json_path,\n",
533
+ " is_gene_available=False,\n",
534
+ " is_trait_available=False,\n",
535
+ " is_biased=True,\n",
536
+ " df=pd.DataFrame(),\n",
537
+ " note=f\"Error during gene data normalization: {str(e)}\"\n",
538
+ " )"
539
+ ]
540
+ }
541
+ ],
542
+ "metadata": {
543
+ "language_info": {
544
+ "codemirror_mode": {
545
+ "name": "ipython",
546
+ "version": 3
547
+ },
548
+ "file_extension": ".py",
549
+ "mimetype": "text/x-python",
550
+ "name": "python",
551
+ "nbconvert_exporter": "python",
552
+ "pygments_lexer": "ipython3",
553
+ "version": "3.10.16"
554
+ }
555
+ },
556
+ "nbformat": 4,
557
+ "nbformat_minor": 5
558
+ }
code/COVID-19/GSE273225.ipynb ADDED
@@ -0,0 +1,447 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": 1,
6
+ "id": "a9eb8e58",
7
+ "metadata": {
8
+ "execution": {
9
+ "iopub.execute_input": "2025-03-25T08:31:33.983464Z",
10
+ "iopub.status.busy": "2025-03-25T08:31:33.983232Z",
11
+ "iopub.status.idle": "2025-03-25T08:31:34.146265Z",
12
+ "shell.execute_reply": "2025-03-25T08:31:34.145925Z"
13
+ }
14
+ },
15
+ "outputs": [],
16
+ "source": [
17
+ "import sys\n",
18
+ "import os\n",
19
+ "sys.path.append(os.path.abspath(os.path.join(os.getcwd(), '../..')))\n",
20
+ "\n",
21
+ "# Path Configuration\n",
22
+ "from tools.preprocess import *\n",
23
+ "\n",
24
+ "# Processing context\n",
25
+ "trait = \"COVID-19\"\n",
26
+ "cohort = \"GSE273225\"\n",
27
+ "\n",
28
+ "# Input paths\n",
29
+ "in_trait_dir = \"../../input/GEO/COVID-19\"\n",
30
+ "in_cohort_dir = \"../../input/GEO/COVID-19/GSE273225\"\n",
31
+ "\n",
32
+ "# Output paths\n",
33
+ "out_data_file = \"../../output/preprocess/COVID-19/GSE273225.csv\"\n",
34
+ "out_gene_data_file = \"../../output/preprocess/COVID-19/gene_data/GSE273225.csv\"\n",
35
+ "out_clinical_data_file = \"../../output/preprocess/COVID-19/clinical_data/GSE273225.csv\"\n",
36
+ "json_path = \"../../output/preprocess/COVID-19/cohort_info.json\"\n"
37
+ ]
38
+ },
39
+ {
40
+ "cell_type": "markdown",
41
+ "id": "6bda55a8",
42
+ "metadata": {},
43
+ "source": [
44
+ "### Step 1: Initial Data Loading"
45
+ ]
46
+ },
47
+ {
48
+ "cell_type": "code",
49
+ "execution_count": 2,
50
+ "id": "a3031a2c",
51
+ "metadata": {
52
+ "execution": {
53
+ "iopub.execute_input": "2025-03-25T08:31:34.147637Z",
54
+ "iopub.status.busy": "2025-03-25T08:31:34.147507Z",
55
+ "iopub.status.idle": "2025-03-25T08:31:34.158834Z",
56
+ "shell.execute_reply": "2025-03-25T08:31:34.158558Z"
57
+ }
58
+ },
59
+ "outputs": [
60
+ {
61
+ "name": "stdout",
62
+ "output_type": "stream",
63
+ "text": [
64
+ "Background Information:\n",
65
+ "!Series_title\t\"The effect of rewarming ischemia on tissue transcriptome signatures: a clinical observational study in lung transplantation\"\n",
66
+ "!Series_summary\t\"BACKGROUND: In lung transplantation (LuTx), various ischemic phases exist, yet the rewarming ischemia time (RIT) during implantation has often been overlooked. During RIT, lungs are deflated and exposed to the body temperature in the recipient's chest cavity. Our prior clinical findings demonstrated that prolonged RIT increases the risk of primary graft dysfunction. However, the molecular mechanisms of rewarming ischemic injury in this context remain unexplored. We aimed to characterize the rewarming ischemia phase during LuTx by measuring organ temperature and comparing transcriptome and metabolome profiles in tissue obtained at the end versus the start of implantation.\"\n",
67
+ "!Series_summary\t\"METHODS: In a clinical observational study, 34 double-LuTx with ice preservation were analyzed. Lung core and surface temperature (n=65 and 55 lungs) was measured during implantation. Biopsies (n=59 lungs) were wedged from right middle lobe and left lingula at start and end of implantation. Tissue transcriptomic and metabolomic profiling were performed.\"\n",
68
+ "!Series_summary\t\"RESULTS: Temperature increased rapidly during implantation, reaching core/surface temperatures of 21.5°C/25.4°C within 30min. Transcriptomics showed increased pro-inflammatory signaling and oxidative stress at the end of implantation. Upregulation of NLRP3 and NFKB1 correlated with RIT. Metabolomics indicated elevated levels of amino acids, hypoxanthine, uric acid, cysteineglutathione disulfide alongside decreased levels of glucose and carnitines. Arginine, tyrosine, and 1-carboxyethylleucine showed correlation with incremental RIT.\"\n",
69
+ "!Series_summary\t\"CONCLUSIONS: The final rewarming ischemia phase in LuTx involves rapid organ rewarming, accompanied by transcriptomic and metabolomic changes indicating pro-inflammatory signaling and disturbed cell metabolism. Limiting implantation time and lung cooling represent potential interventions to alleviate rewarming ischemic injury.\"\n",
70
+ "!Series_overall_design\t\"Lung tissue biopsy pieces preserved at -80°C were homogenized in Total RNA Lysis Solution (Bio-Rad, Cat#7326820, US) with a 3mm tungsten carbide bead (Qiagen, Cat#69997, Netherlands) using the TissueLyser II (Qiagen, Netherlands). The homogenate underwent RNA extraction with TRIzol (Invitrogen, Cat#15596026, US) and RNA purification with the Aurum Total RNA mini Kit (Bio-Rad, Cat#7326820, US). RNA quality was verified using the NanoPhotometer NP80 Touch (Implen, Germany).\"\n",
71
+ "!Series_overall_design\t\"We did nCounter (NanoString Technologies, US) digital gene expression analysis with the Immunology V2 panel targeting 579 immune system-associated genes. The workflow was carried out as established before in critical COVID-191, fatal COVID-19 nursing home outbreaks2, and respiratory infections at the emergency department3. In short, transcripts -including 15 housekeeping genes - were quantified by hybridization with specific fluorescent barcodes linked to a 50 bp reporter probe and an adjacent 50 bp capture probe.\"\n",
72
+ "!Series_overall_design\t\"Data were normalized for background (negative control probes), internal positive control probes and housekeeping genes using nSolver software version 4.0 (NanoString Technologies, US). Differentially expressed genes and predefined biological pathway scores were determined using nSolver, with correction for multiple testing by the Benjamini-Hochberg method at a 5% false discovery rate for multiple comparisons cut-off. Comparison of baseline RNA levels for lung side, mechanical ventilation time, donation type and cold ischemia time was done according to the negative binomial distribution with generalized linear models.\"\n",
73
+ "!Series_overall_design\t\"References\"\n",
74
+ "!Series_overall_design\t\"1. Menezes SM, Braz M, Llorens-Rico V, Wauters J, Van Weyenbergh J. Endogenous IFNβ expression predicts outcome in critical patients with COVID-19. Lancet Microbe. Jun 2021;2(6):e235-e236. doi:10.1016/s2666-5247(21)00063-x\"\n",
75
+ "!Series_overall_design\t\"2. Cuypers L, Keyaerts E, Hong SL, et al. Immunovirological and environmental screening reveals actionable risk factors for fatal COVID-19 during post-vaccination nursing home outbreaks. Nat Aging. Jun 2023;3(6):722-733. doi:10.1038/s43587-023-00421-1\"\n",
76
+ "!Series_overall_design\t\"3. Fukutani KF, Nascimento-Carvalho CM, Bouzas ML, et al. In situ Immune Signatures and Microbial Load at the Nasopharyngeal Interface in Children With Acute Respiratory Infection. Front Microbiol. 2018;9:2475. doi:10.3389/fmicb.2018.02475\"\n",
77
+ "Sample Characteristics Dictionary:\n",
78
+ "{0: ['tissue: left lung', 'tissue: right lung'], 1: ['timepoint: start donor lung implantation', 'timepoint: end donor lung implantation'], 2: ['biopsy set: 1 left', 'biopsy set: 2 right', 'biopsy set: 3 left', 'biopsy set: 3 right', 'biopsy set: 4 left', 'biopsy set: 4 right', 'biopsy set: 5 left', 'biopsy set: 6 right', 'biopsy set: 7 left', 'biopsy set: 7 right', 'biopsy set: 8 left', 'biopsy set: 8 right', 'biopsy set: 9 left', 'biopsy set: 9 right', 'biopsy set: 10 left', 'biopsy set: 10 right', 'biopsy set: 11 left', 'biopsy set: 11 right', 'biopsy set: 12 left', 'biopsy set: 12 right', 'biopsy set: 14 left', 'biopsy set: 14 right', 'biopsy set: 15 left', 'biopsy set: 15 right', 'biopsy set: 16 left', 'biopsy set: 16 right', 'biopsy set: 20 left', 'biopsy set: 20 right', 'biopsy set: 21 right', 'biopsy set: 22 left'], 3: ['donor age (y): 51', 'donor age (y): 63', 'donor age (y): 66', 'donor age (y): 49', 'donor age (y): 73', 'donor age (y): 68', 'donor age (y): 42', 'donor age (y): 60', 'donor age (y): 29', 'donor age (y): 28', 'donor age (y): 59', 'donor age (y): 44', 'donor age (y): 39', 'donor age (y): 76', 'donor age (y): 48', 'donor age (y): 88', 'donor age (y): 64', 'donor age (y): 69', 'donor age (y): 36', 'donor age (y): 62', 'donor age (y): 56', 'donor age (y): 34', 'donor age (y): 50', 'donor age (y): 65', 'donor age (y): 75', 'donor age (y): 58'], 4: ['donor sex: male', 'donor sex: female'], 5: ['donor bmi: 24.7', 'donor bmi: 30.4', 'donor bmi: 26.3', 'donor bmi: 23.9', 'donor bmi: 22.6', 'donor bmi: 27', 'donor bmi: 27.8', 'donor bmi: 24.2', 'donor bmi: 21.3', 'donor bmi: 18', 'donor bmi: 30.7', 'donor bmi: 16.9', 'donor bmi: 17.8', 'donor bmi: 29.2', 'donor bmi: 23.1', 'donor bmi: 25.4', 'donor bmi: 19', 'donor bmi: 22.9', 'donor bmi: 30.8', 'donor bmi: 29.4', 'donor bmi: 29.8', 'donor bmi: 30.5', 'donor bmi: 24.8', 'donor bmi: 32.4', 'donor bmi: 21.2', 'donor bmi: 23.6', 'donor bmi: 27.2'], 6: ['donor smoking history: yes', 'donor smoking history: no'], 7: ['donor cause of death: hypoxic-ischemic encefalopathy', 'donor cause of death: intracranial bleeding', 'donor cause of death: head trauma', 'donor cause of death: ischemic stroke'], 8: ['donor mechanical ventilation (hours): 98', 'donor mechanical ventilation (hours): 265', 'donor mechanical ventilation (hours): 125', 'donor mechanical ventilation (hours): 165', 'donor mechanical ventilation (hours): 87', 'donor mechanical ventilation (hours): 50', 'donor mechanical ventilation (hours): 209', 'donor mechanical ventilation (hours): 51', 'donor mechanical ventilation (hours): 75', 'donor mechanical ventilation (hours): 212', 'donor mechanical ventilation (hours): 164', 'donor mechanical ventilation (hours): 80', 'donor mechanical ventilation (hours): 92', 'donor mechanical ventilation (hours): 26', 'donor mechanical ventilation (hours): 59', 'donor mechanical ventilation (hours): 210', 'donor mechanical ventilation (hours): 74', 'donor mechanical ventilation (hours): 82', 'donor mechanical ventilation (hours): 30', 'donor mechanical ventilation (hours): 124', 'donor mechanical ventilation (hours): 46', 'donor mechanical ventilation (hours): 78', 'donor mechanical ventilation (hours): 138', 'donor mechanical ventilation (hours): 557', 'donor mechanical ventilation (hours): 24', 'donor mechanical ventilation (hours): 141', 'donor mechanical ventilation (hours): 288', 'donor mechanical ventilation (hours): 580', 'donor mechanical ventilation (hours): 93', 'donor mechanical ventilation (hours): 60'], 9: ['donor pao2/fio2 ratio: 370', 'donor pao2/fio2 ratio: 336', 'donor pao2/fio2 ratio: 399', 'donor pao2/fio2 ratio: 453', 'donor pao2/fio2 ratio: 626', 'donor pao2/fio2 ratio: 529', 'donor pao2/fio2 ratio: 428', 'donor pao2/fio2 ratio: 607', 'donor pao2/fio2 ratio: 484', 'donor pao2/fio2 ratio: 392', 'donor pao2/fio2 ratio: 441', 'donor pao2/fio2 ratio: 431', 'donor pao2/fio2 ratio: 495', 'donor pao2/fio2 ratio: 393', 'donor pao2/fio2 ratio: 409', 'donor pao2/fio2 ratio: 386', 'donor pao2/fio2 ratio: 561', 'donor pao2/fio2 ratio: 507', 'donor pao2/fio2 ratio: 449', 'donor pao2/fio2 ratio: 530', 'donor pao2/fio2 ratio: 568', 'donor pao2/fio2 ratio: 332', 'donor pao2/fio2 ratio: 367', 'donor pao2/fio2 ratio: 546', 'donor pao2/fio2 ratio: 226', 'donor pao2/fio2 ratio: 112', 'donor pao2/fio2 ratio: 398', 'donor pao2/fio2 ratio: 497', 'donor pao2/fio2 ratio: 388', 'donor pao2/fio2 ratio: 352'], 10: ['donation type: DBD', 'donation type: DCD'], 11: ['donor warm ischemia time (min): NA', 'donor warm ischemia time (min): 10', 'donor warm ischemia time (min): 8', 'donor warm ischemia time (min): 12', 'donor warm ischemia time (min): 9', 'donor warm ischemia time (min): 11', 'donor warm ischemia time (min): 14', 'donor warm ischemia time (min): 15', 'donor warm ischemia time (min): 19'], 12: ['biopsy rewarming ischemia time (min): 59', 'biopsy rewarming ischemia time (min): 48', 'biopsy rewarming ischemia time (min): 73', 'biopsy rewarming ischemia time (min): 93', 'biopsy rewarming ischemia time (min): 61', 'biopsy rewarming ischemia time (min): 51', 'biopsy rewarming ischemia time (min): 94', 'biopsy rewarming ischemia time (min): 60', 'biopsy rewarming ischemia time (min): 69', 'biopsy rewarming ischemia time (min): 68', 'biopsy rewarming ischemia time (min): 76', 'biopsy rewarming ischemia time (min): 53', 'biopsy rewarming ischemia time (min): 82', 'biopsy rewarming ischemia time (min): 72', 'biopsy rewarming ischemia time (min): 70', 'biopsy rewarming ischemia time (min): 85', 'biopsy rewarming ischemia time (min): 65', 'biopsy rewarming ischemia time (min): 56', 'biopsy rewarming ischemia time (min): 75', 'biopsy rewarming ischemia time (min): 77', 'biopsy rewarming ischemia time (min): 98', 'biopsy rewarming ischemia time (min): 103', 'biopsy rewarming ischemia time (min): 67', 'biopsy rewarming ischemia time (min): 55', 'biopsy rewarming ischemia time (min): 62', 'biopsy rewarming ischemia time (min): 96', 'biopsy rewarming ischemia time (min): 87', 'biopsy rewarming ischemia time (min): 44', 'biopsy rewarming ischemia time (min): 80', 'biopsy rewarming ischemia time (min): 84'], 13: ['cold ischemia (min): 358', 'cold ischemia (min): 277', 'cold ischemia (min): 574', 'cold ischemia (min): 378', 'cold ischemia (min): 400', 'cold ischemia (min): 294', 'cold ischemia (min): 532', 'cold ischemia (min): 203', 'cold ischemia (min): 321', 'cold ischemia (min): 192', 'cold ischemia (min): 335', 'cold ischemia (min): 205', 'cold ischemia (min): 536', 'cold ischemia (min): 350', 'cold ischemia (min): 456', 'cold ischemia (min): 260', 'cold ischemia (min): 533', 'cold ischemia (min): 353', 'cold ischemia (min): 391', 'cold ischemia (min): 212', 'cold ischemia (min): 392', 'cold ischemia (min): 210', 'cold ischemia (min): 410', 'cold ischemia (min): 515', 'cold ischemia (min): 300', 'cold ischemia (min): 452', 'cold ischemia (min): 331', 'cold ischemia (min): 308', 'cold ischemia (min): 543', 'cold ischemia (min): 305']}\n"
79
+ ]
80
+ }
81
+ ],
82
+ "source": [
83
+ "from tools.preprocess import *\n",
84
+ "# 1. Identify the paths to the SOFT file and the matrix file\n",
85
+ "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
86
+ "\n",
87
+ "# 2. Read the matrix file to obtain background information and sample characteristics data\n",
88
+ "background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']\n",
89
+ "clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']\n",
90
+ "background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)\n",
91
+ "\n",
92
+ "# 3. Obtain the sample characteristics dictionary from the clinical dataframe\n",
93
+ "sample_characteristics_dict = get_unique_values_by_row(clinical_data)\n",
94
+ "\n",
95
+ "# 4. Explicitly print out all the background information and the sample characteristics dictionary\n",
96
+ "print(\"Background Information:\")\n",
97
+ "print(background_info)\n",
98
+ "print(\"Sample Characteristics Dictionary:\")\n",
99
+ "print(sample_characteristics_dict)\n"
100
+ ]
101
+ },
102
+ {
103
+ "cell_type": "markdown",
104
+ "id": "911cf4e9",
105
+ "metadata": {},
106
+ "source": [
107
+ "### Step 2: Dataset Analysis and Clinical Feature Extraction"
108
+ ]
109
+ },
110
+ {
111
+ "cell_type": "code",
112
+ "execution_count": 3,
113
+ "id": "2cc40cc0",
114
+ "metadata": {
115
+ "execution": {
116
+ "iopub.execute_input": "2025-03-25T08:31:34.159832Z",
117
+ "iopub.status.busy": "2025-03-25T08:31:34.159732Z",
118
+ "iopub.status.idle": "2025-03-25T08:31:34.165513Z",
119
+ "shell.execute_reply": "2025-03-25T08:31:34.165250Z"
120
+ }
121
+ },
122
+ "outputs": [
123
+ {
124
+ "data": {
125
+ "text/plain": [
126
+ "False"
127
+ ]
128
+ },
129
+ "execution_count": 3,
130
+ "metadata": {},
131
+ "output_type": "execute_result"
132
+ }
133
+ ],
134
+ "source": [
135
+ "# 1. Gene Expression Data Availability\n",
136
+ "# Based on the Series_overall_design and the overall structure, this study includes\n",
137
+ "# gene expression data using nCounter digital gene expression analysis with the Immunology V2 panel\n",
138
+ "# This targets 579 immune system-associated genes, which is suitable for our analysis\n",
139
+ "is_gene_available = True\n",
140
+ "\n",
141
+ "# 2. Variable Availability and Data Type Conversion\n",
142
+ "# 2.1 Trait related data - Check for COVID-19 related data\n",
143
+ "# Looking at the background info, this is a lung transplantation study with no indication of COVID-19\n",
144
+ "# The study is about rewarming ischemia time during lung transplantation\n",
145
+ "trait_row = None # No COVID-19 data available\n",
146
+ "\n",
147
+ "# 2.2 Age data\n",
148
+ "# Available in key 3 as \"donor age (y): XX\"\n",
149
+ "age_row = 3\n",
150
+ "\n",
151
+ "def convert_age(value):\n",
152
+ " \"\"\"Convert age value to numeric (continuous)\"\"\"\n",
153
+ " if value is None:\n",
154
+ " return None\n",
155
+ " try:\n",
156
+ " # Extract the number after the colon\n",
157
+ " if \":\" in value:\n",
158
+ " age_str = value.split(\":\")[1].strip()\n",
159
+ " return float(age_str)\n",
160
+ " return None\n",
161
+ " except:\n",
162
+ " return None\n",
163
+ "\n",
164
+ "# 2.3 Gender data\n",
165
+ "# Available in key 4 as \"donor sex: male/female\"\n",
166
+ "gender_row = 4\n",
167
+ "\n",
168
+ "def convert_gender(value):\n",
169
+ " \"\"\"Convert gender information to binary (0 for female, 1 for male)\"\"\"\n",
170
+ " if value is None:\n",
171
+ " return None\n",
172
+ " try:\n",
173
+ " # Extract the gender after the colon\n",
174
+ " if \":\" in value:\n",
175
+ " gender = value.split(\":\")[1].strip().lower()\n",
176
+ " if gender == \"female\":\n",
177
+ " return 0\n",
178
+ " elif gender == \"male\":\n",
179
+ " return 1\n",
180
+ " return None\n",
181
+ " except:\n",
182
+ " return None\n",
183
+ "\n",
184
+ "# For completeness, define convert_trait even though we don't have COVID-19 data\n",
185
+ "def convert_trait(value):\n",
186
+ " \"\"\"\n",
187
+ " Convert trait information to binary.\n",
188
+ " This is a placeholder as there's no COVID-19 data in this dataset.\n",
189
+ " \"\"\"\n",
190
+ " return None\n",
191
+ "\n",
192
+ "# 3. Save Metadata\n",
193
+ "# Determine if trait data is available (it's not)\n",
194
+ "is_trait_available = trait_row is not None\n",
195
+ "\n",
196
+ "# Validate and save cohort info\n",
197
+ "validate_and_save_cohort_info(\n",
198
+ " is_final=False,\n",
199
+ " cohort=cohort,\n",
200
+ " info_path=json_path,\n",
201
+ " is_gene_available=is_gene_available,\n",
202
+ " is_trait_available=is_trait_available\n",
203
+ ")\n",
204
+ "\n",
205
+ "# 4. Clinical Feature Extraction\n",
206
+ "# Skip this step as trait_row is None (trait data not available)\n"
207
+ ]
208
+ },
209
+ {
210
+ "cell_type": "markdown",
211
+ "id": "d6b6c4f7",
212
+ "metadata": {},
213
+ "source": [
214
+ "### Step 3: Gene Data Extraction"
215
+ ]
216
+ },
217
+ {
218
+ "cell_type": "code",
219
+ "execution_count": 4,
220
+ "id": "de320944",
221
+ "metadata": {
222
+ "execution": {
223
+ "iopub.execute_input": "2025-03-25T08:31:34.166474Z",
224
+ "iopub.status.busy": "2025-03-25T08:31:34.166376Z",
225
+ "iopub.status.idle": "2025-03-25T08:31:34.185433Z",
226
+ "shell.execute_reply": "2025-03-25T08:31:34.185157Z"
227
+ }
228
+ },
229
+ "outputs": [
230
+ {
231
+ "name": "stdout",
232
+ "output_type": "stream",
233
+ "text": [
234
+ "SOFT file: ../../input/GEO/COVID-19/GSE273225/GSE273225_family.soft.gz\n",
235
+ "Matrix file: ../../input/GEO/COVID-19/GSE273225/GSE273225_series_matrix.txt.gz\n",
236
+ "Found the matrix table marker at line 80\n",
237
+ "Gene data shape: (608, 118)\n",
238
+ "First 20 gene/probe identifiers:\n",
239
+ "['ABCB1', 'ABCF1', 'ABL1', 'ADA', 'AHR', 'AICDA', 'AIRE', 'ALAS1', 'APP', 'ARG1', 'ARG2', 'ARHGDIB', 'ATG10', 'ATG12', 'ATG16L1', 'ATG5', 'ATG7', 'ATM', 'B2M', 'B3GAT1']\n"
240
+ ]
241
+ }
242
+ ],
243
+ "source": [
244
+ "# 1. Identify the paths to the SOFT file and the matrix file\n",
245
+ "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
246
+ "print(f\"SOFT file: {soft_file}\")\n",
247
+ "print(f\"Matrix file: {matrix_file}\")\n",
248
+ "\n",
249
+ "# Set gene availability flag\n",
250
+ "is_gene_available = True # Initially assume gene data is available\n",
251
+ "\n",
252
+ "# First check if the matrix file contains the expected marker\n",
253
+ "found_marker = False\n",
254
+ "marker_row = None\n",
255
+ "try:\n",
256
+ " with gzip.open(matrix_file, 'rt') as file:\n",
257
+ " for i, line in enumerate(file):\n",
258
+ " if \"!series_matrix_table_begin\" in line:\n",
259
+ " found_marker = True\n",
260
+ " marker_row = i\n",
261
+ " print(f\"Found the matrix table marker at line {i}\")\n",
262
+ " break\n",
263
+ " \n",
264
+ " if not found_marker:\n",
265
+ " print(\"Warning: Could not find '!series_matrix_table_begin' marker in the file.\")\n",
266
+ " is_gene_available = False\n",
267
+ " \n",
268
+ " # If marker was found, try to extract gene data\n",
269
+ " if is_gene_available:\n",
270
+ " try:\n",
271
+ " # Try using the library function\n",
272
+ " gene_data = get_genetic_data(matrix_file)\n",
273
+ " \n",
274
+ " if gene_data.shape[0] == 0:\n",
275
+ " print(\"Warning: Extracted gene data has 0 rows.\")\n",
276
+ " is_gene_available = False\n",
277
+ " else:\n",
278
+ " print(f\"Gene data shape: {gene_data.shape}\")\n",
279
+ " # Print the first 20 gene/probe identifiers\n",
280
+ " print(\"First 20 gene/probe identifiers:\")\n",
281
+ " print(gene_data.index[:20].tolist())\n",
282
+ " except Exception as e:\n",
283
+ " print(f\"Error extracting gene data with get_genetic_data(): {e}\")\n",
284
+ " is_gene_available = False\n",
285
+ " \n",
286
+ " # If gene data extraction failed, examine file content to diagnose\n",
287
+ " if not is_gene_available:\n",
288
+ " print(\"Examining file content to diagnose the issue:\")\n",
289
+ " try:\n",
290
+ " with gzip.open(matrix_file, 'rt') as file:\n",
291
+ " # Print lines around the marker if found\n",
292
+ " if marker_row is not None:\n",
293
+ " for i, line in enumerate(file):\n",
294
+ " if i >= marker_row - 2 and i <= marker_row + 10:\n",
295
+ " print(f\"Line {i}: {line.strip()[:100]}...\")\n",
296
+ " if i > marker_row + 10:\n",
297
+ " break\n",
298
+ " else:\n",
299
+ " # If marker not found, print first 10 lines\n",
300
+ " for i, line in enumerate(file):\n",
301
+ " if i < 10:\n",
302
+ " print(f\"Line {i}: {line.strip()[:100]}...\")\n",
303
+ " else:\n",
304
+ " break\n",
305
+ " except Exception as e2:\n",
306
+ " print(f\"Error examining file: {e2}\")\n",
307
+ " \n",
308
+ "except Exception as e:\n",
309
+ " print(f\"Error processing file: {e}\")\n",
310
+ " is_gene_available = False\n",
311
+ "\n",
312
+ "# Update validation information if gene data extraction failed\n",
313
+ "if not is_gene_available:\n",
314
+ " print(\"Gene expression data could not be successfully extracted from this dataset.\")\n",
315
+ " # Update the validation record since gene data isn't available\n",
316
+ " is_trait_available = False # We already determined trait data isn't available in step 2\n",
317
+ " validate_and_save_cohort_info(is_final=False, cohort=cohort, info_path=json_path,\n",
318
+ " is_gene_available=is_gene_available, is_trait_available=is_trait_available)\n"
319
+ ]
320
+ },
321
+ {
322
+ "cell_type": "markdown",
323
+ "id": "85ebb7e3",
324
+ "metadata": {},
325
+ "source": [
326
+ "### Step 4: Gene Identifier Review"
327
+ ]
328
+ },
329
+ {
330
+ "cell_type": "code",
331
+ "execution_count": 5,
332
+ "id": "bf908218",
333
+ "metadata": {
334
+ "execution": {
335
+ "iopub.execute_input": "2025-03-25T08:31:34.186389Z",
336
+ "iopub.status.busy": "2025-03-25T08:31:34.186289Z",
337
+ "iopub.status.idle": "2025-03-25T08:31:34.187912Z",
338
+ "shell.execute_reply": "2025-03-25T08:31:34.187646Z"
339
+ }
340
+ },
341
+ "outputs": [],
342
+ "source": [
343
+ "# Review gene identifiers\n",
344
+ "# These identifiers appear to be standard human gene symbols\n",
345
+ "# Examples like ABCB1, B2M, ATM are all recognized human gene symbols\n",
346
+ "\n",
347
+ "requires_gene_mapping = False\n"
348
+ ]
349
+ },
350
+ {
351
+ "cell_type": "markdown",
352
+ "id": "65fea1b9",
353
+ "metadata": {},
354
+ "source": [
355
+ "### Step 5: Data Normalization and Linking"
356
+ ]
357
+ },
358
+ {
359
+ "cell_type": "code",
360
+ "execution_count": 6,
361
+ "id": "2861f96c",
362
+ "metadata": {
363
+ "execution": {
364
+ "iopub.execute_input": "2025-03-25T08:31:34.188847Z",
365
+ "iopub.status.busy": "2025-03-25T08:31:34.188750Z",
366
+ "iopub.status.idle": "2025-03-25T08:31:34.300193Z",
367
+ "shell.execute_reply": "2025-03-25T08:31:34.299817Z"
368
+ }
369
+ },
370
+ "outputs": [
371
+ {
372
+ "name": "stdout",
373
+ "output_type": "stream",
374
+ "text": [
375
+ "Gene data shape after normalization: (576, 118)\n",
376
+ "Normalized gene data saved to ../../output/preprocess/COVID-19/gene_data/GSE273225.csv\n",
377
+ "Abnormality detected in the cohort: GSE273225. Preprocessing failed.\n",
378
+ "Processing complete. Gene data saved but no clinical data linking possible due to missing trait information.\n"
379
+ ]
380
+ }
381
+ ],
382
+ "source": [
383
+ "# 1. Normalize gene symbols and prepare for linking\n",
384
+ "try:\n",
385
+ " # Normalize gene symbols\n",
386
+ " normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n",
387
+ " print(f\"Gene data shape after normalization: {normalized_gene_data.shape}\")\n",
388
+ " \n",
389
+ " # Create output directory if it doesn't exist\n",
390
+ " os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
391
+ " \n",
392
+ " # Save the normalized gene data\n",
393
+ " normalized_gene_data.to_csv(out_gene_data_file)\n",
394
+ " print(f\"Normalized gene data saved to {out_gene_data_file}\")\n",
395
+ " \n",
396
+ " # Since we identified in Step 2 that there's no COVID-19 data available in this dataset\n",
397
+ " # (trait_row is None), we cannot proceed with linking clinical and genetic data\n",
398
+ " is_trait_available = False if 'trait_row' not in locals() else (trait_row is not None)\n",
399
+ " \n",
400
+ " # Validate data quality and save cohort info\n",
401
+ " validate_and_save_cohort_info(\n",
402
+ " is_final=True,\n",
403
+ " cohort=cohort,\n",
404
+ " info_path=json_path,\n",
405
+ " is_gene_available=is_gene_available,\n",
406
+ " is_trait_available=is_trait_available,\n",
407
+ " is_biased=True, # Set to True as we don't have trait data for analysis\n",
408
+ " df=pd.DataFrame(), # Empty DataFrame since we don't have linked data\n",
409
+ " note=\"Gene expression data available but no COVID-19 trait data in this lung transplantation dataset.\"\n",
410
+ " )\n",
411
+ " \n",
412
+ " print(\"Processing complete. Gene data saved but no clinical data linking possible due to missing trait information.\")\n",
413
+ " \n",
414
+ "except Exception as e:\n",
415
+ " print(f\"Error in data processing: {e}\")\n",
416
+ " \n",
417
+ " # Log the error and mark the dataset as unusable\n",
418
+ " validate_and_save_cohort_info(\n",
419
+ " is_final=True,\n",
420
+ " cohort=cohort,\n",
421
+ " info_path=json_path,\n",
422
+ " is_gene_available=False,\n",
423
+ " is_trait_available=False,\n",
424
+ " is_biased=True,\n",
425
+ " df=pd.DataFrame(),\n",
426
+ " note=f\"Error during normalization or processing: {str(e)}\"\n",
427
+ " )"
428
+ ]
429
+ }
430
+ ],
431
+ "metadata": {
432
+ "language_info": {
433
+ "codemirror_mode": {
434
+ "name": "ipython",
435
+ "version": 3
436
+ },
437
+ "file_extension": ".py",
438
+ "mimetype": "text/x-python",
439
+ "name": "python",
440
+ "nbconvert_exporter": "python",
441
+ "pygments_lexer": "ipython3",
442
+ "version": "3.10.16"
443
+ }
444
+ },
445
+ "nbformat": 4,
446
+ "nbformat_minor": 5
447
+ }
code/COVID-19/GSE275334.ipynb ADDED
@@ -0,0 +1,555 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": 1,
6
+ "id": "f686e699",
7
+ "metadata": {
8
+ "execution": {
9
+ "iopub.execute_input": "2025-03-25T08:31:35.078946Z",
10
+ "iopub.status.busy": "2025-03-25T08:31:35.078626Z",
11
+ "iopub.status.idle": "2025-03-25T08:31:35.242332Z",
12
+ "shell.execute_reply": "2025-03-25T08:31:35.242015Z"
13
+ }
14
+ },
15
+ "outputs": [],
16
+ "source": [
17
+ "import sys\n",
18
+ "import os\n",
19
+ "sys.path.append(os.path.abspath(os.path.join(os.getcwd(), '../..')))\n",
20
+ "\n",
21
+ "# Path Configuration\n",
22
+ "from tools.preprocess import *\n",
23
+ "\n",
24
+ "# Processing context\n",
25
+ "trait = \"COVID-19\"\n",
26
+ "cohort = \"GSE275334\"\n",
27
+ "\n",
28
+ "# Input paths\n",
29
+ "in_trait_dir = \"../../input/GEO/COVID-19\"\n",
30
+ "in_cohort_dir = \"../../input/GEO/COVID-19/GSE275334\"\n",
31
+ "\n",
32
+ "# Output paths\n",
33
+ "out_data_file = \"../../output/preprocess/COVID-19/GSE275334.csv\"\n",
34
+ "out_gene_data_file = \"../../output/preprocess/COVID-19/gene_data/GSE275334.csv\"\n",
35
+ "out_clinical_data_file = \"../../output/preprocess/COVID-19/clinical_data/GSE275334.csv\"\n",
36
+ "json_path = \"../../output/preprocess/COVID-19/cohort_info.json\"\n"
37
+ ]
38
+ },
39
+ {
40
+ "cell_type": "markdown",
41
+ "id": "0ddfeb03",
42
+ "metadata": {},
43
+ "source": [
44
+ "### Step 1: Initial Data Loading"
45
+ ]
46
+ },
47
+ {
48
+ "cell_type": "code",
49
+ "execution_count": 2,
50
+ "id": "95216831",
51
+ "metadata": {
52
+ "execution": {
53
+ "iopub.execute_input": "2025-03-25T08:31:35.243705Z",
54
+ "iopub.status.busy": "2025-03-25T08:31:35.243565Z",
55
+ "iopub.status.idle": "2025-03-25T08:31:35.258937Z",
56
+ "shell.execute_reply": "2025-03-25T08:31:35.258680Z"
57
+ }
58
+ },
59
+ "outputs": [
60
+ {
61
+ "name": "stdout",
62
+ "output_type": "stream",
63
+ "text": [
64
+ "Background Information:\n",
65
+ "!Series_title\t\"Immune Exhaustion in ME/CFS and long COVID\"\n",
66
+ "!Series_summary\t\"Gene expression analysis of RNA was performed using the commercially available NanoString® nCounter Immune Exhaustion gene expression panel (NanoString Technologies, Seattle, WA, USA). This panel contains 785 genes to elucidate mechanisms behind T cell, B cell and NK cell exhaustion in disease.\"\n",
67
+ "!Series_summary\t\"Ribonucleic acid (RNA) was extracted from peripheral blood mononuclear cells (PBMCs) isolated from ME/CFS (n=14), long COVID (n=15), and healthy control (HC; n=18) participants. ME/CFS participants were included according to Canadian Consensus Criteria for ME. Long COVID participants were eligible according to the working case definition for Post COVID-19 Condition published by the World Health Organization.\"\n",
68
+ "!Series_overall_design\t\"Raw gene expression data was normalised against positive and negative controls to account for background noise and platform-associated variation. Normalisation and analysis were performed using Rosalind Bio (San Diego, CA, USA) using geometric means of housekeeping genes (ABCF1, ALAS1, EEF1G, G6PD, GAPDH, GUSB, HPRT1, OAZ1, POLR1B, POLR2A, PPIA, RPL19, SDHA, TBP, TUBB) (Supplementary Material 1). Differential expression is reported between ME/CFS and long COVID with HC.\"\n",
69
+ "Sample Characteristics Dictionary:\n",
70
+ "{0: ['cell type: PBMCs'], 1: ['age (years): 24', 'age (years): 46', 'age (years): 50', 'age (years): 37', 'age (years): 19', 'age (years): 40', 'age (years): 63', 'age (years): 54', 'age (years): 48', 'age (years): 34', 'age (years): 22', 'age (years): 59', 'age (years): 39', 'age (years): 27', 'age (years): 61', 'age (years): 38', 'age (years): 44', 'age (years): 41', 'age (years): 49', 'age (years): 43', 'age (years): 62', 'age (years): 30', 'age (years): 47', 'age (years): 53', 'age (years): 29', 'age (years): 32', 'age (years): 55', 'age (years): 51', 'age (years): 31', 'age (years): 60'], 2: ['Sex: Female', 'Sex: Male'], 3: ['disease: Healthy control', 'disease: Long COVID', 'disease: ME/CFS']}\n"
71
+ ]
72
+ }
73
+ ],
74
+ "source": [
75
+ "from tools.preprocess import *\n",
76
+ "# 1. Identify the paths to the SOFT file and the matrix file\n",
77
+ "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
78
+ "\n",
79
+ "# 2. Read the matrix file to obtain background information and sample characteristics data\n",
80
+ "background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']\n",
81
+ "clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']\n",
82
+ "background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)\n",
83
+ "\n",
84
+ "# 3. Obtain the sample characteristics dictionary from the clinical dataframe\n",
85
+ "sample_characteristics_dict = get_unique_values_by_row(clinical_data)\n",
86
+ "\n",
87
+ "# 4. Explicitly print out all the background information and the sample characteristics dictionary\n",
88
+ "print(\"Background Information:\")\n",
89
+ "print(background_info)\n",
90
+ "print(\"Sample Characteristics Dictionary:\")\n",
91
+ "print(sample_characteristics_dict)\n"
92
+ ]
93
+ },
94
+ {
95
+ "cell_type": "markdown",
96
+ "id": "a0d7d779",
97
+ "metadata": {},
98
+ "source": [
99
+ "### Step 2: Dataset Analysis and Clinical Feature Extraction"
100
+ ]
101
+ },
102
+ {
103
+ "cell_type": "code",
104
+ "execution_count": 3,
105
+ "id": "b87dc85e",
106
+ "metadata": {
107
+ "execution": {
108
+ "iopub.execute_input": "2025-03-25T08:31:35.259876Z",
109
+ "iopub.status.busy": "2025-03-25T08:31:35.259774Z",
110
+ "iopub.status.idle": "2025-03-25T08:31:35.270366Z",
111
+ "shell.execute_reply": "2025-03-25T08:31:35.270097Z"
112
+ }
113
+ },
114
+ "outputs": [
115
+ {
116
+ "name": "stdout",
117
+ "output_type": "stream",
118
+ "text": [
119
+ "Clinical Data Preview:\n",
120
+ "{'GSM8475033': [0.0, 24.0, 0.0], 'GSM8475034': [0.0, 46.0, 0.0], 'GSM8475035': [0.0, 50.0, 0.0], 'GSM8475036': [0.0, 37.0, 1.0], 'GSM8475037': [0.0, 19.0, 0.0], 'GSM8475038': [0.0, 40.0, 0.0], 'GSM8475039': [0.0, 46.0, 1.0], 'GSM8475040': [0.0, 63.0, 0.0], 'GSM8475041': [0.0, 54.0, 0.0], 'GSM8475042': [0.0, 46.0, 0.0], 'GSM8475043': [0.0, 48.0, 0.0], 'GSM8475044': [0.0, 34.0, 1.0], 'GSM8475045': [0.0, 22.0, 1.0], 'GSM8475046': [0.0, 59.0, 0.0], 'GSM8475047': [0.0, 39.0, 0.0], 'GSM8475048': [0.0, 27.0, 0.0], 'GSM8475049': [0.0, 61.0, 0.0], 'GSM8475050': [0.0, 38.0, 1.0], 'GSM8475051': [1.0, 44.0, 0.0], 'GSM8475052': [1.0, 41.0, 1.0], 'GSM8475053': [1.0, 49.0, 0.0], 'GSM8475054': [1.0, 19.0, 0.0], 'GSM8475055': [1.0, 38.0, 0.0], 'GSM8475056': [1.0, 43.0, 0.0], 'GSM8475057': [1.0, 62.0, 0.0], 'GSM8475058': [1.0, 30.0, 0.0], 'GSM8475059': [1.0, 59.0, 0.0], 'GSM8475060': [1.0, 40.0, 1.0], 'GSM8475061': [1.0, 61.0, 1.0], 'GSM8475062': [1.0, 47.0, 0.0], 'GSM8475063': [1.0, 59.0, 1.0], 'GSM8475064': [1.0, 37.0, 0.0], 'GSM8475065': [1.0, 53.0, 0.0], 'GSM8475066': [0.0, 30.0, 0.0], 'GSM8475067': [0.0, 29.0, 0.0], 'GSM8475068': [0.0, 48.0, 0.0], 'GSM8475069': [0.0, 32.0, 0.0], 'GSM8475070': [0.0, 55.0, 0.0], 'GSM8475071': [0.0, 51.0, 1.0], 'GSM8475072': [0.0, 48.0, 0.0], 'GSM8475073': [0.0, 31.0, 0.0], 'GSM8475074': [0.0, 60.0, 0.0], 'GSM8475075': [0.0, 24.0, 0.0], 'GSM8475076': [0.0, 47.0, 0.0], 'GSM8475077': [0.0, 20.0, 0.0], 'GSM8475078': [0.0, 42.0, 1.0], 'GSM8475079': [0.0, 41.0, 1.0]}\n",
121
+ "Clinical data saved to ../../output/preprocess/COVID-19/clinical_data/GSE275334.csv\n"
122
+ ]
123
+ }
124
+ ],
125
+ "source": [
126
+ "import pandas as pd\n",
127
+ "import os\n",
128
+ "import json\n",
129
+ "from typing import Optional, Callable, Dict, Any\n",
130
+ "\n",
131
+ "# 1. Gene Expression Data Availability\n",
132
+ "# Based on the background information, this dataset appears to contain gene expression data\n",
133
+ "# from NanoString nCounter Immune Exhaustion gene expression panel, which includes 785 genes.\n",
134
+ "is_gene_available = True\n",
135
+ "\n",
136
+ "# 2. Variable Availability and Data Type Conversion\n",
137
+ "# 2.1 Data Availability\n",
138
+ "# From the sample characteristics dictionary:\n",
139
+ "# - trait (COVID-19) can be inferred from \"disease\" in row 3\n",
140
+ "# - age is available in row 1\n",
141
+ "# - gender/sex is available in row 2\n",
142
+ "trait_row = 3\n",
143
+ "age_row = 1\n",
144
+ "gender_row = 2\n",
145
+ "\n",
146
+ "# 2.2 Data Type Conversion Functions\n",
147
+ "def convert_trait(value: str) -> int:\n",
148
+ " \"\"\"\n",
149
+ " Convert trait values to binary (0 or 1).\n",
150
+ " For this dataset, we're looking for COVID-19 which maps to \"Long COVID\".\n",
151
+ " \"\"\"\n",
152
+ " if value is None:\n",
153
+ " return None\n",
154
+ " \n",
155
+ " # Extract the value after colon if present\n",
156
+ " if \":\" in value:\n",
157
+ " value = value.split(\":\", 1)[1].strip()\n",
158
+ " \n",
159
+ " # Convert to binary based on whether it's \"Long COVID\" or not\n",
160
+ " if \"long covid\" in value.lower():\n",
161
+ " return 1\n",
162
+ " else:\n",
163
+ " return 0\n",
164
+ "\n",
165
+ "def convert_age(value: str) -> float:\n",
166
+ " \"\"\"\n",
167
+ " Convert age values to continuous (float).\n",
168
+ " \"\"\"\n",
169
+ " if value is None:\n",
170
+ " return None\n",
171
+ " \n",
172
+ " # Extract the value after colon if present\n",
173
+ " if \":\" in value:\n",
174
+ " value = value.split(\":\", 1)[1].strip()\n",
175
+ " \n",
176
+ " try:\n",
177
+ " return float(value)\n",
178
+ " except (ValueError, TypeError):\n",
179
+ " return None\n",
180
+ "\n",
181
+ "def convert_gender(value: str) -> int:\n",
182
+ " \"\"\"\n",
183
+ " Convert gender values to binary (0 for female, 1 for male).\n",
184
+ " \"\"\"\n",
185
+ " if value is None:\n",
186
+ " return None\n",
187
+ " \n",
188
+ " # Extract the value after colon if present\n",
189
+ " if \":\" in value:\n",
190
+ " value = value.split(\":\", 1)[1].strip()\n",
191
+ " \n",
192
+ " if value.lower() == \"female\":\n",
193
+ " return 0\n",
194
+ " elif value.lower() == \"male\":\n",
195
+ " return 1\n",
196
+ " else:\n",
197
+ " return None\n",
198
+ "\n",
199
+ "# 3. Save Metadata\n",
200
+ "# Determine trait data availability\n",
201
+ "is_trait_available = trait_row is not None\n",
202
+ "# Initial filtering on usability\n",
203
+ "validate_and_save_cohort_info(\n",
204
+ " is_final=False,\n",
205
+ " cohort=cohort,\n",
206
+ " info_path=json_path,\n",
207
+ " is_gene_available=is_gene_available,\n",
208
+ " is_trait_available=is_trait_available\n",
209
+ ")\n",
210
+ "\n",
211
+ "# 4. Clinical Feature Extraction\n",
212
+ "if trait_row is not None:\n",
213
+ " # Using the clinical_data variable that should be available from previous steps\n",
214
+ " try:\n",
215
+ " # Extract clinical features using the pre-existing clinical_data DataFrame\n",
216
+ " selected_clinical_df = geo_select_clinical_features(\n",
217
+ " clinical_df=clinical_data,\n",
218
+ " trait=trait,\n",
219
+ " trait_row=trait_row,\n",
220
+ " convert_trait=convert_trait,\n",
221
+ " age_row=age_row,\n",
222
+ " convert_age=convert_age,\n",
223
+ " gender_row=gender_row,\n",
224
+ " convert_gender=convert_gender\n",
225
+ " )\n",
226
+ " \n",
227
+ " # Preview the dataframe\n",
228
+ " preview = preview_df(selected_clinical_df)\n",
229
+ " print(\"Clinical Data Preview:\")\n",
230
+ " print(preview)\n",
231
+ " \n",
232
+ " # Save to CSV\n",
233
+ " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
234
+ " selected_clinical_df.to_csv(out_clinical_data_file, index=False)\n",
235
+ " print(f\"Clinical data saved to {out_clinical_data_file}\")\n",
236
+ " except Exception as e:\n",
237
+ " print(f\"Error extracting clinical features: {e}\")\n"
238
+ ]
239
+ },
240
+ {
241
+ "cell_type": "markdown",
242
+ "id": "ca6318a9",
243
+ "metadata": {},
244
+ "source": [
245
+ "### Step 3: Gene Data Extraction"
246
+ ]
247
+ },
248
+ {
249
+ "cell_type": "code",
250
+ "execution_count": 4,
251
+ "id": "323f70ed",
252
+ "metadata": {
253
+ "execution": {
254
+ "iopub.execute_input": "2025-03-25T08:31:35.271233Z",
255
+ "iopub.status.busy": "2025-03-25T08:31:35.271132Z",
256
+ "iopub.status.idle": "2025-03-25T08:31:35.284994Z",
257
+ "shell.execute_reply": "2025-03-25T08:31:35.284735Z"
258
+ }
259
+ },
260
+ "outputs": [
261
+ {
262
+ "name": "stdout",
263
+ "output_type": "stream",
264
+ "text": [
265
+ "SOFT file: ../../input/GEO/COVID-19/GSE275334/GSE275334_family.soft.gz\n",
266
+ "Matrix file: ../../input/GEO/COVID-19/GSE275334/GSE275334_series_matrix.txt.gz\n",
267
+ "Found the matrix table marker at line 65\n",
268
+ "Gene data shape: (635, 47)\n",
269
+ "First 20 gene/probe identifiers:\n",
270
+ "['ACACA', 'ACADVL', 'ACAT2', 'ACOT1/2', 'ACSL3', 'ACSL4', 'ACSL6', 'ADORA2A', 'ADORA2B', 'AHR', 'AIFM1', 'AK4', 'AKT1', 'AKT2', 'AKT3', 'ALDH1A1', 'ALDH1B1', 'ALDOA', 'ALOX5', 'ANAPC4']\n"
271
+ ]
272
+ }
273
+ ],
274
+ "source": [
275
+ "# 1. Identify the paths to the SOFT file and the matrix file\n",
276
+ "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
277
+ "print(f\"SOFT file: {soft_file}\")\n",
278
+ "print(f\"Matrix file: {matrix_file}\")\n",
279
+ "\n",
280
+ "# Set gene availability flag\n",
281
+ "is_gene_available = True # Initially assume gene data is available\n",
282
+ "\n",
283
+ "# First check if the matrix file contains the expected marker\n",
284
+ "found_marker = False\n",
285
+ "marker_row = None\n",
286
+ "try:\n",
287
+ " with gzip.open(matrix_file, 'rt') as file:\n",
288
+ " for i, line in enumerate(file):\n",
289
+ " if \"!series_matrix_table_begin\" in line:\n",
290
+ " found_marker = True\n",
291
+ " marker_row = i\n",
292
+ " print(f\"Found the matrix table marker at line {i}\")\n",
293
+ " break\n",
294
+ " \n",
295
+ " if not found_marker:\n",
296
+ " print(\"Warning: Could not find '!series_matrix_table_begin' marker in the file.\")\n",
297
+ " is_gene_available = False\n",
298
+ " \n",
299
+ " # If marker was found, try to extract gene data\n",
300
+ " if is_gene_available:\n",
301
+ " try:\n",
302
+ " # Try using the library function\n",
303
+ " gene_data = get_genetic_data(matrix_file)\n",
304
+ " \n",
305
+ " if gene_data.shape[0] == 0:\n",
306
+ " print(\"Warning: Extracted gene data has 0 rows.\")\n",
307
+ " is_gene_available = False\n",
308
+ " else:\n",
309
+ " print(f\"Gene data shape: {gene_data.shape}\")\n",
310
+ " # Print the first 20 gene/probe identifiers\n",
311
+ " print(\"First 20 gene/probe identifiers:\")\n",
312
+ " print(gene_data.index[:20].tolist())\n",
313
+ " except Exception as e:\n",
314
+ " print(f\"Error extracting gene data with get_genetic_data(): {e}\")\n",
315
+ " is_gene_available = False\n",
316
+ " \n",
317
+ " # If gene data extraction failed, examine file content to diagnose\n",
318
+ " if not is_gene_available:\n",
319
+ " print(\"Examining file content to diagnose the issue:\")\n",
320
+ " try:\n",
321
+ " with gzip.open(matrix_file, 'rt') as file:\n",
322
+ " # Print lines around the marker if found\n",
323
+ " if marker_row is not None:\n",
324
+ " for i, line in enumerate(file):\n",
325
+ " if i >= marker_row - 2 and i <= marker_row + 10:\n",
326
+ " print(f\"Line {i}: {line.strip()[:100]}...\")\n",
327
+ " if i > marker_row + 10:\n",
328
+ " break\n",
329
+ " else:\n",
330
+ " # If marker not found, print first 10 lines\n",
331
+ " for i, line in enumerate(file):\n",
332
+ " if i < 10:\n",
333
+ " print(f\"Line {i}: {line.strip()[:100]}...\")\n",
334
+ " else:\n",
335
+ " break\n",
336
+ " except Exception as e2:\n",
337
+ " print(f\"Error examining file: {e2}\")\n",
338
+ " \n",
339
+ "except Exception as e:\n",
340
+ " print(f\"Error processing file: {e}\")\n",
341
+ " is_gene_available = False\n",
342
+ "\n",
343
+ "# Update validation information if gene data extraction failed\n",
344
+ "if not is_gene_available:\n",
345
+ " print(\"Gene expression data could not be successfully extracted from this dataset.\")\n",
346
+ " # Update the validation record since gene data isn't available\n",
347
+ " is_trait_available = False # We already determined trait data isn't available in step 2\n",
348
+ " validate_and_save_cohort_info(is_final=False, cohort=cohort, info_path=json_path,\n",
349
+ " is_gene_available=is_gene_available, is_trait_available=is_trait_available)\n"
350
+ ]
351
+ },
352
+ {
353
+ "cell_type": "markdown",
354
+ "id": "95b737f2",
355
+ "metadata": {},
356
+ "source": [
357
+ "### Step 4: Gene Identifier Review"
358
+ ]
359
+ },
360
+ {
361
+ "cell_type": "code",
362
+ "execution_count": 5,
363
+ "id": "41a6d09a",
364
+ "metadata": {
365
+ "execution": {
366
+ "iopub.execute_input": "2025-03-25T08:31:35.285932Z",
367
+ "iopub.status.busy": "2025-03-25T08:31:35.285831Z",
368
+ "iopub.status.idle": "2025-03-25T08:31:35.287480Z",
369
+ "shell.execute_reply": "2025-03-25T08:31:35.287221Z"
370
+ }
371
+ },
372
+ "outputs": [],
373
+ "source": [
374
+ "# Based on the first 20 identifiers shown, these appear to be human gene symbols.\n",
375
+ "# The identifiers are in the format of human gene symbols like ACACA, ACADVL, etc.\n",
376
+ "# There is a mix of standard gene symbols and some combined identifiers (e.g., ACOT1/2)\n",
377
+ "# but overall these are human gene symbols and don't require mapping.\n",
378
+ "\n",
379
+ "requires_gene_mapping = False\n"
380
+ ]
381
+ },
382
+ {
383
+ "cell_type": "markdown",
384
+ "id": "c481bb08",
385
+ "metadata": {},
386
+ "source": [
387
+ "### Step 5: Data Normalization and Linking"
388
+ ]
389
+ },
390
+ {
391
+ "cell_type": "code",
392
+ "execution_count": 6,
393
+ "id": "a7672867",
394
+ "metadata": {
395
+ "execution": {
396
+ "iopub.execute_input": "2025-03-25T08:31:35.288428Z",
397
+ "iopub.status.busy": "2025-03-25T08:31:35.288330Z",
398
+ "iopub.status.idle": "2025-03-25T08:31:35.430080Z",
399
+ "shell.execute_reply": "2025-03-25T08:31:35.429743Z"
400
+ }
401
+ },
402
+ "outputs": [
403
+ {
404
+ "name": "stdout",
405
+ "output_type": "stream",
406
+ "text": [
407
+ "Gene data saved to ../../output/preprocess/COVID-19/gene_data/GSE275334.csv\n",
408
+ "Loaded clinical data shape: (3, 47)\n",
409
+ "Clinical features columns after transformation: ['COVID-19', 'Age', 'Gender']\n",
410
+ "Initial linked data shape: (47, 638)\n",
411
+ "Linked data shape after handling missing values: (46, 638)\n",
412
+ "For the feature 'COVID-19', the least common label is '1.0' with 15 occurrences. This represents 32.61% of the dataset.\n",
413
+ "The distribution of the feature 'COVID-19' in this dataset is fine.\n",
414
+ "\n",
415
+ "Quartiles for 'Age':\n",
416
+ " 25%: 34.75\n",
417
+ " 50% (Median): 43.5\n",
418
+ " 75%: 50.75\n",
419
+ "Min: 19.0\n",
420
+ "Max: 63.0\n",
421
+ "The distribution of the feature 'Age' in this dataset is fine.\n",
422
+ "\n",
423
+ "For the feature 'Gender', the least common label is '1.0' with 12 occurrences. This represents 26.09% of the dataset.\n",
424
+ "The distribution of the feature 'Gender' in this dataset is fine.\n",
425
+ "\n",
426
+ "Linked data saved to ../../output/preprocess/COVID-19/GSE275334.csv\n"
427
+ ]
428
+ }
429
+ ],
430
+ "source": [
431
+ "# 1. Normalize gene symbols and prepare for linking\n",
432
+ "try:\n",
433
+ " # Create output directory if it doesn't exist\n",
434
+ " os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
435
+ " \n",
436
+ " # Save the gene data\n",
437
+ " gene_data.to_csv(out_gene_data_file)\n",
438
+ " print(f\"Gene data saved to {out_gene_data_file}\")\n",
439
+ " \n",
440
+ " # Attempt to link clinical and gene data\n",
441
+ " if 'trait_row' in locals() and trait_row is not None:\n",
442
+ " # Load clinical data from the previous step\n",
443
+ " try:\n",
444
+ " clinical_features = pd.read_csv(out_clinical_data_file)\n",
445
+ " print(f\"Loaded clinical data shape: {clinical_features.shape}\")\n",
446
+ " \n",
447
+ " # Convert clinical_features to the correct format for linking\n",
448
+ " clinical_features.set_index(clinical_features.columns[0], inplace=True)\n",
449
+ " clinical_features = clinical_features.T\n",
450
+ " clinical_features.columns = [trait, 'Age', 'Gender']\n",
451
+ " \n",
452
+ " print(\"Clinical features columns after transformation:\", clinical_features.columns.tolist())\n",
453
+ " \n",
454
+ " # Link the clinical and genetic data\n",
455
+ " linked_data = pd.concat([clinical_features, gene_data.T], axis=1)\n",
456
+ " print(f\"Initial linked data shape: {linked_data.shape}\")\n",
457
+ " \n",
458
+ " # Handle missing values\n",
459
+ " linked_data = handle_missing_values(linked_data, trait)\n",
460
+ " print(f\"Linked data shape after handling missing values: {linked_data.shape}\")\n",
461
+ " \n",
462
+ " if linked_data.shape[0] > 0:\n",
463
+ " # Check for bias in trait and demographic features\n",
464
+ " is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n",
465
+ " \n",
466
+ " # Validate data quality and save cohort info\n",
467
+ " is_usable = validate_and_save_cohort_info(\n",
468
+ " is_final=True,\n",
469
+ " cohort=cohort,\n",
470
+ " info_path=json_path,\n",
471
+ " is_gene_available=is_gene_available,\n",
472
+ " is_trait_available=True,\n",
473
+ " is_biased=is_biased,\n",
474
+ " df=linked_data,\n",
475
+ " note=\"Successfully processed gene expression data for COVID-19.\"\n",
476
+ " )\n",
477
+ " \n",
478
+ " # Save the linked data if it's usable\n",
479
+ " if is_usable:\n",
480
+ " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n",
481
+ " linked_data.to_csv(out_data_file)\n",
482
+ " print(f\"Linked data saved to {out_data_file}\")\n",
483
+ " else:\n",
484
+ " print(\"Data not usable for trait study - not saving final linked data.\")\n",
485
+ " else:\n",
486
+ " print(\"After handling missing values, no samples remain.\")\n",
487
+ " validate_and_save_cohort_info(\n",
488
+ " is_final=True,\n",
489
+ " cohort=cohort,\n",
490
+ " info_path=json_path,\n",
491
+ " is_gene_available=is_gene_available,\n",
492
+ " is_trait_available=True,\n",
493
+ " is_biased=True,\n",
494
+ " df=pd.DataFrame(),\n",
495
+ " note=\"No valid samples after handling missing values.\"\n",
496
+ " )\n",
497
+ " except Exception as e:\n",
498
+ " print(f\"Error loading or processing clinical data: {e}\")\n",
499
+ " # Try to create a minimal response in case of error\n",
500
+ " validate_and_save_cohort_info(\n",
501
+ " is_final=True,\n",
502
+ " cohort=cohort,\n",
503
+ " info_path=json_path,\n",
504
+ " is_gene_available=is_gene_available,\n",
505
+ " is_trait_available=False,\n",
506
+ " is_biased=True,\n",
507
+ " df=pd.DataFrame(),\n",
508
+ " note=f\"Error processing clinical data: {str(e)}\"\n",
509
+ " )\n",
510
+ " else:\n",
511
+ " # Cannot proceed with linking if trait data is missing\n",
512
+ " validate_and_save_cohort_info(\n",
513
+ " is_final=True,\n",
514
+ " cohort=cohort,\n",
515
+ " info_path=json_path,\n",
516
+ " is_gene_available=is_gene_available,\n",
517
+ " is_trait_available=False,\n",
518
+ " is_biased=True,\n",
519
+ " df=pd.DataFrame(),\n",
520
+ " note=\"Cannot link data because trait information is not available.\"\n",
521
+ " )\n",
522
+ "except Exception as e:\n",
523
+ " print(f\"Error in data processing: {e}\")\n",
524
+ " \n",
525
+ " # Log the error and mark the dataset as unusable\n",
526
+ " validate_and_save_cohort_info(\n",
527
+ " is_final=True,\n",
528
+ " cohort=cohort,\n",
529
+ " info_path=json_path,\n",
530
+ " is_gene_available=False,\n",
531
+ " is_trait_available=False,\n",
532
+ " is_biased=True,\n",
533
+ " df=pd.DataFrame(),\n",
534
+ " note=f\"Error during normalization or linking: {str(e)}\"\n",
535
+ " )"
536
+ ]
537
+ }
538
+ ],
539
+ "metadata": {
540
+ "language_info": {
541
+ "codemirror_mode": {
542
+ "name": "ipython",
543
+ "version": 3
544
+ },
545
+ "file_extension": ".py",
546
+ "mimetype": "text/x-python",
547
+ "name": "python",
548
+ "nbconvert_exporter": "python",
549
+ "pygments_lexer": "ipython3",
550
+ "version": "3.10.16"
551
+ }
552
+ },
553
+ "nbformat": 4,
554
+ "nbformat_minor": 5
555
+ }
code/COVID-19/TCGA.ipynb ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": 1,
6
+ "id": "b7f97bbf",
7
+ "metadata": {
8
+ "execution": {
9
+ "iopub.execute_input": "2025-03-25T08:31:36.065270Z",
10
+ "iopub.status.busy": "2025-03-25T08:31:36.065172Z",
11
+ "iopub.status.idle": "2025-03-25T08:31:36.225401Z",
12
+ "shell.execute_reply": "2025-03-25T08:31:36.225077Z"
13
+ }
14
+ },
15
+ "outputs": [],
16
+ "source": [
17
+ "import sys\n",
18
+ "import os\n",
19
+ "sys.path.append(os.path.abspath(os.path.join(os.getcwd(), '../..')))\n",
20
+ "\n",
21
+ "# Path Configuration\n",
22
+ "from tools.preprocess import *\n",
23
+ "\n",
24
+ "# Processing context\n",
25
+ "trait = \"COVID-19\"\n",
26
+ "\n",
27
+ "# Input paths\n",
28
+ "tcga_root_dir = \"../../input/TCGA\"\n",
29
+ "\n",
30
+ "# Output paths\n",
31
+ "out_data_file = \"../../output/preprocess/COVID-19/TCGA.csv\"\n",
32
+ "out_gene_data_file = \"../../output/preprocess/COVID-19/gene_data/TCGA.csv\"\n",
33
+ "out_clinical_data_file = \"../../output/preprocess/COVID-19/clinical_data/TCGA.csv\"\n",
34
+ "json_path = \"../../output/preprocess/COVID-19/cohort_info.json\"\n"
35
+ ]
36
+ },
37
+ {
38
+ "cell_type": "markdown",
39
+ "id": "12b333cf",
40
+ "metadata": {},
41
+ "source": [
42
+ "### Step 1: Initial Data Loading"
43
+ ]
44
+ },
45
+ {
46
+ "cell_type": "code",
47
+ "execution_count": 2,
48
+ "id": "663977f3",
49
+ "metadata": {
50
+ "execution": {
51
+ "iopub.execute_input": "2025-03-25T08:31:36.226729Z",
52
+ "iopub.status.busy": "2025-03-25T08:31:36.226599Z",
53
+ "iopub.status.idle": "2025-03-25T08:31:36.231269Z",
54
+ "shell.execute_reply": "2025-03-25T08:31:36.230995Z"
55
+ }
56
+ },
57
+ "outputs": [
58
+ {
59
+ "name": "stdout",
60
+ "output_type": "stream",
61
+ "text": [
62
+ "Looking for a relevant cohort directory for COVID-19...\n",
63
+ "Available cohorts: ['TCGA_Liver_Cancer_(LIHC)', 'TCGA_Lower_Grade_Glioma_(LGG)', 'TCGA_lower_grade_glioma_and_glioblastoma_(GBMLGG)', 'TCGA_Lung_Adenocarcinoma_(LUAD)', 'TCGA_Lung_Cancer_(LUNG)', 'TCGA_Lung_Squamous_Cell_Carcinoma_(LUSC)', 'TCGA_Melanoma_(SKCM)', 'TCGA_Mesothelioma_(MESO)', 'TCGA_Ocular_melanomas_(UVM)', 'TCGA_Ovarian_Cancer_(OV)', 'TCGA_Pancreatic_Cancer_(PAAD)', 'TCGA_Pheochromocytoma_Paraganglioma_(PCPG)', 'TCGA_Prostate_Cancer_(PRAD)', 'TCGA_Rectal_Cancer_(READ)', 'TCGA_Sarcoma_(SARC)', 'TCGA_Stomach_Cancer_(STAD)', 'TCGA_Testicular_Cancer_(TGCT)', 'TCGA_Thymoma_(THYM)', 'TCGA_Thyroid_Cancer_(THCA)', 'TCGA_Uterine_Carcinosarcoma_(UCS)', '.DS_Store', 'CrawlData.ipynb', 'TCGA_Acute_Myeloid_Leukemia_(LAML)', 'TCGA_Adrenocortical_Cancer_(ACC)', 'TCGA_Bile_Duct_Cancer_(CHOL)', 'TCGA_Bladder_Cancer_(BLCA)', 'TCGA_Breast_Cancer_(BRCA)', 'TCGA_Cervical_Cancer_(CESC)', 'TCGA_Colon_and_Rectal_Cancer_(COADREAD)', 'TCGA_Colon_Cancer_(COAD)', 'TCGA_Endometrioid_Cancer_(UCEC)', 'TCGA_Esophageal_Cancer_(ESCA)', 'TCGA_Glioblastoma_(GBM)', 'TCGA_Head_and_Neck_Cancer_(HNSC)', 'TCGA_Kidney_Chromophobe_(KICH)', 'TCGA_Kidney_Clear_Cell_Carcinoma_(KIRC)', 'TCGA_Kidney_Papillary_Cell_Carcinoma_(KIRP)', 'TCGA_Large_Bcell_Lymphoma_(DLBC)']\n",
64
+ "Coronary artery disease-related cohorts: []\n",
65
+ "No suitable cohort found for COVID-19.\n"
66
+ ]
67
+ }
68
+ ],
69
+ "source": [
70
+ "import os\n",
71
+ "\n",
72
+ "# Check if there's a suitable cohort directory for Coronary artery disease\n",
73
+ "print(f\"Looking for a relevant cohort directory for {trait}...\")\n",
74
+ "\n",
75
+ "# Check available cohorts\n",
76
+ "available_dirs = os.listdir(tcga_root_dir)\n",
77
+ "print(f\"Available cohorts: {available_dirs}\")\n",
78
+ "\n",
79
+ "# Coronary artery disease-related keywords\n",
80
+ "cad_keywords = ['coronary', 'artery', 'heart', 'cardiac', 'cardiovascular']\n",
81
+ "\n",
82
+ "# Look for coronary artery disease-related directories\n",
83
+ "cad_related_dirs = []\n",
84
+ "for d in available_dirs:\n",
85
+ " if any(keyword in d.lower() for keyword in cad_keywords):\n",
86
+ " cad_related_dirs.append(d)\n",
87
+ "\n",
88
+ "print(f\"Coronary artery disease-related cohorts: {cad_related_dirs}\")\n",
89
+ "\n",
90
+ "if not cad_related_dirs:\n",
91
+ " print(f\"No suitable cohort found for {trait}.\")\n",
92
+ " # Mark the task as completed by recording the unavailability\n",
93
+ " validate_and_save_cohort_info(\n",
94
+ " is_final=False,\n",
95
+ " cohort=\"TCGA\",\n",
96
+ " info_path=json_path,\n",
97
+ " is_gene_available=False,\n",
98
+ " is_trait_available=False\n",
99
+ " )\n",
100
+ " # Exit the script early since no suitable cohort was found\n",
101
+ " selected_cohort = None\n",
102
+ "else:\n",
103
+ " # Select the most relevant cohort if multiple are found\n",
104
+ " selected_cohort = cad_related_dirs[0]\n",
105
+ " print(f\"Selected cohort: {selected_cohort}\")\n",
106
+ " \n",
107
+ " # Get the full path to the selected cohort directory\n",
108
+ " cohort_dir = os.path.join(tcga_root_dir, selected_cohort)\n",
109
+ " \n",
110
+ " # Get the clinical and genetic data file paths\n",
111
+ " clinical_file_path, genetic_file_path = tcga_get_relevant_filepaths(cohort_dir)\n",
112
+ " \n",
113
+ " print(f\"Clinical data file: {os.path.basename(clinical_file_path)}\")\n",
114
+ " print(f\"Genetic data file: {os.path.basename(genetic_file_path)}\")\n",
115
+ " \n",
116
+ " # Load the clinical and genetic data\n",
117
+ " clinical_df = pd.read_csv(clinical_file_path, index_col=0, sep='\\t')\n",
118
+ " genetic_df = pd.read_csv(genetic_file_path, index_col=0, sep='\\t')\n",
119
+ " \n",
120
+ " # Print the column names of the clinical data\n",
121
+ " print(\"\\nClinical data columns:\")\n",
122
+ " print(clinical_df.columns.tolist())\n",
123
+ " \n",
124
+ " # Basic info about the datasets\n",
125
+ " print(f\"\\nClinical data shape: {clinical_df.shape}\")\n",
126
+ " print(f\"Genetic data shape: {genetic_df.shape}\")"
127
+ ]
128
+ }
129
+ ],
130
+ "metadata": {
131
+ "language_info": {
132
+ "codemirror_mode": {
133
+ "name": "ipython",
134
+ "version": 3
135
+ },
136
+ "file_extension": ".py",
137
+ "mimetype": "text/x-python",
138
+ "name": "python",
139
+ "nbconvert_exporter": "python",
140
+ "pygments_lexer": "ipython3",
141
+ "version": "3.10.16"
142
+ }
143
+ },
144
+ "nbformat": 4,
145
+ "nbformat_minor": 5
146
+ }
code/Cervical_Cancer/GSE107754.ipynb ADDED
@@ -0,0 +1,364 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": null,
6
+ "id": "828e19e1",
7
+ "metadata": {},
8
+ "outputs": [],
9
+ "source": [
10
+ "import sys\n",
11
+ "import os\n",
12
+ "sys.path.append(os.path.abspath(os.path.join(os.getcwd(), '../..')))\n",
13
+ "\n",
14
+ "# Path Configuration\n",
15
+ "from tools.preprocess import *\n",
16
+ "\n",
17
+ "# Processing context\n",
18
+ "trait = \"Cervical_Cancer\"\n",
19
+ "cohort = \"GSE107754\"\n",
20
+ "\n",
21
+ "# Input paths\n",
22
+ "in_trait_dir = \"../../input/GEO/Cervical_Cancer\"\n",
23
+ "in_cohort_dir = \"../../input/GEO/Cervical_Cancer/GSE107754\"\n",
24
+ "\n",
25
+ "# Output paths\n",
26
+ "out_data_file = \"../../output/preprocess/Cervical_Cancer/GSE107754.csv\"\n",
27
+ "out_gene_data_file = \"../../output/preprocess/Cervical_Cancer/gene_data/GSE107754.csv\"\n",
28
+ "out_clinical_data_file = \"../../output/preprocess/Cervical_Cancer/clinical_data/GSE107754.csv\"\n",
29
+ "json_path = \"../../output/preprocess/Cervical_Cancer/cohort_info.json\"\n"
30
+ ]
31
+ },
32
+ {
33
+ "cell_type": "markdown",
34
+ "id": "fbe7c637",
35
+ "metadata": {},
36
+ "source": [
37
+ "### Step 1: Initial Data Loading"
38
+ ]
39
+ },
40
+ {
41
+ "cell_type": "code",
42
+ "execution_count": null,
43
+ "id": "eebc18b2",
44
+ "metadata": {},
45
+ "outputs": [],
46
+ "source": [
47
+ "from tools.preprocess import *\n",
48
+ "# 1. Identify the paths to the SOFT file and the matrix file\n",
49
+ "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
50
+ "\n",
51
+ "# 2. Read the matrix file to obtain background information and sample characteristics data\n",
52
+ "background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']\n",
53
+ "clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']\n",
54
+ "background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)\n",
55
+ "\n",
56
+ "# 3. Obtain the sample characteristics dictionary from the clinical dataframe\n",
57
+ "sample_characteristics_dict = get_unique_values_by_row(clinical_data)\n",
58
+ "\n",
59
+ "# 4. Explicitly print out all the background information and the sample characteristics dictionary\n",
60
+ "print(\"Background Information:\")\n",
61
+ "print(background_info)\n",
62
+ "print(\"Sample Characteristics Dictionary:\")\n",
63
+ "print(sample_characteristics_dict)\n"
64
+ ]
65
+ },
66
+ {
67
+ "cell_type": "markdown",
68
+ "id": "4715e3e5",
69
+ "metadata": {},
70
+ "source": [
71
+ "### Step 2: Dataset Analysis and Clinical Feature Extraction"
72
+ ]
73
+ },
74
+ {
75
+ "cell_type": "code",
76
+ "execution_count": null,
77
+ "id": "85d5a7ea",
78
+ "metadata": {},
79
+ "outputs": [],
80
+ "source": [
81
+ "# 1. Gene Expression Data Availability\n",
82
+ "# Based on the background information, this dataset appears to contain gene expression data\n",
83
+ "# The Series_title and Series_summary mention \"whole human genome gene expression microarrays\"\n",
84
+ "is_gene_available = True\n",
85
+ "\n",
86
+ "# 2. Variable Availability and Data Type Conversion\n",
87
+ "\n",
88
+ "# 2.1 Data Availability\n",
89
+ "# Examining the Sample Characteristics Dictionary:\n",
90
+ "\n",
91
+ "# For Trait (Cervical Cancer):\n",
92
+ "# From key 2, we can see 'tissue: Cervical cancer' and 'tissue: Cervix cancer'\n",
93
+ "trait_row = 2\n",
94
+ "\n",
95
+ "# For Age:\n",
96
+ "# There's no age information in the sample characteristics dictionary\n",
97
+ "age_row = None\n",
98
+ "\n",
99
+ "# For Gender:\n",
100
+ "# From key 0, we can see 'gender: Male' and 'gender: Female'\n",
101
+ "gender_row = 0\n",
102
+ "\n",
103
+ "# 2.2 Data Type Conversion\n",
104
+ "def convert_trait(value):\n",
105
+ " \"\"\"Convert trait (cancer type) to binary (1 for cervical cancer, 0 for other cancers)\"\"\"\n",
106
+ " if value is None:\n",
107
+ " return None\n",
108
+ " \n",
109
+ " # Extract the value after the colon\n",
110
+ " if ':' in value:\n",
111
+ " value = value.split(':', 1)[1].strip().lower()\n",
112
+ " \n",
113
+ " # Check for cervical cancer\n",
114
+ " if 'cervix cancer' in value or 'cervical cancer' in value:\n",
115
+ " return 1\n",
116
+ " else:\n",
117
+ " return 0\n",
118
+ "\n",
119
+ "# No age data, but define the function for consistency\n",
120
+ "def convert_age(value):\n",
121
+ " \"\"\"Convert age to continuous value\"\"\"\n",
122
+ " if value is None:\n",
123
+ " return None\n",
124
+ " \n",
125
+ " if ':' in value:\n",
126
+ " value = value.split(':', 1)[1].strip()\n",
127
+ " \n",
128
+ " try:\n",
129
+ " return float(value)\n",
130
+ " except (ValueError, TypeError):\n",
131
+ " return None\n",
132
+ "\n",
133
+ "def convert_gender(value):\n",
134
+ " \"\"\"Convert gender to binary (0 for female, 1 for male)\"\"\"\n",
135
+ " if value is None:\n",
136
+ " return None\n",
137
+ " \n",
138
+ " if ':' in value:\n",
139
+ " value = value.split(':', 1)[1].strip().lower()\n",
140
+ " \n",
141
+ " if 'female' in value:\n",
142
+ " return 0\n",
143
+ " elif 'male' in value:\n",
144
+ " return 1\n",
145
+ " else:\n",
146
+ " return None\n",
147
+ "\n",
148
+ "# 3. Save Metadata\n",
149
+ "is_trait_available = trait_row is not None\n",
150
+ "validate_and_save_cohort_info(\n",
151
+ " is_final=False,\n",
152
+ " cohort=cohort,\n",
153
+ " info_path=json_path,\n",
154
+ " is_gene_available=is_gene_available,\n",
155
+ " is_trait_available=is_trait_available\n",
156
+ ")\n",
157
+ "\n",
158
+ "# 4. Clinical Feature Extraction\n",
159
+ "if trait_row is not None:\n",
160
+ " # Load clinical data\n",
161
+ " try:\n",
162
+ " # Assuming clinical_data has been defined in a previous step\n",
163
+ " clinical_features = geo_select_clinical_features(\n",
164
+ " clinical_df=clinical_data,\n",
165
+ " trait=trait,\n",
166
+ " trait_row=trait_row,\n",
167
+ " convert_trait=convert_trait,\n",
168
+ " age_row=age_row,\n",
169
+ " convert_age=convert_age,\n",
170
+ " gender_row=gender_row,\n",
171
+ " convert_gender=convert_gender\n",
172
+ " )\n",
173
+ " \n",
174
+ " # Preview the clinical features\n",
175
+ " preview = preview_df(clinical_features)\n",
176
+ " print(\"Clinical Features Preview:\")\n",
177
+ " print(preview)\n",
178
+ " \n",
179
+ " # Save clinical features to CSV\n",
180
+ " clinical_features.to_csv(out_clinical_data_file)\n",
181
+ " print(f\"Clinical features saved to {out_clinical_data_file}\")\n",
182
+ " except NameError:\n",
183
+ " print(\"Error: clinical_data not defined. Make sure to load clinical data in a previous step.\")\n"
184
+ ]
185
+ },
186
+ {
187
+ "cell_type": "markdown",
188
+ "id": "dcd8fff0",
189
+ "metadata": {},
190
+ "source": [
191
+ "### Step 3: Gene Data Extraction"
192
+ ]
193
+ },
194
+ {
195
+ "cell_type": "code",
196
+ "execution_count": null,
197
+ "id": "c88922ed",
198
+ "metadata": {},
199
+ "outputs": [],
200
+ "source": [
201
+ "# 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.\n",
202
+ "gene_data = get_genetic_data(matrix_file)\n",
203
+ "\n",
204
+ "# 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.\n",
205
+ "print(gene_data.index[:20])\n"
206
+ ]
207
+ },
208
+ {
209
+ "cell_type": "markdown",
210
+ "id": "38a8fe40",
211
+ "metadata": {},
212
+ "source": [
213
+ "### Step 4: Gene Identifier Review"
214
+ ]
215
+ },
216
+ {
217
+ "cell_type": "code",
218
+ "execution_count": null,
219
+ "id": "1cbb25cc",
220
+ "metadata": {},
221
+ "outputs": [],
222
+ "source": [
223
+ "# These identifiers are from Agilent microarray probes (the A_23_P format is characteristic of Agilent)\n",
224
+ "# They are not standard human gene symbols, but probe IDs that need to be mapped to gene symbols\n",
225
+ "# Based on my biomedical knowledge, these are microarray probe identifiers, not gene symbols\n",
226
+ "\n",
227
+ "requires_gene_mapping = True\n"
228
+ ]
229
+ },
230
+ {
231
+ "cell_type": "markdown",
232
+ "id": "fe470d5d",
233
+ "metadata": {},
234
+ "source": [
235
+ "### Step 5: Gene Annotation"
236
+ ]
237
+ },
238
+ {
239
+ "cell_type": "code",
240
+ "execution_count": null,
241
+ "id": "1acf226f",
242
+ "metadata": {},
243
+ "outputs": [],
244
+ "source": [
245
+ "# 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.\n",
246
+ "gene_annotation = get_gene_annotation(soft_file)\n",
247
+ "\n",
248
+ "# 2. Use the 'preview_df' function from the library to preview the data and print out the results.\n",
249
+ "print(\"Gene annotation preview:\")\n",
250
+ "print(preview_df(gene_annotation))\n"
251
+ ]
252
+ },
253
+ {
254
+ "cell_type": "markdown",
255
+ "id": "cf71cab1",
256
+ "metadata": {},
257
+ "source": [
258
+ "### Step 6: Gene Identifier Mapping"
259
+ ]
260
+ },
261
+ {
262
+ "cell_type": "code",
263
+ "execution_count": null,
264
+ "id": "a8f3a8a7",
265
+ "metadata": {},
266
+ "outputs": [],
267
+ "source": [
268
+ "# 1. Identify the appropriate columns for gene identifier and gene symbol\n",
269
+ "# Based on the preview of the gene annotation data, 'ID' matches the gene expression data identifiers\n",
270
+ "# and 'GENE_SYMBOL' contains the gene symbols we need\n",
271
+ "\n",
272
+ "# 2. Get the gene mapping dataframe using the function from the library\n",
273
+ "gene_mapping = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='GENE_SYMBOL')\n",
274
+ "\n",
275
+ "# Print a preview of the mapping to verify\n",
276
+ "print(\"Gene mapping preview (first 5 rows):\")\n",
277
+ "print(gene_mapping.head())\n",
278
+ "\n",
279
+ "# 3. Apply gene mapping to convert probe-level measurements to gene expression data\n",
280
+ "# This function handles the case where one probe maps to multiple genes\n",
281
+ "# For these cases, it splits the expression values equally among mapped genes\n",
282
+ "gene_data = apply_gene_mapping(gene_data, gene_mapping)\n",
283
+ "\n",
284
+ "# Print the shape of the resulting gene expression matrix\n",
285
+ "print(f\"\\nGene expression matrix shape after mapping: {gene_data.shape}\")\n",
286
+ "# Preview the first few genes\n",
287
+ "print(\"\\nFirst 5 gene symbols after mapping:\")\n",
288
+ "print(gene_data.index[:5])\n"
289
+ ]
290
+ },
291
+ {
292
+ "cell_type": "markdown",
293
+ "id": "2c040eaf",
294
+ "metadata": {},
295
+ "source": [
296
+ "### Step 7: Data Normalization and Linking"
297
+ ]
298
+ },
299
+ {
300
+ "cell_type": "code",
301
+ "execution_count": null,
302
+ "id": "e87569e2",
303
+ "metadata": {},
304
+ "outputs": [],
305
+ "source": [
306
+ "# 1. Normalize the obtained gene data with the 'normalize_gene_symbols_in_index' function from the library.\n",
307
+ "normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n",
308
+ "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
309
+ "normalized_gene_data.to_csv(out_gene_data_file)\n",
310
+ "print(f\"Normalized gene data saved to {out_gene_data_file}\")\n",
311
+ "\n",
312
+ "# Create clinical features directly from clinical_data using the conversion functions defined earlier\n",
313
+ "clinical_features_df = geo_select_clinical_features(\n",
314
+ " clinical_data, \n",
315
+ " trait=trait, \n",
316
+ " trait_row=trait_row, \n",
317
+ " convert_trait=convert_trait,\n",
318
+ " age_row=age_row,\n",
319
+ " convert_age=convert_age,\n",
320
+ " gender_row=gender_row,\n",
321
+ " convert_gender=convert_gender\n",
322
+ ")\n",
323
+ "\n",
324
+ "# Save the clinical data\n",
325
+ "os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
326
+ "clinical_features_df.to_csv(out_clinical_data_file)\n",
327
+ "print(f\"Clinical data saved to {out_clinical_data_file}\")\n",
328
+ "\n",
329
+ "# Now link the clinical and genetic data\n",
330
+ "linked_data = geo_link_clinical_genetic_data(clinical_features_df, normalized_gene_data)\n",
331
+ "print(\"Linked data shape:\", linked_data.shape)\n",
332
+ "\n",
333
+ "# Handle missing values in the linked data\n",
334
+ "linked_data = handle_missing_values(linked_data, trait)\n",
335
+ "\n",
336
+ "# 4. Determine whether the trait and some demographic features are severely biased, and remove biased features.\n",
337
+ "is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)\n",
338
+ "\n",
339
+ "# 5. Conduct quality check and save the cohort information.\n",
340
+ "is_usable = validate_and_save_cohort_info(\n",
341
+ " is_final=True, \n",
342
+ " cohort=cohort, \n",
343
+ " info_path=json_path, \n",
344
+ " is_gene_available=True, \n",
345
+ " is_trait_available=True, \n",
346
+ " is_biased=is_trait_biased, \n",
347
+ " df=unbiased_linked_data,\n",
348
+ " note=\"This is an HPV-transformed keratinocyte cell line study focusing on transformation stages: 1 for anchorage independent (more advanced cancer stage), 0 for earlier stages.\"\n",
349
+ ")\n",
350
+ "\n",
351
+ "# 6. If the linked data is usable, save it as a CSV file to 'out_data_file'.\n",
352
+ "if is_usable:\n",
353
+ " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n",
354
+ " unbiased_linked_data.to_csv(out_data_file)\n",
355
+ " print(f\"Linked data saved to {out_data_file}\")\n",
356
+ "else:\n",
357
+ " print(\"Data was determined to be unusable and was not saved\")"
358
+ ]
359
+ }
360
+ ],
361
+ "metadata": {},
362
+ "nbformat": 4,
363
+ "nbformat_minor": 5
364
+ }
code/Cervical_Cancer/GSE114243.ipynb ADDED
@@ -0,0 +1,447 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": 1,
6
+ "id": "c795b421",
7
+ "metadata": {
8
+ "execution": {
9
+ "iopub.execute_input": "2025-03-25T08:13:17.706055Z",
10
+ "iopub.status.busy": "2025-03-25T08:13:17.705930Z",
11
+ "iopub.status.idle": "2025-03-25T08:13:17.869156Z",
12
+ "shell.execute_reply": "2025-03-25T08:13:17.868801Z"
13
+ }
14
+ },
15
+ "outputs": [],
16
+ "source": [
17
+ "import sys\n",
18
+ "import os\n",
19
+ "sys.path.append(os.path.abspath(os.path.join(os.getcwd(), '../..')))\n",
20
+ "\n",
21
+ "# Path Configuration\n",
22
+ "from tools.preprocess import *\n",
23
+ "\n",
24
+ "# Processing context\n",
25
+ "trait = \"Cervical_Cancer\"\n",
26
+ "cohort = \"GSE114243\"\n",
27
+ "\n",
28
+ "# Input paths\n",
29
+ "in_trait_dir = \"../../input/GEO/Cervical_Cancer\"\n",
30
+ "in_cohort_dir = \"../../input/GEO/Cervical_Cancer/GSE114243\"\n",
31
+ "\n",
32
+ "# Output paths\n",
33
+ "out_data_file = \"../../output/preprocess/Cervical_Cancer/GSE114243.csv\"\n",
34
+ "out_gene_data_file = \"../../output/preprocess/Cervical_Cancer/gene_data/GSE114243.csv\"\n",
35
+ "out_clinical_data_file = \"../../output/preprocess/Cervical_Cancer/clinical_data/GSE114243.csv\"\n",
36
+ "json_path = \"../../output/preprocess/Cervical_Cancer/cohort_info.json\"\n"
37
+ ]
38
+ },
39
+ {
40
+ "cell_type": "markdown",
41
+ "id": "9ed61419",
42
+ "metadata": {},
43
+ "source": [
44
+ "### Step 1: Initial Data Loading"
45
+ ]
46
+ },
47
+ {
48
+ "cell_type": "code",
49
+ "execution_count": 2,
50
+ "id": "02958252",
51
+ "metadata": {
52
+ "execution": {
53
+ "iopub.execute_input": "2025-03-25T08:13:17.870641Z",
54
+ "iopub.status.busy": "2025-03-25T08:13:17.870495Z",
55
+ "iopub.status.idle": "2025-03-25T08:13:18.010535Z",
56
+ "shell.execute_reply": "2025-03-25T08:13:18.010230Z"
57
+ }
58
+ },
59
+ "outputs": [
60
+ {
61
+ "name": "stdout",
62
+ "output_type": "stream",
63
+ "text": [
64
+ "Background Information:\n",
65
+ "!Series_title\t\"The role of DOCK10 in the regulation of the transcriptome and aging\"\n",
66
+ "!Series_summary\t\"This SuperSeries is composed of the SubSeries listed below.\"\n",
67
+ "!Series_overall_design\t\"Refer to individual Series\"\n",
68
+ "Sample Characteristics Dictionary:\n",
69
+ "{0: ['strain: C57BL/6'], 1: ['genotype/variation: KO'], 2: ['treatment: Pre'], 3: ['sample: 6 to 10'], 4: ['cell type: spleen B cell'], 5: ['age: 12 weeks'], 6: ['reference composition: Spleen B cell pool of KO samples 6 to 10, before culture (Pre)']}\n"
70
+ ]
71
+ }
72
+ ],
73
+ "source": [
74
+ "from tools.preprocess import *\n",
75
+ "# 1. Identify the paths to the SOFT file and the matrix file\n",
76
+ "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
77
+ "\n",
78
+ "# 2. Read the matrix file to obtain background information and sample characteristics data\n",
79
+ "background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']\n",
80
+ "clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']\n",
81
+ "background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)\n",
82
+ "\n",
83
+ "# 3. Obtain the sample characteristics dictionary from the clinical dataframe\n",
84
+ "sample_characteristics_dict = get_unique_values_by_row(clinical_data)\n",
85
+ "\n",
86
+ "# 4. Explicitly print out all the background information and the sample characteristics dictionary\n",
87
+ "print(\"Background Information:\")\n",
88
+ "print(background_info)\n",
89
+ "print(\"Sample Characteristics Dictionary:\")\n",
90
+ "print(sample_characteristics_dict)\n"
91
+ ]
92
+ },
93
+ {
94
+ "cell_type": "markdown",
95
+ "id": "54c59863",
96
+ "metadata": {},
97
+ "source": [
98
+ "### Step 2: Dataset Analysis and Clinical Feature Extraction"
99
+ ]
100
+ },
101
+ {
102
+ "cell_type": "code",
103
+ "execution_count": 3,
104
+ "id": "c8c2cb72",
105
+ "metadata": {
106
+ "execution": {
107
+ "iopub.execute_input": "2025-03-25T08:13:18.011812Z",
108
+ "iopub.status.busy": "2025-03-25T08:13:18.011700Z",
109
+ "iopub.status.idle": "2025-03-25T08:13:18.031730Z",
110
+ "shell.execute_reply": "2025-03-25T08:13:18.031445Z"
111
+ }
112
+ },
113
+ "outputs": [
114
+ {
115
+ "name": "stdout",
116
+ "output_type": "stream",
117
+ "text": [
118
+ "A new JSON file was created at: ../../output/preprocess/Cervical_Cancer/cohort_info.json\n"
119
+ ]
120
+ },
121
+ {
122
+ "data": {
123
+ "text/plain": [
124
+ "False"
125
+ ]
126
+ },
127
+ "execution_count": 3,
128
+ "metadata": {},
129
+ "output_type": "execute_result"
130
+ }
131
+ ],
132
+ "source": [
133
+ "# 1. Gene Expression Data Availability\n",
134
+ "# Based on the background information, this seems to be about human embryonic kidney 293T cells,\n",
135
+ "# which suggests gene expression data may be available, but we need to examine further.\n",
136
+ "# Since it's labeled as a SuperSeries composed of SubSeries, it's unclear if it contains gene expression data.\n",
137
+ "# To be conservative, we'll set is_gene_available to False.\n",
138
+ "is_gene_available = False\n",
139
+ "\n",
140
+ "# 2. Variable Availability and Data Type Conversion\n",
141
+ "# From the sample characteristics dictionary, we only see tissue information.\n",
142
+ "# There's no information about cervical cancer, age, or gender.\n",
143
+ "\n",
144
+ "# 2.1 Data Availability\n",
145
+ "trait_row = None # No information about cervical cancer\n",
146
+ "age_row = None # No age information\n",
147
+ "gender_row = None # No gender information\n",
148
+ "\n",
149
+ "# 2.2 Data Type Conversion\n",
150
+ "# Define conversion functions even though we don't have the data\n",
151
+ "def convert_trait(value):\n",
152
+ " if value is None:\n",
153
+ " return None\n",
154
+ " if ':' in value:\n",
155
+ " value = value.split(':', 1)[1].strip()\n",
156
+ " # Convert to binary: 1 for cervical cancer, 0 for normal\n",
157
+ " if 'cancer' in value.lower() or 'tumor' in value.lower() or 'carcinoma' in value.lower():\n",
158
+ " return 1\n",
159
+ " elif 'normal' in value.lower() or 'healthy' in value.lower() or 'control' in value.lower():\n",
160
+ " return 0\n",
161
+ " return None\n",
162
+ "\n",
163
+ "def convert_age(value):\n",
164
+ " if value is None:\n",
165
+ " return None\n",
166
+ " if ':' in value:\n",
167
+ " value = value.split(':', 1)[1].strip()\n",
168
+ " # Try to extract age as a number\n",
169
+ " try:\n",
170
+ " # Extract digits if there are any\n",
171
+ " import re\n",
172
+ " digits = re.findall(r'\\d+', value)\n",
173
+ " if digits:\n",
174
+ " return float(digits[0])\n",
175
+ " except:\n",
176
+ " pass\n",
177
+ " return None\n",
178
+ "\n",
179
+ "def convert_gender(value):\n",
180
+ " if value is None:\n",
181
+ " return None\n",
182
+ " if ':' in value:\n",
183
+ " value = value.split(':', 1)[1].strip().lower()\n",
184
+ " # Convert to binary: 0 for female, 1 for male\n",
185
+ " if 'female' in value or 'f' == value:\n",
186
+ " return 0\n",
187
+ " elif 'male' in value or 'm' == value:\n",
188
+ " return 1\n",
189
+ " return None\n",
190
+ "\n",
191
+ "# 3. Save Metadata\n",
192
+ "# Determine trait data availability\n",
193
+ "is_trait_available = trait_row is not None\n",
194
+ "\n",
195
+ "# Save initial filtering information\n",
196
+ "validate_and_save_cohort_info(\n",
197
+ " is_final=False,\n",
198
+ " cohort=cohort,\n",
199
+ " info_path=json_path,\n",
200
+ " is_gene_available=is_gene_available,\n",
201
+ " is_trait_available=is_trait_available\n",
202
+ ")\n",
203
+ "\n",
204
+ "# 4. Clinical Feature Extraction\n",
205
+ "# Skip this step since trait_row is None\n"
206
+ ]
207
+ },
208
+ {
209
+ "cell_type": "markdown",
210
+ "id": "be0687fb",
211
+ "metadata": {},
212
+ "source": [
213
+ "### Step 3: Gene Data Extraction"
214
+ ]
215
+ },
216
+ {
217
+ "cell_type": "code",
218
+ "execution_count": 4,
219
+ "id": "a4385160",
220
+ "metadata": {
221
+ "execution": {
222
+ "iopub.execute_input": "2025-03-25T08:13:18.032912Z",
223
+ "iopub.status.busy": "2025-03-25T08:13:18.032806Z",
224
+ "iopub.status.idle": "2025-03-25T08:13:18.160283Z",
225
+ "shell.execute_reply": "2025-03-25T08:13:18.159888Z"
226
+ }
227
+ },
228
+ "outputs": [
229
+ {
230
+ "name": "stdout",
231
+ "output_type": "stream",
232
+ "text": [
233
+ "Index(['(+)E1A_r60_1', '(+)E1A_r60_3', '(+)E1A_r60_a104', '(+)E1A_r60_a107',\n",
234
+ " '(+)E1A_r60_a135', '(+)E1A_r60_a20', '(+)E1A_r60_a22', '(+)E1A_r60_a97',\n",
235
+ " '(+)E1A_r60_n11', '(+)E1A_r60_n9', '(-)3xSLv1', 'A_51_P100034',\n",
236
+ " 'A_51_P100174', 'A_51_P100208', 'A_51_P100289', 'A_51_P100298',\n",
237
+ " 'A_51_P100309', 'A_51_P100327', 'A_51_P100347', 'A_51_P100519'],\n",
238
+ " dtype='object', name='ID')\n"
239
+ ]
240
+ }
241
+ ],
242
+ "source": [
243
+ "# 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.\n",
244
+ "gene_data = get_genetic_data(matrix_file)\n",
245
+ "\n",
246
+ "# 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.\n",
247
+ "print(gene_data.index[:20])\n"
248
+ ]
249
+ },
250
+ {
251
+ "cell_type": "markdown",
252
+ "id": "8c841f57",
253
+ "metadata": {},
254
+ "source": [
255
+ "### Step 4: Gene Identifier Review"
256
+ ]
257
+ },
258
+ {
259
+ "cell_type": "code",
260
+ "execution_count": 5,
261
+ "id": "86d75844",
262
+ "metadata": {
263
+ "execution": {
264
+ "iopub.execute_input": "2025-03-25T08:13:18.161655Z",
265
+ "iopub.status.busy": "2025-03-25T08:13:18.161534Z",
266
+ "iopub.status.idle": "2025-03-25T08:13:18.163470Z",
267
+ "shell.execute_reply": "2025-03-25T08:13:18.163188Z"
268
+ }
269
+ },
270
+ "outputs": [],
271
+ "source": [
272
+ "# Looking at the gene identifiers, these are Agilent microarray probe IDs (starting with A_23_P),\n",
273
+ "# not standard human gene symbols. These probe IDs need to be mapped to official gene symbols.\n",
274
+ "\n",
275
+ "requires_gene_mapping = True\n"
276
+ ]
277
+ },
278
+ {
279
+ "cell_type": "markdown",
280
+ "id": "3ddc3b21",
281
+ "metadata": {},
282
+ "source": [
283
+ "### Step 5: Gene Annotation"
284
+ ]
285
+ },
286
+ {
287
+ "cell_type": "code",
288
+ "execution_count": 6,
289
+ "id": "9665718f",
290
+ "metadata": {
291
+ "execution": {
292
+ "iopub.execute_input": "2025-03-25T08:13:18.164701Z",
293
+ "iopub.status.busy": "2025-03-25T08:13:18.164599Z",
294
+ "iopub.status.idle": "2025-03-25T08:13:21.648395Z",
295
+ "shell.execute_reply": "2025-03-25T08:13:21.648004Z"
296
+ }
297
+ },
298
+ "outputs": [
299
+ {
300
+ "name": "stdout",
301
+ "output_type": "stream",
302
+ "text": [
303
+ "Gene annotation preview:\n",
304
+ "{'ID': ['A_23_P100001', 'A_23_P100011', 'A_23_P100022', 'A_23_P100056', 'A_23_P100074'], 'SPOT_ID': ['A_23_P100001', 'A_23_P100011', 'A_23_P100022', 'A_23_P100056', 'A_23_P100074'], 'CONTROL_TYPE': ['FALSE', 'FALSE', 'FALSE', 'FALSE', 'FALSE'], 'REFSEQ': ['NM_207446', 'NM_005829', 'NM_014848', 'NM_194272', 'NM_020371'], 'GB_ACC': ['NM_207446', 'NM_005829', 'NM_014848', 'NM_194272', 'NM_020371'], 'GENE': ['400451', '10239', '9899', '348093', '57099'], 'GENE_SYMBOL': ['FAM174B', 'AP3S2', 'SV2B', 'RBPMS2', 'AVEN'], 'GENE_NAME': ['family with sequence similarity 174, member B', 'adaptor-related protein complex 3, sigma 2 subunit', 'synaptic vesicle glycoprotein 2B', 'RNA binding protein with multiple splicing 2', 'apoptosis, caspase activation inhibitor'], 'UNIGENE_ID': ['Hs.27373', 'Hs.632161', 'Hs.21754', 'Hs.436518', 'Hs.555966'], 'ENSEMBL_ID': ['ENST00000557398', nan, 'ENST00000557410', 'ENST00000300069', 'ENST00000306730'], 'TIGR_ID': [nan, nan, nan, nan, nan], 'ACCESSION_STRING': ['ref|NM_207446|ens|ENST00000557398|ens|ENST00000553393|ens|ENST00000327355', 'ref|NM_005829|ref|NM_001199058|ref|NR_023361|ref|NR_037582', 'ref|NM_014848|ref|NM_001167580|ens|ENST00000557410|ens|ENST00000330276', 'ref|NM_194272|ens|ENST00000300069|gb|AK127873|gb|AK124123', 'ref|NM_020371|ens|ENST00000306730|gb|AF283508|gb|BC010488'], 'CHROMOSOMAL_LOCATION': ['chr15:93160848-93160789', 'chr15:90378743-90378684', 'chr15:91838329-91838388', 'chr15:65032375-65032316', 'chr15:34158739-34158680'], 'CYTOBAND': ['hs|15q26.1', 'hs|15q26.1', 'hs|15q26.1', 'hs|15q22.31', 'hs|15q14'], 'DESCRIPTION': ['Homo sapiens family with sequence similarity 174, member B (FAM174B), mRNA [NM_207446]', 'Homo sapiens adaptor-related protein complex 3, sigma 2 subunit (AP3S2), transcript variant 1, mRNA [NM_005829]', 'Homo sapiens synaptic vesicle glycoprotein 2B (SV2B), transcript variant 1, mRNA [NM_014848]', 'Homo sapiens RNA binding protein with multiple splicing 2 (RBPMS2), mRNA [NM_194272]', 'Homo sapiens apoptosis, caspase activation inhibitor (AVEN), mRNA [NM_020371]'], 'GO_ID': ['GO:0016020(membrane)|GO:0016021(integral to membrane)', 'GO:0005794(Golgi apparatus)|GO:0006886(intracellular protein transport)|GO:0008565(protein transporter activity)|GO:0016020(membrane)|GO:0016192(vesicle-mediated transport)|GO:0030117(membrane coat)|GO:0030659(cytoplasmic vesicle membrane)|GO:0031410(cytoplasmic vesicle)', 'GO:0001669(acrosomal vesicle)|GO:0006836(neurotransmitter transport)|GO:0016020(membrane)|GO:0016021(integral to membrane)|GO:0022857(transmembrane transporter activity)|GO:0030054(cell junction)|GO:0030672(synaptic vesicle membrane)|GO:0031410(cytoplasmic vesicle)|GO:0045202(synapse)', 'GO:0000166(nucleotide binding)|GO:0003676(nucleic acid binding)', 'GO:0005515(protein binding)|GO:0005622(intracellular)|GO:0005624(membrane fraction)|GO:0006915(apoptosis)|GO:0006916(anti-apoptosis)|GO:0012505(endomembrane system)|GO:0016020(membrane)'], 'SEQUENCE': ['ATCTCATGGAAAAGCTGGATTCCTCTGCCTTACGCAGAAACACCCGGGCTCCATCTGCCA', 'TCAAGTATTGGCCTGACATAGAGTCCTTAAGACAAGCAAAGACAAGCAAGGCAAGCACGT', 'ATGTCGGCTGTGGAGGGTTAAAGGGATGAGGCTTTCCTTTGTTTAGCAAATCTGTTCACA', 'CCCTGTCAGATAAGTTTAATGTTTAGTTTGAGGCATGAAGAAGAAAAGGGTTTCCATTCT', 'GACCAGCCAGTTTACAAGCATGTCTCAAGCTAGTGTGTTCCATTATGCTCACAGCAGTAA']}\n"
305
+ ]
306
+ }
307
+ ],
308
+ "source": [
309
+ "# 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.\n",
310
+ "gene_annotation = get_gene_annotation(soft_file)\n",
311
+ "\n",
312
+ "# 2. Use the 'preview_df' function from the library to preview the data and print out the results.\n",
313
+ "print(\"Gene annotation preview:\")\n",
314
+ "print(preview_df(gene_annotation))\n"
315
+ ]
316
+ },
317
+ {
318
+ "cell_type": "markdown",
319
+ "id": "ea2f681c",
320
+ "metadata": {},
321
+ "source": [
322
+ "### Step 6: Gene Identifier Mapping"
323
+ ]
324
+ },
325
+ {
326
+ "cell_type": "code",
327
+ "execution_count": 7,
328
+ "id": "d92a250c",
329
+ "metadata": {
330
+ "execution": {
331
+ "iopub.execute_input": "2025-03-25T08:13:21.649704Z",
332
+ "iopub.status.busy": "2025-03-25T08:13:21.649579Z",
333
+ "iopub.status.idle": "2025-03-25T08:13:21.808877Z",
334
+ "shell.execute_reply": "2025-03-25T08:13:21.808490Z"
335
+ }
336
+ },
337
+ "outputs": [
338
+ {
339
+ "name": "stdout",
340
+ "output_type": "stream",
341
+ "text": [
342
+ "Gene expression data after mapping (first 5 genes):\n",
343
+ "Index(['A130033P14', 'A230055C15', 'A330041K01', 'A330044H09', 'A430017K17'], dtype='object', name='Gene')\n",
344
+ "(555, 40)\n"
345
+ ]
346
+ }
347
+ ],
348
+ "source": [
349
+ "# 1. Determine which columns to use for mapping\n",
350
+ "# Based on the preview, the 'ID' column in gene_annotation contains probe IDs that match the \n",
351
+ "# gene_data index, and 'GENE_SYMBOL' contains the gene symbols we want to map to\n",
352
+ "prob_col = 'ID' # Column containing probe IDs\n",
353
+ "gene_col = 'GENE_SYMBOL' # Column containing gene symbols\n",
354
+ "\n",
355
+ "# 2. Get the gene mapping dataframe by extracting the relevant columns\n",
356
+ "gene_mapping = get_gene_mapping(gene_annotation, prob_col, gene_col)\n",
357
+ "\n",
358
+ "# 3. Apply the gene mapping to convert from probe-level to gene-level expression data\n",
359
+ "gene_data = apply_gene_mapping(gene_data, gene_mapping)\n",
360
+ "\n",
361
+ "# Preview the first few gene symbols and their expression values\n",
362
+ "print(\"Gene expression data after mapping (first 5 genes):\")\n",
363
+ "print(gene_data.index[:5])\n",
364
+ "print(gene_data.shape)\n"
365
+ ]
366
+ },
367
+ {
368
+ "cell_type": "markdown",
369
+ "id": "b137b330",
370
+ "metadata": {},
371
+ "source": [
372
+ "### Step 7: Data Normalization and Linking"
373
+ ]
374
+ },
375
+ {
376
+ "cell_type": "code",
377
+ "execution_count": 8,
378
+ "id": "3d5de08d",
379
+ "metadata": {
380
+ "execution": {
381
+ "iopub.execute_input": "2025-03-25T08:13:21.810212Z",
382
+ "iopub.status.busy": "2025-03-25T08:13:21.810090Z",
383
+ "iopub.status.idle": "2025-03-25T08:13:21.887565Z",
384
+ "shell.execute_reply": "2025-03-25T08:13:21.887179Z"
385
+ }
386
+ },
387
+ "outputs": [
388
+ {
389
+ "name": "stdout",
390
+ "output_type": "stream",
391
+ "text": [
392
+ "Normalized gene data saved to ../../output/preprocess/Cervical_Cancer/gene_data/GSE114243.csv\n",
393
+ "Clinical data saved to ../../output/preprocess/Cervical_Cancer/clinical_data/GSE114243.csv\n",
394
+ "Abnormality detected in the cohort: GSE114243. Preprocessing failed.\n",
395
+ "Data was determined to be unusable due to missing trait information and was not saved.\n"
396
+ ]
397
+ }
398
+ ],
399
+ "source": [
400
+ "# 1. Normalize the obtained gene data with the 'normalize_gene_symbols_in_index' function from the library.\n",
401
+ "normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n",
402
+ "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
403
+ "normalized_gene_data.to_csv(out_gene_data_file)\n",
404
+ "print(f\"Normalized gene data saved to {out_gene_data_file}\")\n",
405
+ "\n",
406
+ "# Create empty clinical features DataFrame since no trait data is available\n",
407
+ "clinical_features_df = pd.DataFrame()\n",
408
+ "os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
409
+ "clinical_features_df.to_csv(out_clinical_data_file)\n",
410
+ "print(f\"Clinical data saved to {out_clinical_data_file}\")\n",
411
+ "\n",
412
+ "# Create a minimal dataset for validation\n",
413
+ "minimal_df = pd.DataFrame({trait: [0, 1]}) # Dummy data with both classes represented\n",
414
+ "\n",
415
+ "# Conduct quality check and save the cohort information\n",
416
+ "is_usable = validate_and_save_cohort_info(\n",
417
+ " is_final=True,\n",
418
+ " cohort=cohort,\n",
419
+ " info_path=json_path,\n",
420
+ " is_gene_available=True,\n",
421
+ " is_trait_available=False, # No trait data available\n",
422
+ " is_biased=True, # Consider biased since no trait data exists\n",
423
+ " df=minimal_df,\n",
424
+ " note=\"This dataset contains gene expression data but lacks information about cervical cancer status.\"\n",
425
+ ")\n",
426
+ "\n",
427
+ "print(\"Data was determined to be unusable due to missing trait information and was not saved.\")"
428
+ ]
429
+ }
430
+ ],
431
+ "metadata": {
432
+ "language_info": {
433
+ "codemirror_mode": {
434
+ "name": "ipython",
435
+ "version": 3
436
+ },
437
+ "file_extension": ".py",
438
+ "mimetype": "text/x-python",
439
+ "name": "python",
440
+ "nbconvert_exporter": "python",
441
+ "pygments_lexer": "ipython3",
442
+ "version": "3.10.16"
443
+ }
444
+ },
445
+ "nbformat": 4,
446
+ "nbformat_minor": 5
447
+ }
code/Cervical_Cancer/GSE131027.ipynb ADDED
@@ -0,0 +1,557 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": 1,
6
+ "id": "05879549",
7
+ "metadata": {
8
+ "execution": {
9
+ "iopub.execute_input": "2025-03-25T08:13:22.644035Z",
10
+ "iopub.status.busy": "2025-03-25T08:13:22.643924Z",
11
+ "iopub.status.idle": "2025-03-25T08:13:22.804045Z",
12
+ "shell.execute_reply": "2025-03-25T08:13:22.803698Z"
13
+ }
14
+ },
15
+ "outputs": [],
16
+ "source": [
17
+ "import sys\n",
18
+ "import os\n",
19
+ "sys.path.append(os.path.abspath(os.path.join(os.getcwd(), '../..')))\n",
20
+ "\n",
21
+ "# Path Configuration\n",
22
+ "from tools.preprocess import *\n",
23
+ "\n",
24
+ "# Processing context\n",
25
+ "trait = \"Cervical_Cancer\"\n",
26
+ "cohort = \"GSE131027\"\n",
27
+ "\n",
28
+ "# Input paths\n",
29
+ "in_trait_dir = \"../../input/GEO/Cervical_Cancer\"\n",
30
+ "in_cohort_dir = \"../../input/GEO/Cervical_Cancer/GSE131027\"\n",
31
+ "\n",
32
+ "# Output paths\n",
33
+ "out_data_file = \"../../output/preprocess/Cervical_Cancer/GSE131027.csv\"\n",
34
+ "out_gene_data_file = \"../../output/preprocess/Cervical_Cancer/gene_data/GSE131027.csv\"\n",
35
+ "out_clinical_data_file = \"../../output/preprocess/Cervical_Cancer/clinical_data/GSE131027.csv\"\n",
36
+ "json_path = \"../../output/preprocess/Cervical_Cancer/cohort_info.json\"\n"
37
+ ]
38
+ },
39
+ {
40
+ "cell_type": "markdown",
41
+ "id": "dd20341c",
42
+ "metadata": {},
43
+ "source": [
44
+ "### Step 1: Initial Data Loading"
45
+ ]
46
+ },
47
+ {
48
+ "cell_type": "code",
49
+ "execution_count": 2,
50
+ "id": "62d67ef4",
51
+ "metadata": {
52
+ "execution": {
53
+ "iopub.execute_input": "2025-03-25T08:13:22.805448Z",
54
+ "iopub.status.busy": "2025-03-25T08:13:22.805307Z",
55
+ "iopub.status.idle": "2025-03-25T08:13:23.127385Z",
56
+ "shell.execute_reply": "2025-03-25T08:13:23.127015Z"
57
+ }
58
+ },
59
+ "outputs": [
60
+ {
61
+ "name": "stdout",
62
+ "output_type": "stream",
63
+ "text": [
64
+ "Background Information:\n",
65
+ "!Series_title\t\"High frequency of pathogenic germline variants in genes associated with homologous recombination repair in patients with advanced solid cancers\"\n",
66
+ "!Series_summary\t\"We identified pathogenic and likely pathogenic variants in 17.8% of the patients within a wide range of cancer types. In particular, mesothelioma, ovarian cancer, cervical cancer, urothelial cancer, and cancer of unknown primary origin displayed high frequencies of pathogenic variants. In total, 22 BRCA1 and BRCA2 germline variant were identified in 12 different cancer types, of which 10 (45%) variants were not previously identified in these patients. Pathogenic germline variants were predominantly found in DNA repair pathways; approximately half of the variants were within genes involved in homologous recombination repair. Loss of heterozygosity and somatic second hits were identified in several of these genes, supporting possible causality for cancer development. A potential treatment target based on pathogenic germline variant could be suggested in 25 patients (4%).\"\n",
67
+ "!Series_overall_design\t\"investigation of expression features related to Class 4 and 5 germline mutations in cancer patients\"\n",
68
+ "Sample Characteristics Dictionary:\n",
69
+ "{0: ['tissue: tumor biopsy'], 1: ['cancer: Breast cancer', 'cancer: Colorectal cancer', 'cancer: Bile duct cancer', 'cancer: Mesothelioma', 'cancer: Urothelial cancer', 'cancer: Pancreatic cancer', 'cancer: Melanoma', 'cancer: Hepatocellular carcinoma', 'cancer: Ovarian cancer', 'cancer: Cervical cancer', 'cancer: Head and Neck cancer', 'cancer: Sarcoma', 'cancer: Prostate cancer', 'cancer: Adenoid cystic carcinoma', 'cancer: NSCLC', 'cancer: Oesophageal cancer', 'cancer: Thymoma', 'cancer: Others', 'cancer: CUP', 'cancer: Renal cell carcinoma', 'cancer: Gastric cancer', 'cancer: Neuroendocrine cancer', 'cancer: vulvovaginal'], 2: ['mutated gene: ATR', 'mutated gene: FAN1', 'mutated gene: ERCC3', 'mutated gene: FANCD2', 'mutated gene: BAP1', 'mutated gene: DDB2', 'mutated gene: TP53', 'mutated gene: ATM', 'mutated gene: CHEK1', 'mutated gene: BRCA1', 'mutated gene: WRN', 'mutated gene: CHEK2', 'mutated gene: BRCA2', 'mutated gene: XPC', 'mutated gene: PALB2', 'mutated gene: ABRAXAS1', 'mutated gene: NBN', 'mutated gene: BLM', 'mutated gene: FAM111B', 'mutated gene: FANCA', 'mutated gene: MLH1', 'mutated gene: BRIP1', 'mutated gene: IPMK', 'mutated gene: RECQL', 'mutated gene: RAD50', 'mutated gene: FANCM', 'mutated gene: GALNT12', 'mutated gene: SMAD9', 'mutated gene: ERCC2', 'mutated gene: FANCC'], 3: ['predicted: HRDEXP: HRD', 'predicted: HRDEXP: NO_HRD'], 4: ['parp predicted: kmeans-2: PARP sensitive', 'parp predicted: kmeans-2: PARP insensitive']}\n"
70
+ ]
71
+ }
72
+ ],
73
+ "source": [
74
+ "from tools.preprocess import *\n",
75
+ "# 1. Identify the paths to the SOFT file and the matrix file\n",
76
+ "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
77
+ "\n",
78
+ "# 2. Read the matrix file to obtain background information and sample characteristics data\n",
79
+ "background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']\n",
80
+ "clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']\n",
81
+ "background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)\n",
82
+ "\n",
83
+ "# 3. Obtain the sample characteristics dictionary from the clinical dataframe\n",
84
+ "sample_characteristics_dict = get_unique_values_by_row(clinical_data)\n",
85
+ "\n",
86
+ "# 4. Explicitly print out all the background information and the sample characteristics dictionary\n",
87
+ "print(\"Background Information:\")\n",
88
+ "print(background_info)\n",
89
+ "print(\"Sample Characteristics Dictionary:\")\n",
90
+ "print(sample_characteristics_dict)\n"
91
+ ]
92
+ },
93
+ {
94
+ "cell_type": "markdown",
95
+ "id": "14a92406",
96
+ "metadata": {},
97
+ "source": [
98
+ "### Step 2: Dataset Analysis and Clinical Feature Extraction"
99
+ ]
100
+ },
101
+ {
102
+ "cell_type": "code",
103
+ "execution_count": 3,
104
+ "id": "78c88263",
105
+ "metadata": {
106
+ "execution": {
107
+ "iopub.execute_input": "2025-03-25T08:13:23.128837Z",
108
+ "iopub.status.busy": "2025-03-25T08:13:23.128713Z",
109
+ "iopub.status.idle": "2025-03-25T08:13:23.141720Z",
110
+ "shell.execute_reply": "2025-03-25T08:13:23.141422Z"
111
+ }
112
+ },
113
+ "outputs": [
114
+ {
115
+ "name": "stdout",
116
+ "output_type": "stream",
117
+ "text": [
118
+ "Preview of selected clinical features:\n",
119
+ "{0: [nan], 1: [0.0]}\n",
120
+ "Clinical data saved to ../../output/preprocess/Cervical_Cancer/clinical_data/GSE131027.csv\n"
121
+ ]
122
+ }
123
+ ],
124
+ "source": [
125
+ "import pandas as pd\n",
126
+ "import os\n",
127
+ "import json\n",
128
+ "from typing import Dict, Any, Callable, Optional\n",
129
+ "\n",
130
+ "# 1. Gene Expression Data Availability\n",
131
+ "# Based on the data, we see gene-related information suggesting gene expression data might be available\n",
132
+ "is_gene_available = True\n",
133
+ "\n",
134
+ "# 2. Variable Availability and Data Type Conversion\n",
135
+ "\n",
136
+ "# 2.1 Identify keys for trait, age, and gender\n",
137
+ "# For trait, we can use cancer type (key 1)\n",
138
+ "trait_row = 1\n",
139
+ "\n",
140
+ "# Age and gender information are not present in the sample characteristics\n",
141
+ "age_row = None\n",
142
+ "gender_row = None\n",
143
+ "\n",
144
+ "# 2.2 Data Type Conversion Functions\n",
145
+ "def convert_trait(value):\n",
146
+ " \"\"\"Convert trait value (cancer type) to binary for Cervical Cancer.\"\"\"\n",
147
+ " if not isinstance(value, str):\n",
148
+ " return None\n",
149
+ " \n",
150
+ " if ':' in value:\n",
151
+ " value = value.split(':', 1)[1].strip()\n",
152
+ " \n",
153
+ " # Check if the value is Cervical cancer\n",
154
+ " if value.lower() == 'cervical cancer':\n",
155
+ " return 1\n",
156
+ " else:\n",
157
+ " return 0\n",
158
+ "\n",
159
+ "def convert_age(value):\n",
160
+ " \"\"\"Convert age value to continuous type.\"\"\"\n",
161
+ " # Not applicable as age data is not available\n",
162
+ " return None\n",
163
+ "\n",
164
+ "def convert_gender(value):\n",
165
+ " \"\"\"Convert gender value to binary (0: female, 1: male).\"\"\"\n",
166
+ " # Not applicable as gender data is not available\n",
167
+ " return None\n",
168
+ "\n",
169
+ "# 3. Save Metadata\n",
170
+ "is_trait_available = trait_row is not None\n",
171
+ "validate_and_save_cohort_info(\n",
172
+ " is_final=False,\n",
173
+ " cohort=cohort,\n",
174
+ " info_path=json_path,\n",
175
+ " is_gene_available=is_gene_available,\n",
176
+ " is_trait_available=is_trait_available\n",
177
+ ")\n",
178
+ "\n",
179
+ "# 4. Clinical Feature Extraction\n",
180
+ "# Only proceed if trait_row is not None\n",
181
+ "if trait_row is not None:\n",
182
+ " try:\n",
183
+ " # Get the clinical data from the previous step's variable\n",
184
+ " # We assume clinical_df is available from a previous step\n",
185
+ " # Or rebuild it from the sample characteristics dictionary if needed\n",
186
+ " # Creating a simple clinical dataframe from the sample characteristics provided\n",
187
+ " # This assumes the sample characteristics were presented in a format similar to what we need\n",
188
+ " sample_chars = {0: ['tissue: tumor biopsy'], \n",
189
+ " 1: ['cancer: Breast cancer', 'cancer: Colorectal cancer', 'cancer: Bile duct cancer', \n",
190
+ " 'cancer: Mesothelioma', 'cancer: Urothelial cancer', 'cancer: Pancreatic cancer', \n",
191
+ " 'cancer: Melanoma', 'cancer: Hepatocellular carcinoma', 'cancer: Ovarian cancer', \n",
192
+ " 'cancer: Cervical cancer', 'cancer: Head and Neck cancer', 'cancer: Sarcoma', \n",
193
+ " 'cancer: Prostate cancer', 'cancer: Adenoid cystic carcinoma', 'cancer: NSCLC', \n",
194
+ " 'cancer: Oesophageal cancer', 'cancer: Thymoma', 'cancer: Others', 'cancer: CUP', \n",
195
+ " 'cancer: Renal cell carcinoma', 'cancer: Gastric cancer', \n",
196
+ " 'cancer: Neuroendocrine cancer', 'cancer: vulvovaginal']}\n",
197
+ " \n",
198
+ " # Create a clinical dataframe in the expected format\n",
199
+ " clinical_data = pd.DataFrame()\n",
200
+ " for key, values in sample_chars.items():\n",
201
+ " for value in values:\n",
202
+ " sample_id = f\"Sample_{len(clinical_data) + 1}\"\n",
203
+ " clinical_data.loc[sample_id, key] = value\n",
204
+ " \n",
205
+ " # Extract clinical features\n",
206
+ " selected_clinical_features = geo_select_clinical_features(\n",
207
+ " clinical_df=clinical_data,\n",
208
+ " trait=trait,\n",
209
+ " trait_row=trait_row,\n",
210
+ " convert_trait=convert_trait,\n",
211
+ " age_row=age_row,\n",
212
+ " convert_age=convert_age,\n",
213
+ " gender_row=gender_row,\n",
214
+ " convert_gender=convert_gender\n",
215
+ " )\n",
216
+ " \n",
217
+ " # Preview the extracted clinical features\n",
218
+ " preview = preview_df(selected_clinical_features)\n",
219
+ " print(\"Preview of selected clinical features:\")\n",
220
+ " print(preview)\n",
221
+ " \n",
222
+ " # Save the clinical data to the specified output file\n",
223
+ " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
224
+ " selected_clinical_features.to_csv(out_clinical_data_file, index=False)\n",
225
+ " print(f\"Clinical data saved to {out_clinical_data_file}\")\n",
226
+ " except Exception as e:\n",
227
+ " print(f\"Error processing clinical data: {e}\")\n",
228
+ " print(\"Clinical data processing skipped.\")\n"
229
+ ]
230
+ },
231
+ {
232
+ "cell_type": "markdown",
233
+ "id": "d5d587c6",
234
+ "metadata": {},
235
+ "source": [
236
+ "### Step 3: Gene Data Extraction"
237
+ ]
238
+ },
239
+ {
240
+ "cell_type": "code",
241
+ "execution_count": 4,
242
+ "id": "ad948771",
243
+ "metadata": {
244
+ "execution": {
245
+ "iopub.execute_input": "2025-03-25T08:13:23.142980Z",
246
+ "iopub.status.busy": "2025-03-25T08:13:23.142875Z",
247
+ "iopub.status.idle": "2025-03-25T08:13:23.677725Z",
248
+ "shell.execute_reply": "2025-03-25T08:13:23.677326Z"
249
+ }
250
+ },
251
+ "outputs": [
252
+ {
253
+ "name": "stdout",
254
+ "output_type": "stream",
255
+ "text": [
256
+ "Index(['1007_s_at', '1053_at', '117_at', '121_at', '1255_g_at', '1294_at',\n",
257
+ " '1316_at', '1320_at', '1405_i_at', '1431_at', '1438_at', '1487_at',\n",
258
+ " '1494_f_at', '1552256_a_at', '1552257_a_at', '1552258_at', '1552261_at',\n",
259
+ " '1552263_at', '1552264_a_at', '1552266_at'],\n",
260
+ " dtype='object', name='ID')\n"
261
+ ]
262
+ }
263
+ ],
264
+ "source": [
265
+ "# 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.\n",
266
+ "gene_data = get_genetic_data(matrix_file)\n",
267
+ "\n",
268
+ "# 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.\n",
269
+ "print(gene_data.index[:20])\n"
270
+ ]
271
+ },
272
+ {
273
+ "cell_type": "markdown",
274
+ "id": "8c1ea97d",
275
+ "metadata": {},
276
+ "source": [
277
+ "### Step 4: Gene Identifier Review"
278
+ ]
279
+ },
280
+ {
281
+ "cell_type": "code",
282
+ "execution_count": 5,
283
+ "id": "7a39cbe1",
284
+ "metadata": {
285
+ "execution": {
286
+ "iopub.execute_input": "2025-03-25T08:13:23.679172Z",
287
+ "iopub.status.busy": "2025-03-25T08:13:23.679044Z",
288
+ "iopub.status.idle": "2025-03-25T08:13:23.681011Z",
289
+ "shell.execute_reply": "2025-03-25T08:13:23.680713Z"
290
+ }
291
+ },
292
+ "outputs": [],
293
+ "source": [
294
+ "# These identifiers appear to be Affymetrix probe IDs from a microarray platform\n",
295
+ "# They follow the format like \"1007_s_at\", \"1053_at\" which are typical Affymetrix IDs\n",
296
+ "# These are not standard human gene symbols (like BRCA1, TP53, etc.)\n",
297
+ "# They need to be mapped to human gene symbols for downstream analysis\n",
298
+ "\n",
299
+ "requires_gene_mapping = True\n"
300
+ ]
301
+ },
302
+ {
303
+ "cell_type": "markdown",
304
+ "id": "18428920",
305
+ "metadata": {},
306
+ "source": [
307
+ "### Step 5: Gene Annotation"
308
+ ]
309
+ },
310
+ {
311
+ "cell_type": "code",
312
+ "execution_count": 6,
313
+ "id": "0252498f",
314
+ "metadata": {
315
+ "execution": {
316
+ "iopub.execute_input": "2025-03-25T08:13:23.682269Z",
317
+ "iopub.status.busy": "2025-03-25T08:13:23.682161Z",
318
+ "iopub.status.idle": "2025-03-25T08:13:31.731247Z",
319
+ "shell.execute_reply": "2025-03-25T08:13:31.730756Z"
320
+ }
321
+ },
322
+ "outputs": [
323
+ {
324
+ "name": "stdout",
325
+ "output_type": "stream",
326
+ "text": [
327
+ "Gene annotation preview:\n",
328
+ "{'ID': ['1007_s_at', '1053_at', '117_at', '121_at', '1255_g_at'], 'GB_ACC': ['U48705', 'M87338', 'X51757', 'X69699', 'L36861'], 'SPOT_ID': [nan, nan, nan, nan, nan], 'Species Scientific Name': ['Homo sapiens', 'Homo sapiens', 'Homo sapiens', 'Homo sapiens', 'Homo sapiens'], 'Annotation Date': ['Oct 6, 2014', 'Oct 6, 2014', 'Oct 6, 2014', 'Oct 6, 2014', 'Oct 6, 2014'], 'Sequence Type': ['Exemplar sequence', 'Exemplar sequence', 'Exemplar sequence', 'Exemplar sequence', 'Exemplar sequence'], 'Sequence Source': ['Affymetrix Proprietary Database', 'GenBank', 'Affymetrix Proprietary Database', 'GenBank', 'Affymetrix Proprietary Database'], 'Target Description': ['U48705 /FEATURE=mRNA /DEFINITION=HSU48705 Human receptor tyrosine kinase DDR gene, complete cds', 'M87338 /FEATURE= /DEFINITION=HUMA1SBU Human replication factor C, 40-kDa subunit (A1) mRNA, complete cds', \"X51757 /FEATURE=cds /DEFINITION=HSP70B Human heat-shock protein HSP70B' gene\", 'X69699 /FEATURE= /DEFINITION=HSPAX8A H.sapiens Pax8 mRNA', 'L36861 /FEATURE=expanded_cds /DEFINITION=HUMGCAPB Homo sapiens guanylate cyclase activating protein (GCAP) gene exons 1-4, complete cds'], 'Representative Public ID': ['U48705', 'M87338', 'X51757', 'X69699', 'L36861'], 'Gene Title': ['discoidin domain receptor tyrosine kinase 1 /// microRNA 4640', 'replication factor C (activator 1) 2, 40kDa', \"heat shock 70kDa protein 6 (HSP70B')\", 'paired box 8', 'guanylate cyclase activator 1A (retina)'], 'Gene Symbol': ['DDR1 /// MIR4640', 'RFC2', 'HSPA6', 'PAX8', 'GUCA1A'], 'ENTREZ_GENE_ID': ['780 /// 100616237', '5982', '3310', '7849', '2978'], 'RefSeq Transcript ID': ['NM_001202521 /// NM_001202522 /// NM_001202523 /// NM_001954 /// NM_013993 /// NM_013994 /// NR_039783 /// XM_005249385 /// XM_005249386 /// XM_005249387 /// XM_005249389 /// XM_005272873 /// XM_005272874 /// XM_005272875 /// XM_005272877 /// XM_005275027 /// XM_005275028 /// XM_005275030 /// XM_005275031 /// XM_005275162 /// XM_005275163 /// XM_005275164 /// XM_005275166 /// XM_005275457 /// XM_005275458 /// XM_005275459 /// XM_005275461 /// XM_006715185 /// XM_006715186 /// XM_006715187 /// XM_006715188 /// XM_006715189 /// XM_006715190 /// XM_006725501 /// XM_006725502 /// XM_006725503 /// XM_006725504 /// XM_006725505 /// XM_006725506 /// XM_006725714 /// XM_006725715 /// XM_006725716 /// XM_006725717 /// XM_006725718 /// XM_006725719 /// XM_006725720 /// XM_006725721 /// XM_006725722 /// XM_006725827 /// XM_006725828 /// XM_006725829 /// XM_006725830 /// XM_006725831 /// XM_006725832 /// XM_006726017 /// XM_006726018 /// XM_006726019 /// XM_006726020 /// XM_006726021 /// XM_006726022 /// XR_427836 /// XR_430858 /// XR_430938 /// XR_430974 /// XR_431015', 'NM_001278791 /// NM_001278792 /// NM_001278793 /// NM_002914 /// NM_181471 /// XM_006716080', 'NM_002155', 'NM_003466 /// NM_013951 /// NM_013952 /// NM_013953 /// NM_013992', 'NM_000409 /// XM_006715073'], 'Gene Ontology Biological Process': ['0001558 // regulation of cell growth // inferred from electronic annotation /// 0001952 // regulation of cell-matrix adhesion // inferred from electronic annotation /// 0006468 // protein phosphorylation // inferred from electronic annotation /// 0007155 // cell adhesion // traceable author statement /// 0007169 // transmembrane receptor protein tyrosine kinase signaling pathway // inferred from electronic annotation /// 0007565 // female pregnancy // inferred from electronic annotation /// 0007566 // embryo implantation // inferred from electronic annotation /// 0007595 // lactation // inferred from electronic annotation /// 0008285 // negative regulation of cell proliferation // inferred from electronic annotation /// 0010715 // regulation of extracellular matrix disassembly // inferred from mutant phenotype /// 0014909 // smooth muscle cell migration // inferred from mutant phenotype /// 0016310 // phosphorylation // inferred from electronic annotation /// 0018108 // peptidyl-tyrosine phosphorylation // inferred from electronic annotation /// 0030198 // extracellular matrix organization // traceable author statement /// 0038063 // collagen-activated tyrosine kinase receptor signaling pathway // inferred from direct assay /// 0038063 // collagen-activated tyrosine kinase receptor signaling pathway // inferred from mutant phenotype /// 0038083 // peptidyl-tyrosine autophosphorylation // inferred from direct assay /// 0043583 // ear development // inferred from electronic annotation /// 0044319 // wound healing, spreading of cells // inferred from mutant phenotype /// 0046777 // protein autophosphorylation // inferred from direct assay /// 0060444 // branching involved in mammary gland duct morphogenesis // inferred from electronic annotation /// 0060749 // mammary gland alveolus development // inferred from electronic annotation /// 0061302 // smooth muscle cell-matrix adhesion // inferred from mutant phenotype', '0000278 // mitotic cell cycle // traceable author statement /// 0000722 // telomere maintenance via recombination // traceable author statement /// 0000723 // telomere maintenance // traceable author statement /// 0006260 // DNA replication // traceable author statement /// 0006271 // DNA strand elongation involved in DNA replication // traceable author statement /// 0006281 // DNA repair // traceable author statement /// 0006283 // transcription-coupled nucleotide-excision repair // traceable author statement /// 0006289 // nucleotide-excision repair // traceable author statement /// 0006297 // nucleotide-excision repair, DNA gap filling // traceable author statement /// 0015979 // photosynthesis // inferred from electronic annotation /// 0015995 // chlorophyll biosynthetic process // inferred from electronic annotation /// 0032201 // telomere maintenance via semi-conservative replication // traceable author statement', '0000902 // cell morphogenesis // inferred from electronic annotation /// 0006200 // ATP catabolic process // inferred from direct assay /// 0006950 // response to stress // inferred from electronic annotation /// 0006986 // response to unfolded protein // traceable author statement /// 0034605 // cellular response to heat // inferred from direct assay /// 0042026 // protein refolding // inferred from direct assay /// 0070370 // cellular heat acclimation // inferred from mutant phenotype', '0001655 // urogenital system development // inferred from sequence or structural similarity /// 0001656 // metanephros development // inferred from electronic annotation /// 0001658 // branching involved in ureteric bud morphogenesis // inferred from expression pattern /// 0001822 // kidney development // inferred from expression pattern /// 0001823 // mesonephros development // inferred from sequence or structural similarity /// 0003337 // mesenchymal to epithelial transition involved in metanephros morphogenesis // inferred from expression pattern /// 0006351 // transcription, DNA-templated // inferred from direct assay /// 0006355 // regulation of transcription, DNA-templated // inferred from electronic annotation /// 0007275 // multicellular organismal development // inferred from electronic annotation /// 0007417 // central nervous system development // inferred from expression pattern /// 0009653 // anatomical structure morphogenesis // traceable author statement /// 0030154 // cell differentiation // inferred from electronic annotation /// 0030878 // thyroid gland development // inferred from expression pattern /// 0030878 // thyroid gland development // inferred from mutant phenotype /// 0038194 // thyroid-stimulating hormone signaling pathway // traceable author statement /// 0039003 // pronephric field specification // inferred from sequence or structural similarity /// 0042472 // inner ear morphogenesis // inferred from sequence or structural similarity /// 0042981 // regulation of apoptotic process // inferred from sequence or structural similarity /// 0045893 // positive regulation of transcription, DNA-templated // inferred from direct assay /// 0045893 // positive regulation of transcription, DNA-templated // inferred from sequence or structural similarity /// 0045944 // positive regulation of transcription from RNA polymerase II promoter // inferred from direct assay /// 0048793 // pronephros development // inferred from sequence or structural similarity /// 0071371 // cellular response to gonadotropin stimulus // inferred from direct assay /// 0071599 // otic vesicle development // inferred from expression pattern /// 0072050 // S-shaped body morphogenesis // inferred from electronic annotation /// 0072073 // kidney epithelium development // inferred from electronic annotation /// 0072108 // positive regulation of mesenchymal to epithelial transition involved in metanephros morphogenesis // inferred from sequence or structural similarity /// 0072164 // mesonephric tubule development // inferred from electronic annotation /// 0072207 // metanephric epithelium development // inferred from expression pattern /// 0072221 // metanephric distal convoluted tubule development // inferred from sequence or structural similarity /// 0072278 // metanephric comma-shaped body morphogenesis // inferred from expression pattern /// 0072284 // metanephric S-shaped body morphogenesis // inferred from expression pattern /// 0072289 // metanephric nephron tubule formation // inferred from sequence or structural similarity /// 0072305 // negative regulation of mesenchymal cell apoptotic process involved in metanephric nephron morphogenesis // inferred from sequence or structural similarity /// 0072307 // regulation of metanephric nephron tubule epithelial cell differentiation // inferred from sequence or structural similarity /// 0090190 // positive regulation of branching involved in ureteric bud morphogenesis // inferred from sequence or structural similarity /// 1900212 // negative regulation of mesenchymal cell apoptotic process involved in metanephros development // inferred from sequence or structural similarity /// 1900215 // negative regulation of apoptotic process involved in metanephric collecting duct development // inferred from sequence or structural similarity /// 1900218 // negative regulation of apoptotic process involved in metanephric nephron tubule development // inferred from sequence or structural similarity /// 2000594 // positive regulation of metanephric DCT cell differentiation // inferred from sequence or structural similarity /// 2000611 // positive regulation of thyroid hormone generation // inferred from mutant phenotype /// 2000612 // regulation of thyroid-stimulating hormone secretion // inferred from mutant phenotype', '0007165 // signal transduction // non-traceable author statement /// 0007601 // visual perception // inferred from electronic annotation /// 0007602 // phototransduction // inferred from electronic annotation /// 0007603 // phototransduction, visible light // traceable author statement /// 0016056 // rhodopsin mediated signaling pathway // traceable author statement /// 0022400 // regulation of rhodopsin mediated signaling pathway // traceable author statement /// 0030828 // positive regulation of cGMP biosynthetic process // inferred from electronic annotation /// 0031282 // regulation of guanylate cyclase activity // inferred from electronic annotation /// 0031284 // positive regulation of guanylate cyclase activity // inferred from electronic annotation /// 0050896 // response to stimulus // inferred from electronic annotation'], 'Gene Ontology Cellular Component': ['0005576 // extracellular region // inferred from electronic annotation /// 0005615 // extracellular space // inferred from direct assay /// 0005886 // plasma membrane // traceable author statement /// 0005887 // integral component of plasma membrane // traceable author statement /// 0016020 // membrane // inferred from electronic annotation /// 0016021 // integral component of membrane // inferred from electronic annotation /// 0043235 // receptor complex // inferred from direct assay /// 0070062 // extracellular vesicular exosome // inferred from direct assay', '0005634 // nucleus // inferred from electronic annotation /// 0005654 // nucleoplasm // traceable author statement /// 0005663 // DNA replication factor C complex // inferred from direct assay', '0005737 // cytoplasm // inferred from direct assay /// 0005814 // centriole // inferred from direct assay /// 0005829 // cytosol // inferred from direct assay /// 0008180 // COP9 signalosome // inferred from direct assay /// 0070062 // extracellular vesicular exosome // inferred from direct assay /// 0072562 // blood microparticle // inferred from direct assay', '0005634 // nucleus // inferred from direct assay /// 0005654 // nucleoplasm // inferred from sequence or structural similarity /// 0005730 // nucleolus // inferred from direct assay', '0001750 // photoreceptor outer segment // inferred from electronic annotation /// 0001917 // photoreceptor inner segment // inferred from electronic annotation /// 0005578 // proteinaceous extracellular matrix // inferred from electronic annotation /// 0005886 // plasma membrane // inferred from direct assay /// 0016020 // membrane // inferred from electronic annotation /// 0097381 // photoreceptor disc membrane // traceable author statement'], 'Gene Ontology Molecular Function': ['0000166 // nucleotide binding // inferred from electronic annotation /// 0004672 // protein kinase activity // inferred from electronic annotation /// 0004713 // protein tyrosine kinase activity // inferred from electronic annotation /// 0004714 // transmembrane receptor protein tyrosine kinase activity // traceable author statement /// 0005515 // protein binding // inferred from physical interaction /// 0005518 // collagen binding // inferred from direct assay /// 0005518 // collagen binding // inferred from mutant phenotype /// 0005524 // ATP binding // inferred from electronic annotation /// 0016301 // kinase activity // inferred from electronic annotation /// 0016740 // transferase activity // inferred from electronic annotation /// 0016772 // transferase activity, transferring phosphorus-containing groups // inferred from electronic annotation /// 0038062 // protein tyrosine kinase collagen receptor activity // inferred from direct assay /// 0046872 // metal ion binding // inferred from electronic annotation', '0000166 // nucleotide binding // inferred from electronic annotation /// 0003677 // DNA binding // inferred from electronic annotation /// 0005515 // protein binding // inferred from physical interaction /// 0005524 // ATP binding // inferred from electronic annotation /// 0016851 // magnesium chelatase activity // inferred from electronic annotation /// 0017111 // nucleoside-triphosphatase activity // inferred from electronic annotation', '0000166 // nucleotide binding // inferred from electronic annotation /// 0005524 // ATP binding // inferred from electronic annotation /// 0019899 // enzyme binding // inferred from physical interaction /// 0031072 // heat shock protein binding // inferred from physical interaction /// 0042623 // ATPase activity, coupled // inferred from direct assay /// 0051082 // unfolded protein binding // inferred from direct assay', '0000979 // RNA polymerase II core promoter sequence-specific DNA binding // inferred from direct assay /// 0003677 // DNA binding // inferred from direct assay /// 0003677 // DNA binding // inferred from mutant phenotype /// 0003700 // sequence-specific DNA binding transcription factor activity // inferred from direct assay /// 0004996 // thyroid-stimulating hormone receptor activity // traceable author statement /// 0005515 // protein binding // inferred from physical interaction /// 0044212 // transcription regulatory region DNA binding // inferred from direct assay', '0005509 // calcium ion binding // inferred from electronic annotation /// 0008048 // calcium sensitive guanylate cyclase activator activity // inferred from electronic annotation /// 0030249 // guanylate cyclase regulator activity // inferred from electronic annotation /// 0046872 // metal ion binding // inferred from electronic annotation']}\n"
329
+ ]
330
+ }
331
+ ],
332
+ "source": [
333
+ "# 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.\n",
334
+ "gene_annotation = get_gene_annotation(soft_file)\n",
335
+ "\n",
336
+ "# 2. Use the 'preview_df' function from the library to preview the data and print out the results.\n",
337
+ "print(\"Gene annotation preview:\")\n",
338
+ "print(preview_df(gene_annotation))\n"
339
+ ]
340
+ },
341
+ {
342
+ "cell_type": "markdown",
343
+ "id": "c895e628",
344
+ "metadata": {},
345
+ "source": [
346
+ "### Step 6: Gene Identifier Mapping"
347
+ ]
348
+ },
349
+ {
350
+ "cell_type": "code",
351
+ "execution_count": 7,
352
+ "id": "063873a8",
353
+ "metadata": {
354
+ "execution": {
355
+ "iopub.execute_input": "2025-03-25T08:13:31.732782Z",
356
+ "iopub.status.busy": "2025-03-25T08:13:31.732656Z",
357
+ "iopub.status.idle": "2025-03-25T08:13:32.130892Z",
358
+ "shell.execute_reply": "2025-03-25T08:13:32.130492Z"
359
+ }
360
+ },
361
+ "outputs": [
362
+ {
363
+ "name": "stdout",
364
+ "output_type": "stream",
365
+ "text": [
366
+ "Gene mapping preview (first 5 rows):\n",
367
+ " ID Gene\n",
368
+ "0 1007_s_at DDR1 /// MIR4640\n",
369
+ "1 1053_at RFC2\n",
370
+ "2 117_at HSPA6\n",
371
+ "3 121_at PAX8\n",
372
+ "4 1255_g_at GUCA1A\n",
373
+ "\n",
374
+ "Gene expression data shape after mapping: (21278, 92)\n",
375
+ "\n",
376
+ "First few gene symbols after mapping:\n",
377
+ "Index(['A1BG', 'A1BG-AS1', 'A1CF', 'A2M', 'A2M-AS1', 'A2ML1', 'A2MP1',\n",
378
+ " 'A4GALT', 'A4GNT', 'AA06'],\n",
379
+ " dtype='object', name='Gene')\n"
380
+ ]
381
+ }
382
+ ],
383
+ "source": [
384
+ "# 1. Identify the appropriate columns for gene identifiers and gene symbols\n",
385
+ "# Based on the preview, 'ID' stores the probe identifiers and 'Gene Symbol' stores gene symbols\n",
386
+ "probe_col = 'ID'\n",
387
+ "gene_col = 'Gene Symbol'\n",
388
+ "\n",
389
+ "# 2. Use get_gene_mapping to extract these columns and create a mapping dataframe\n",
390
+ "gene_mapping = get_gene_mapping(gene_annotation, probe_col, gene_col)\n",
391
+ "\n",
392
+ "# Print a small preview of the mapping to verify its structure\n",
393
+ "print(\"Gene mapping preview (first 5 rows):\")\n",
394
+ "print(gene_mapping.head())\n",
395
+ "\n",
396
+ "# 3. Apply the gene mapping to convert probe-level data to gene expression data\n",
397
+ "gene_data = apply_gene_mapping(gene_data, gene_mapping)\n",
398
+ "\n",
399
+ "# Print the shape of the resulting gene expression data\n",
400
+ "print(f\"\\nGene expression data shape after mapping: {gene_data.shape}\")\n",
401
+ "\n",
402
+ "# Print the first few gene symbols\n",
403
+ "print(\"\\nFirst few gene symbols after mapping:\")\n",
404
+ "print(gene_data.index[:10])\n"
405
+ ]
406
+ },
407
+ {
408
+ "cell_type": "markdown",
409
+ "id": "ad8ecb06",
410
+ "metadata": {},
411
+ "source": [
412
+ "### Step 7: Data Normalization and Linking"
413
+ ]
414
+ },
415
+ {
416
+ "cell_type": "code",
417
+ "execution_count": 8,
418
+ "id": "00b7c8a7",
419
+ "metadata": {
420
+ "execution": {
421
+ "iopub.execute_input": "2025-03-25T08:13:32.132301Z",
422
+ "iopub.status.busy": "2025-03-25T08:13:32.132185Z",
423
+ "iopub.status.idle": "2025-03-25T08:13:33.501928Z",
424
+ "shell.execute_reply": "2025-03-25T08:13:33.501546Z"
425
+ }
426
+ },
427
+ "outputs": [
428
+ {
429
+ "name": "stdout",
430
+ "output_type": "stream",
431
+ "text": [
432
+ "Normalized gene data saved to ../../output/preprocess/Cervical_Cancer/gene_data/GSE131027.csv\n",
433
+ "Original clinical data shape: (24, 2)\n",
434
+ "Clinical data index: Index(['Sample_1', 'Sample_2', 'Sample_3', 'Sample_4', 'Sample_5', 'Sample_6',\n",
435
+ " 'Sample_7', 'Sample_8', 'Sample_9', 'Sample_10', 'Sample_11',\n",
436
+ " 'Sample_12', 'Sample_13', 'Sample_14', 'Sample_15', 'Sample_16',\n",
437
+ " 'Sample_17', 'Sample_18', 'Sample_19', 'Sample_20', 'Sample_21',\n",
438
+ " 'Sample_22', 'Sample_23', 'Sample_24'],\n",
439
+ " dtype='object')\n",
440
+ "Clinical data columns: Index([0, 1], dtype='int64')\n",
441
+ "Clinical features DataFrame shape: (1, 23)\n",
442
+ "Clinical features DataFrame (first 5 rows):\n",
443
+ " Sample_2 Sample_3 Sample_4 Sample_5 Sample_6 Sample_7 \\\n",
444
+ "Cervical_Cancer 0 0 0 0 0 0 \n",
445
+ "\n",
446
+ " Sample_8 Sample_9 Sample_10 Sample_11 ... Sample_15 \\\n",
447
+ "Cervical_Cancer 0 0 0 1 ... 0 \n",
448
+ "\n",
449
+ " Sample_16 Sample_17 Sample_18 Sample_19 Sample_20 \\\n",
450
+ "Cervical_Cancer 0 0 0 0 0 \n",
451
+ "\n",
452
+ " Sample_21 Sample_22 Sample_23 Sample_24 \n",
453
+ "Cervical_Cancer 0 0 0 0 \n",
454
+ "\n",
455
+ "[1 rows x 23 columns]\n",
456
+ "Clinical data saved to ../../output/preprocess/Cervical_Cancer/clinical_data/GSE131027.csv\n",
457
+ "Linked data shape: (115, 19846)\n",
458
+ "Linked data shape after handling missing values: (0, 1)\n",
459
+ "Quartiles for 'Cervical_Cancer':\n",
460
+ " 25%: nan\n",
461
+ " 50% (Median): nan\n",
462
+ " 75%: nan\n",
463
+ "Min: nan\n",
464
+ "Max: nan\n",
465
+ "The distribution of the feature 'Cervical_Cancer' in this dataset is fine.\n",
466
+ "\n",
467
+ "Abnormality detected in the cohort: GSE131027. Preprocessing failed.\n",
468
+ "Data was determined to be unusable and was not saved\n"
469
+ ]
470
+ }
471
+ ],
472
+ "source": [
473
+ "# 1. Normalize the obtained gene data with the 'normalize_gene_symbols_in_index' function from the library.\n",
474
+ "normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n",
475
+ "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
476
+ "normalized_gene_data.to_csv(out_gene_data_file)\n",
477
+ "print(f\"Normalized gene data saved to {out_gene_data_file}\")\n",
478
+ "\n",
479
+ "# Debug the clinical data to understand its structure better\n",
480
+ "print(\"Original clinical data shape:\", clinical_data.shape)\n",
481
+ "print(\"Clinical data index:\", clinical_data.index)\n",
482
+ "print(\"Clinical data columns:\", clinical_data.columns)\n",
483
+ "\n",
484
+ "# Reconstruct clinical features - Create a dictionary of sample IDs to their cancer types\n",
485
+ "cancer_types = {}\n",
486
+ "for sample_id, row in clinical_data.iterrows():\n",
487
+ " for col in clinical_data.columns:\n",
488
+ " if col != '!Sample_geo_accession':\n",
489
+ " value = row.get(col)\n",
490
+ " if isinstance(value, str) and 'cancer:' in value:\n",
491
+ " cancer_type = value.split(':', 1)[1].strip()\n",
492
+ " is_cervical = 1 if cancer_type.lower() == 'cervical cancer' else 0\n",
493
+ " cancer_types[sample_id] = is_cervical\n",
494
+ "\n",
495
+ "# Create a DataFrame for the trait (Cervical_Cancer)\n",
496
+ "trait_df = pd.DataFrame({trait: cancer_types})\n",
497
+ "clinical_features_df = trait_df.T # Transpose to match required format\n",
498
+ "\n",
499
+ "print(\"Clinical features DataFrame shape:\", clinical_features_df.shape)\n",
500
+ "print(\"Clinical features DataFrame (first 5 rows):\")\n",
501
+ "print(clinical_features_df.head())\n",
502
+ "\n",
503
+ "# Save the clinical data\n",
504
+ "os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
505
+ "clinical_features_df.to_csv(out_clinical_data_file)\n",
506
+ "print(f\"Clinical data saved to {out_clinical_data_file}\")\n",
507
+ "\n",
508
+ "# Now link the clinical and genetic data using the library function\n",
509
+ "linked_data = geo_link_clinical_genetic_data(clinical_features_df, normalized_gene_data)\n",
510
+ "print(\"Linked data shape:\", linked_data.shape)\n",
511
+ "\n",
512
+ "# Handle missing values in the linked data\n",
513
+ "linked_data = handle_missing_values(linked_data, trait)\n",
514
+ "print(\"Linked data shape after handling missing values:\", linked_data.shape)\n",
515
+ "\n",
516
+ "# 4. Determine whether the trait and some demographic features are severely biased, and remove biased features.\n",
517
+ "is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)\n",
518
+ "\n",
519
+ "# 5. Conduct quality check and save the cohort information.\n",
520
+ "is_usable = validate_and_save_cohort_info(\n",
521
+ " is_final=True, \n",
522
+ " cohort=cohort, \n",
523
+ " info_path=json_path, \n",
524
+ " is_gene_available=True, \n",
525
+ " is_trait_available=True, \n",
526
+ " is_biased=is_trait_biased, \n",
527
+ " df=unbiased_linked_data,\n",
528
+ " note=\"Dataset contains gene expression data for various cancer types including cervical cancer.\"\n",
529
+ ")\n",
530
+ "\n",
531
+ "# 6. If the linked data is usable, save it as a CSV file to 'out_data_file'.\n",
532
+ "if is_usable:\n",
533
+ " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n",
534
+ " unbiased_linked_data.to_csv(out_data_file)\n",
535
+ " print(f\"Linked data saved to {out_data_file}\")\n",
536
+ "else:\n",
537
+ " print(\"Data was determined to be unusable and was not saved\")"
538
+ ]
539
+ }
540
+ ],
541
+ "metadata": {
542
+ "language_info": {
543
+ "codemirror_mode": {
544
+ "name": "ipython",
545
+ "version": 3
546
+ },
547
+ "file_extension": ".py",
548
+ "mimetype": "text/x-python",
549
+ "name": "python",
550
+ "nbconvert_exporter": "python",
551
+ "pygments_lexer": "ipython3",
552
+ "version": "3.10.16"
553
+ }
554
+ },
555
+ "nbformat": 4,
556
+ "nbformat_minor": 5
557
+ }
code/Cervical_Cancer/GSE137034.ipynb ADDED
@@ -0,0 +1,450 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": 1,
6
+ "id": "c4ec14a0",
7
+ "metadata": {
8
+ "execution": {
9
+ "iopub.execute_input": "2025-03-25T08:13:34.420767Z",
10
+ "iopub.status.busy": "2025-03-25T08:13:34.420591Z",
11
+ "iopub.status.idle": "2025-03-25T08:13:34.589431Z",
12
+ "shell.execute_reply": "2025-03-25T08:13:34.589081Z"
13
+ }
14
+ },
15
+ "outputs": [],
16
+ "source": [
17
+ "import sys\n",
18
+ "import os\n",
19
+ "sys.path.append(os.path.abspath(os.path.join(os.getcwd(), '../..')))\n",
20
+ "\n",
21
+ "# Path Configuration\n",
22
+ "from tools.preprocess import *\n",
23
+ "\n",
24
+ "# Processing context\n",
25
+ "trait = \"Cervical_Cancer\"\n",
26
+ "cohort = \"GSE137034\"\n",
27
+ "\n",
28
+ "# Input paths\n",
29
+ "in_trait_dir = \"../../input/GEO/Cervical_Cancer\"\n",
30
+ "in_cohort_dir = \"../../input/GEO/Cervical_Cancer/GSE137034\"\n",
31
+ "\n",
32
+ "# Output paths\n",
33
+ "out_data_file = \"../../output/preprocess/Cervical_Cancer/GSE137034.csv\"\n",
34
+ "out_gene_data_file = \"../../output/preprocess/Cervical_Cancer/gene_data/GSE137034.csv\"\n",
35
+ "out_clinical_data_file = \"../../output/preprocess/Cervical_Cancer/clinical_data/GSE137034.csv\"\n",
36
+ "json_path = \"../../output/preprocess/Cervical_Cancer/cohort_info.json\"\n"
37
+ ]
38
+ },
39
+ {
40
+ "cell_type": "markdown",
41
+ "id": "28452637",
42
+ "metadata": {},
43
+ "source": [
44
+ "### Step 1: Initial Data Loading"
45
+ ]
46
+ },
47
+ {
48
+ "cell_type": "code",
49
+ "execution_count": 2,
50
+ "id": "7d581880",
51
+ "metadata": {
52
+ "execution": {
53
+ "iopub.execute_input": "2025-03-25T08:13:34.590914Z",
54
+ "iopub.status.busy": "2025-03-25T08:13:34.590762Z",
55
+ "iopub.status.idle": "2025-03-25T08:13:34.667527Z",
56
+ "shell.execute_reply": "2025-03-25T08:13:34.667213Z"
57
+ }
58
+ },
59
+ "outputs": [
60
+ {
61
+ "name": "stdout",
62
+ "output_type": "stream",
63
+ "text": [
64
+ "Background Information:\n",
65
+ "!Series_title\t\"Chromatin accessibility governs the differential response of cancer and T-cells to arginine starvation\"\n",
66
+ "!Series_summary\t\"This SuperSeries is composed of the SubSeries listed below.\"\n",
67
+ "!Series_overall_design\t\"Refer to individual Series\"\n",
68
+ "Sample Characteristics Dictionary:\n",
69
+ "{0: ['tissue: THP1 cells', 'tissue: Stimulated human CD4 T-cells'], 1: ['treatment: Cells cultured in full RPMI', 'treatment: Cells cultured in RPMI without arginine']}\n"
70
+ ]
71
+ }
72
+ ],
73
+ "source": [
74
+ "from tools.preprocess import *\n",
75
+ "# 1. Identify the paths to the SOFT file and the matrix file\n",
76
+ "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
77
+ "\n",
78
+ "# 2. Read the matrix file to obtain background information and sample characteristics data\n",
79
+ "background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']\n",
80
+ "clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']\n",
81
+ "background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)\n",
82
+ "\n",
83
+ "# 3. Obtain the sample characteristics dictionary from the clinical dataframe\n",
84
+ "sample_characteristics_dict = get_unique_values_by_row(clinical_data)\n",
85
+ "\n",
86
+ "# 4. Explicitly print out all the background information and the sample characteristics dictionary\n",
87
+ "print(\"Background Information:\")\n",
88
+ "print(background_info)\n",
89
+ "print(\"Sample Characteristics Dictionary:\")\n",
90
+ "print(sample_characteristics_dict)\n"
91
+ ]
92
+ },
93
+ {
94
+ "cell_type": "markdown",
95
+ "id": "95249088",
96
+ "metadata": {},
97
+ "source": [
98
+ "### Step 2: Dataset Analysis and Clinical Feature Extraction"
99
+ ]
100
+ },
101
+ {
102
+ "cell_type": "code",
103
+ "execution_count": 3,
104
+ "id": "4a1dca44",
105
+ "metadata": {
106
+ "execution": {
107
+ "iopub.execute_input": "2025-03-25T08:13:34.668770Z",
108
+ "iopub.status.busy": "2025-03-25T08:13:34.668516Z",
109
+ "iopub.status.idle": "2025-03-25T08:13:34.672367Z",
110
+ "shell.execute_reply": "2025-03-25T08:13:34.672068Z"
111
+ }
112
+ },
113
+ "outputs": [
114
+ {
115
+ "name": "stdout",
116
+ "output_type": "stream",
117
+ "text": [
118
+ "No relevant cervical cancer trait information found in this dataset.\n"
119
+ ]
120
+ }
121
+ ],
122
+ "source": [
123
+ "# Analysis of the dataset\n",
124
+ "# 1. Gene Expression Data Availability\n",
125
+ "# Based on the background information, this appears to be a SuperSeries about chromatin accessibility\n",
126
+ "# While chromatin accessibility is related to gene regulation, this dataset may not contain direct gene expression data\n",
127
+ "is_gene_available = False\n",
128
+ "\n",
129
+ "# 2. Variable Analysis for trait, age, and gender\n",
130
+ "# 2.1 Data Availability\n",
131
+ "# From the sample characteristics, we have:\n",
132
+ "# - Row 0: tissue type (THP1 cells vs Stimulated human CD4 T-cells)\n",
133
+ "# - Row 1: treatment condition (full RPMI vs RPMI without arginine)\n",
134
+ "# \n",
135
+ "# This dataset appears to be about immune cells and arginine starvation, not directly about cervical cancer.\n",
136
+ "# None of the available characteristics directly map to cervical cancer status.\n",
137
+ "trait_row = None # No direct cervical cancer trait information\n",
138
+ "age_row = None # Age information is not available\n",
139
+ "gender_row = None # Gender information is not available\n",
140
+ "\n",
141
+ "# 2.2 Data Type Conversion Functions\n",
142
+ "# Since we don't have valid trait information for cervical cancer, we don't need these functions\n",
143
+ "# but they are defined as None for completeness\n",
144
+ "convert_trait = None\n",
145
+ "convert_age = None\n",
146
+ "convert_gender = None\n",
147
+ "\n",
148
+ "# 3. Save Metadata\n",
149
+ "# Determine if trait data is available based on trait_row\n",
150
+ "is_trait_available = trait_row is not None\n",
151
+ "\n",
152
+ "# Validate and save cohort information\n",
153
+ "validate_and_save_cohort_info(\n",
154
+ " is_final=False,\n",
155
+ " cohort=cohort,\n",
156
+ " info_path=json_path,\n",
157
+ " is_gene_available=is_gene_available,\n",
158
+ " is_trait_available=is_trait_available\n",
159
+ ")\n",
160
+ "\n",
161
+ "# 4. Clinical Feature Extraction\n",
162
+ "# Since trait_row is None, we skip this substep\n",
163
+ "if trait_row is not None:\n",
164
+ " # This block would only execute if trait_row was not None\n",
165
+ " selected_clinical_df = geo_select_clinical_features(\n",
166
+ " clinical_df=clinical_data,\n",
167
+ " trait=trait,\n",
168
+ " trait_row=trait_row,\n",
169
+ " convert_trait=convert_trait,\n",
170
+ " age_row=age_row,\n",
171
+ " convert_age=convert_age,\n",
172
+ " gender_row=gender_row,\n",
173
+ " convert_gender=convert_gender\n",
174
+ " )\n",
175
+ " \n",
176
+ " # Preview the extracted clinical features\n",
177
+ " print(\"Clinical Features Preview:\")\n",
178
+ " print(preview_df(selected_clinical_df))\n",
179
+ " \n",
180
+ " # Save the clinical data\n",
181
+ " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
182
+ " selected_clinical_df.to_csv(out_clinical_data_file, index=False)\n",
183
+ " print(f\"Clinical data saved to {out_clinical_data_file}\")\n",
184
+ "else:\n",
185
+ " print(\"No relevant cervical cancer trait information found in this dataset.\")\n"
186
+ ]
187
+ },
188
+ {
189
+ "cell_type": "markdown",
190
+ "id": "9836a114",
191
+ "metadata": {},
192
+ "source": [
193
+ "### Step 3: Gene Data Extraction"
194
+ ]
195
+ },
196
+ {
197
+ "cell_type": "code",
198
+ "execution_count": 4,
199
+ "id": "5fc6ce51",
200
+ "metadata": {
201
+ "execution": {
202
+ "iopub.execute_input": "2025-03-25T08:13:34.673394Z",
203
+ "iopub.status.busy": "2025-03-25T08:13:34.673288Z",
204
+ "iopub.status.idle": "2025-03-25T08:13:34.736663Z",
205
+ "shell.execute_reply": "2025-03-25T08:13:34.736293Z"
206
+ }
207
+ },
208
+ "outputs": [
209
+ {
210
+ "name": "stdout",
211
+ "output_type": "stream",
212
+ "text": [
213
+ "Index(['ILMN_1343291', 'ILMN_1343295', 'ILMN_1651209', 'ILMN_1651228',\n",
214
+ " 'ILMN_1651229', 'ILMN_1651230', 'ILMN_1651232', 'ILMN_1651236',\n",
215
+ " 'ILMN_1651238', 'ILMN_1651253', 'ILMN_1651254', 'ILMN_1651259',\n",
216
+ " 'ILMN_1651260', 'ILMN_1651262', 'ILMN_1651268', 'ILMN_1651278',\n",
217
+ " 'ILMN_1651281', 'ILMN_1651282', 'ILMN_1651285', 'ILMN_1651286'],\n",
218
+ " dtype='object', name='ID')\n"
219
+ ]
220
+ }
221
+ ],
222
+ "source": [
223
+ "# 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.\n",
224
+ "gene_data = get_genetic_data(matrix_file)\n",
225
+ "\n",
226
+ "# 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.\n",
227
+ "print(gene_data.index[:20])\n"
228
+ ]
229
+ },
230
+ {
231
+ "cell_type": "markdown",
232
+ "id": "926ee17e",
233
+ "metadata": {},
234
+ "source": [
235
+ "### Step 4: Gene Identifier Review"
236
+ ]
237
+ },
238
+ {
239
+ "cell_type": "code",
240
+ "execution_count": 5,
241
+ "id": "4bb3f263",
242
+ "metadata": {
243
+ "execution": {
244
+ "iopub.execute_input": "2025-03-25T08:13:34.737898Z",
245
+ "iopub.status.busy": "2025-03-25T08:13:34.737783Z",
246
+ "iopub.status.idle": "2025-03-25T08:13:34.739685Z",
247
+ "shell.execute_reply": "2025-03-25T08:13:34.739395Z"
248
+ }
249
+ },
250
+ "outputs": [],
251
+ "source": [
252
+ "# Based on the gene identifiers observed in the gene expression data, I can see these are\n",
253
+ "# Illumina probe IDs (starting with ILMN_), not standard human gene symbols.\n",
254
+ "# These are microarray probe identifiers that need to be mapped to gene symbols for biological interpretation.\n",
255
+ "\n",
256
+ "requires_gene_mapping = True\n"
257
+ ]
258
+ },
259
+ {
260
+ "cell_type": "markdown",
261
+ "id": "75f16d71",
262
+ "metadata": {},
263
+ "source": [
264
+ "### Step 5: Gene Annotation"
265
+ ]
266
+ },
267
+ {
268
+ "cell_type": "code",
269
+ "execution_count": 6,
270
+ "id": "1d22fcfb",
271
+ "metadata": {
272
+ "execution": {
273
+ "iopub.execute_input": "2025-03-25T08:13:34.740849Z",
274
+ "iopub.status.busy": "2025-03-25T08:13:34.740746Z",
275
+ "iopub.status.idle": "2025-03-25T08:13:36.504768Z",
276
+ "shell.execute_reply": "2025-03-25T08:13:36.504377Z"
277
+ }
278
+ },
279
+ "outputs": [
280
+ {
281
+ "name": "stdout",
282
+ "output_type": "stream",
283
+ "text": [
284
+ "Gene annotation preview:\n",
285
+ "{'ID': ['ILMN_1343048', 'ILMN_1343049', 'ILMN_1343050', 'ILMN_1343052', 'ILMN_1343059'], 'Species': [nan, nan, nan, nan, nan], 'Source': [nan, nan, nan, nan, nan], 'Search_Key': [nan, nan, nan, nan, nan], 'Transcript': [nan, nan, nan, nan, nan], 'ILMN_Gene': [nan, nan, nan, nan, nan], 'Source_Reference_ID': [nan, nan, nan, nan, nan], 'RefSeq_ID': [nan, nan, nan, nan, nan], 'Unigene_ID': [nan, nan, nan, nan, nan], 'Entrez_Gene_ID': [nan, nan, nan, nan, nan], 'GI': [nan, nan, nan, nan, nan], 'Accession': [nan, nan, nan, nan, nan], 'Symbol': ['phage_lambda_genome', 'phage_lambda_genome', 'phage_lambda_genome:low', 'phage_lambda_genome:low', 'thrB'], 'Protein_Product': [nan, nan, nan, nan, 'thrB'], 'Probe_Id': [nan, nan, nan, nan, nan], 'Array_Address_Id': [5090180.0, 6510136.0, 7560739.0, 1450438.0, 1240647.0], 'Probe_Type': [nan, nan, nan, nan, nan], 'Probe_Start': [nan, nan, nan, nan, nan], 'SEQUENCE': ['GAATAAAGAACAATCTGCTGATGATCCCTCCGTGGATCTGATTCGTGTAA', 'CCATGTGATACGAGGGCGCGTAGTTTGCATTATCGTTTTTATCGTTTCAA', 'CCGACAGATGTATGTAAGGCCAACGTGCTCAAATCTTCATACAGAAAGAT', 'TCTGTCACTGTCAGGAAAGTGGTAAAACTGCAACTCAATTACTGCAATGC', 'CTTGTGCCTGAGCTGTCAAAAGTAGAGCACGTCGCCGAGATGAAGGGCGC'], 'Chromosome': [nan, nan, nan, nan, nan], 'Probe_Chr_Orientation': [nan, nan, nan, nan, nan], 'Probe_Coordinates': [nan, nan, nan, nan, nan], 'Cytoband': [nan, nan, nan, nan, nan], 'Definition': [nan, nan, nan, nan, nan], 'Ontology_Component': [nan, nan, nan, nan, nan], 'Ontology_Process': [nan, nan, nan, nan, nan], 'Ontology_Function': [nan, nan, nan, nan, nan], 'Synonyms': [nan, nan, nan, nan, nan], 'Obsolete_Probe_Id': [nan, nan, nan, nan, nan], 'GB_ACC': [nan, nan, nan, nan, nan]}\n"
286
+ ]
287
+ }
288
+ ],
289
+ "source": [
290
+ "# 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.\n",
291
+ "gene_annotation = get_gene_annotation(soft_file)\n",
292
+ "\n",
293
+ "# 2. Use the 'preview_df' function from the library to preview the data and print out the results.\n",
294
+ "print(\"Gene annotation preview:\")\n",
295
+ "print(preview_df(gene_annotation))\n"
296
+ ]
297
+ },
298
+ {
299
+ "cell_type": "markdown",
300
+ "id": "84e4d61b",
301
+ "metadata": {},
302
+ "source": [
303
+ "### Step 6: Gene Identifier Mapping"
304
+ ]
305
+ },
306
+ {
307
+ "cell_type": "code",
308
+ "execution_count": 7,
309
+ "id": "8e69c7ec",
310
+ "metadata": {
311
+ "execution": {
312
+ "iopub.execute_input": "2025-03-25T08:13:36.506150Z",
313
+ "iopub.status.busy": "2025-03-25T08:13:36.506023Z",
314
+ "iopub.status.idle": "2025-03-25T08:13:36.609112Z",
315
+ "shell.execute_reply": "2025-03-25T08:13:36.608707Z"
316
+ }
317
+ },
318
+ "outputs": [
319
+ {
320
+ "name": "stdout",
321
+ "output_type": "stream",
322
+ "text": [
323
+ "Gene mapping dataframe contains 44837 rows.\n",
324
+ "First few rows of gene mapping dataframe:\n",
325
+ " ID Gene\n",
326
+ "0 ILMN_1343048 phage_lambda_genome\n",
327
+ "1 ILMN_1343049 phage_lambda_genome\n",
328
+ "2 ILMN_1343050 phage_lambda_genome:low\n",
329
+ "3 ILMN_1343052 phage_lambda_genome:low\n",
330
+ "4 ILMN_1343059 thrB\n",
331
+ "\n",
332
+ "Gene expression data after mapping contains 19428 rows (genes) and 12 columns (samples).\n",
333
+ "First few rows of gene expression data:\n",
334
+ " GSM4066056 GSM4066057 GSM4066058 GSM4066059 GSM4066060 GSM4066061 \\\n",
335
+ "Gene \n",
336
+ "A1BG 104.734027 107.031137 106.886337 113.500383 102.537192 107.564250 \n",
337
+ "A1CF 321.270674 307.527615 328.183334 308.400692 321.742142 309.907990 \n",
338
+ "A26C3 316.660403 309.286984 312.437777 311.793639 332.664815 318.939242 \n",
339
+ "A2BP1 412.924163 425.162126 436.675346 431.607999 435.392324 414.417847 \n",
340
+ "A2LD1 672.827158 649.832542 549.741167 454.964517 548.334108 531.383400 \n",
341
+ "\n",
342
+ " GSM4066062 GSM4066063 GSM4066064 GSM4066065 GSM4066066 GSM4066067 \n",
343
+ "Gene \n",
344
+ "A1BG 102.604249 110.358317 111.931083 108.178350 105.403362 119.752683 \n",
345
+ "A1CF 324.954404 313.219361 313.711137 332.812281 336.827117 317.123024 \n",
346
+ "A26C3 308.638665 298.541888 316.146780 326.388599 315.097036 318.664994 \n",
347
+ "A2BP1 424.703767 420.752160 424.171614 429.189257 406.857785 416.910436 \n",
348
+ "A2LD1 125.979400 114.403167 150.408808 133.218425 111.299500 117.343208 \n"
349
+ ]
350
+ }
351
+ ],
352
+ "source": [
353
+ "# 1. Identify the columns in the gene annotation dataframe that contain gene identifiers and gene symbols\n",
354
+ "# From the preview, the 'ID' column matches the gene expression identifiers (ILMN_*)\n",
355
+ "# And the 'Symbol' column contains the gene symbols\n",
356
+ "\n",
357
+ "# 2. Create the gene mapping dataframe using the get_gene_mapping function\n",
358
+ "gene_mapping = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='Symbol')\n",
359
+ "\n",
360
+ "# Print summary of the mapping to verify\n",
361
+ "print(f\"Gene mapping dataframe contains {len(gene_mapping)} rows.\")\n",
362
+ "print(\"First few rows of gene mapping dataframe:\")\n",
363
+ "print(gene_mapping.head())\n",
364
+ "\n",
365
+ "# 3. Apply the gene mapping to convert probe-level measurements to gene expression data\n",
366
+ "gene_data = apply_gene_mapping(gene_data, gene_mapping)\n",
367
+ "\n",
368
+ "# Print summary of the resulting gene expression data\n",
369
+ "print(f\"\\nGene expression data after mapping contains {len(gene_data)} rows (genes) and {gene_data.shape[1]} columns (samples).\")\n",
370
+ "print(\"First few rows of gene expression data:\")\n",
371
+ "print(gene_data.head())\n"
372
+ ]
373
+ },
374
+ {
375
+ "cell_type": "markdown",
376
+ "id": "7c1498f2",
377
+ "metadata": {},
378
+ "source": [
379
+ "### Step 7: Data Normalization and Linking"
380
+ ]
381
+ },
382
+ {
383
+ "cell_type": "code",
384
+ "execution_count": 8,
385
+ "id": "55e16370",
386
+ "metadata": {
387
+ "execution": {
388
+ "iopub.execute_input": "2025-03-25T08:13:36.610521Z",
389
+ "iopub.status.busy": "2025-03-25T08:13:36.610401Z",
390
+ "iopub.status.idle": "2025-03-25T08:13:36.827601Z",
391
+ "shell.execute_reply": "2025-03-25T08:13:36.827210Z"
392
+ }
393
+ },
394
+ "outputs": [
395
+ {
396
+ "name": "stdout",
397
+ "output_type": "stream",
398
+ "text": [
399
+ "Normalized gene data saved to ../../output/preprocess/Cervical_Cancer/gene_data/GSE137034.csv\n",
400
+ "Abnormality detected in the cohort: GSE137034. Preprocessing failed.\n",
401
+ "The dataset doesn't contain cervical cancer trait information and wasn't saved.\n"
402
+ ]
403
+ }
404
+ ],
405
+ "source": [
406
+ "# Since we determined in Step 2 that this dataset doesn't contain relevant cervical cancer trait information\n",
407
+ "# we need to finalize with explicit values to satisfy function requirements\n",
408
+ "\n",
409
+ "# Save normalized gene data for completeness\n",
410
+ "normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n",
411
+ "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
412
+ "normalized_gene_data.to_csv(out_gene_data_file)\n",
413
+ "print(f\"Normalized gene data saved to {out_gene_data_file}\")\n",
414
+ "\n",
415
+ "# Create a minimal dataframe for consistent API\n",
416
+ "minimal_df = pd.DataFrame(index=normalized_gene_data.columns)\n",
417
+ "\n",
418
+ "# Validate and save with explicit values\n",
419
+ "is_usable = validate_and_save_cohort_info(\n",
420
+ " is_final=True, \n",
421
+ " cohort=cohort, \n",
422
+ " info_path=json_path, \n",
423
+ " is_gene_available=False, # As determined in Step 2\n",
424
+ " is_trait_available=False, # As determined in Step 2\n",
425
+ " is_biased=False, # Providing an explicit value to satisfy the function requirement\n",
426
+ " df=minimal_df,\n",
427
+ " note=\"This dataset contains gene expression data from THP1 cells and stimulated human CD4 T-cells, but doesn't contain cervical cancer information.\"\n",
428
+ ")\n",
429
+ "\n",
430
+ "print(\"The dataset doesn't contain cervical cancer trait information and wasn't saved.\")"
431
+ ]
432
+ }
433
+ ],
434
+ "metadata": {
435
+ "language_info": {
436
+ "codemirror_mode": {
437
+ "name": "ipython",
438
+ "version": 3
439
+ },
440
+ "file_extension": ".py",
441
+ "mimetype": "text/x-python",
442
+ "name": "python",
443
+ "nbconvert_exporter": "python",
444
+ "pygments_lexer": "ipython3",
445
+ "version": "3.10.16"
446
+ }
447
+ },
448
+ "nbformat": 4,
449
+ "nbformat_minor": 5
450
+ }
code/Cervical_Cancer/GSE138079.ipynb ADDED
@@ -0,0 +1,494 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": 1,
6
+ "id": "1731fd45",
7
+ "metadata": {
8
+ "execution": {
9
+ "iopub.execute_input": "2025-03-25T08:13:37.723056Z",
10
+ "iopub.status.busy": "2025-03-25T08:13:37.722821Z",
11
+ "iopub.status.idle": "2025-03-25T08:13:37.888276Z",
12
+ "shell.execute_reply": "2025-03-25T08:13:37.887811Z"
13
+ }
14
+ },
15
+ "outputs": [],
16
+ "source": [
17
+ "import sys\n",
18
+ "import os\n",
19
+ "sys.path.append(os.path.abspath(os.path.join(os.getcwd(), '../..')))\n",
20
+ "\n",
21
+ "# Path Configuration\n",
22
+ "from tools.preprocess import *\n",
23
+ "\n",
24
+ "# Processing context\n",
25
+ "trait = \"Cervical_Cancer\"\n",
26
+ "cohort = \"GSE138079\"\n",
27
+ "\n",
28
+ "# Input paths\n",
29
+ "in_trait_dir = \"../../input/GEO/Cervical_Cancer\"\n",
30
+ "in_cohort_dir = \"../../input/GEO/Cervical_Cancer/GSE138079\"\n",
31
+ "\n",
32
+ "# Output paths\n",
33
+ "out_data_file = \"../../output/preprocess/Cervical_Cancer/GSE138079.csv\"\n",
34
+ "out_gene_data_file = \"../../output/preprocess/Cervical_Cancer/gene_data/GSE138079.csv\"\n",
35
+ "out_clinical_data_file = \"../../output/preprocess/Cervical_Cancer/clinical_data/GSE138079.csv\"\n",
36
+ "json_path = \"../../output/preprocess/Cervical_Cancer/cohort_info.json\"\n"
37
+ ]
38
+ },
39
+ {
40
+ "cell_type": "markdown",
41
+ "id": "2c2a4afe",
42
+ "metadata": {},
43
+ "source": [
44
+ "### Step 1: Initial Data Loading"
45
+ ]
46
+ },
47
+ {
48
+ "cell_type": "code",
49
+ "execution_count": 2,
50
+ "id": "1e60cb50",
51
+ "metadata": {
52
+ "execution": {
53
+ "iopub.execute_input": "2025-03-25T08:13:37.889704Z",
54
+ "iopub.status.busy": "2025-03-25T08:13:37.889557Z",
55
+ "iopub.status.idle": "2025-03-25T08:13:38.072504Z",
56
+ "shell.execute_reply": "2025-03-25T08:13:38.072017Z"
57
+ }
58
+ },
59
+ "outputs": [
60
+ {
61
+ "name": "stdout",
62
+ "output_type": "stream",
63
+ "text": [
64
+ "Background Information:\n",
65
+ "!Series_title\t\"Identification of deregulated pathways, key regulators, and novel miRNA-mRNA interactions in HPV-mediated transformation. [mRNA cell lines-Agilent]\"\n",
66
+ "!Series_summary\t\"Next to a persistent infection with high-risk human papillomavirus (HPV), molecular changes are required for the development of cervical cancer. To identify which molecular alterations drive carcinogenesis, we performed a comprehensive and longitudinal molecular characterization of HPV-transformed keratinocyte cell lines. Comparative genomic hybridization, mRNA, and miRNA expression analysis of four HPV-containing keratinocyte cell lines at eight different time points was performed. Data was analyzed using unsupervised hierarchical clustering, integrated longitudinal expression analysis, and pathway enrichment analysis. Biological relevance of identified key regulatory genes was evaluated in vitro and dual-luciferase assays were used to confirm predicted miRNA-mRNA interactions. We show that the acquisition of anchorage independence of HPV-containing keratinocyte cell lines is particularly associated with copy number alterations. Approximately one third of differentially expressed mRNAs and miRNAs was directly attributable to copy number alterations. Focal adhesion, TGF-beta signaling, and mTOR signaling pathways were enriched among these genes. PITX2 was identified as key regulator of TGF-beta signaling and inhibited cell growth in vitro, most likely by inducing cell cycle arrest and apoptosis. Predicted miRNA-mRNA interactions miR-221-3p_BRWD3, miR-221-3p_FOS, and miR-138-5p_PLXNB2 were confirmed in vitro. Integrated longitudinal analysis of our HPV-induced carcinogenesis model pinpointed relevant interconnected molecular changes and crucial signaling pathways in HPV-mediated transformation.\"\n",
67
+ "!Series_overall_design\t\"Expression profiles of 8 sequential passages of 4 HPV-transformed human foreskin primary keratinocyte cell lines either treated with or without demethylation agent DAC were analyzed using whole human genome oligo microarrays (G4112A, mRNA 4x44K; Agilent).\"\n",
68
+ "Sample Characteristics Dictionary:\n",
69
+ "{0: ['cell type: primary human foreskin keratinocytes transfected with HPV16', 'cell type: primary human foreskin keratinocytes transfected with HPV18'], 1: ['transformation stage: immortal', 'transformation stage: anchorage independent', 'transformation stage: extended lifespan'], 2: ['timepoint: timepoint 1', 'timepoint: timepoint 2', 'timepoint: timepoint 3', 'timepoint: timepoint 4', 'timepoint: timepoint 5', 'timepoint: timepoint 6', 'timepoint: timepoint 7', 'timepoint: timepoint 8'], 3: ['treatment: no treatment', 'treatment: 5000 nM 5-aza-2’-deoxycytidine (DAC)']}\n"
70
+ ]
71
+ }
72
+ ],
73
+ "source": [
74
+ "from tools.preprocess import *\n",
75
+ "# 1. Identify the paths to the SOFT file and the matrix file\n",
76
+ "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
77
+ "\n",
78
+ "# 2. Read the matrix file to obtain background information and sample characteristics data\n",
79
+ "background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']\n",
80
+ "clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']\n",
81
+ "background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)\n",
82
+ "\n",
83
+ "# 3. Obtain the sample characteristics dictionary from the clinical dataframe\n",
84
+ "sample_characteristics_dict = get_unique_values_by_row(clinical_data)\n",
85
+ "\n",
86
+ "# 4. Explicitly print out all the background information and the sample characteristics dictionary\n",
87
+ "print(\"Background Information:\")\n",
88
+ "print(background_info)\n",
89
+ "print(\"Sample Characteristics Dictionary:\")\n",
90
+ "print(sample_characteristics_dict)\n"
91
+ ]
92
+ },
93
+ {
94
+ "cell_type": "markdown",
95
+ "id": "e515f670",
96
+ "metadata": {},
97
+ "source": [
98
+ "### Step 2: Dataset Analysis and Clinical Feature Extraction"
99
+ ]
100
+ },
101
+ {
102
+ "cell_type": "code",
103
+ "execution_count": 3,
104
+ "id": "8a08dba2",
105
+ "metadata": {
106
+ "execution": {
107
+ "iopub.execute_input": "2025-03-25T08:13:38.073938Z",
108
+ "iopub.status.busy": "2025-03-25T08:13:38.073829Z",
109
+ "iopub.status.idle": "2025-03-25T08:13:38.079980Z",
110
+ "shell.execute_reply": "2025-03-25T08:13:38.079618Z"
111
+ }
112
+ },
113
+ "outputs": [
114
+ {
115
+ "data": {
116
+ "text/plain": [
117
+ "False"
118
+ ]
119
+ },
120
+ "execution_count": 3,
121
+ "metadata": {},
122
+ "output_type": "execute_result"
123
+ }
124
+ ],
125
+ "source": [
126
+ "import pandas as pd\n",
127
+ "import os\n",
128
+ "import json\n",
129
+ "from typing import Callable, Dict, Any, Optional\n",
130
+ "\n",
131
+ "# 1. Gene Expression Data Availability\n",
132
+ "# Based on the Series_title and Series_summary, this data contains mRNA microarray data from Agilent\n",
133
+ "is_gene_available = True\n",
134
+ "\n",
135
+ "# 2. Variable Availability and Data Type Conversion\n",
136
+ "\n",
137
+ "# 2.1 Data Availability\n",
138
+ "# For trait: The \"transformation stage\" in index 1 indicates different stages of cancer development\n",
139
+ "trait_row = 1\n",
140
+ "\n",
141
+ "# For age: Not available in the sample characteristics\n",
142
+ "age_row = None\n",
143
+ "\n",
144
+ "# For gender: Not explicitly available, but this is from male foreskin samples\n",
145
+ "gender_row = None\n",
146
+ "\n",
147
+ "# 2.2 Data Type Conversion Functions\n",
148
+ "def convert_trait(value: str) -> int:\n",
149
+ " \"\"\"Convert transformation stage to binary: 1 for anchorage independent (more advanced cancer stage), 0 otherwise.\"\"\"\n",
150
+ " if isinstance(value, str):\n",
151
+ " # Extract the value after colon\n",
152
+ " if ':' in value:\n",
153
+ " value = value.split(':', 1)[1].strip()\n",
154
+ " \n",
155
+ " # Binary classification based on transformation stage\n",
156
+ " if 'anchorage independent' in value.lower():\n",
157
+ " return 1 # Advanced transformation stage\n",
158
+ " elif 'immortal' in value.lower() or 'extended lifespan' in value.lower():\n",
159
+ " return 0 # Earlier transformation stage\n",
160
+ " return None\n",
161
+ "\n",
162
+ "def convert_age(value: str) -> Optional[float]:\n",
163
+ " \"\"\"Convert age to continuous value.\"\"\"\n",
164
+ " # Not used as age is not available\n",
165
+ " return None\n",
166
+ "\n",
167
+ "def convert_gender(value: str) -> Optional[int]:\n",
168
+ " \"\"\"Convert gender to binary (0 for female, 1 for male).\"\"\"\n",
169
+ " # Not used as gender is not explicitly available\n",
170
+ " return None\n",
171
+ "\n",
172
+ "# 3. Save Metadata\n",
173
+ "# trait_row is not None, meaning trait data is available\n",
174
+ "is_trait_available = trait_row is not None\n",
175
+ "\n",
176
+ "# Initial filtering on usability\n",
177
+ "validate_and_save_cohort_info(\n",
178
+ " is_final=False,\n",
179
+ " cohort=cohort,\n",
180
+ " info_path=json_path,\n",
181
+ " is_gene_available=is_gene_available,\n",
182
+ " is_trait_available=is_trait_available\n",
183
+ ")\n",
184
+ "\n",
185
+ "# Since this is a cell line study and not a human cohort study, and we don't have \n",
186
+ "# access to the clinical_data variable from a previous step, we'll skip the clinical \n",
187
+ "# feature extraction step for now. The trait information would need to be processed \n",
188
+ "# when we have access to the actual data.\n"
189
+ ]
190
+ },
191
+ {
192
+ "cell_type": "markdown",
193
+ "id": "26c53110",
194
+ "metadata": {},
195
+ "source": [
196
+ "### Step 3: Gene Data Extraction"
197
+ ]
198
+ },
199
+ {
200
+ "cell_type": "code",
201
+ "execution_count": 4,
202
+ "id": "c3e863d5",
203
+ "metadata": {
204
+ "execution": {
205
+ "iopub.execute_input": "2025-03-25T08:13:38.081210Z",
206
+ "iopub.status.busy": "2025-03-25T08:13:38.081106Z",
207
+ "iopub.status.idle": "2025-03-25T08:13:38.359188Z",
208
+ "shell.execute_reply": "2025-03-25T08:13:38.358548Z"
209
+ }
210
+ },
211
+ "outputs": [
212
+ {
213
+ "name": "stdout",
214
+ "output_type": "stream",
215
+ "text": [
216
+ "Index(['12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23',\n",
217
+ " '24', '25', '26', '27', '28', '29', '30', '31'],\n",
218
+ " dtype='object', name='ID')\n"
219
+ ]
220
+ }
221
+ ],
222
+ "source": [
223
+ "# 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.\n",
224
+ "gene_data = get_genetic_data(matrix_file)\n",
225
+ "\n",
226
+ "# 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.\n",
227
+ "print(gene_data.index[:20])\n"
228
+ ]
229
+ },
230
+ {
231
+ "cell_type": "markdown",
232
+ "id": "db9f686c",
233
+ "metadata": {},
234
+ "source": [
235
+ "### Step 4: Gene Identifier Review"
236
+ ]
237
+ },
238
+ {
239
+ "cell_type": "code",
240
+ "execution_count": 5,
241
+ "id": "560f2027",
242
+ "metadata": {
243
+ "execution": {
244
+ "iopub.execute_input": "2025-03-25T08:13:38.360971Z",
245
+ "iopub.status.busy": "2025-03-25T08:13:38.360850Z",
246
+ "iopub.status.idle": "2025-03-25T08:13:38.363266Z",
247
+ "shell.execute_reply": "2025-03-25T08:13:38.362826Z"
248
+ }
249
+ },
250
+ "outputs": [],
251
+ "source": [
252
+ "# Looking at the gene identifiers, these appear to be numerical identifiers (12, 13, 14, etc.)\n",
253
+ "# rather than human gene symbols like BRCA1, TP53, etc.\n",
254
+ "# These are likely probe IDs or array-specific identifiers that need to be mapped to gene symbols\n",
255
+ "\n",
256
+ "requires_gene_mapping = True\n"
257
+ ]
258
+ },
259
+ {
260
+ "cell_type": "markdown",
261
+ "id": "b8281f79",
262
+ "metadata": {},
263
+ "source": [
264
+ "### Step 5: Gene Annotation"
265
+ ]
266
+ },
267
+ {
268
+ "cell_type": "code",
269
+ "execution_count": 6,
270
+ "id": "f950ad5d",
271
+ "metadata": {
272
+ "execution": {
273
+ "iopub.execute_input": "2025-03-25T08:13:38.364842Z",
274
+ "iopub.status.busy": "2025-03-25T08:13:38.364737Z",
275
+ "iopub.status.idle": "2025-03-25T08:13:42.580336Z",
276
+ "shell.execute_reply": "2025-03-25T08:13:42.579687Z"
277
+ }
278
+ },
279
+ "outputs": [
280
+ {
281
+ "name": "stdout",
282
+ "output_type": "stream",
283
+ "text": [
284
+ "Gene annotation preview:\n",
285
+ "{'ID': ['1', '2', '3', '4', '5'], 'COL': ['266', '266', '266', '266', '266'], 'ROW': [170.0, 168.0, 166.0, 164.0, 162.0], 'NAME': ['GE_BrightCorner', 'DarkCorner', 'DarkCorner', 'DarkCorner', 'DarkCorner'], 'SPOT_ID': ['GE_BrightCorner', 'DarkCorner', 'DarkCorner', 'DarkCorner', 'DarkCorner'], 'CONTROL_TYPE': ['pos', 'pos', 'pos', 'pos', 'pos'], 'REFSEQ': [nan, nan, nan, nan, nan], 'GB_ACC': [nan, nan, nan, nan, nan], 'GENE': [nan, nan, nan, nan, nan], 'GENE_SYMBOL': [nan, nan, nan, nan, nan], 'GENE_NAME': [nan, nan, nan, nan, nan], 'UNIGENE_ID': [nan, nan, nan, nan, nan], 'ENSEMBL_ID': [nan, nan, nan, nan, nan], 'TIGR_ID': [nan, nan, nan, nan, nan], 'ACCESSION_STRING': [nan, nan, nan, nan, nan], 'CHROMOSOMAL_LOCATION': [nan, nan, nan, nan, nan], 'CYTOBAND': [nan, nan, nan, nan, nan], 'DESCRIPTION': [nan, nan, nan, nan, nan], 'GO_ID': [nan, nan, nan, nan, nan], 'SEQUENCE': [nan, nan, nan, nan, nan], 'SPOT_ID.1': [nan, nan, nan, nan, nan], 'ORDER': [1.0, 2.0, 3.0, 4.0, 5.0]}\n"
286
+ ]
287
+ }
288
+ ],
289
+ "source": [
290
+ "# 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.\n",
291
+ "gene_annotation = get_gene_annotation(soft_file)\n",
292
+ "\n",
293
+ "# 2. Use the 'preview_df' function from the library to preview the data and print out the results.\n",
294
+ "print(\"Gene annotation preview:\")\n",
295
+ "print(preview_df(gene_annotation))\n"
296
+ ]
297
+ },
298
+ {
299
+ "cell_type": "markdown",
300
+ "id": "598beb17",
301
+ "metadata": {},
302
+ "source": [
303
+ "### Step 6: Gene Identifier Mapping"
304
+ ]
305
+ },
306
+ {
307
+ "cell_type": "code",
308
+ "execution_count": 7,
309
+ "id": "606ad1ac",
310
+ "metadata": {
311
+ "execution": {
312
+ "iopub.execute_input": "2025-03-25T08:13:42.582174Z",
313
+ "iopub.status.busy": "2025-03-25T08:13:42.582052Z",
314
+ "iopub.status.idle": "2025-03-25T08:13:42.921531Z",
315
+ "shell.execute_reply": "2025-03-25T08:13:42.920857Z"
316
+ }
317
+ },
318
+ "outputs": [
319
+ {
320
+ "name": "stdout",
321
+ "output_type": "stream",
322
+ "text": [
323
+ "Available columns in gene annotation:\n",
324
+ "['ID', 'COL', 'ROW', 'NAME', 'SPOT_ID', 'CONTROL_TYPE', 'REFSEQ', 'GB_ACC', 'GENE', 'GENE_SYMBOL', 'GENE_NAME', 'UNIGENE_ID', 'ENSEMBL_ID', 'TIGR_ID', 'ACCESSION_STRING', 'CHROMOSOMAL_LOCATION', 'CYTOBAND', 'DESCRIPTION', 'GO_ID', 'SEQUENCE', 'SPOT_ID.1', 'ORDER']\n",
325
+ "\n",
326
+ "Sample of gene annotation data with non-null gene symbols:\n",
327
+ "{'ID': ['12', '14', '15', '16', '18'], 'COL': ['266', '266', '266', '266', '266'], 'ROW': [148.0, 144.0, 142.0, 140.0, 136.0], 'NAME': ['A_24_P66027', 'A_23_P212522', 'A_24_P934473', 'A_24_P9671', 'A_24_P801451'], 'SPOT_ID': ['A_24_P66027', 'A_23_P212522', 'A_24_P934473', 'A_24_P9671', 'A_24_P801451'], 'CONTROL_TYPE': ['FALSE', 'FALSE', 'FALSE', 'FALSE', 'FALSE'], 'REFSEQ': ['NM_004900', 'NM_014616', nan, 'NM_001539', 'NM_006709'], 'GB_ACC': ['NM_004900', 'NM_014616', 'AK092846', 'NM_001539', 'NM_006709'], 'GENE': [9582.0, 23200.0, 100132006.0, 3301.0, 10919.0], 'GENE_SYMBOL': ['APOBEC3B', 'ATP11B', 'LOC100132006', 'DNAJA1', 'EHMT2'], 'GENE_NAME': ['apolipoprotein B mRNA editing enzyme, catalytic polypeptide-like 3B', 'ATPase, class VI, type 11B', 'hypothetical protein LOC100132006', 'DnaJ (Hsp40) homolog, subfamily A, member 1', 'euchromatic histone-lysine N-methyltransferase 2'], 'UNIGENE_ID': ['Hs.226307', 'Hs.478429', 'Hs.593666', 'Hs.445203', 'Hs.709218'], 'ENSEMBL_ID': ['ENST00000407298', 'ENST00000323116', nan, 'ENST00000330899', 'ENST00000375537'], 'TIGR_ID': ['NP075413', 'THC2580543', 'THC2483825', 'THC2482967', 'THC2496448'], 'ACCESSION_STRING': ['ref|NM_004900|ref|NM_145699|ens|ENST00000407298|ens|ENST00000333467', 'ref|NM_014616|ens|ENST00000323116|gb|AB023173|gb|AL133061', 'gb|AK092846|gb|AX747763|thc|THC2483825', 'ref|NM_001539|gb|AY186741|ens|ENST00000330899|gb|BT007292', 'ref|NM_006709|ref|NM_025256|gb|BC018718|ens|ENST00000375537'], 'CHROMOSOMAL_LOCATION': ['chr22:37717484-37717543', 'chr3:184121316-184121375', 'chr16:8649039-8649098', 'chr9:33026682-33027066', 'unmapped'], 'CYTOBAND': ['hs|22q13.1', 'hs|3q26.33', 'hs|16p13.2', 'hs|9p13.3', nan], 'DESCRIPTION': ['Homo sapiens apolipoprotein B mRNA editing enzyme, catalytic polypeptide-like 3B (APOBEC3B), mRNA [NM_004900]', 'Homo sapiens ATPase, class VI, type 11B (ATP11B), mRNA [NM_014616]', 'Homo sapiens cDNA FLJ35527 fis, clone SPLEN2001781. [AK092846]', 'Homo sapiens DnaJ (Hsp40) homolog, subfamily A, member 1 (DNAJA1), mRNA [NM_001539]', 'Homo sapiens euchromatic histone-lysine N-methyltransferase 2 (EHMT2), transcript variant NG36/G9a, mRNA [NM_006709]'], 'GO_ID': ['GO:0003723(RNA binding)|GO:0005575(cellular_component)|GO:0008150(biological_process)|GO:0008270(zinc ion binding)|GO:0016787(hydrolase activity)|GO:0016814(hydrolase activity, acting on carbon-nitrogen (but not peptide) bonds, in cyclic amidines)|GO:0046872(metal ion binding)', 'GO:0000166(nucleotide binding)|GO:0000287(magnesium ion binding)|GO:0004012(phospholipid-translocating ATPase activity)|GO:0005524(ATP binding)|GO:0005637(nuclear inner membrane)|GO:0006754(ATP biosynthetic process)|GO:0006811(ion transport)|GO:0008152(metabolic process)|GO:0015075(ion transmembrane transporter activity)|GO:0015662(ATPase activity, coupled to transmembrane movement of ions, phosphorylative mechanism)|GO:0015914(phospholipid transport)|GO:0015917(aminophospholipid transport)|GO:0016020(membrane)|GO:0016021(integral to membrane)|GO:0016787(hydrolase activity)|GO:0016820(hydrolase activity, acting on acid anhydrides, catalyzing transmembrane movement of substances)', nan, 'GO:0005737(cytoplasm)|GO:0005856(cytoskeleton)|GO:0006457(protein folding)|GO:0006986(response to unfolded protein)|GO:0007283(spermatogenesis)|GO:0008270(zinc ion binding)|GO:0016020(membrane)|GO:0030317(sperm motility)|GO:0030521(androgen receptor signaling pathway)|GO:0031072(heat shock protein binding)|GO:0046872(metal ion binding)|GO:0050750(low-density lipoprotein receptor binding)|GO:0051082(unfolded protein binding)', 'GO:0000122(negative regulation of transcription from RNA polymerase II promoter)|GO:0000239(pachytene)|GO:0005515(protein binding)|GO:0005575(cellular_component)|GO:0005634(nucleus)|GO:0007130(synaptonemal complex assembly)|GO:0007286(spermatid development)|GO:0008150(biological_process)|GO:0008168(methyltransferase activity)|GO:0008270(zinc ion binding)|GO:0009566(fertilization)|GO:0016568(chromatin modification)|GO:0016740(transferase activity)|GO:0018024(histone-lysine N-methyltransferase activity)|GO:0035265(organ growth)|GO:0046872(metal ion binding)|GO:0051567(histone H3-K9 methylation)'], 'SEQUENCE': ['GCTGCCCGCATCTATGATTACGACCCCCTATATAAGGAGGCGCTGCAAATGCTGCGGGAT', 'ATTTTCTAACTGTCCTCTTTCTTGGGTCTAAAGCTCATAATACACAAAGGCTTCCAGACC', 'AAGCCAAGTACTTTAGAGAAGAAAAACGGTCTCAGCTGAACCTGTAGTGAGAGCATGCAG', 'ATCCAGGTCAGATTGTCAAGCATGGAGATATCAAGTGTGTACTAAATGAAGGCATGCCAA', 'AAATCGGGCCATCCGCACCAGAGGAAGATCATTCTGCCGGGACGTGGCTCGGGGCTATGA'], 'SPOT_ID.1': [nan, nan, nan, nan, nan], 'ORDER': [12.0, 14.0, 15.0, 16.0, 18.0]}\n",
328
+ "\n",
329
+ "Gene mapping dataframe:\n",
330
+ "{'ID': ['12', '14', '15', '16', '18'], 'Gene': ['APOBEC3B', 'ATP11B', 'LOC100132006', 'DNAJA1', 'EHMT2']}\n"
331
+ ]
332
+ },
333
+ {
334
+ "name": "stdout",
335
+ "output_type": "stream",
336
+ "text": [
337
+ "\n",
338
+ "Converted gene expression data:\n",
339
+ "{'GSM4098797': [11.295818278999999, 4.511519006, 4.029339788, 7.998331606, 3.529187489], 'GSM4098798': [11.311701529, 4.350843151, 3.829114997, 6.938423613, 3.403435718], 'GSM4098799': [11.490747099, 3.940382921, 3.518664325, 8.071803433, 3.703306235], 'GSM4098800': [10.62815242, 4.278446209, 3.952369234, 7.445960991, 4.175610589], 'GSM4098801': [11.425336329, 4.211956199, 3.755241441, 7.389486419, 3.693382222], 'GSM4098802': [11.309095206, 3.807001272, 3.779241628, 8.267602906, 3.980138411], 'GSM4098803': [10.929429424, 3.925654364, 3.833418791, 8.355437797, 3.735606345], 'GSM4098804': [10.700006593000001, 4.314044971, 3.658411735, 7.448207267, 3.828141668], 'GSM4098805': [11.592457953, 3.520838128, 3.908003521, 7.832426589, 3.520838128], 'GSM4098806': [9.173432164000001, 4.137373263, 2.928105386, 8.132917185, 3.335657835], 'GSM4098807': [11.6466158, 4.51745926, 3.900382259, 8.405353632, 3.930806637], 'GSM4098808': [12.349148621, 4.781086546, 3.085499595, 8.276549505, 3.163182708], 'GSM4098809': [11.668675356, 4.036497385, 3.7901343, 8.222292761, 4.074914684], 'GSM4098810': [12.122596969, 4.134970053, 4.05199999, 8.051823544, 3.235740223], 'GSM4098811': [12.495397475, 4.101323054, 3.644023212, 7.634603293, 3.463214042], 'GSM4098812': [12.218892765, 4.595064891, 3.427753343, 7.684041323, 4.018747086], 'GSM4098813': [9.685849347, 4.22606317, 4.325947699, 7.562952071, 3.331314104], 'GSM4098814': [10.0964321, 4.867040912, 4.532427035, 7.256587897, 3.597141516], 'GSM4098815': [11.212807124, 4.23800568, 3.183184688, 7.921425237, 3.781316708], 'GSM4098816': [11.756302245, 4.374955768, 3.143092663, 8.429888285, 3.896505162], 'GSM4098817': [11.480266855, 4.644577848, 3.275647524, 7.337444716, 3.275647524], 'GSM4098818': [11.572050526, 4.216746355, 3.132219007, 8.030310185, 3.764970611], 'GSM4098819': [12.111974762, 4.871226415, 4.395134425, 8.383003976, 4.41419136], 'GSM4098820': [11.797386841, 4.357093025, 3.741237359, 7.488852897, 3.344227418], 'GSM4098821': [11.022180294, 4.528972801, 3.781929803, 8.127972724, 2.901117994], 'GSM4098822': [9.985806461, 4.334899168, 4.691320904, 8.08196884, 3.566150133], 'GSM4098823': [10.955167297, 3.988884942, 3.870179586, 7.627231669, 4.178270066], 'GSM4098824': [11.519869761, 3.560649062, 4.054721721, 8.318647838, 3.560649062], 'GSM4098825': [11.50559043, 4.354759526, 3.913857056, 8.252489038, 3.986446731], 'GSM4098826': [11.521872274, 4.162068735, 3.99068833, 7.49736804, 3.9320142], 'GSM4098827': [11.530309796000001, 4.258577062, 3.876582889, 7.638285155, 3.798833313], 'GSM4098828': [11.650405668, 4.588559402, 3.844650541, 7.649147453, 3.753795349], 'GSM4098829': [11.439998252999999, 4.569085095, 4.930172588, 8.660099047, 4.148122963], 'GSM4098830': [11.774968708000001, 4.475843846, 5.006921531, 8.306217473, 3.611226197], 'GSM4098831': [11.678834608999999, 3.992244703, 4.468223005, 8.725613368, 3.984856471], 'GSM4098832': [13.36665025, 4.663087485, 4.1664225, 7.613446924, 3.731352081], 'GSM4098833': [12.313311616, 4.346523659, 5.099913979, 8.275625494, 3.945911967], 'GSM4098834': [12.060811490999999, 4.256161059, 4.55451106, 8.202508423, 3.966656535], 'GSM4098835': [11.724259242, 4.12452232, 4.209760987, 8.452567683, 3.884865532], 'GSM4098836': [11.290614289, 4.416970969, 4.283844755, 7.950836689, 3.777055871], 'GSM4098837': [11.671444767999999, 4.70877685, 3.468851143, 7.662878274, 4.133964458], 'GSM4098838': [12.383108663, 4.247671487, 3.620601132, 8.539622569, 4.578953058], 'GSM4098839': [12.529668529, 4.662650635, 4.289667541, 8.474277445, 4.148552504], 'GSM4098840': [12.163355781, 4.763055707, 4.609645595, 8.260846839, 3.881485497], 'GSM4098841': [12.196179489999999, 4.237644549, 3.939796283, 9.030725874, 4.300612679], 'GSM4098842': [12.492096591, 4.359883689, 4.468801492, 7.923179402, 4.223197571], 'GSM4098843': [12.492539869, 4.067942975, 3.826995086, 7.624608546, 3.457999265], 'GSM4098844': [12.640559166, 4.277883701, 4.132814383, 8.098631342, 3.802210543], 'GSM4098845': [10.515985308, 4.428130209, 5.640199416, 8.424042297, 4.159216319], 'GSM4098846': [10.72859967, 4.545376526, 5.43525345, 8.116347941, 3.959945264], 'GSM4098847': [12.588295016, 4.252219424, 4.565555293, 8.229620491, 3.876710204], 'GSM4098848': [12.856335031, 4.837687313, 4.476784638, 8.59978321, 3.782853842], 'GSM4098849': [12.482955217, 4.410063383, 3.112111144, 7.688118613, 3.484341798], 'GSM4098850': [12.175504981, 4.525790096, 3.835247245, 8.192688326, 3.56097626], 'GSM4098851': [12.600100614999999, 4.792830166, 3.575349359, 8.635279662, 4.100254296], 'GSM4098852': [12.561666092, 4.402865814, 3.602970048, 8.325050001, 3.566874369], 'GSM4098853': [11.732715874, 4.649540088, 5.771464833, 8.48636833, 3.710872842], 'GSM4098854': [11.89072243, 4.280776313, 5.88416279, 8.784441166, 4.096685464], 'GSM4098855': [11.612091881, 3.987538223, 4.154718691, 8.135290914, 4.328919317], 'GSM4098856': [12.379367429999999, 4.596680653, 4.046847858, 8.006627098, 3.830326299], 'GSM4098857': [11.803956761, 4.698200208, 4.380661404, 8.690838172, 4.107066454], 'GSM4098858': [12.737503504, 3.667374991, 4.345379919, 8.318647024, 4.319829603], 'GSM4098859': [13.0600405, 4.769800866, 4.181172288, 8.374885971, 3.827799923], 'GSM4098860': [12.161425048, 4.629566597, 4.041705826, 7.91833211, 3.650639297]}\n"
340
+ ]
341
+ }
342
+ ],
343
+ "source": [
344
+ "# 1. Identify relevant columns from the gene annotation data for mapping\n",
345
+ "# The gene identifiers in gene_data are numeric IDs\n",
346
+ "# From the preview, we need to map 'ID' in the annotation to a gene symbol column\n",
347
+ "\n",
348
+ "# Looking at the columns in gene_annotation\n",
349
+ "print(\"Available columns in gene annotation:\")\n",
350
+ "print(gene_annotation.columns.tolist())\n",
351
+ "\n",
352
+ "# Let's get a better look at the annotation data beyond the first few rows\n",
353
+ "# to find rows that actually have gene symbol information\n",
354
+ "print(\"\\nSample of gene annotation data with non-null gene symbols:\")\n",
355
+ "sample_with_genes = gene_annotation[gene_annotation['GENE_SYMBOL'].notna()].head(5)\n",
356
+ "print(preview_df(sample_with_genes))\n",
357
+ "\n",
358
+ "# 2. Create the gene mapping dataframe\n",
359
+ "# Based on the data, we'll map 'ID' to 'GENE_SYMBOL'\n",
360
+ "mapping_df = get_gene_mapping(gene_annotation, 'ID', 'GENE_SYMBOL')\n",
361
+ "print(\"\\nGene mapping dataframe:\")\n",
362
+ "print(preview_df(mapping_df))\n",
363
+ "\n",
364
+ "# 3. Apply the gene mapping to convert probe-level measurements to gene expression\n",
365
+ "gene_data_mapped = apply_gene_mapping(gene_data, mapping_df)\n",
366
+ "\n",
367
+ "# Normalize gene symbols to ensure consistency\n",
368
+ "gene_data = normalize_gene_symbols_in_index(gene_data_mapped)\n",
369
+ "\n",
370
+ "# Preview the result\n",
371
+ "print(\"\\nConverted gene expression data:\")\n",
372
+ "print(preview_df(gene_data))\n"
373
+ ]
374
+ },
375
+ {
376
+ "cell_type": "markdown",
377
+ "id": "72a8d3cd",
378
+ "metadata": {},
379
+ "source": [
380
+ "### Step 7: Data Normalization and Linking"
381
+ ]
382
+ },
383
+ {
384
+ "cell_type": "code",
385
+ "execution_count": 8,
386
+ "id": "ff461b59",
387
+ "metadata": {
388
+ "execution": {
389
+ "iopub.execute_input": "2025-03-25T08:13:42.923358Z",
390
+ "iopub.status.busy": "2025-03-25T08:13:42.923235Z",
391
+ "iopub.status.idle": "2025-03-25T08:13:52.345716Z",
392
+ "shell.execute_reply": "2025-03-25T08:13:52.344636Z"
393
+ }
394
+ },
395
+ "outputs": [
396
+ {
397
+ "name": "stdout",
398
+ "output_type": "stream",
399
+ "text": [
400
+ "Normalized gene data saved to ../../output/preprocess/Cervical_Cancer/gene_data/GSE138079.csv\n",
401
+ "Clinical data saved to ../../output/preprocess/Cervical_Cancer/clinical_data/GSE138079.csv\n",
402
+ "Linked data shape: (64, 17902)\n"
403
+ ]
404
+ },
405
+ {
406
+ "name": "stdout",
407
+ "output_type": "stream",
408
+ "text": [
409
+ "For the feature 'Cervical_Cancer', the least common label is '0.0' with 23 occurrences. This represents 35.94% of the dataset.\n",
410
+ "The distribution of the feature 'Cervical_Cancer' in this dataset is fine.\n",
411
+ "\n"
412
+ ]
413
+ },
414
+ {
415
+ "name": "stdout",
416
+ "output_type": "stream",
417
+ "text": [
418
+ "Linked data saved to ../../output/preprocess/Cervical_Cancer/GSE138079.csv\n"
419
+ ]
420
+ }
421
+ ],
422
+ "source": [
423
+ "# 1. Normalize the obtained gene data with the 'normalize_gene_symbols_in_index' function from the library.\n",
424
+ "normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n",
425
+ "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
426
+ "normalized_gene_data.to_csv(out_gene_data_file)\n",
427
+ "print(f\"Normalized gene data saved to {out_gene_data_file}\")\n",
428
+ "\n",
429
+ "# Create clinical features directly from clinical_data using the conversion functions defined earlier\n",
430
+ "clinical_features_df = geo_select_clinical_features(\n",
431
+ " clinical_data, \n",
432
+ " trait=trait, \n",
433
+ " trait_row=trait_row, \n",
434
+ " convert_trait=convert_trait,\n",
435
+ " age_row=age_row,\n",
436
+ " convert_age=convert_age,\n",
437
+ " gender_row=gender_row,\n",
438
+ " convert_gender=convert_gender\n",
439
+ ")\n",
440
+ "\n",
441
+ "# Save the clinical data\n",
442
+ "os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
443
+ "clinical_features_df.to_csv(out_clinical_data_file)\n",
444
+ "print(f\"Clinical data saved to {out_clinical_data_file}\")\n",
445
+ "\n",
446
+ "# Now link the clinical and genetic data\n",
447
+ "linked_data = geo_link_clinical_genetic_data(clinical_features_df, normalized_gene_data)\n",
448
+ "print(\"Linked data shape:\", linked_data.shape)\n",
449
+ "\n",
450
+ "# Handle missing values in the linked data\n",
451
+ "linked_data = handle_missing_values(linked_data, trait)\n",
452
+ "\n",
453
+ "# 4. Determine whether the trait and some demographic features are severely biased, and remove biased features.\n",
454
+ "is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)\n",
455
+ "\n",
456
+ "# 5. Conduct quality check and save the cohort information.\n",
457
+ "is_usable = validate_and_save_cohort_info(\n",
458
+ " is_final=True, \n",
459
+ " cohort=cohort, \n",
460
+ " info_path=json_path, \n",
461
+ " is_gene_available=True, \n",
462
+ " is_trait_available=True, \n",
463
+ " is_biased=is_trait_biased, \n",
464
+ " df=unbiased_linked_data,\n",
465
+ " note=\"This is an HPV-transformed keratinocyte cell line study focusing on transformation stages: 1 for anchorage independent (more advanced cancer stage), 0 for earlier stages.\"\n",
466
+ ")\n",
467
+ "\n",
468
+ "# 6. If the linked data is usable, save it as a CSV file to 'out_data_file'.\n",
469
+ "if is_usable:\n",
470
+ " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n",
471
+ " unbiased_linked_data.to_csv(out_data_file)\n",
472
+ " print(f\"Linked data saved to {out_data_file}\")\n",
473
+ "else:\n",
474
+ " print(\"Data was determined to be unusable and was not saved\")"
475
+ ]
476
+ }
477
+ ],
478
+ "metadata": {
479
+ "language_info": {
480
+ "codemirror_mode": {
481
+ "name": "ipython",
482
+ "version": 3
483
+ },
484
+ "file_extension": ".py",
485
+ "mimetype": "text/x-python",
486
+ "name": "python",
487
+ "nbconvert_exporter": "python",
488
+ "pygments_lexer": "ipython3",
489
+ "version": "3.10.16"
490
+ }
491
+ },
492
+ "nbformat": 4,
493
+ "nbformat_minor": 5
494
+ }
code/Chronic_obstructive_pulmonary_disease_(COPD)/GSE21359.ipynb ADDED
@@ -0,0 +1,722 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": 1,
6
+ "id": "9f62ece1",
7
+ "metadata": {
8
+ "execution": {
9
+ "iopub.execute_input": "2025-03-25T08:20:56.069305Z",
10
+ "iopub.status.busy": "2025-03-25T08:20:56.069012Z",
11
+ "iopub.status.idle": "2025-03-25T08:20:56.225825Z",
12
+ "shell.execute_reply": "2025-03-25T08:20:56.225399Z"
13
+ }
14
+ },
15
+ "outputs": [],
16
+ "source": [
17
+ "import sys\n",
18
+ "import os\n",
19
+ "sys.path.append(os.path.abspath(os.path.join(os.getcwd(), '../..')))\n",
20
+ "\n",
21
+ "# Path Configuration\n",
22
+ "from tools.preprocess import *\n",
23
+ "\n",
24
+ "# Processing context\n",
25
+ "trait = \"Chronic_obstructive_pulmonary_disease_(COPD)\"\n",
26
+ "cohort = \"GSE21359\"\n",
27
+ "\n",
28
+ "# Input paths\n",
29
+ "in_trait_dir = \"../../input/GEO/Chronic_obstructive_pulmonary_disease_(COPD)\"\n",
30
+ "in_cohort_dir = \"../../input/GEO/Chronic_obstructive_pulmonary_disease_(COPD)/GSE21359\"\n",
31
+ "\n",
32
+ "# Output paths\n",
33
+ "out_data_file = \"../../output/preprocess/Chronic_obstructive_pulmonary_disease_(COPD)/GSE21359.csv\"\n",
34
+ "out_gene_data_file = \"../../output/preprocess/Chronic_obstructive_pulmonary_disease_(COPD)/gene_data/GSE21359.csv\"\n",
35
+ "out_clinical_data_file = \"../../output/preprocess/Chronic_obstructive_pulmonary_disease_(COPD)/clinical_data/GSE21359.csv\"\n",
36
+ "json_path = \"../../output/preprocess/Chronic_obstructive_pulmonary_disease_(COPD)/cohort_info.json\"\n"
37
+ ]
38
+ },
39
+ {
40
+ "cell_type": "markdown",
41
+ "id": "c09dabe8",
42
+ "metadata": {},
43
+ "source": [
44
+ "### Step 1: Initial Data Loading"
45
+ ]
46
+ },
47
+ {
48
+ "cell_type": "code",
49
+ "execution_count": 2,
50
+ "id": "503721f4",
51
+ "metadata": {
52
+ "execution": {
53
+ "iopub.execute_input": "2025-03-25T08:20:56.227270Z",
54
+ "iopub.status.busy": "2025-03-25T08:20:56.227133Z",
55
+ "iopub.status.idle": "2025-03-25T08:20:56.544305Z",
56
+ "shell.execute_reply": "2025-03-25T08:20:56.543920Z"
57
+ }
58
+ },
59
+ "outputs": [
60
+ {
61
+ "name": "stdout",
62
+ "output_type": "stream",
63
+ "text": [
64
+ "Background Information:\n",
65
+ "!Series_title\t\"Association of CXCL14 in the Human Airway Epithelium with Chronic Obstructive Lung Disease and Lung Cancer\"\n",
66
+ "!Series_summary\t\"CXCL14, a recently described chemokine constitutively expressed in various epithelia, has multiple putative roles in inflammation and carcinogenesis. Based on the knowledge that cigarette smoking and the smoking-induced disorders, such as chronic obstructive pulmonary disease (COPD) and lung cancer, are associated with inflammation, we hypothesized that the airway epithelium, the primary site of smoking-induced pathologic changes in COPD and adenocarcinoma, responds to cigarette smoking with an altered CXCL14 gene expression as a part of disease-relevant molecular phenotype. Microarray analysis with subsequent TaqMan PCR validation revealed very low constitutive CXCL14 gene expression in the airway epithelium of healthy nonsmokers (n=53) which was strongly up-regulated in healthy smokers ( n=59; p<0.001) and further increased in COPD smokers (n=23; p<10-7 vs nonsmokers; p<0.005 vs healthy smokers). In smokers, CXCL14 expression inversely correlated with lung function parameters FEV1 and FEV1/FVC. Genome-wide analysis also showed that up-regulated correlation of CXCL14 expression with genes related to cell growth and proliferation, squamous differentiation and cancer. The analysis of 193 lung adenocarcinoma samples demonstrated a dramatic up-regulation of CXCL14 in a smoking-dependent manner. [need to include survival data once we get it]. Together, these data suggest that smoking-induced expression of CXCL14 in association with genome-wide reprogramming of processes related to tissue homeostasis, differentiation and tumorigenesis, represents a novel molecular link between cigarette smoking, COPD and lung cancer.\"\n",
67
+ "!Series_overall_design\t\"Affymetrix arrays were used to assess the expression of CXCL14 gene expression data in small airway epithelium obtained by fiberoptic bronchoscopy of 53 healthy non-smokers and 59 healthy smokers and 23 smokers with COPD.\"\n",
68
+ "Sample Characteristics Dictionary:\n",
69
+ "{0: ['Age: 41', 'age: 35', 'age: 61', 'age: 37', 'age: 47', 'age: 38', 'age: 49', 'age: 45', 'age: 36', 'age: 46', 'age: 48', 'age: 50', 'age: 56', 'age: 59', 'age: 34', 'age: 44', 'Age: 45', 'age: 29', 'age: 42', 'Age: 47', 'age: 55', 'age: 51', 'age: 60', 'age: 52', 'age: 40', 'age: 41', 'age: 43', 'age: 31', 'age: 53', 'age: 62'], 1: ['Sex: M', 'sex: M', 'sex: F', 'Sex: F'], 2: ['Ethnic group: black', 'ethnic group: black', 'ethnic group: white', 'ethnic group: hispanic', 'Ethnic group: white', 'ethnic group: black/hispanic', 'ethnic group: asian'], 3: ['Smoking Status: non-smoker', 'smoking status: non-smoker', 'smoking status: smoker, 21 pack-years', 'smoking status: smoker, 23 pack-years', 'smoking status: smoker, 28 pack-years', 'smoking status: smoker, 20 pack-years', 'smoking status: smoker, 38 pack-years', 'smoking status: smoker, 80 pack-years', 'smoking status: smoker, 60 pack-years', 'Smoking status: non-smoker', 'smoking status: COPD, GOLD-I, 50 pack-years', 'Smoking status: COPD, GOLD-II, 33 pack-years', 'smoking status: COPD, GOLD-II, 35 pack-years', 'smoking status: COPD, GOLD-II, 20 pack-years', 'smoking status: COPD, GOLD-I, 48 pack-years', 'smoking status: COPD, GOLD-II, 75 pack-years', 'smoking status: COPD, GOLD-II, 27 pack-years', 'smoking status: COPD, GOLD-II, 60 pack-years', 'smoking status: COPD, GOLD-III, 110 pack-years', 'smoking status: COPD, GOLD-I, 22 pack-years', 'smoking status: COPD, GOLD-I, 23 pack-years', 'smoking status: smoker, 24 pack-years', 'smoking status: smoker, 29 pack-years', 'smoking status: smoker, 45 pack-years', 'smoking status: smoker, 32 pack-years', 'smoking status: smoker, 36 pack-years', 'smoking status: smoker, 15 pack-years', 'smoking status: smoker, 22 pack-years', 'smoking status: smoker, 33 pack-years', 'smoking status: smoker, 16 pack-years']}\n"
70
+ ]
71
+ }
72
+ ],
73
+ "source": [
74
+ "from tools.preprocess import *\n",
75
+ "# 1. Identify the paths to the SOFT file and the matrix file\n",
76
+ "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
77
+ "\n",
78
+ "# 2. Read the matrix file to obtain background information and sample characteristics data\n",
79
+ "background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']\n",
80
+ "clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']\n",
81
+ "background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)\n",
82
+ "\n",
83
+ "# 3. Obtain the sample characteristics dictionary from the clinical dataframe\n",
84
+ "sample_characteristics_dict = get_unique_values_by_row(clinical_data)\n",
85
+ "\n",
86
+ "# 4. Explicitly print out all the background information and the sample characteristics dictionary\n",
87
+ "print(\"Background Information:\")\n",
88
+ "print(background_info)\n",
89
+ "print(\"Sample Characteristics Dictionary:\")\n",
90
+ "print(sample_characteristics_dict)\n"
91
+ ]
92
+ },
93
+ {
94
+ "cell_type": "markdown",
95
+ "id": "57a8c06c",
96
+ "metadata": {},
97
+ "source": [
98
+ "### Step 2: Dataset Analysis and Clinical Feature Extraction"
99
+ ]
100
+ },
101
+ {
102
+ "cell_type": "code",
103
+ "execution_count": 3,
104
+ "id": "daea0c4b",
105
+ "metadata": {
106
+ "execution": {
107
+ "iopub.execute_input": "2025-03-25T08:20:56.545664Z",
108
+ "iopub.status.busy": "2025-03-25T08:20:56.545550Z",
109
+ "iopub.status.idle": "2025-03-25T08:20:56.556109Z",
110
+ "shell.execute_reply": "2025-03-25T08:20:56.555783Z"
111
+ }
112
+ },
113
+ "outputs": [
114
+ {
115
+ "name": "stdout",
116
+ "output_type": "stream",
117
+ "text": [
118
+ "Clinical Features Preview:\n",
119
+ "{0: [nan, 41.0, nan], 1: [nan, nan, 1.0], 2: [nan, nan, nan], 3: [0.0, nan, nan]}\n",
120
+ "Clinical features saved to ../../output/preprocess/Chronic_obstructive_pulmonary_disease_(COPD)/clinical_data/GSE21359.csv\n"
121
+ ]
122
+ }
123
+ ],
124
+ "source": [
125
+ "import os\n",
126
+ "import json\n",
127
+ "import pandas as pd\n",
128
+ "from typing import Dict, Any, Optional, Callable\n",
129
+ "\n",
130
+ "# 1. Gene Expression Data Availability\n",
131
+ "# This dataset appears to be using Affymetrix arrays to assess gene expression, \n",
132
+ "# so it's likely to contain gene expression data\n",
133
+ "is_gene_available = True\n",
134
+ "\n",
135
+ "# 2.1 Data Availability\n",
136
+ "# Trait (COPD) information is in row 3 under \"smoking status\"\n",
137
+ "trait_row = 3\n",
138
+ "# Age information is in row 0\n",
139
+ "age_row = 0\n",
140
+ "# Gender information is in row 1\n",
141
+ "gender_row = 1\n",
142
+ "\n",
143
+ "# 2.2 Data Type Conversion Functions\n",
144
+ "def convert_trait(value):\n",
145
+ " \"\"\"Convert trait information to binary (0: non-COPD, 1: COPD)\"\"\"\n",
146
+ " if value is None or not isinstance(value, str):\n",
147
+ " return None\n",
148
+ " \n",
149
+ " # Extract value after colon\n",
150
+ " if ':' in value:\n",
151
+ " value = value.split(':', 1)[1].strip()\n",
152
+ " \n",
153
+ " # Check if the person has COPD\n",
154
+ " if 'COPD' in value:\n",
155
+ " return 1\n",
156
+ " elif 'non-smoker' in value or 'smoker,' in value:\n",
157
+ " return 0\n",
158
+ " else:\n",
159
+ " return None\n",
160
+ "\n",
161
+ "def convert_age(value):\n",
162
+ " \"\"\"Convert age information to continuous values\"\"\"\n",
163
+ " if value is None or not isinstance(value, str):\n",
164
+ " return None\n",
165
+ " \n",
166
+ " # Extract value after colon\n",
167
+ " if ':' in value:\n",
168
+ " value = value.split(':', 1)[1].strip()\n",
169
+ " \n",
170
+ " try:\n",
171
+ " return float(value)\n",
172
+ " except ValueError:\n",
173
+ " return None\n",
174
+ "\n",
175
+ "def convert_gender(value):\n",
176
+ " \"\"\"Convert gender information to binary (0: female, 1: male)\"\"\"\n",
177
+ " if value is None or not isinstance(value, str):\n",
178
+ " return None\n",
179
+ " \n",
180
+ " # Extract value after colon\n",
181
+ " if ':' in value:\n",
182
+ " value = value.split(':', 1)[1].strip()\n",
183
+ " \n",
184
+ " # Convert gender to binary\n",
185
+ " if value.upper() == 'F':\n",
186
+ " return 0\n",
187
+ " elif value.upper() == 'M':\n",
188
+ " return 1\n",
189
+ " else:\n",
190
+ " return None\n",
191
+ "\n",
192
+ "# 3. Save Metadata\n",
193
+ "# Check if trait data is available\n",
194
+ "is_trait_available = trait_row is not None\n",
195
+ "validate_and_save_cohort_info(\n",
196
+ " is_final=False, \n",
197
+ " cohort=cohort, \n",
198
+ " info_path=json_path, \n",
199
+ " is_gene_available=is_gene_available, \n",
200
+ " is_trait_available=is_trait_available\n",
201
+ ")\n",
202
+ "\n",
203
+ "# 4. Clinical Feature Extraction\n",
204
+ "if trait_row is not None:\n",
205
+ " # Create DataFrame from the sample characteristics dictionary\n",
206
+ " sample_char_dict = {0: ['Age: 41', 'age: 35', 'age: 61', 'age: 37', 'age: 47', 'age: 38', 'age: 49', 'age: 45', 'age: 36', 'age: 46', 'age: 48', 'age: 50', 'age: 56', 'age: 59', 'age: 34', 'age: 44', 'Age: 45', 'age: 29', 'age: 42', 'Age: 47', 'age: 55', 'age: 51', 'age: 60', 'age: 52', 'age: 40', 'age: 41', 'age: 43', 'age: 31', 'age: 53', 'age: 62'], \n",
207
+ " 1: ['Sex: M', 'sex: M', 'sex: F', 'Sex: F'], \n",
208
+ " 2: ['Ethnic group: black', 'ethnic group: black', 'ethnic group: white', 'ethnic group: hispanic', 'Ethnic group: white', 'ethnic group: black/hispanic', 'ethnic group: asian'], \n",
209
+ " 3: ['Smoking Status: non-smoker', 'smoking status: non-smoker', 'smoking status: smoker, 21 pack-years', 'smoking status: smoker, 23 pack-years', 'smoking status: smoker, 28 pack-years', 'smoking status: smoker, 20 pack-years', 'smoking status: smoker, 38 pack-years', 'smoking status: smoker, 80 pack-years', 'smoking status: smoker, 60 pack-years', 'Smoking status: non-smoker', 'smoking status: COPD, GOLD-I, 50 pack-years', 'Smoking status: COPD, GOLD-II, 33 pack-years', 'smoking status: COPD, GOLD-II, 35 pack-years', 'smoking status: COPD, GOLD-II, 20 pack-years', 'smoking status: COPD, GOLD-I, 48 pack-years', 'smoking status: COPD, GOLD-II, 75 pack-years', 'smoking status: COPD, GOLD-II, 27 pack-years', 'smoking status: COPD, GOLD-II, 60 pack-years', 'smoking status: COPD, GOLD-III, 110 pack-years', 'smoking status: COPD, GOLD-I, 22 pack-years', 'smoking status: COPD, GOLD-I, 23 pack-years', 'smoking status: smoker, 24 pack-years', 'smoking status: smoker, 29 pack-years', 'smoking status: smoker, 45 pack-years', 'smoking status: smoker, 32 pack-years', 'smoking status: smoker, 36 pack-years', 'smoking status: smoker, 15 pack-years', 'smoking status: smoker, 22 pack-years', 'smoking status: smoker, 33 pack-years', 'smoking status: smoker, 16 pack-years']}\n",
210
+ " \n",
211
+ " # Convert dict to DataFrame\n",
212
+ " clinical_data = pd.DataFrame.from_dict(sample_char_dict, orient='index')\n",
213
+ " clinical_data = clinical_data.transpose()\n",
214
+ " \n",
215
+ " # Extract clinical features\n",
216
+ " clinical_features_df = geo_select_clinical_features(\n",
217
+ " clinical_df=clinical_data,\n",
218
+ " trait=trait,\n",
219
+ " trait_row=trait_row,\n",
220
+ " convert_trait=convert_trait,\n",
221
+ " age_row=age_row,\n",
222
+ " convert_age=convert_age,\n",
223
+ " gender_row=gender_row,\n",
224
+ " convert_gender=convert_gender\n",
225
+ " )\n",
226
+ " \n",
227
+ " # Preview the extracted features\n",
228
+ " preview = preview_df(clinical_features_df)\n",
229
+ " print(\"Clinical Features Preview:\")\n",
230
+ " print(preview)\n",
231
+ " \n",
232
+ " # Create directory if it doesn't exist\n",
233
+ " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
234
+ " \n",
235
+ " # Save the clinical features to CSV\n",
236
+ " clinical_features_df.to_csv(out_clinical_data_file, index=False)\n",
237
+ " print(f\"Clinical features saved to {out_clinical_data_file}\")\n"
238
+ ]
239
+ },
240
+ {
241
+ "cell_type": "markdown",
242
+ "id": "5bf6c1c6",
243
+ "metadata": {},
244
+ "source": [
245
+ "### Step 3: Gene Data Extraction"
246
+ ]
247
+ },
248
+ {
249
+ "cell_type": "code",
250
+ "execution_count": 4,
251
+ "id": "cdd316a1",
252
+ "metadata": {
253
+ "execution": {
254
+ "iopub.execute_input": "2025-03-25T08:20:56.557235Z",
255
+ "iopub.status.busy": "2025-03-25T08:20:56.557128Z",
256
+ "iopub.status.idle": "2025-03-25T08:20:57.163134Z",
257
+ "shell.execute_reply": "2025-03-25T08:20:57.162448Z"
258
+ }
259
+ },
260
+ "outputs": [
261
+ {
262
+ "name": "stdout",
263
+ "output_type": "stream",
264
+ "text": [
265
+ "Matrix file found: ../../input/GEO/Chronic_obstructive_pulmonary_disease_(COPD)/GSE21359/GSE21359_series_matrix.txt.gz\n"
266
+ ]
267
+ },
268
+ {
269
+ "name": "stdout",
270
+ "output_type": "stream",
271
+ "text": [
272
+ "Gene data shape: (54675, 135)\n",
273
+ "First 20 gene/probe identifiers:\n",
274
+ "Index(['1007_s_at', '1053_at', '117_at', '121_at', '1255_g_at', '1294_at',\n",
275
+ " '1316_at', '1320_at', '1405_i_at', '1431_at', '1438_at', '1487_at',\n",
276
+ " '1494_f_at', '1552256_a_at', '1552257_a_at', '1552258_at', '1552261_at',\n",
277
+ " '1552263_at', '1552264_a_at', '1552266_at'],\n",
278
+ " dtype='object', name='ID')\n"
279
+ ]
280
+ }
281
+ ],
282
+ "source": [
283
+ "# 1. Get the SOFT and matrix file paths again \n",
284
+ "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
285
+ "print(f\"Matrix file found: {matrix_file}\")\n",
286
+ "\n",
287
+ "# 2. Use the get_genetic_data function from the library to get the gene_data\n",
288
+ "try:\n",
289
+ " gene_data = get_genetic_data(matrix_file)\n",
290
+ " print(f\"Gene data shape: {gene_data.shape}\")\n",
291
+ " \n",
292
+ " # 3. Print the first 20 row IDs (gene or probe identifiers)\n",
293
+ " print(\"First 20 gene/probe identifiers:\")\n",
294
+ " print(gene_data.index[:20])\n",
295
+ "except Exception as e:\n",
296
+ " print(f\"Error extracting gene data: {e}\")\n"
297
+ ]
298
+ },
299
+ {
300
+ "cell_type": "markdown",
301
+ "id": "b38bf927",
302
+ "metadata": {},
303
+ "source": [
304
+ "### Step 4: Gene Identifier Review"
305
+ ]
306
+ },
307
+ {
308
+ "cell_type": "code",
309
+ "execution_count": 5,
310
+ "id": "92473627",
311
+ "metadata": {
312
+ "execution": {
313
+ "iopub.execute_input": "2025-03-25T08:20:57.164533Z",
314
+ "iopub.status.busy": "2025-03-25T08:20:57.164406Z",
315
+ "iopub.status.idle": "2025-03-25T08:20:57.166696Z",
316
+ "shell.execute_reply": "2025-03-25T08:20:57.166231Z"
317
+ }
318
+ },
319
+ "outputs": [],
320
+ "source": [
321
+ "# Examining the gene identifiers shows that they are in the format of Affymetrix probe IDs (e.g., 1007_s_at)\n",
322
+ "# rather than standard human gene symbols (like BRCA1, TP53, etc.)\n",
323
+ "# These probe IDs need to be mapped to human gene symbols for biological interpretation\n",
324
+ "\n",
325
+ "requires_gene_mapping = True\n"
326
+ ]
327
+ },
328
+ {
329
+ "cell_type": "markdown",
330
+ "id": "b99398bd",
331
+ "metadata": {},
332
+ "source": [
333
+ "### Step 5: Gene Annotation"
334
+ ]
335
+ },
336
+ {
337
+ "cell_type": "code",
338
+ "execution_count": 6,
339
+ "id": "00c20b68",
340
+ "metadata": {
341
+ "execution": {
342
+ "iopub.execute_input": "2025-03-25T08:20:57.168092Z",
343
+ "iopub.status.busy": "2025-03-25T08:20:57.167985Z",
344
+ "iopub.status.idle": "2025-03-25T08:21:08.269103Z",
345
+ "shell.execute_reply": "2025-03-25T08:21:08.268466Z"
346
+ }
347
+ },
348
+ "outputs": [
349
+ {
350
+ "name": "stdout",
351
+ "output_type": "stream",
352
+ "text": [
353
+ "\n",
354
+ "Gene annotation preview:\n",
355
+ "Columns in gene annotation: ['ID', 'GB_ACC', 'SPOT_ID', 'Species Scientific Name', 'Annotation Date', 'Sequence Type', 'Sequence Source', 'Target Description', 'Representative Public ID', 'Gene Title', 'Gene Symbol', 'ENTREZ_GENE_ID', 'RefSeq Transcript ID', 'Gene Ontology Biological Process', 'Gene Ontology Cellular Component', 'Gene Ontology Molecular Function']\n",
356
+ "{'ID': ['1007_s_at', '1053_at', '117_at', '121_at', '1255_g_at'], 'GB_ACC': ['U48705', 'M87338', 'X51757', 'X69699', 'L36861'], 'SPOT_ID': [nan, nan, nan, nan, nan], 'Species Scientific Name': ['Homo sapiens', 'Homo sapiens', 'Homo sapiens', 'Homo sapiens', 'Homo sapiens'], 'Annotation Date': ['Oct 6, 2014', 'Oct 6, 2014', 'Oct 6, 2014', 'Oct 6, 2014', 'Oct 6, 2014'], 'Sequence Type': ['Exemplar sequence', 'Exemplar sequence', 'Exemplar sequence', 'Exemplar sequence', 'Exemplar sequence'], 'Sequence Source': ['Affymetrix Proprietary Database', 'GenBank', 'Affymetrix Proprietary Database', 'GenBank', 'Affymetrix Proprietary Database'], 'Target Description': ['U48705 /FEATURE=mRNA /DEFINITION=HSU48705 Human receptor tyrosine kinase DDR gene, complete cds', 'M87338 /FEATURE= /DEFINITION=HUMA1SBU Human replication factor C, 40-kDa subunit (A1) mRNA, complete cds', \"X51757 /FEATURE=cds /DEFINITION=HSP70B Human heat-shock protein HSP70B' gene\", 'X69699 /FEATURE= /DEFINITION=HSPAX8A H.sapiens Pax8 mRNA', 'L36861 /FEATURE=expanded_cds /DEFINITION=HUMGCAPB Homo sapiens guanylate cyclase activating protein (GCAP) gene exons 1-4, complete cds'], 'Representative Public ID': ['U48705', 'M87338', 'X51757', 'X69699', 'L36861'], 'Gene Title': ['discoidin domain receptor tyrosine kinase 1 /// microRNA 4640', 'replication factor C (activator 1) 2, 40kDa', \"heat shock 70kDa protein 6 (HSP70B')\", 'paired box 8', 'guanylate cyclase activator 1A (retina)'], 'Gene Symbol': ['DDR1 /// MIR4640', 'RFC2', 'HSPA6', 'PAX8', 'GUCA1A'], 'ENTREZ_GENE_ID': ['780 /// 100616237', '5982', '3310', '7849', '2978'], 'RefSeq Transcript ID': ['NM_001202521 /// NM_001202522 /// NM_001202523 /// NM_001954 /// NM_013993 /// NM_013994 /// NR_039783 /// XM_005249385 /// XM_005249386 /// XM_005249387 /// XM_005249389 /// XM_005272873 /// XM_005272874 /// XM_005272875 /// XM_005272877 /// XM_005275027 /// XM_005275028 /// XM_005275030 /// XM_005275031 /// XM_005275162 /// XM_005275163 /// XM_005275164 /// XM_005275166 /// XM_005275457 /// XM_005275458 /// XM_005275459 /// XM_005275461 /// XM_006715185 /// XM_006715186 /// XM_006715187 /// XM_006715188 /// XM_006715189 /// XM_006715190 /// XM_006725501 /// XM_006725502 /// XM_006725503 /// XM_006725504 /// XM_006725505 /// XM_006725506 /// XM_006725714 /// XM_006725715 /// XM_006725716 /// XM_006725717 /// XM_006725718 /// XM_006725719 /// XM_006725720 /// XM_006725721 /// XM_006725722 /// XM_006725827 /// XM_006725828 /// XM_006725829 /// XM_006725830 /// XM_006725831 /// XM_006725832 /// XM_006726017 /// XM_006726018 /// XM_006726019 /// XM_006726020 /// XM_006726021 /// XM_006726022 /// XR_427836 /// XR_430858 /// XR_430938 /// XR_430974 /// XR_431015', 'NM_001278791 /// NM_001278792 /// NM_001278793 /// NM_002914 /// NM_181471 /// XM_006716080', 'NM_002155', 'NM_003466 /// NM_013951 /// NM_013952 /// NM_013953 /// NM_013992', 'NM_000409 /// XM_006715073'], 'Gene Ontology Biological Process': ['0001558 // regulation of cell growth // inferred from electronic annotation /// 0001952 // regulation of cell-matrix adhesion // inferred from electronic annotation /// 0006468 // protein phosphorylation // inferred from electronic annotation /// 0007155 // cell adhesion // traceable author statement /// 0007169 // transmembrane receptor protein tyrosine kinase signaling pathway // inferred from electronic annotation /// 0007565 // female pregnancy // inferred from electronic annotation /// 0007566 // embryo implantation // inferred from electronic annotation /// 0007595 // lactation // inferred from electronic annotation /// 0008285 // negative regulation of cell proliferation // inferred from electronic annotation /// 0010715 // regulation of extracellular matrix disassembly // inferred from mutant phenotype /// 0014909 // smooth muscle cell migration // inferred from mutant phenotype /// 0016310 // phosphorylation // inferred from electronic annotation /// 0018108 // peptidyl-tyrosine phosphorylation // inferred from electronic annotation /// 0030198 // extracellular matrix organization // traceable author statement /// 0038063 // collagen-activated tyrosine kinase receptor signaling pathway // inferred from direct assay /// 0038063 // collagen-activated tyrosine kinase receptor signaling pathway // inferred from mutant phenotype /// 0038083 // peptidyl-tyrosine autophosphorylation // inferred from direct assay /// 0043583 // ear development // inferred from electronic annotation /// 0044319 // wound healing, spreading of cells // inferred from mutant phenotype /// 0046777 // protein autophosphorylation // inferred from direct assay /// 0060444 // branching involved in mammary gland duct morphogenesis // inferred from electronic annotation /// 0060749 // mammary gland alveolus development // inferred from electronic annotation /// 0061302 // smooth muscle cell-matrix adhesion // inferred from mutant phenotype', '0000278 // mitotic cell cycle // traceable author statement /// 0000722 // telomere maintenance via recombination // traceable author statement /// 0000723 // telomere maintenance // traceable author statement /// 0006260 // DNA replication // traceable author statement /// 0006271 // DNA strand elongation involved in DNA replication // traceable author statement /// 0006281 // DNA repair // traceable author statement /// 0006283 // transcription-coupled nucleotide-excision repair // traceable author statement /// 0006289 // nucleotide-excision repair // traceable author statement /// 0006297 // nucleotide-excision repair, DNA gap filling // traceable author statement /// 0015979 // photosynthesis // inferred from electronic annotation /// 0015995 // chlorophyll biosynthetic process // inferred from electronic annotation /// 0032201 // telomere maintenance via semi-conservative replication // traceable author statement', '0000902 // cell morphogenesis // inferred from electronic annotation /// 0006200 // ATP catabolic process // inferred from direct assay /// 0006950 // response to stress // inferred from electronic annotation /// 0006986 // response to unfolded protein // traceable author statement /// 0034605 // cellular response to heat // inferred from direct assay /// 0042026 // protein refolding // inferred from direct assay /// 0070370 // cellular heat acclimation // inferred from mutant phenotype', '0001655 // urogenital system development // inferred from sequence or structural similarity /// 0001656 // metanephros development // inferred from electronic annotation /// 0001658 // branching involved in ureteric bud morphogenesis // inferred from expression pattern /// 0001822 // kidney development // inferred from expression pattern /// 0001823 // mesonephros development // inferred from sequence or structural similarity /// 0003337 // mesenchymal to epithelial transition involved in metanephros morphogenesis // inferred from expression pattern /// 0006351 // transcription, DNA-templated // inferred from direct assay /// 0006355 // regulation of transcription, DNA-templated // inferred from electronic annotation /// 0007275 // multicellular organismal development // inferred from electronic annotation /// 0007417 // central nervous system development // inferred from expression pattern /// 0009653 // anatomical structure morphogenesis // traceable author statement /// 0030154 // cell differentiation // inferred from electronic annotation /// 0030878 // thyroid gland development // inferred from expression pattern /// 0030878 // thyroid gland development // inferred from mutant phenotype /// 0038194 // thyroid-stimulating hormone signaling pathway // traceable author statement /// 0039003 // pronephric field specification // inferred from sequence or structural similarity /// 0042472 // inner ear morphogenesis // inferred from sequence or structural similarity /// 0042981 // regulation of apoptotic process // inferred from sequence or structural similarity /// 0045893 // positive regulation of transcription, DNA-templated // inferred from direct assay /// 0045893 // positive regulation of transcription, DNA-templated // inferred from sequence or structural similarity /// 0045944 // positive regulation of transcription from RNA polymerase II promoter // inferred from direct assay /// 0048793 // pronephros development // inferred from sequence or structural similarity /// 0071371 // cellular response to gonadotropin stimulus // inferred from direct assay /// 0071599 // otic vesicle development // inferred from expression pattern /// 0072050 // S-shaped body morphogenesis // inferred from electronic annotation /// 0072073 // kidney epithelium development // inferred from electronic annotation /// 0072108 // positive regulation of mesenchymal to epithelial transition involved in metanephros morphogenesis // inferred from sequence or structural similarity /// 0072164 // mesonephric tubule development // inferred from electronic annotation /// 0072207 // metanephric epithelium development // inferred from expression pattern /// 0072221 // metanephric distal convoluted tubule development // inferred from sequence or structural similarity /// 0072278 // metanephric comma-shaped body morphogenesis // inferred from expression pattern /// 0072284 // metanephric S-shaped body morphogenesis // inferred from expression pattern /// 0072289 // metanephric nephron tubule formation // inferred from sequence or structural similarity /// 0072305 // negative regulation of mesenchymal cell apoptotic process involved in metanephric nephron morphogenesis // inferred from sequence or structural similarity /// 0072307 // regulation of metanephric nephron tubule epithelial cell differentiation // inferred from sequence or structural similarity /// 0090190 // positive regulation of branching involved in ureteric bud morphogenesis // inferred from sequence or structural similarity /// 1900212 // negative regulation of mesenchymal cell apoptotic process involved in metanephros development // inferred from sequence or structural similarity /// 1900215 // negative regulation of apoptotic process involved in metanephric collecting duct development // inferred from sequence or structural similarity /// 1900218 // negative regulation of apoptotic process involved in metanephric nephron tubule development // inferred from sequence or structural similarity /// 2000594 // positive regulation of metanephric DCT cell differentiation // inferred from sequence or structural similarity /// 2000611 // positive regulation of thyroid hormone generation // inferred from mutant phenotype /// 2000612 // regulation of thyroid-stimulating hormone secretion // inferred from mutant phenotype', '0007165 // signal transduction // non-traceable author statement /// 0007601 // visual perception // inferred from electronic annotation /// 0007602 // phototransduction // inferred from electronic annotation /// 0007603 // phototransduction, visible light // traceable author statement /// 0016056 // rhodopsin mediated signaling pathway // traceable author statement /// 0022400 // regulation of rhodopsin mediated signaling pathway // traceable author statement /// 0030828 // positive regulation of cGMP biosynthetic process // inferred from electronic annotation /// 0031282 // regulation of guanylate cyclase activity // inferred from electronic annotation /// 0031284 // positive regulation of guanylate cyclase activity // inferred from electronic annotation /// 0050896 // response to stimulus // inferred from electronic annotation'], 'Gene Ontology Cellular Component': ['0005576 // extracellular region // inferred from electronic annotation /// 0005615 // extracellular space // inferred from direct assay /// 0005886 // plasma membrane // traceable author statement /// 0005887 // integral component of plasma membrane // traceable author statement /// 0016020 // membrane // inferred from electronic annotation /// 0016021 // integral component of membrane // inferred from electronic annotation /// 0043235 // receptor complex // inferred from direct assay /// 0070062 // extracellular vesicular exosome // inferred from direct assay', '0005634 // nucleus // inferred from electronic annotation /// 0005654 // nucleoplasm // traceable author statement /// 0005663 // DNA replication factor C complex // inferred from direct assay', '0005737 // cytoplasm // inferred from direct assay /// 0005814 // centriole // inferred from direct assay /// 0005829 // cytosol // inferred from direct assay /// 0008180 // COP9 signalosome // inferred from direct assay /// 0070062 // extracellular vesicular exosome // inferred from direct assay /// 0072562 // blood microparticle // inferred from direct assay', '0005634 // nucleus // inferred from direct assay /// 0005654 // nucleoplasm // inferred from sequence or structural similarity /// 0005730 // nucleolus // inferred from direct assay', '0001750 // photoreceptor outer segment // inferred from electronic annotation /// 0001917 // photoreceptor inner segment // inferred from electronic annotation /// 0005578 // proteinaceous extracellular matrix // inferred from electronic annotation /// 0005886 // plasma membrane // inferred from direct assay /// 0016020 // membrane // inferred from electronic annotation /// 0097381 // photoreceptor disc membrane // traceable author statement'], 'Gene Ontology Molecular Function': ['0000166 // nucleotide binding // inferred from electronic annotation /// 0004672 // protein kinase activity // inferred from electronic annotation /// 0004713 // protein tyrosine kinase activity // inferred from electronic annotation /// 0004714 // transmembrane receptor protein tyrosine kinase activity // traceable author statement /// 0005515 // protein binding // inferred from physical interaction /// 0005518 // collagen binding // inferred from direct assay /// 0005518 // collagen binding // inferred from mutant phenotype /// 0005524 // ATP binding // inferred from electronic annotation /// 0016301 // kinase activity // inferred from electronic annotation /// 0016740 // transferase activity // inferred from electronic annotation /// 0016772 // transferase activity, transferring phosphorus-containing groups // inferred from electronic annotation /// 0038062 // protein tyrosine kinase collagen receptor activity // inferred from direct assay /// 0046872 // metal ion binding // inferred from electronic annotation', '0000166 // nucleotide binding // inferred from electronic annotation /// 0003677 // DNA binding // inferred from electronic annotation /// 0005515 // protein binding // inferred from physical interaction /// 0005524 // ATP binding // inferred from electronic annotation /// 0016851 // magnesium chelatase activity // inferred from electronic annotation /// 0017111 // nucleoside-triphosphatase activity // inferred from electronic annotation', '0000166 // nucleotide binding // inferred from electronic annotation /// 0005524 // ATP binding // inferred from electronic annotation /// 0019899 // enzyme binding // inferred from physical interaction /// 0031072 // heat shock protein binding // inferred from physical interaction /// 0042623 // ATPase activity, coupled // inferred from direct assay /// 0051082 // unfolded protein binding // inferred from direct assay', '0000979 // RNA polymerase II core promoter sequence-specific DNA binding // inferred from direct assay /// 0003677 // DNA binding // inferred from direct assay /// 0003677 // DNA binding // inferred from mutant phenotype /// 0003700 // sequence-specific DNA binding transcription factor activity // inferred from direct assay /// 0004996 // thyroid-stimulating hormone receptor activity // traceable author statement /// 0005515 // protein binding // inferred from physical interaction /// 0044212 // transcription regulatory region DNA binding // inferred from direct assay', '0005509 // calcium ion binding // inferred from electronic annotation /// 0008048 // calcium sensitive guanylate cyclase activator activity // inferred from electronic annotation /// 0030249 // guanylate cyclase regulator activity // inferred from electronic annotation /// 0046872 // metal ion binding // inferred from electronic annotation']}\n",
357
+ "\n",
358
+ "Searching for platform information in SOFT file:\n",
359
+ "Platform ID not found in first 100 lines\n",
360
+ "\n",
361
+ "Searching for gene symbol information in SOFT file:\n",
362
+ "Found references to gene symbols:\n",
363
+ "!Platform_relation = Alternative to: GPL19918 (Gene symbol version, 10K)\n",
364
+ "!Platform_relation = Alternative to: GPL20182 (Gene Symbol Version)\n",
365
+ "#Gene Symbol = A gene symbol, when one is available (from UniGene).\n",
366
+ "ID\tGB_ACC\tSPOT_ID\tSpecies Scientific Name\tAnnotation Date\tSequence Type\tSequence Source\tTarget Description\tRepresentative Public ID\tGene Title\tGene Symbol\tENTREZ_GENE_ID\tRefSeq Transcript ID\tGene Ontology Biological Process\tGene Ontology Cellular Component\tGene Ontology Molecular Function\n",
367
+ "\n",
368
+ "Checking for additional annotation files in the directory:\n",
369
+ "[]\n"
370
+ ]
371
+ }
372
+ ],
373
+ "source": [
374
+ "# 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.\n",
375
+ "gene_annotation = get_gene_annotation(soft_file)\n",
376
+ "\n",
377
+ "# 2. Analyze the gene annotation dataframe to identify which columns contain the gene identifiers and gene symbols\n",
378
+ "print(\"\\nGene annotation preview:\")\n",
379
+ "print(f\"Columns in gene annotation: {gene_annotation.columns.tolist()}\")\n",
380
+ "print(preview_df(gene_annotation, n=5))\n",
381
+ "\n",
382
+ "# Let's look for platform information in the SOFT file to understand the annotation better\n",
383
+ "print(\"\\nSearching for platform information in SOFT file:\")\n",
384
+ "with gzip.open(soft_file, 'rt') as f:\n",
385
+ " for i, line in enumerate(f):\n",
386
+ " if '!Series_platform_id' in line:\n",
387
+ " print(line.strip())\n",
388
+ " break\n",
389
+ " if i > 100: # Limit search to first 100 lines\n",
390
+ " print(\"Platform ID not found in first 100 lines\")\n",
391
+ " break\n",
392
+ "\n",
393
+ "# Check if the SOFT file includes any reference to gene symbols\n",
394
+ "print(\"\\nSearching for gene symbol information in SOFT file:\")\n",
395
+ "with gzip.open(soft_file, 'rt') as f:\n",
396
+ " gene_symbol_lines = []\n",
397
+ " for i, line in enumerate(f):\n",
398
+ " if 'GENE_SYMBOL' in line or 'gene_symbol' in line.lower() or 'symbol' in line.lower():\n",
399
+ " gene_symbol_lines.append(line.strip())\n",
400
+ " if i > 1000 and len(gene_symbol_lines) > 0: # Limit search but ensure we found something\n",
401
+ " break\n",
402
+ " \n",
403
+ " if gene_symbol_lines:\n",
404
+ " print(\"Found references to gene symbols:\")\n",
405
+ " for line in gene_symbol_lines[:5]: # Show just first 5 matches\n",
406
+ " print(line)\n",
407
+ " else:\n",
408
+ " print(\"No explicit gene symbol references found in first 1000 lines\")\n",
409
+ "\n",
410
+ "# Look for alternative annotation files or references in the directory\n",
411
+ "print(\"\\nChecking for additional annotation files in the directory:\")\n",
412
+ "all_files = os.listdir(in_cohort_dir)\n",
413
+ "print([f for f in all_files if 'annotation' in f.lower() or 'platform' in f.lower() or 'gpl' in f.lower()])\n"
414
+ ]
415
+ },
416
+ {
417
+ "cell_type": "markdown",
418
+ "id": "48b0e844",
419
+ "metadata": {},
420
+ "source": [
421
+ "### Step 6: Gene Identifier Mapping"
422
+ ]
423
+ },
424
+ {
425
+ "cell_type": "code",
426
+ "execution_count": 7,
427
+ "id": "19d4593a",
428
+ "metadata": {
429
+ "execution": {
430
+ "iopub.execute_input": "2025-03-25T08:21:08.270422Z",
431
+ "iopub.status.busy": "2025-03-25T08:21:08.270292Z",
432
+ "iopub.status.idle": "2025-03-25T08:21:10.343563Z",
433
+ "shell.execute_reply": "2025-03-25T08:21:10.342897Z"
434
+ }
435
+ },
436
+ "outputs": [
437
+ {
438
+ "name": "stdout",
439
+ "output_type": "stream",
440
+ "text": [
441
+ "Mapping dataframe shape: (45782, 2)\n",
442
+ "Mapping sample:\n",
443
+ " ID Gene\n",
444
+ "0 1007_s_at DDR1 /// MIR4640\n",
445
+ "1 1053_at RFC2\n",
446
+ "2 117_at HSPA6\n",
447
+ "3 121_at PAX8\n",
448
+ "4 1255_g_at GUCA1A\n"
449
+ ]
450
+ },
451
+ {
452
+ "name": "stdout",
453
+ "output_type": "stream",
454
+ "text": [
455
+ "Gene expression data shape after mapping: (21278, 135)\n",
456
+ "First few rows of gene expression data:\n",
457
+ " GSM101095 GSM101096 GSM101097 GSM101098 GSM101100 \\\n",
458
+ "Gene \n",
459
+ "A1BG 26.664608 23.200108 23.611168 20.731066 22.466328 \n",
460
+ "A1BG-AS1 38.430410 37.644897 27.018625 25.424614 33.169040 \n",
461
+ "A1CF 32.887757 27.871269 27.148127 24.667728 23.662186 \n",
462
+ "A2M 305.641970 1104.150857 162.984248 257.923840 254.933860 \n",
463
+ "A2M-AS1 20.335550 27.066956 28.000036 32.134990 39.643590 \n",
464
+ "\n",
465
+ " GSM101101 GSM101102 GSM101103 GSM101104 GSM101105 ... \\\n",
466
+ "Gene ... \n",
467
+ "A1BG 25.030586 25.183960 22.589863 23.743465 27.456318 ... \n",
468
+ "A1BG-AS1 26.234987 23.183222 24.775188 20.421490 25.106298 ... \n",
469
+ "A1CF 27.690921 32.027879 26.455109 29.115901 29.179587 ... \n",
470
+ "A2M 162.423000 205.575187 184.443614 171.407947 88.020766 ... \n",
471
+ "A2M-AS1 47.090164 40.219450 32.511940 27.311834 26.748950 ... \n",
472
+ "\n",
473
+ " GSM434061 GSM434062 GSM434063 GSM434064 GSM458579 GSM458580 \\\n",
474
+ "Gene \n",
475
+ "A1BG 36.4369 86.7034 69.8861 116.91500 55.5067 90.07020 \n",
476
+ "A1BG-AS1 11.9127 89.5264 67.4591 28.44960 17.9411 9.96002 \n",
477
+ "A1CF 152.4898 76.8428 153.6378 46.09965 137.8570 169.70480 \n",
478
+ "A2M 405.1700 504.6519 817.4321 862.06154 1040.7970 295.14000 \n",
479
+ "A2M-AS1 313.0060 215.3160 251.0310 201.64300 205.5960 180.92900 \n",
480
+ "\n",
481
+ " GSM458581 GSM458582 GSM469991 GSM470000 \n",
482
+ "Gene \n",
483
+ "A1BG 53.5092 83.99710 130.17200 72.42720 \n",
484
+ "A1BG-AS1 84.5107 48.65930 29.05250 248.15300 \n",
485
+ "A1CF 41.3142 154.99446 126.77519 113.47501 \n",
486
+ "A2M 1105.5896 271.15290 2166.79520 1080.31820 \n",
487
+ "A2M-AS1 221.6670 204.65500 291.91100 277.13000 \n",
488
+ "\n",
489
+ "[5 rows x 135 columns]\n",
490
+ "Gene expression data shape after normalization: (19845, 135)\n",
491
+ "First few genes after normalization:\n",
492
+ "Index(['A1BG', 'A1BG-AS1', 'A1CF', 'A2M', 'A2M-AS1', 'A2ML1', 'A2MP1',\n",
493
+ " 'A4GALT', 'A4GNT', 'AA06'],\n",
494
+ " dtype='object', name='Gene')\n"
495
+ ]
496
+ },
497
+ {
498
+ "name": "stdout",
499
+ "output_type": "stream",
500
+ "text": [
501
+ "Gene expression data saved to ../../output/preprocess/Chronic_obstructive_pulmonary_disease_(COPD)/gene_data/GSE21359.csv\n"
502
+ ]
503
+ }
504
+ ],
505
+ "source": [
506
+ "# 1. Identify the correct columns for mapping\n",
507
+ "prob_col = \"ID\" # This is the column containing probe IDs in the gene annotation\n",
508
+ "gene_col = \"Gene Symbol\" # This is the column containing gene symbols\n",
509
+ "\n",
510
+ "# 2. Get the gene mapping dataframe \n",
511
+ "mapping_df = get_gene_mapping(gene_annotation, prob_col, gene_col)\n",
512
+ "print(f\"Mapping dataframe shape: {mapping_df.shape}\")\n",
513
+ "print(\"Mapping sample:\")\n",
514
+ "print(mapping_df.head())\n",
515
+ "\n",
516
+ "# 3. Convert probe-level measurements to gene expression data\n",
517
+ "gene_data = apply_gene_mapping(gene_data, mapping_df)\n",
518
+ "print(f\"Gene expression data shape after mapping: {gene_data.shape}\")\n",
519
+ "print(\"First few rows of gene expression data:\")\n",
520
+ "print(gene_data.head())\n",
521
+ "\n",
522
+ "# Let's normalize the gene symbols in the index\n",
523
+ "gene_data = normalize_gene_symbols_in_index(gene_data)\n",
524
+ "print(f\"Gene expression data shape after normalization: {gene_data.shape}\")\n",
525
+ "print(\"First few genes after normalization:\")\n",
526
+ "print(gene_data.index[:10])\n",
527
+ "\n",
528
+ "# Create directory if it doesn't exist\n",
529
+ "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
530
+ "\n",
531
+ "# Save the gene expression data\n",
532
+ "gene_data.to_csv(out_gene_data_file)\n",
533
+ "print(f\"Gene expression data saved to {out_gene_data_file}\")\n"
534
+ ]
535
+ },
536
+ {
537
+ "cell_type": "markdown",
538
+ "id": "91a6276c",
539
+ "metadata": {},
540
+ "source": [
541
+ "### Step 7: Data Normalization and Linking"
542
+ ]
543
+ },
544
+ {
545
+ "cell_type": "code",
546
+ "execution_count": 8,
547
+ "id": "9e333f42",
548
+ "metadata": {
549
+ "execution": {
550
+ "iopub.execute_input": "2025-03-25T08:21:10.345103Z",
551
+ "iopub.status.busy": "2025-03-25T08:21:10.344967Z",
552
+ "iopub.status.idle": "2025-03-25T08:21:26.235333Z",
553
+ "shell.execute_reply": "2025-03-25T08:21:26.234691Z"
554
+ }
555
+ },
556
+ "outputs": [
557
+ {
558
+ "name": "stdout",
559
+ "output_type": "stream",
560
+ "text": [
561
+ "Normalized gene data shape: (19845, 135)\n",
562
+ "Gene data column names (sample IDs):\n",
563
+ "Index(['GSM101095', 'GSM101096', 'GSM101097', 'GSM101098', 'GSM101100'], dtype='object')\n"
564
+ ]
565
+ },
566
+ {
567
+ "name": "stdout",
568
+ "output_type": "stream",
569
+ "text": [
570
+ "\n",
571
+ "Raw clinical data structure:\n",
572
+ "Clinical data shape: (4, 136)\n",
573
+ "Clinical data columns: Index(['!Sample_geo_accession', 'GSM101095', 'GSM101096', 'GSM101097',\n",
574
+ " 'GSM101098'],\n",
575
+ " dtype='object')\n",
576
+ "\n",
577
+ "Sample characteristics dictionary:\n",
578
+ "{0: ['Age: 41', 'age: 35', 'age: 61', 'age: 37', 'age: 47', 'age: 38', 'age: 49', 'age: 45', 'age: 36', 'age: 46', 'age: 48', 'age: 50', 'age: 56', 'age: 59', 'age: 34', 'age: 44', 'Age: 45', 'age: 29', 'age: 42', 'Age: 47', 'age: 55', 'age: 51', 'age: 60', 'age: 52', 'age: 40', 'age: 41', 'age: 43', 'age: 31', 'age: 53', 'age: 62'], 1: ['Sex: M', 'sex: M', 'sex: F', 'Sex: F'], 2: ['Ethnic group: black', 'ethnic group: black', 'ethnic group: white', 'ethnic group: hispanic', 'Ethnic group: white', 'ethnic group: black/hispanic', 'ethnic group: asian'], 3: ['Smoking Status: non-smoker', 'smoking status: non-smoker', 'smoking status: smoker, 21 pack-years', 'smoking status: smoker, 23 pack-years', 'smoking status: smoker, 28 pack-years', 'smoking status: smoker, 20 pack-years', 'smoking status: smoker, 38 pack-years', 'smoking status: smoker, 80 pack-years', 'smoking status: smoker, 60 pack-years', 'Smoking status: non-smoker', 'smoking status: COPD, GOLD-I, 50 pack-years', 'Smoking status: COPD, GOLD-II, 33 pack-years', 'smoking status: COPD, GOLD-II, 35 pack-years', 'smoking status: COPD, GOLD-II, 20 pack-years', 'smoking status: COPD, GOLD-I, 48 pack-years', 'smoking status: COPD, GOLD-II, 75 pack-years', 'smoking status: COPD, GOLD-II, 27 pack-years', 'smoking status: COPD, GOLD-II, 60 pack-years', 'smoking status: COPD, GOLD-III, 110 pack-years', 'smoking status: COPD, GOLD-I, 22 pack-years', 'smoking status: COPD, GOLD-I, 23 pack-years', 'smoking status: smoker, 24 pack-years', 'smoking status: smoker, 29 pack-years', 'smoking status: smoker, 45 pack-years', 'smoking status: smoker, 32 pack-years', 'smoking status: smoker, 36 pack-years', 'smoking status: smoker, 15 pack-years', 'smoking status: smoker, 22 pack-years', 'smoking status: smoker, 33 pack-years', 'smoking status: smoker, 16 pack-years']}\n",
579
+ "\n",
580
+ "Values in trait row:\n",
581
+ "['!Sample_characteristics_ch1' 'Smoking Status: non-smoker'\n",
582
+ " 'smoking status: non-smoker' 'smoking status: non-smoker'\n",
583
+ " 'smoking status: non-smoker']\n",
584
+ "\n",
585
+ "Created clinical features dataframe:\n",
586
+ "Shape: (1, 135)\n",
587
+ " GSM101095 GSM101096 GSM101097 \\\n",
588
+ "Chronic_obstructive_pulmonary_disease_(COPD) 0 0 0 \n",
589
+ "\n",
590
+ " GSM101098 GSM101100 \n",
591
+ "Chronic_obstructive_pulmonary_disease_(COPD) 0 0 \n",
592
+ "\n",
593
+ "Linked data shape before handling missing values: (135, 19846)\n",
594
+ "Actual trait column in linked data: Chronic_obstructive_pulmonary_disease_(COPD)\n"
595
+ ]
596
+ },
597
+ {
598
+ "name": "stderr",
599
+ "output_type": "stream",
600
+ "text": [
601
+ "/media/techt/DATA/GenoAgent/tools/preprocess.py:455: FutureWarning: Downcasting object dtype arrays on .fillna, .ffill, .bfill is deprecated and will change in a future version. Call result.infer_objects(copy=False) instead. To opt-in to the future behavior, set `pd.set_option('future.no_silent_downcasting', True)`\n",
602
+ " df[gene_cols] = df[gene_cols].fillna(df[gene_cols].mean())\n"
603
+ ]
604
+ },
605
+ {
606
+ "name": "stdout",
607
+ "output_type": "stream",
608
+ "text": [
609
+ "Linked data shape after handling missing values: (135, 19846)\n",
610
+ "For the feature 'Chronic_obstructive_pulmonary_disease_(COPD)', the least common label is '1' with 23 occurrences. This represents 17.04% of the dataset.\n",
611
+ "The distribution of the feature 'Chronic_obstructive_pulmonary_disease_(COPD)' in this dataset is fine.\n",
612
+ "\n"
613
+ ]
614
+ },
615
+ {
616
+ "name": "stdout",
617
+ "output_type": "stream",
618
+ "text": [
619
+ "Linked data saved to ../../output/preprocess/Chronic_obstructive_pulmonary_disease_(COPD)/GSE21359.csv\n"
620
+ ]
621
+ }
622
+ ],
623
+ "source": [
624
+ "# 1. Normalize gene symbols in the gene expression data \n",
625
+ "# (This was already done in the previous step, so no need to repeat)\n",
626
+ "print(f\"Normalized gene data shape: {gene_data.shape}\")\n",
627
+ "\n",
628
+ "# 2. Examine the sample IDs in the gene expression data to understand the structure\n",
629
+ "print(\"Gene data column names (sample IDs):\")\n",
630
+ "print(gene_data.columns[:5]) # Print first 5 for brevity\n",
631
+ "\n",
632
+ "# Inspect the clinical data format from the matrix file directly\n",
633
+ "background_info, clinical_data = get_background_and_clinical_data(matrix_file)\n",
634
+ "print(\"\\nRaw clinical data structure:\")\n",
635
+ "print(f\"Clinical data shape: {clinical_data.shape}\")\n",
636
+ "print(f\"Clinical data columns: {clinical_data.columns[:5]}\")\n",
637
+ "\n",
638
+ "# Get the sample characteristics to re-extract the disease information\n",
639
+ "sample_characteristics_dict = get_unique_values_by_row(clinical_data)\n",
640
+ "print(\"\\nSample characteristics dictionary:\")\n",
641
+ "print(sample_characteristics_dict)\n",
642
+ "\n",
643
+ "# 3. Directly create clinical features from the raw data again\n",
644
+ "# Verify trait row contains the disease information (OA vs RA)\n",
645
+ "print(\"\\nValues in trait row:\")\n",
646
+ "trait_values = clinical_data.iloc[trait_row].values\n",
647
+ "print(trait_values[:5])\n",
648
+ "\n",
649
+ "# Create clinical dataframe with proper structure\n",
650
+ "# First get the sample IDs from gene data as these are our actual sample identifiers\n",
651
+ "sample_ids = gene_data.columns.tolist()\n",
652
+ "\n",
653
+ "# Create the clinical features dataframe with those sample IDs\n",
654
+ "clinical_features = pd.DataFrame(index=[trait], columns=sample_ids)\n",
655
+ "\n",
656
+ "# Fill the clinical features with our trait values by mapping GSM IDs to actual values\n",
657
+ "for col in clinical_data.columns:\n",
658
+ " if col in sample_ids:\n",
659
+ " # Extract the disease value and convert it\n",
660
+ " disease_val = clinical_data.iloc[trait_row][col]\n",
661
+ " clinical_features.loc[trait, col] = convert_trait(disease_val)\n",
662
+ "\n",
663
+ "print(\"\\nCreated clinical features dataframe:\")\n",
664
+ "print(f\"Shape: {clinical_features.shape}\")\n",
665
+ "print(clinical_features.iloc[:, :5]) # Show first 5 columns\n",
666
+ "\n",
667
+ "# 4. Link clinical and genetic data\n",
668
+ "linked_data = geo_link_clinical_genetic_data(clinical_features, gene_data)\n",
669
+ "print(f\"\\nLinked data shape before handling missing values: {linked_data.shape}\")\n",
670
+ "\n",
671
+ "# 5. Handle missing values - we need to use the actual column name, not the trait variable\n",
672
+ "# First identify the actual trait column name in the linked data\n",
673
+ "trait_column = clinical_features.index[0] # This should be 'Osteoarthritis'\n",
674
+ "print(f\"Actual trait column in linked data: {trait_column}\")\n",
675
+ "\n",
676
+ "# Now handle missing values with the correct column name\n",
677
+ "linked_data_clean = handle_missing_values(linked_data, trait_column)\n",
678
+ "print(f\"Linked data shape after handling missing values: {linked_data_clean.shape}\")\n",
679
+ "\n",
680
+ "# 6. Evaluate bias in trait and demographic features\n",
681
+ "is_biased, linked_data_clean = judge_and_remove_biased_features(linked_data_clean, trait_column)\n",
682
+ "\n",
683
+ "# 7. Conduct final quality validation\n",
684
+ "note = \"Dataset contains gene expression data from synovial fibroblasts of RA and OA patients. Data includes high serum and low serum responses.\"\n",
685
+ "is_usable = validate_and_save_cohort_info(\n",
686
+ " is_final=True,\n",
687
+ " cohort=cohort,\n",
688
+ " info_path=json_path,\n",
689
+ " is_gene_available=True,\n",
690
+ " is_trait_available=(linked_data_clean.shape[0] > 0),\n",
691
+ " is_biased=is_biased,\n",
692
+ " df=linked_data_clean,\n",
693
+ " note=note\n",
694
+ ")\n",
695
+ "\n",
696
+ "# 8. Save linked data if usable\n",
697
+ "if is_usable:\n",
698
+ " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n",
699
+ " linked_data_clean.to_csv(out_data_file)\n",
700
+ " print(f\"Linked data saved to {out_data_file}\")\n",
701
+ "else:\n",
702
+ " print(\"Dataset deemed not usable due to quality issues - linked data not saved\")"
703
+ ]
704
+ }
705
+ ],
706
+ "metadata": {
707
+ "language_info": {
708
+ "codemirror_mode": {
709
+ "name": "ipython",
710
+ "version": 3
711
+ },
712
+ "file_extension": ".py",
713
+ "mimetype": "text/x-python",
714
+ "name": "python",
715
+ "nbconvert_exporter": "python",
716
+ "pygments_lexer": "ipython3",
717
+ "version": "3.10.16"
718
+ }
719
+ },
720
+ "nbformat": 4,
721
+ "nbformat_minor": 5
722
+ }
code/Chronic_obstructive_pulmonary_disease_(COPD)/GSE32030.ipynb ADDED
@@ -0,0 +1,664 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": 1,
6
+ "id": "5d2dfeea",
7
+ "metadata": {
8
+ "execution": {
9
+ "iopub.execute_input": "2025-03-25T08:21:27.291310Z",
10
+ "iopub.status.busy": "2025-03-25T08:21:27.291087Z",
11
+ "iopub.status.idle": "2025-03-25T08:21:27.452798Z",
12
+ "shell.execute_reply": "2025-03-25T08:21:27.452483Z"
13
+ }
14
+ },
15
+ "outputs": [],
16
+ "source": [
17
+ "import sys\n",
18
+ "import os\n",
19
+ "sys.path.append(os.path.abspath(os.path.join(os.getcwd(), '../..')))\n",
20
+ "\n",
21
+ "# Path Configuration\n",
22
+ "from tools.preprocess import *\n",
23
+ "\n",
24
+ "# Processing context\n",
25
+ "trait = \"Chronic_obstructive_pulmonary_disease_(COPD)\"\n",
26
+ "cohort = \"GSE32030\"\n",
27
+ "\n",
28
+ "# Input paths\n",
29
+ "in_trait_dir = \"../../input/GEO/Chronic_obstructive_pulmonary_disease_(COPD)\"\n",
30
+ "in_cohort_dir = \"../../input/GEO/Chronic_obstructive_pulmonary_disease_(COPD)/GSE32030\"\n",
31
+ "\n",
32
+ "# Output paths\n",
33
+ "out_data_file = \"../../output/preprocess/Chronic_obstructive_pulmonary_disease_(COPD)/GSE32030.csv\"\n",
34
+ "out_gene_data_file = \"../../output/preprocess/Chronic_obstructive_pulmonary_disease_(COPD)/gene_data/GSE32030.csv\"\n",
35
+ "out_clinical_data_file = \"../../output/preprocess/Chronic_obstructive_pulmonary_disease_(COPD)/clinical_data/GSE32030.csv\"\n",
36
+ "json_path = \"../../output/preprocess/Chronic_obstructive_pulmonary_disease_(COPD)/cohort_info.json\"\n"
37
+ ]
38
+ },
39
+ {
40
+ "cell_type": "markdown",
41
+ "id": "937ad1fa",
42
+ "metadata": {},
43
+ "source": [
44
+ "### Step 1: Initial Data Loading"
45
+ ]
46
+ },
47
+ {
48
+ "cell_type": "code",
49
+ "execution_count": 2,
50
+ "id": "fddbb499",
51
+ "metadata": {
52
+ "execution": {
53
+ "iopub.execute_input": "2025-03-25T08:21:27.454220Z",
54
+ "iopub.status.busy": "2025-03-25T08:21:27.454080Z",
55
+ "iopub.status.idle": "2025-03-25T08:21:27.844263Z",
56
+ "shell.execute_reply": "2025-03-25T08:21:27.843932Z"
57
+ }
58
+ },
59
+ "outputs": [
60
+ {
61
+ "name": "stdout",
62
+ "output_type": "stream",
63
+ "text": [
64
+ "Background Information:\n",
65
+ "!Series_title\t\"Empirical Bayes Conditional Independence Graphs for Dense Regulatory Network Recovery\"\n",
66
+ "!Series_summary\t\"Motivation: Computational inference methods that make use of graphical models to extract regulatory networks from gene expression data can have difficulty reconstructing dense regions of a network, a consequence of both computational complexity and unreliable parameter estimation when sample size is small. As a result, identification of hub genes is of special difficulty for these methods.Methods: We present a new algorithm, Empirical Light Mutual Min (ELMM), for large network reconstruction that has properties well suited for dense graph recovery. ELMM reconstructs the undirected graph of a regulatory network using empirical Bayes conditional independence testing with a heuristic relaxation of independence constraints in dense areas of the graph. This relaxation allows only one gene of a pair with a putative relation to be aware of the network connection, an approach that is aimed at easing multiple testing problems associated with recovering densely connected structures.Results: Using in silico data, we show that ELMM has better performance than commonly used network inference algorithms including PC Algorithm, GeneNet, and ARACNE. We also apply ELMM to reconstruct a network among 5,400 genes expressed in human lung airway epithelium of healthy nonsmokers, healthy smokers, and smokers with pulmonary diseases assayed using microarrays. The analysis identifies dense subnetworks that are consistent with known regulatory relationships in the lung airway and also suggests novel hub regulatory relationships among a number of genes that play roles in oxidative stress, wound response, and secretion.\"\n",
67
+ "!Series_overall_design\t\"We present a new approach to extracting regulatory networks from gene expression data. The algorithm is applied to reconstruct the gene regulatory network in human lung airway epithelium using microarray data extracted from healthy nonsmokers and smokers and smokers with pulmonary diseases.\"\n",
68
+ "Sample Characteristics Dictionary:\n",
69
+ "{0: ['department of genetic medicine id: DGM-00028', 'ethnicity: Afr', 'department of genetic medicine id: DGM-00060', 'department of genetic medicine id: DGM-00061', 'department of genetic medicine id: DGM-00104', 'department of genetic medicine id: DGM-10131', 'department of genetic medicine id: DGM-00167', 'department of genetic medicine id: DGM-00171', 'department of genetic medicine id: DGM-00262', 'department of genetic medicine id: DGM-00313', 'department of genetic medicine id: DGM-10287', 'department of genetic medicine id: DGM-00382', 'department of genetic medicine id: DGM-10139', 'department of genetic medicine id: DGM-00471', 'department of genetic medicine id: DGM-00512', 'department of genetic medicine id: DGM-02088', 'department of genetic medicine id: DGM-10152', 'department of genetic medicine id: DGM-00632', 'department of genetic medicine id: DGM-00683', 'department of genetic medicine id: DGM-10404', 'department of genetic medicine id: DGM-00791', 'department of genetic medicine id: DGM-10132', 'department of genetic medicine id: DGM-10135', 'department of genetic medicine id: DGM-01275', 'department of genetic medicine id: DGM-10144', 'department of genetic medicine id: DGM-10130', 'department of genetic medicine id: DGM-10406', 'department of genetic medicine id: DGM-01607', 'department of genetic medicine id: DGM-01737', 'department of genetic medicine id: DGM-01749'], 1: ['smoking status: S', 'department of genetic medicine id: DGM-00038', 'department of genetic medicine id: DGM-00029', 'department of genetic medicine id: DGM-00030', 'department of genetic medicine id: DGM-00035', 'department of genetic medicine id: DGM-00036', 'department of genetic medicine id: DGM-00041', 'department of genetic medicine id: DGM-00044', 'department of genetic medicine id: DGM-00052', 'department of genetic medicine id: DGM-00073', 'department of genetic medicine id: DGM-00069', 'department of genetic medicine id: DGM-00072', 'department of genetic medicine id: DGM-00078', 'smoking status: NS', 'department of genetic medicine id: DGM-00123', 'department of genetic medicine id: DGM-00244', 'department of genetic medicine id: DGM-00249', 'department of genetic medicine id: DGM-00416', 'department of genetic medicine id: DGM-00465', 'department of genetic medicine id: DGM-00530', 'department of genetic medicine id: DGM-00548', 'department of genetic medicine id: DGM-00551', 'department of genetic medicine id: DGM-00553', 'department of genetic medicine id: DGM-00625', 'department of genetic medicine id: DGM-00661', 'department of genetic medicine id: DGM-00685', 'department of genetic medicine id: DGM-00696', 'department of genetic medicine id: DGM-00757', 'department of genetic medicine id: DGM-00751', 'department of genetic medicine id: DGM-00778'], 2: ['copd status: yes', 'smoking status: S', 'smoking status: NS', nan, 'serum 25-oh-d: low vitamin D', 'serum 25-oh-d: mid vitamin D', 'serum 25-oh-d: high vitamin D', 'cell type: mixture of epithelium, basal, ciliated, secretory, undifferentiated and inflammatory cells'], 3: [nan, 'copd status: yes', 'serum 25-oh-d: mid vitamin D', 'serum 25-oh-d: high vitamin D', 'serum 25-oh-d: low vitamin D', 'time: n/a']}\n"
70
+ ]
71
+ }
72
+ ],
73
+ "source": [
74
+ "from tools.preprocess import *\n",
75
+ "# 1. Identify the paths to the SOFT file and the matrix file\n",
76
+ "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
77
+ "\n",
78
+ "# 2. Read the matrix file to obtain background information and sample characteristics data\n",
79
+ "background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']\n",
80
+ "clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']\n",
81
+ "background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)\n",
82
+ "\n",
83
+ "# 3. Obtain the sample characteristics dictionary from the clinical dataframe\n",
84
+ "sample_characteristics_dict = get_unique_values_by_row(clinical_data)\n",
85
+ "\n",
86
+ "# 4. Explicitly print out all the background information and the sample characteristics dictionary\n",
87
+ "print(\"Background Information:\")\n",
88
+ "print(background_info)\n",
89
+ "print(\"Sample Characteristics Dictionary:\")\n",
90
+ "print(sample_characteristics_dict)\n"
91
+ ]
92
+ },
93
+ {
94
+ "cell_type": "markdown",
95
+ "id": "75abe0a5",
96
+ "metadata": {},
97
+ "source": [
98
+ "### Step 2: Dataset Analysis and Clinical Feature Extraction"
99
+ ]
100
+ },
101
+ {
102
+ "cell_type": "code",
103
+ "execution_count": 3,
104
+ "id": "fa407627",
105
+ "metadata": {
106
+ "execution": {
107
+ "iopub.execute_input": "2025-03-25T08:21:27.845595Z",
108
+ "iopub.status.busy": "2025-03-25T08:21:27.845488Z",
109
+ "iopub.status.idle": "2025-03-25T08:21:27.854118Z",
110
+ "shell.execute_reply": "2025-03-25T08:21:27.853859Z"
111
+ }
112
+ },
113
+ "outputs": [
114
+ {
115
+ "name": "stdout",
116
+ "output_type": "stream",
117
+ "text": [
118
+ "Preview of selected clinical features:\n",
119
+ "{0: [1.0], 1: [nan], 2: [nan], 3: [nan], 4: [nan], 5: [nan], 6: [nan], 7: [nan], 8: [nan], 9: [nan], 10: [nan], 11: [nan], 12: [nan], 13: [nan], 14: [nan], 15: [nan], 16: [nan], 17: [nan], 18: [nan], 19: [nan], 20: [nan], 21: [nan], 22: [nan], 23: [nan], 24: [nan], 25: [nan], 26: [nan], 27: [nan], 28: [nan], 29: [nan]}\n",
120
+ "Clinical data saved to ../../output/preprocess/Chronic_obstructive_pulmonary_disease_(COPD)/clinical_data/GSE32030.csv\n"
121
+ ]
122
+ }
123
+ ],
124
+ "source": [
125
+ "import pandas as pd\n",
126
+ "import numpy as np\n",
127
+ "import os\n",
128
+ "import re\n",
129
+ "from typing import Dict, Any, Optional, Callable\n",
130
+ "\n",
131
+ "# 1. Determine gene expression data availability\n",
132
+ "# Based on the background information, this dataset contains microarray data for gene expression\n",
133
+ "is_gene_available = True\n",
134
+ "\n",
135
+ "# 2. Variable Availability and Data Type Conversion\n",
136
+ "# 2.1 Data Availability\n",
137
+ "# For trait (COPD status), it appears to be in row 2\n",
138
+ "trait_row = 2\n",
139
+ "\n",
140
+ "# Age data doesn't appear to be available in the sample characteristics\n",
141
+ "age_row = None\n",
142
+ "\n",
143
+ "# Gender data doesn't appear to be available in the sample characteristics\n",
144
+ "gender_row = None\n",
145
+ "\n",
146
+ "# 2.2 Data Type Conversion\n",
147
+ "def convert_trait(value):\n",
148
+ " if pd.isna(value):\n",
149
+ " return None\n",
150
+ " \n",
151
+ " # Extract the value after colon\n",
152
+ " if \":\" in value:\n",
153
+ " value = value.split(\":\", 1)[1].strip().lower()\n",
154
+ " \n",
155
+ " # Check for COPD status\n",
156
+ " if \"yes\" in value:\n",
157
+ " return 1\n",
158
+ " elif \"no\" in value:\n",
159
+ " return 0\n",
160
+ " return None\n",
161
+ "\n",
162
+ "def convert_age(value):\n",
163
+ " # This function isn't needed since age data isn't available\n",
164
+ " return None\n",
165
+ "\n",
166
+ "def convert_gender(value):\n",
167
+ " # This function isn't needed since gender data isn't available\n",
168
+ " return None\n",
169
+ "\n",
170
+ "# 3. Save Metadata\n",
171
+ "# Check if trait data is available (trait_row is not None)\n",
172
+ "is_trait_available = trait_row is not None\n",
173
+ "\n",
174
+ "# Validate and save initial cohort info\n",
175
+ "validate_and_save_cohort_info(\n",
176
+ " is_final=False,\n",
177
+ " cohort=cohort,\n",
178
+ " info_path=json_path,\n",
179
+ " is_gene_available=is_gene_available,\n",
180
+ " is_trait_available=is_trait_available\n",
181
+ ")\n",
182
+ "\n",
183
+ "# 4. Clinical Feature Extraction\n",
184
+ "if trait_row is not None:\n",
185
+ " # Create clinical data DataFrame\n",
186
+ " # The sample characteristics dictionary has rows as keys and values as lists\n",
187
+ " sample_char_dict = {\n",
188
+ " 0: ['department of genetic medicine id: DGM-00028', 'ethnicity: Afr', 'department of genetic medicine id: DGM-00060', 'department of genetic medicine id: DGM-00061', 'department of genetic medicine id: DGM-00104', 'department of genetic medicine id: DGM-10131', 'department of genetic medicine id: DGM-00167', 'department of genetic medicine id: DGM-00171', 'department of genetic medicine id: DGM-00262', 'department of genetic medicine id: DGM-00313', 'department of genetic medicine id: DGM-10287', 'department of genetic medicine id: DGM-00382', 'department of genetic medicine id: DGM-10139', 'department of genetic medicine id: DGM-00471', 'department of genetic medicine id: DGM-00512', 'department of genetic medicine id: DGM-02088', 'department of genetic medicine id: DGM-10152', 'department of genetic medicine id: DGM-00632', 'department of genetic medicine id: DGM-00683', 'department of genetic medicine id: DGM-10404', 'department of genetic medicine id: DGM-00791', 'department of genetic medicine id: DGM-10132', 'department of genetic medicine id: DGM-10135', 'department of genetic medicine id: DGM-01275', 'department of genetic medicine id: DGM-10144', 'department of genetic medicine id: DGM-10130', 'department of genetic medicine id: DGM-10406', 'department of genetic medicine id: DGM-01607', 'department of genetic medicine id: DGM-01737', 'department of genetic medicine id: DGM-01749'],\n",
189
+ " 1: ['smoking status: S', 'department of genetic medicine id: DGM-00038', 'department of genetic medicine id: DGM-00029', 'department of genetic medicine id: DGM-00030', 'department of genetic medicine id: DGM-00035', 'department of genetic medicine id: DGM-00036', 'department of genetic medicine id: DGM-00041', 'department of genetic medicine id: DGM-00044', 'department of genetic medicine id: DGM-00052', 'department of genetic medicine id: DGM-00073', 'department of genetic medicine id: DGM-00069', 'department of genetic medicine id: DGM-00072', 'department of genetic medicine id: DGM-00078', 'smoking status: NS', 'department of genetic medicine id: DGM-00123', 'department of genetic medicine id: DGM-00244', 'department of genetic medicine id: DGM-00249', 'department of genetic medicine id: DGM-00416', 'department of genetic medicine id: DGM-00465', 'department of genetic medicine id: DGM-00530', 'department of genetic medicine id: DGM-00548', 'department of genetic medicine id: DGM-00551', 'department of genetic medicine id: DGM-00553', 'department of genetic medicine id: DGM-00625', 'department of genetic medicine id: DGM-00661', 'department of genetic medicine id: DGM-00685', 'department of genetic medicine id: DGM-00696', 'department of genetic medicine id: DGM-00757', 'department of genetic medicine id: DGM-00751', 'department of genetic medicine id: DGM-00778'],\n",
190
+ " 2: ['copd status: yes', 'smoking status: S', 'smoking status: NS', np.nan, 'serum 25-oh-d: low vitamin D', 'serum 25-oh-d: mid vitamin D', 'serum 25-oh-d: high vitamin D', 'cell type: mixture of epithelium, basal, ciliated, secretory, undifferentiated and inflammatory cells'],\n",
191
+ " 3: [np.nan, 'copd status: yes', 'serum 25-oh-d: mid vitamin D', 'serum 25-oh-d: high vitamin D', 'serum 25-oh-d: low vitamin D', 'time: n/a']\n",
192
+ " }\n",
193
+ " \n",
194
+ " # Using the correct format for the geo_select_clinical_features function\n",
195
+ " clinical_data = pd.DataFrame.from_dict(sample_char_dict, orient='index')\n",
196
+ " \n",
197
+ " # Extract clinical features using the library function\n",
198
+ " selected_clinical_df = geo_select_clinical_features(\n",
199
+ " clinical_df=clinical_data,\n",
200
+ " trait=trait,\n",
201
+ " trait_row=trait_row,\n",
202
+ " convert_trait=convert_trait,\n",
203
+ " age_row=age_row,\n",
204
+ " convert_age=convert_age,\n",
205
+ " gender_row=gender_row,\n",
206
+ " convert_gender=convert_gender\n",
207
+ " )\n",
208
+ " \n",
209
+ " # Preview the DataFrame to check extraction results\n",
210
+ " preview_results = preview_df(selected_clinical_df)\n",
211
+ " print(\"Preview of selected clinical features:\")\n",
212
+ " print(preview_results)\n",
213
+ " \n",
214
+ " # Create directory if it doesn't exist\n",
215
+ " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
216
+ " \n",
217
+ " # Save the clinical data to CSV\n",
218
+ " selected_clinical_df.to_csv(out_clinical_data_file, index=False)\n",
219
+ " print(f\"Clinical data saved to {out_clinical_data_file}\")\n"
220
+ ]
221
+ },
222
+ {
223
+ "cell_type": "markdown",
224
+ "id": "fb319b26",
225
+ "metadata": {},
226
+ "source": [
227
+ "### Step 3: Gene Data Extraction"
228
+ ]
229
+ },
230
+ {
231
+ "cell_type": "code",
232
+ "execution_count": 4,
233
+ "id": "c74e9add",
234
+ "metadata": {
235
+ "execution": {
236
+ "iopub.execute_input": "2025-03-25T08:21:27.855172Z",
237
+ "iopub.status.busy": "2025-03-25T08:21:27.855072Z",
238
+ "iopub.status.idle": "2025-03-25T08:21:28.713863Z",
239
+ "shell.execute_reply": "2025-03-25T08:21:28.713541Z"
240
+ }
241
+ },
242
+ "outputs": [
243
+ {
244
+ "name": "stdout",
245
+ "output_type": "stream",
246
+ "text": [
247
+ "Matrix file found: ../../input/GEO/Chronic_obstructive_pulmonary_disease_(COPD)/GSE32030/GSE32030_series_matrix.txt.gz\n"
248
+ ]
249
+ },
250
+ {
251
+ "name": "stdout",
252
+ "output_type": "stream",
253
+ "text": [
254
+ "Gene data shape: (54675, 270)\n",
255
+ "First 20 gene/probe identifiers:\n",
256
+ "Index(['1007_s_at', '1053_at', '117_at', '121_at', '1255_g_at', '1294_at',\n",
257
+ " '1316_at', '1320_at', '1405_i_at', '1431_at', '1438_at', '1487_at',\n",
258
+ " '1494_f_at', '1552256_a_at', '1552257_a_at', '1552258_at', '1552261_at',\n",
259
+ " '1552263_at', '1552264_a_at', '1552266_at'],\n",
260
+ " dtype='object', name='ID')\n"
261
+ ]
262
+ }
263
+ ],
264
+ "source": [
265
+ "# 1. Get the SOFT and matrix file paths again \n",
266
+ "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
267
+ "print(f\"Matrix file found: {matrix_file}\")\n",
268
+ "\n",
269
+ "# 2. Use the get_genetic_data function from the library to get the gene_data\n",
270
+ "try:\n",
271
+ " gene_data = get_genetic_data(matrix_file)\n",
272
+ " print(f\"Gene data shape: {gene_data.shape}\")\n",
273
+ " \n",
274
+ " # 3. Print the first 20 row IDs (gene or probe identifiers)\n",
275
+ " print(\"First 20 gene/probe identifiers:\")\n",
276
+ " print(gene_data.index[:20])\n",
277
+ "except Exception as e:\n",
278
+ " print(f\"Error extracting gene data: {e}\")\n"
279
+ ]
280
+ },
281
+ {
282
+ "cell_type": "markdown",
283
+ "id": "015e7e88",
284
+ "metadata": {},
285
+ "source": [
286
+ "### Step 4: Gene Identifier Review"
287
+ ]
288
+ },
289
+ {
290
+ "cell_type": "code",
291
+ "execution_count": 5,
292
+ "id": "5db9073f",
293
+ "metadata": {
294
+ "execution": {
295
+ "iopub.execute_input": "2025-03-25T08:21:28.715722Z",
296
+ "iopub.status.busy": "2025-03-25T08:21:28.715568Z",
297
+ "iopub.status.idle": "2025-03-25T08:21:28.717562Z",
298
+ "shell.execute_reply": "2025-03-25T08:21:28.717295Z"
299
+ }
300
+ },
301
+ "outputs": [],
302
+ "source": [
303
+ "# Review gene identifiers\n",
304
+ "# The gene identifiers (e.g., '1007_s_at', '1053_at') appear to be Affymetrix probe IDs\n",
305
+ "# rather than standard human gene symbols (which would look like BRCA1, TP53, etc.)\n",
306
+ "# These need to be mapped to gene symbols for biological interpretation\n",
307
+ "\n",
308
+ "requires_gene_mapping = True\n"
309
+ ]
310
+ },
311
+ {
312
+ "cell_type": "markdown",
313
+ "id": "5d2e8fcb",
314
+ "metadata": {},
315
+ "source": [
316
+ "### Step 5: Gene Annotation"
317
+ ]
318
+ },
319
+ {
320
+ "cell_type": "code",
321
+ "execution_count": 6,
322
+ "id": "4082114b",
323
+ "metadata": {
324
+ "execution": {
325
+ "iopub.execute_input": "2025-03-25T08:21:28.719197Z",
326
+ "iopub.status.busy": "2025-03-25T08:21:28.719096Z",
327
+ "iopub.status.idle": "2025-03-25T08:21:42.433785Z",
328
+ "shell.execute_reply": "2025-03-25T08:21:42.433399Z"
329
+ }
330
+ },
331
+ "outputs": [
332
+ {
333
+ "name": "stdout",
334
+ "output_type": "stream",
335
+ "text": [
336
+ "\n",
337
+ "Gene annotation preview:\n",
338
+ "Columns in gene annotation: ['ID', 'GB_ACC', 'SPOT_ID', 'Species Scientific Name', 'Annotation Date', 'Sequence Type', 'Sequence Source', 'Target Description', 'Representative Public ID', 'Gene Title', 'Gene Symbol', 'ENTREZ_GENE_ID', 'RefSeq Transcript ID', 'Gene Ontology Biological Process', 'Gene Ontology Cellular Component', 'Gene Ontology Molecular Function']\n",
339
+ "{'ID': ['1007_s_at', '1053_at', '117_at', '121_at', '1255_g_at'], 'GB_ACC': ['U48705', 'M87338', 'X51757', 'X69699', 'L36861'], 'SPOT_ID': [nan, nan, nan, nan, nan], 'Species Scientific Name': ['Homo sapiens', 'Homo sapiens', 'Homo sapiens', 'Homo sapiens', 'Homo sapiens'], 'Annotation Date': ['Oct 6, 2014', 'Oct 6, 2014', 'Oct 6, 2014', 'Oct 6, 2014', 'Oct 6, 2014'], 'Sequence Type': ['Exemplar sequence', 'Exemplar sequence', 'Exemplar sequence', 'Exemplar sequence', 'Exemplar sequence'], 'Sequence Source': ['Affymetrix Proprietary Database', 'GenBank', 'Affymetrix Proprietary Database', 'GenBank', 'Affymetrix Proprietary Database'], 'Target Description': ['U48705 /FEATURE=mRNA /DEFINITION=HSU48705 Human receptor tyrosine kinase DDR gene, complete cds', 'M87338 /FEATURE= /DEFINITION=HUMA1SBU Human replication factor C, 40-kDa subunit (A1) mRNA, complete cds', \"X51757 /FEATURE=cds /DEFINITION=HSP70B Human heat-shock protein HSP70B' gene\", 'X69699 /FEATURE= /DEFINITION=HSPAX8A H.sapiens Pax8 mRNA', 'L36861 /FEATURE=expanded_cds /DEFINITION=HUMGCAPB Homo sapiens guanylate cyclase activating protein (GCAP) gene exons 1-4, complete cds'], 'Representative Public ID': ['U48705', 'M87338', 'X51757', 'X69699', 'L36861'], 'Gene Title': ['discoidin domain receptor tyrosine kinase 1 /// microRNA 4640', 'replication factor C (activator 1) 2, 40kDa', \"heat shock 70kDa protein 6 (HSP70B')\", 'paired box 8', 'guanylate cyclase activator 1A (retina)'], 'Gene Symbol': ['DDR1 /// MIR4640', 'RFC2', 'HSPA6', 'PAX8', 'GUCA1A'], 'ENTREZ_GENE_ID': ['780 /// 100616237', '5982', '3310', '7849', '2978'], 'RefSeq Transcript ID': ['NM_001202521 /// NM_001202522 /// NM_001202523 /// NM_001954 /// NM_013993 /// NM_013994 /// NR_039783 /// XM_005249385 /// XM_005249386 /// XM_005249387 /// XM_005249389 /// XM_005272873 /// XM_005272874 /// XM_005272875 /// XM_005272877 /// XM_005275027 /// XM_005275028 /// XM_005275030 /// XM_005275031 /// XM_005275162 /// XM_005275163 /// XM_005275164 /// XM_005275166 /// XM_005275457 /// XM_005275458 /// XM_005275459 /// XM_005275461 /// XM_006715185 /// XM_006715186 /// XM_006715187 /// XM_006715188 /// XM_006715189 /// XM_006715190 /// XM_006725501 /// XM_006725502 /// XM_006725503 /// XM_006725504 /// XM_006725505 /// XM_006725506 /// XM_006725714 /// XM_006725715 /// XM_006725716 /// XM_006725717 /// XM_006725718 /// XM_006725719 /// XM_006725720 /// XM_006725721 /// XM_006725722 /// XM_006725827 /// XM_006725828 /// XM_006725829 /// XM_006725830 /// XM_006725831 /// XM_006725832 /// XM_006726017 /// XM_006726018 /// XM_006726019 /// XM_006726020 /// XM_006726021 /// XM_006726022 /// XR_427836 /// XR_430858 /// XR_430938 /// XR_430974 /// XR_431015', 'NM_001278791 /// NM_001278792 /// NM_001278793 /// NM_002914 /// NM_181471 /// XM_006716080', 'NM_002155', 'NM_003466 /// NM_013951 /// NM_013952 /// NM_013953 /// NM_013992', 'NM_000409 /// XM_006715073'], 'Gene Ontology Biological Process': ['0001558 // regulation of cell growth // inferred from electronic annotation /// 0001952 // regulation of cell-matrix adhesion // inferred from electronic annotation /// 0006468 // protein phosphorylation // inferred from electronic annotation /// 0007155 // cell adhesion // traceable author statement /// 0007169 // transmembrane receptor protein tyrosine kinase signaling pathway // inferred from electronic annotation /// 0007565 // female pregnancy // inferred from electronic annotation /// 0007566 // embryo implantation // inferred from electronic annotation /// 0007595 // lactation // inferred from electronic annotation /// 0008285 // negative regulation of cell proliferation // inferred from electronic annotation /// 0010715 // regulation of extracellular matrix disassembly // inferred from mutant phenotype /// 0014909 // smooth muscle cell migration // inferred from mutant phenotype /// 0016310 // phosphorylation // inferred from electronic annotation /// 0018108 // peptidyl-tyrosine phosphorylation // inferred from electronic annotation /// 0030198 // extracellular matrix organization // traceable author statement /// 0038063 // collagen-activated tyrosine kinase receptor signaling pathway // inferred from direct assay /// 0038063 // collagen-activated tyrosine kinase receptor signaling pathway // inferred from mutant phenotype /// 0038083 // peptidyl-tyrosine autophosphorylation // inferred from direct assay /// 0043583 // ear development // inferred from electronic annotation /// 0044319 // wound healing, spreading of cells // inferred from mutant phenotype /// 0046777 // protein autophosphorylation // inferred from direct assay /// 0060444 // branching involved in mammary gland duct morphogenesis // inferred from electronic annotation /// 0060749 // mammary gland alveolus development // inferred from electronic annotation /// 0061302 // smooth muscle cell-matrix adhesion // inferred from mutant phenotype', '0000278 // mitotic cell cycle // traceable author statement /// 0000722 // telomere maintenance via recombination // traceable author statement /// 0000723 // telomere maintenance // traceable author statement /// 0006260 // DNA replication // traceable author statement /// 0006271 // DNA strand elongation involved in DNA replication // traceable author statement /// 0006281 // DNA repair // traceable author statement /// 0006283 // transcription-coupled nucleotide-excision repair // traceable author statement /// 0006289 // nucleotide-excision repair // traceable author statement /// 0006297 // nucleotide-excision repair, DNA gap filling // traceable author statement /// 0015979 // photosynthesis // inferred from electronic annotation /// 0015995 // chlorophyll biosynthetic process // inferred from electronic annotation /// 0032201 // telomere maintenance via semi-conservative replication // traceable author statement', '0000902 // cell morphogenesis // inferred from electronic annotation /// 0006200 // ATP catabolic process // inferred from direct assay /// 0006950 // response to stress // inferred from electronic annotation /// 0006986 // response to unfolded protein // traceable author statement /// 0034605 // cellular response to heat // inferred from direct assay /// 0042026 // protein refolding // inferred from direct assay /// 0070370 // cellular heat acclimation // inferred from mutant phenotype', '0001655 // urogenital system development // inferred from sequence or structural similarity /// 0001656 // metanephros development // inferred from electronic annotation /// 0001658 // branching involved in ureteric bud morphogenesis // inferred from expression pattern /// 0001822 // kidney development // inferred from expression pattern /// 0001823 // mesonephros development // inferred from sequence or structural similarity /// 0003337 // mesenchymal to epithelial transition involved in metanephros morphogenesis // inferred from expression pattern /// 0006351 // transcription, DNA-templated // inferred from direct assay /// 0006355 // regulation of transcription, DNA-templated // inferred from electronic annotation /// 0007275 // multicellular organismal development // inferred from electronic annotation /// 0007417 // central nervous system development // inferred from expression pattern /// 0009653 // anatomical structure morphogenesis // traceable author statement /// 0030154 // cell differentiation // inferred from electronic annotation /// 0030878 // thyroid gland development // inferred from expression pattern /// 0030878 // thyroid gland development // inferred from mutant phenotype /// 0038194 // thyroid-stimulating hormone signaling pathway // traceable author statement /// 0039003 // pronephric field specification // inferred from sequence or structural similarity /// 0042472 // inner ear morphogenesis // inferred from sequence or structural similarity /// 0042981 // regulation of apoptotic process // inferred from sequence or structural similarity /// 0045893 // positive regulation of transcription, DNA-templated // inferred from direct assay /// 0045893 // positive regulation of transcription, DNA-templated // inferred from sequence or structural similarity /// 0045944 // positive regulation of transcription from RNA polymerase II promoter // inferred from direct assay /// 0048793 // pronephros development // inferred from sequence or structural similarity /// 0071371 // cellular response to gonadotropin stimulus // inferred from direct assay /// 0071599 // otic vesicle development // inferred from expression pattern /// 0072050 // S-shaped body morphogenesis // inferred from electronic annotation /// 0072073 // kidney epithelium development // inferred from electronic annotation /// 0072108 // positive regulation of mesenchymal to epithelial transition involved in metanephros morphogenesis // inferred from sequence or structural similarity /// 0072164 // mesonephric tubule development // inferred from electronic annotation /// 0072207 // metanephric epithelium development // inferred from expression pattern /// 0072221 // metanephric distal convoluted tubule development // inferred from sequence or structural similarity /// 0072278 // metanephric comma-shaped body morphogenesis // inferred from expression pattern /// 0072284 // metanephric S-shaped body morphogenesis // inferred from expression pattern /// 0072289 // metanephric nephron tubule formation // inferred from sequence or structural similarity /// 0072305 // negative regulation of mesenchymal cell apoptotic process involved in metanephric nephron morphogenesis // inferred from sequence or structural similarity /// 0072307 // regulation of metanephric nephron tubule epithelial cell differentiation // inferred from sequence or structural similarity /// 0090190 // positive regulation of branching involved in ureteric bud morphogenesis // inferred from sequence or structural similarity /// 1900212 // negative regulation of mesenchymal cell apoptotic process involved in metanephros development // inferred from sequence or structural similarity /// 1900215 // negative regulation of apoptotic process involved in metanephric collecting duct development // inferred from sequence or structural similarity /// 1900218 // negative regulation of apoptotic process involved in metanephric nephron tubule development // inferred from sequence or structural similarity /// 2000594 // positive regulation of metanephric DCT cell differentiation // inferred from sequence or structural similarity /// 2000611 // positive regulation of thyroid hormone generation // inferred from mutant phenotype /// 2000612 // regulation of thyroid-stimulating hormone secretion // inferred from mutant phenotype', '0007165 // signal transduction // non-traceable author statement /// 0007601 // visual perception // inferred from electronic annotation /// 0007602 // phototransduction // inferred from electronic annotation /// 0007603 // phototransduction, visible light // traceable author statement /// 0016056 // rhodopsin mediated signaling pathway // traceable author statement /// 0022400 // regulation of rhodopsin mediated signaling pathway // traceable author statement /// 0030828 // positive regulation of cGMP biosynthetic process // inferred from electronic annotation /// 0031282 // regulation of guanylate cyclase activity // inferred from electronic annotation /// 0031284 // positive regulation of guanylate cyclase activity // inferred from electronic annotation /// 0050896 // response to stimulus // inferred from electronic annotation'], 'Gene Ontology Cellular Component': ['0005576 // extracellular region // inferred from electronic annotation /// 0005615 // extracellular space // inferred from direct assay /// 0005886 // plasma membrane // traceable author statement /// 0005887 // integral component of plasma membrane // traceable author statement /// 0016020 // membrane // inferred from electronic annotation /// 0016021 // integral component of membrane // inferred from electronic annotation /// 0043235 // receptor complex // inferred from direct assay /// 0070062 // extracellular vesicular exosome // inferred from direct assay', '0005634 // nucleus // inferred from electronic annotation /// 0005654 // nucleoplasm // traceable author statement /// 0005663 // DNA replication factor C complex // inferred from direct assay', '0005737 // cytoplasm // inferred from direct assay /// 0005814 // centriole // inferred from direct assay /// 0005829 // cytosol // inferred from direct assay /// 0008180 // COP9 signalosome // inferred from direct assay /// 0070062 // extracellular vesicular exosome // inferred from direct assay /// 0072562 // blood microparticle // inferred from direct assay', '0005634 // nucleus // inferred from direct assay /// 0005654 // nucleoplasm // inferred from sequence or structural similarity /// 0005730 // nucleolus // inferred from direct assay', '0001750 // photoreceptor outer segment // inferred from electronic annotation /// 0001917 // photoreceptor inner segment // inferred from electronic annotation /// 0005578 // proteinaceous extracellular matrix // inferred from electronic annotation /// 0005886 // plasma membrane // inferred from direct assay /// 0016020 // membrane // inferred from electronic annotation /// 0097381 // photoreceptor disc membrane // traceable author statement'], 'Gene Ontology Molecular Function': ['0000166 // nucleotide binding // inferred from electronic annotation /// 0004672 // protein kinase activity // inferred from electronic annotation /// 0004713 // protein tyrosine kinase activity // inferred from electronic annotation /// 0004714 // transmembrane receptor protein tyrosine kinase activity // traceable author statement /// 0005515 // protein binding // inferred from physical interaction /// 0005518 // collagen binding // inferred from direct assay /// 0005518 // collagen binding // inferred from mutant phenotype /// 0005524 // ATP binding // inferred from electronic annotation /// 0016301 // kinase activity // inferred from electronic annotation /// 0016740 // transferase activity // inferred from electronic annotation /// 0016772 // transferase activity, transferring phosphorus-containing groups // inferred from electronic annotation /// 0038062 // protein tyrosine kinase collagen receptor activity // inferred from direct assay /// 0046872 // metal ion binding // inferred from electronic annotation', '0000166 // nucleotide binding // inferred from electronic annotation /// 0003677 // DNA binding // inferred from electronic annotation /// 0005515 // protein binding // inferred from physical interaction /// 0005524 // ATP binding // inferred from electronic annotation /// 0016851 // magnesium chelatase activity // inferred from electronic annotation /// 0017111 // nucleoside-triphosphatase activity // inferred from electronic annotation', '0000166 // nucleotide binding // inferred from electronic annotation /// 0005524 // ATP binding // inferred from electronic annotation /// 0019899 // enzyme binding // inferred from physical interaction /// 0031072 // heat shock protein binding // inferred from physical interaction /// 0042623 // ATPase activity, coupled // inferred from direct assay /// 0051082 // unfolded protein binding // inferred from direct assay', '0000979 // RNA polymerase II core promoter sequence-specific DNA binding // inferred from direct assay /// 0003677 // DNA binding // inferred from direct assay /// 0003677 // DNA binding // inferred from mutant phenotype /// 0003700 // sequence-specific DNA binding transcription factor activity // inferred from direct assay /// 0004996 // thyroid-stimulating hormone receptor activity // traceable author statement /// 0005515 // protein binding // inferred from physical interaction /// 0044212 // transcription regulatory region DNA binding // inferred from direct assay', '0005509 // calcium ion binding // inferred from electronic annotation /// 0008048 // calcium sensitive guanylate cyclase activator activity // inferred from electronic annotation /// 0030249 // guanylate cyclase regulator activity // inferred from electronic annotation /// 0046872 // metal ion binding // inferred from electronic annotation']}\n",
340
+ "\n",
341
+ "Searching for platform information in SOFT file:\n",
342
+ "Platform ID not found in first 100 lines\n",
343
+ "\n",
344
+ "Searching for gene symbol information in SOFT file:\n",
345
+ "Found references to gene symbols:\n",
346
+ "!Platform_relation = Alternative to: GPL19918 (Gene symbol version, 10K)\n",
347
+ "!Platform_relation = Alternative to: GPL20182 (Gene Symbol Version)\n",
348
+ "#Gene Symbol = A gene symbol, when one is available (from UniGene).\n",
349
+ "ID\tGB_ACC\tSPOT_ID\tSpecies Scientific Name\tAnnotation Date\tSequence Type\tSequence Source\tTarget Description\tRepresentative Public ID\tGene Title\tGene Symbol\tENTREZ_GENE_ID\tRefSeq Transcript ID\tGene Ontology Biological Process\tGene Ontology Cellular Component\tGene Ontology Molecular Function\n",
350
+ "\n",
351
+ "Checking for additional annotation files in the directory:\n",
352
+ "[]\n"
353
+ ]
354
+ }
355
+ ],
356
+ "source": [
357
+ "# 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.\n",
358
+ "gene_annotation = get_gene_annotation(soft_file)\n",
359
+ "\n",
360
+ "# 2. Analyze the gene annotation dataframe to identify which columns contain the gene identifiers and gene symbols\n",
361
+ "print(\"\\nGene annotation preview:\")\n",
362
+ "print(f\"Columns in gene annotation: {gene_annotation.columns.tolist()}\")\n",
363
+ "print(preview_df(gene_annotation, n=5))\n",
364
+ "\n",
365
+ "# Let's look for platform information in the SOFT file to understand the annotation better\n",
366
+ "print(\"\\nSearching for platform information in SOFT file:\")\n",
367
+ "with gzip.open(soft_file, 'rt') as f:\n",
368
+ " for i, line in enumerate(f):\n",
369
+ " if '!Series_platform_id' in line:\n",
370
+ " print(line.strip())\n",
371
+ " break\n",
372
+ " if i > 100: # Limit search to first 100 lines\n",
373
+ " print(\"Platform ID not found in first 100 lines\")\n",
374
+ " break\n",
375
+ "\n",
376
+ "# Check if the SOFT file includes any reference to gene symbols\n",
377
+ "print(\"\\nSearching for gene symbol information in SOFT file:\")\n",
378
+ "with gzip.open(soft_file, 'rt') as f:\n",
379
+ " gene_symbol_lines = []\n",
380
+ " for i, line in enumerate(f):\n",
381
+ " if 'GENE_SYMBOL' in line or 'gene_symbol' in line.lower() or 'symbol' in line.lower():\n",
382
+ " gene_symbol_lines.append(line.strip())\n",
383
+ " if i > 1000 and len(gene_symbol_lines) > 0: # Limit search but ensure we found something\n",
384
+ " break\n",
385
+ " \n",
386
+ " if gene_symbol_lines:\n",
387
+ " print(\"Found references to gene symbols:\")\n",
388
+ " for line in gene_symbol_lines[:5]: # Show just first 5 matches\n",
389
+ " print(line)\n",
390
+ " else:\n",
391
+ " print(\"No explicit gene symbol references found in first 1000 lines\")\n",
392
+ "\n",
393
+ "# Look for alternative annotation files or references in the directory\n",
394
+ "print(\"\\nChecking for additional annotation files in the directory:\")\n",
395
+ "all_files = os.listdir(in_cohort_dir)\n",
396
+ "print([f for f in all_files if 'annotation' in f.lower() or 'platform' in f.lower() or 'gpl' in f.lower()])\n"
397
+ ]
398
+ },
399
+ {
400
+ "cell_type": "markdown",
401
+ "id": "a126c357",
402
+ "metadata": {},
403
+ "source": [
404
+ "### Step 6: Gene Identifier Mapping"
405
+ ]
406
+ },
407
+ {
408
+ "cell_type": "code",
409
+ "execution_count": 7,
410
+ "id": "4bd07934",
411
+ "metadata": {
412
+ "execution": {
413
+ "iopub.execute_input": "2025-03-25T08:21:42.435667Z",
414
+ "iopub.status.busy": "2025-03-25T08:21:42.435552Z",
415
+ "iopub.status.idle": "2025-03-25T08:21:45.807327Z",
416
+ "shell.execute_reply": "2025-03-25T08:21:45.806684Z"
417
+ }
418
+ },
419
+ "outputs": [
420
+ {
421
+ "name": "stdout",
422
+ "output_type": "stream",
423
+ "text": [
424
+ "Gene mapping shape: (45782, 2)\n",
425
+ "Preview of gene mapping dataframe:\n",
426
+ "{'ID': ['1007_s_at', '1053_at', '117_at', '121_at', '1255_g_at'], 'Gene': ['DDR1 /// MIR4640', 'RFC2', 'HSPA6', 'PAX8', 'GUCA1A']}\n"
427
+ ]
428
+ },
429
+ {
430
+ "name": "stdout",
431
+ "output_type": "stream",
432
+ "text": [
433
+ "Gene expression data shape after mapping: (21278, 270)\n",
434
+ "Preview of gene expression data after mapping:\n",
435
+ "{'GSM549645': [0.0, 0.0, 0.0, 0.0, 0.0], 'GSM549646': [83.487, 24.5968, 191.55792000000002, 2417.498, 155.804], 'GSM549647': [0.0, 0.0, 0.0, 0.0, 0.0], 'GSM549648': [0.0, 0.0, 0.0, 0.0, 0.0], 'GSM549649': [0.0, 0.0, 0.0, 0.0, 0.0], 'GSM549650': [0.0, 0.0, 0.0, 0.0, 0.0], 'GSM549651': [0.0, 0.0, 0.0, 0.0, 0.0], 'GSM549652': [0.0, 0.0, 0.0, 0.0, 0.0], 'GSM549653': [0.0, 0.0, 0.0, 0.0, 0.0], 'GSM549654': [0.0, 0.0, 0.0, 0.0, 0.0], 'GSM549655': [0.0, 0.0, 0.0, 0.0, 0.0], 'GSM549656': [0.0, 0.0, 0.0, 0.0, 0.0], 'GSM549657': [0.0, 0.0, 0.0, 0.0, 0.0], 'GSM549658': [0.0, 0.0, 0.0, 0.0, 0.0], 'GSM549659': [0.0, 0.0, 0.0, 0.0, 0.0], 'GSM549660': [0.0, 0.0, 0.0, 0.0, 0.0], 'GSM549661': [0.0, 0.0, 0.0, 0.0, 0.0], 'GSM549662': [0.0, 0.0, 0.0, 0.0, 0.0], 'GSM549663': [0.0, 0.0, 0.0, 0.0, 0.0], 'GSM549664': [0.0, 0.0, 0.0, 0.0, 0.0], 'GSM549665': [0.0, 0.0, 0.0, 0.0, 0.0], 'GSM549666': [0.0, 0.0, 0.0, 0.0, 0.0], 'GSM549667': [0.0, 0.0, 0.0, 0.0, 0.0], 'GSM549668': [0.0, 0.0, 0.0, 0.0, 0.0], 'GSM549669': [0.0, 0.0, 0.0, 0.0, 0.0], 'GSM549670': [0.0, 0.0, 0.0, 0.0, 0.0], 'GSM549671': [0.0, 0.0, 0.0, 0.0, 0.0], 'GSM549672': [0.0, 0.0, 0.0, 0.0, 0.0], 'GSM549673': [0.0, 0.0, 0.0, 0.0, 0.0], 'GSM549674': [0.0, 0.0, 0.0, 0.0, 0.0], 'GSM549675': [0.0, 0.0, 0.0, 0.0, 0.0], 'GSM549676': [0.0, 0.0, 0.0, 0.0, 0.0], 'GSM549677': [0.0, 0.0, 0.0, 0.0, 0.0], 'GSM549678': [0.0, 0.0, 0.0, 0.0, 0.0], 'GSM549679': [0.0, 0.0, 0.0, 0.0, 0.0], 'GSM549680': [0.0, 0.0, 0.0, 0.0, 0.0], 'GSM549681': [79.8985, 33.8459, 63.103899999999996, 1106.6274999999998, 97.6581], 'GSM549682': [106.748, 13.6255, 109.96461, 548.9238, 169.609], 'GSM549683': [56.3852, 6.20186, 19.28494, 689.6041, 152.512], 'GSM549684': [103.892, 170.254, 128.8056, 3142.0717999999997, 116.834], 'GSM549685': [96.0217, 26.3959, 59.059509999999996, 298.7124, 246.903], 'GSM549686': [92.5172, 47.0249, 39.6686, 1025.4899, 239.629], 'GSM549687': [112.926, 17.8522, 178.0674, 474.0219, 162.484], 'GSM549688': [101.499, 13.0719, 21.300600000000003, 515.4746, 167.698], 'GSM549689': [89.8639, 13.2181, 50.0547, 598.1255, 162.291], 'GSM549690': [94.3876, 14.6992, 115.45563999999999, 259.3296, 155.956], 'GSM549691': [81.1039, 111.923, 118.52878999999999, 556.3079, 196.811], 'GSM549692': [0.0, 0.0, 0.0, 0.0, 0.0], 'GSM549693': [0.0, 0.0, 0.0, 0.0, 0.0], 'GSM549694': [145.432, 18.2403, 149.34135, 633.056, 122.885], 'GSM549695': [73.3468, 64.1878, 44.3457, 942.999, 208.25], 'GSM549696': [108.285, 33.2299, 212.95942000000002, 375.5501, 167.874], 'GSM549697': [124.976, 8.75021, 111.8255, 769.7198, 204.835], 'GSM549698': [69.7605, 17.0834, 64.7095, 373.198, 158.053], 'GSM549699': [107.592, 43.5908, 138.7194, 570.734, 132.418], 'GSM549700': [7.17064, 24.6093, 45.22879, 337.1489, 235.543], 'GSM549701': [34.6541, 17.6079, 99.8776, 975.0500000000001, 259.372], 'GSM549702': [0.0, 0.0, 0.0, 0.0, 0.0], 'GSM549703': [183.701, 19.3953, 277.4496, 1082.1532, 211.555], 'GSM549704': [142.264, 28.553, 28.873109999999997, 532.496, 136.837], 'GSM549705': [107.299, 10.8269, 48.199600000000004, 286.3279, 146.149], 'GSM549706': [188.175, 16.5678, 78.14500000000001, 517.939, 139.76], 'GSM549707': [177.098, 34.0955, 63.03193, 1204.2428, 182.461], 'GSM549708': [89.995, 18.7426, 118.566, 1321.1582, 204.395], 'GSM549709': [70.258, 34.8666, 60.5271, 353.6587, 114.924], 'GSM549710': [60.799, 19.9833, 198.94548, 796.954, 157.771], 'GSM549711': [80.6466, 14.4982, 25.522289999999998, 1695.833, 198.77], 'GSM549712': [161.328, 23.284, 75.31163, 386.2253, 131.845], 'GSM549713': [0.0, 0.0, 0.0, 0.0, 0.0], 'GSM549714': [42.4446, 15.7597, 31.61233, 577.6783, 157.883], 'GSM549715': [57.4838, 20.786, 138.3775, 374.71709999999996, 227.028], 'GSM549716': [80.9654, 14.209, 206.14034, 364.59229999999997, 196.922], 'GSM549717': [115.75, 33.7845, 181.32569999999998, 607.8303999999999, 209.76], 'GSM549718': [0.0, 0.0, 0.0, 0.0, 0.0], 'GSM549719': [198.899, 123.785, 201.5245, 933.3109999999999, 208.961], 'GSM549720': [147.466, 94.2022, 118.3036, 3761.7142000000003, 213.531], 'GSM549721': [97.2731, 17.9249, 143.2686, 552.2657, 331.664], 'GSM549722': [0.0, 0.0, 0.0, 0.0, 0.0], 'GSM549723': [117.342, 14.86, 174.5779, 2989.244, 338.921], 'GSM549724': [96.0609, 15.716, 141.5864, 493.2584, 271.366], 'GSM549725': [0.0, 0.0, 0.0, 0.0, 0.0], 'GSM549726': [0.0, 0.0, 0.0, 0.0, 0.0], 'GSM549727': [135.918, 101.086, 188.51556, 584.6, 286.441], 'GSM549728': [135.262, 27.5867, 101.0747, 343.3082, 192.168], 'GSM549729': [0.0, 0.0, 0.0, 0.0, 0.0], 'GSM549730': [85.1284, 21.6714, 194.88240000000002, 405.323, 237.595], 'GSM549731': [0.0, 0.0, 0.0, 0.0, 0.0], 'GSM549732': [0.0, 0.0, 0.0, 0.0, 0.0], 'GSM549733': [0.0, 0.0, 0.0, 0.0, 0.0], 'GSM549734': [0.0, 0.0, 0.0, 0.0, 0.0], 'GSM549735': [0.0, 0.0, 0.0, 0.0, 0.0], 'GSM549736': [0.0, 0.0, 0.0, 0.0, 0.0], 'GSM549737': [0.0, 0.0, 0.0, 0.0, 0.0], 'GSM549738': [0.0, 0.0, 0.0, 0.0, 0.0], 'GSM549739': [0.0, 0.0, 0.0, 0.0, 0.0], 'GSM549740': [0.0, 0.0, 0.0, 0.0, 0.0], 'GSM549742': [102.525, 37.3286, 284.0047, 1892.2227, 180.101], 'GSM549743': [117.759, 111.526, 122.05963, 380.6166, 270.506], 'GSM549744': [84.8877, 51.5581, 176.8804, 717.3501, 204.978], 'GSM549745': [57.158, 13.8994, 66.26289, 299.7611, 203.035], 'GSM549746': [119.755, 177.131, 33.6361, 447.231, 160.842], 'GSM549747': [93.1971, 14.5636, 38.62879, 444.996, 135.855], 'GSM549748': [105.483, 45.7346, 32.6573, 612.0436, 175.287], 'GSM549749': [52.9281, 116.751, 108.8237, 378.7838, 199.777], 'GSM549751': [112.23, 49.049, 52.1387, 908.6529999999999, 138.632], 'GSM549752': [0.0, 0.0, 0.0, 0.0, 0.0], 'GSM549753': [73.6893, 32.6686, 137.9174, 513.083, 160.705], 'GSM549754': [77.9724, 18.6286, 20.003619999999998, 627.147, 129.998], 'GSM549755': [173.35, 98.2514, 82.5012, 1427.838, 160.175], 'GSM549756': [26.4713, 32.8067, 99.715, 387.28700000000003, 234.95], 'GSM549757': [75.5629, 23.5903, 244.0832, 585.525, 126.536], 'GSM549758': [92.5288, 24.9548, 220.4152, 345.773, 147.479], 'GSM549759': [0.0, 0.0, 0.0, 0.0, 0.0], 'GSM549760': [118.227, 53.3219, 158.85789999999997, 350.57, 157.223], 'GSM549761': [37.1261, 47.8838, 191.3957, 585.7436, 203.579], 'GSM549762': [41.7881, 15.2259, 340.365, 479.73900000000003, 141.619], 'GSM549763': [0.0, 0.0, 0.0, 0.0, 0.0], 'GSM549764': [52.7428, 84.3251, 181.4475, 589.184, 104.067], 'GSM549765': [0.0, 0.0, 0.0, 0.0, 0.0], 'GSM549766': [233.169, 34.525, 162.6141, 380.06969999999995, 180.595], 'GSM549767': [0.0, 0.0, 0.0, 0.0, 0.0], 'GSM549768': [226.56, 137.929, 227.7192, 351.4525, 204.234], 'GSM549769': [0.0, 0.0, 0.0, 0.0, 0.0], 'GSM549770': [0.0, 0.0, 0.0, 0.0, 0.0], 'GSM549771': [81.2921, 21.5796, 66.58802, 358.2874, 126.463], 'GSM549772': [132.18, 23.2595, 136.70881000000003, 548.9593, 202.11], 'GSM549773': [0.0, 0.0, 0.0, 0.0, 0.0], 'GSM549774': [53.3759, 98.2225, 149.86019000000002, 342.4681, 191.429], 'GSM549775': [150.976, 30.2578, 218.45680000000002, 602.6143999999999, 126.973], 'GSM549776': [59.0237, 13.9924, 156.4393, 389.9093, 178.275], 'GSM549777': [109.544, 223.866, 143.57254, 1060.1621, 172.028], 'GSM549778': [199.898, 38.5934, 402.121, 868.739, 202.949], 'GSM549779': [158.479, 72.9566, 142.1064, 1010.8523, 179.791], 'GSM549780': [177.685, 148.571, 196.14395, 420.722, 178.046], 'GSM549781': [19.1452, 107.463, 145.3769, 443.711, 324.683], 'GSM549783': [0.0, 0.0, 0.0, 0.0, 0.0], 'GSM549784': [0.0, 0.0, 0.0, 0.0, 0.0], 'GSM549785': [0.0, 0.0, 0.0, 0.0, 0.0], 'GSM549786': [0.0, 0.0, 0.0, 0.0, 0.0], 'GSM549787': [0.0, 0.0, 0.0, 0.0, 0.0], 'GSM549788': [121.093, 19.1427, 151.1011, 737.7529999999999, 210.965], 'GSM549789': [0.0, 0.0, 0.0, 0.0, 0.0], 'GSM549790': [0.0, 0.0, 0.0, 0.0, 0.0], 'GSM549791': [0.0, 0.0, 0.0, 0.0, 0.0], 'GSM549792': [0.0, 0.0, 0.0, 0.0, 0.0], 'GSM549793': [0.0, 0.0, 0.0, 0.0, 0.0], 'GSM549794': [0.0, 0.0, 0.0, 0.0, 0.0], 'GSM549795': [0.0, 0.0, 0.0, 0.0, 0.0], 'GSM549796': [0.0, 0.0, 0.0, 0.0, 0.0], 'GSM549797': [0.0, 0.0, 0.0, 0.0, 0.0], 'GSM549798': [0.0, 0.0, 0.0, 0.0, 0.0], 'GSM549799': [0.0, 0.0, 0.0, 0.0, 0.0], 'GSM549800': [0.0, 0.0, 0.0, 0.0, 0.0], 'GSM549801': [0.0, 0.0, 0.0, 0.0, 0.0], 'GSM549802': [0.0, 0.0, 0.0, 0.0, 0.0], 'GSM549803': [0.0, 0.0, 0.0, 0.0, 0.0], 'GSM549804': [0.0, 0.0, 0.0, 0.0, 0.0], 'GSM549805': [0.0, 0.0, 0.0, 0.0, 0.0], 'GSM549806': [0.0, 0.0, 0.0, 0.0, 0.0], 'GSM549807': [0.0, 0.0, 0.0, 0.0, 0.0], 'GSM549808': [0.0, 0.0, 0.0, 0.0, 0.0], 'GSM549809': [0.0, 0.0, 0.0, 0.0, 0.0], 'GSM549810': [0.0, 0.0, 0.0, 0.0, 0.0], 'GSM549811': [0.0, 0.0, 0.0, 0.0, 0.0], 'GSM549812': [0.0, 0.0, 0.0, 0.0, 0.0], 'GSM549813': [0.0, 0.0, 0.0, 0.0, 0.0], 'GSM549814': [0.0, 0.0, 0.0, 0.0, 0.0], 'GSM549815': [19.387, 38.8757, 60.567400000000006, 337.2875, 147.551], 'GSM549816': [50.9951, 20.8406, 30.584553000000003, 506.486, 145.483], 'GSM549817': [0.0, 0.0, 0.0, 0.0, 0.0], 'GSM549818': [93.6746, 168.798, 105.08609999999999, 215.679, 148.589], 'GSM549819': [0.0, 0.0, 0.0, 0.0, 0.0], 'GSM549820': [0.0, 0.0, 0.0, 0.0, 0.0], 'GSM549821': [130.232, 37.8335, 149.86756, 466.117, 213.617], 'GSM569911': [116.002, 23.0029, 190.6557, 351.28290000000004, 195.064], 'GSM569912': [66.6933, 33.971, 193.4934, 355.5367, 196.432], 'GSM569913': [137.351, 132.715, 87.11158, 354.317, 175.905], 'GSM569914': [57.4315, 33.4559, 103.12708, 610.013, 221.058], 'GSM569915': [65.1075, 37.7201, 137.94915, 1824.444, 263.326], 'GSM569916': [48.5214, 37.2721, 36.291900000000005, 412.703, 234.132], 'GSM569917': [44.6359, 20.4832, 151.24349999999998, 542.8928999999999, 209.84], 'GSM569918': [69.322, 67.7748, 123.69810000000001, 777.2716, 99.847], 'GSM569919': [24.9046, 79.2262, 20.598750000000003, 695.9859, 147.574], 'GSM569920': [139.054, 235.286, 131.22938, 576.1043999999999, 254.284], 'GSM569921': [97.4634, 70.4461, 162.9117, 608.5450000000001, 127.923], 'GSM569922': [29.465, 111.283, 30.5985, 566.4000000000001, 178.086], 'GSM569923': [125.246, 175.492, 19.844079999999998, 884.897, 127.627], 'GSM569924': [86.1242, 80.2365, 133.56458999999998, 559.3254, 165.852], 'GSM569925': [228.702, 35.0545, 136.4715, 610.391, 130.059], 'GSM569926': [153.626, 23.8631, 147.5693, 1229.7387, 130.665], 'GSM599910': [70.3282, 11.2307, 140.5716, 241.9946, 196.603], 'GSM599911': [60.8249, 145.274, 283.4954, 547.0609999999999, 148.359], 'GSM599912': [39.379, 23.6161, 125.4984, 627.439, 326.518], 'GSM599913': [53.5048, 15.5618, 78.1506, 724.7255, 119.698], 'GSM599914': [107.087, 22.3735, 95.1035, 714.3497, 223.895], 'GSM599915': [34.9291, 7.50517, 55.8276, 406.01599999999996, 204.857], 'GSM599916': [53.0812, 51.4187, 76.1837, 722.2659, 160.397], 'GSM599917': [49.0427, 27.6813, 74.6809, 465.952, 115.685], 'GSM599918': [187.701, 66.5259, 78.81049999999999, 275.52930000000003, 251.993], 'GSM599919': [15.0983, 18.2123, 169.8992, 823.3629999999999, 101.393]}\n"
436
+ ]
437
+ },
438
+ {
439
+ "name": "stdout",
440
+ "output_type": "stream",
441
+ "text": [
442
+ "Gene expression data saved to ../../output/preprocess/Chronic_obstructive_pulmonary_disease_(COPD)/gene_data/GSE32030.csv\n"
443
+ ]
444
+ }
445
+ ],
446
+ "source": [
447
+ "# 1. Identify which columns in gene_annotation contain probe IDs and gene symbols\n",
448
+ "# Based on the preview, 'ID' contains probe IDs and 'Gene Symbol' contains gene symbols\n",
449
+ "id_column = 'ID'\n",
450
+ "gene_symbol_column = 'Gene Symbol'\n",
451
+ "\n",
452
+ "# 2. Get a gene mapping dataframe\n",
453
+ "gene_mapping = get_gene_mapping(gene_annotation, id_column, gene_symbol_column)\n",
454
+ "print(f\"Gene mapping shape: {gene_mapping.shape}\")\n",
455
+ "print(\"Preview of gene mapping dataframe:\")\n",
456
+ "print(preview_df(gene_mapping))\n",
457
+ "\n",
458
+ "# 3. Apply gene mapping to convert from probe-level to gene-level expression\n",
459
+ "gene_data = apply_gene_mapping(gene_data, gene_mapping)\n",
460
+ "print(f\"Gene expression data shape after mapping: {gene_data.shape}\")\n",
461
+ "print(\"Preview of gene expression data after mapping:\")\n",
462
+ "print(preview_df(gene_data))\n",
463
+ "\n",
464
+ "# Create directory if it doesn't exist\n",
465
+ "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
466
+ "\n",
467
+ "# Save the gene data to CSV\n",
468
+ "gene_data.to_csv(out_gene_data_file)\n",
469
+ "print(f\"Gene expression data saved to {out_gene_data_file}\")\n"
470
+ ]
471
+ },
472
+ {
473
+ "cell_type": "markdown",
474
+ "id": "7bc532f7",
475
+ "metadata": {},
476
+ "source": [
477
+ "### Step 7: Data Normalization and Linking"
478
+ ]
479
+ },
480
+ {
481
+ "cell_type": "code",
482
+ "execution_count": 8,
483
+ "id": "a4b3adcb",
484
+ "metadata": {
485
+ "execution": {
486
+ "iopub.execute_input": "2025-03-25T08:21:45.809274Z",
487
+ "iopub.status.busy": "2025-03-25T08:21:45.809149Z",
488
+ "iopub.status.idle": "2025-03-25T08:21:53.839654Z",
489
+ "shell.execute_reply": "2025-03-25T08:21:53.839026Z"
490
+ }
491
+ },
492
+ "outputs": [
493
+ {
494
+ "name": "stdout",
495
+ "output_type": "stream",
496
+ "text": [
497
+ "Normalized gene data shape: (21278, 270)\n",
498
+ "Gene data column names (sample IDs):\n",
499
+ "Index(['GSM549645', 'GSM549646', 'GSM549647', 'GSM549648', 'GSM549649'], dtype='object')\n"
500
+ ]
501
+ },
502
+ {
503
+ "name": "stdout",
504
+ "output_type": "stream",
505
+ "text": [
506
+ "\n",
507
+ "Raw clinical data structure:\n",
508
+ "Clinical data shape: (4, 271)\n",
509
+ "Clinical data columns: Index(['!Sample_geo_accession', 'GSM549645', 'GSM549646', 'GSM549647',\n",
510
+ " 'GSM549648'],\n",
511
+ " dtype='object')\n",
512
+ "\n",
513
+ "Sample characteristics dictionary:\n",
514
+ "{0: ['department of genetic medicine id: DGM-00028', 'ethnicity: Afr', 'department of genetic medicine id: DGM-00060', 'department of genetic medicine id: DGM-00061', 'department of genetic medicine id: DGM-00104', 'department of genetic medicine id: DGM-10131', 'department of genetic medicine id: DGM-00167', 'department of genetic medicine id: DGM-00171', 'department of genetic medicine id: DGM-00262', 'department of genetic medicine id: DGM-00313', 'department of genetic medicine id: DGM-10287', 'department of genetic medicine id: DGM-00382', 'department of genetic medicine id: DGM-10139', 'department of genetic medicine id: DGM-00471', 'department of genetic medicine id: DGM-00512', 'department of genetic medicine id: DGM-02088', 'department of genetic medicine id: DGM-10152', 'department of genetic medicine id: DGM-00632', 'department of genetic medicine id: DGM-00683', 'department of genetic medicine id: DGM-10404', 'department of genetic medicine id: DGM-00791', 'department of genetic medicine id: DGM-10132', 'department of genetic medicine id: DGM-10135', 'department of genetic medicine id: DGM-01275', 'department of genetic medicine id: DGM-10144', 'department of genetic medicine id: DGM-10130', 'department of genetic medicine id: DGM-10406', 'department of genetic medicine id: DGM-01607', 'department of genetic medicine id: DGM-01737', 'department of genetic medicine id: DGM-01749'], 1: ['smoking status: S', 'department of genetic medicine id: DGM-00038', 'department of genetic medicine id: DGM-00029', 'department of genetic medicine id: DGM-00030', 'department of genetic medicine id: DGM-00035', 'department of genetic medicine id: DGM-00036', 'department of genetic medicine id: DGM-00041', 'department of genetic medicine id: DGM-00044', 'department of genetic medicine id: DGM-00052', 'department of genetic medicine id: DGM-00073', 'department of genetic medicine id: DGM-00069', 'department of genetic medicine id: DGM-00072', 'department of genetic medicine id: DGM-00078', 'smoking status: NS', 'department of genetic medicine id: DGM-00123', 'department of genetic medicine id: DGM-00244', 'department of genetic medicine id: DGM-00249', 'department of genetic medicine id: DGM-00416', 'department of genetic medicine id: DGM-00465', 'department of genetic medicine id: DGM-00530', 'department of genetic medicine id: DGM-00548', 'department of genetic medicine id: DGM-00551', 'department of genetic medicine id: DGM-00553', 'department of genetic medicine id: DGM-00625', 'department of genetic medicine id: DGM-00661', 'department of genetic medicine id: DGM-00685', 'department of genetic medicine id: DGM-00696', 'department of genetic medicine id: DGM-00757', 'department of genetic medicine id: DGM-00751', 'department of genetic medicine id: DGM-00778'], 2: ['copd status: yes', 'smoking status: S', 'smoking status: NS', nan, 'serum 25-oh-d: low vitamin D', 'serum 25-oh-d: mid vitamin D', 'serum 25-oh-d: high vitamin D', 'cell type: mixture of epithelium, basal, ciliated, secretory, undifferentiated and inflammatory cells'], 3: [nan, 'copd status: yes', 'serum 25-oh-d: mid vitamin D', 'serum 25-oh-d: high vitamin D', 'serum 25-oh-d: low vitamin D', 'time: n/a']}\n",
515
+ "\n",
516
+ "Values in trait row:\n",
517
+ "['!Sample_characteristics_ch1' 'copd status: yes' 'smoking status: S'\n",
518
+ " 'copd status: yes' 'copd status: yes']\n",
519
+ "\n",
520
+ "Created clinical features dataframe:\n",
521
+ "Shape: (1, 270)\n",
522
+ " GSM549645 GSM549646 GSM549647 \\\n",
523
+ "Chronic_obstructive_pulmonary_disease_(COPD) 1 None 1 \n",
524
+ "\n",
525
+ " GSM549648 GSM549649 \n",
526
+ "Chronic_obstructive_pulmonary_disease_(COPD) 1 1 \n",
527
+ "\n",
528
+ "Linked data shape before handling missing values: (270, 21279)\n",
529
+ "Actual trait column in linked data: Chronic_obstructive_pulmonary_disease_(COPD)\n"
530
+ ]
531
+ },
532
+ {
533
+ "name": "stderr",
534
+ "output_type": "stream",
535
+ "text": [
536
+ "/media/techt/DATA/GenoAgent/tools/preprocess.py:400: FutureWarning: The behavior of DataFrame concatenation with empty or all-NA entries is deprecated. In a future version, this will no longer exclude empty or all-NA columns when determining the result dtypes. To retain the old behavior, exclude the relevant entries before the concat operation.\n",
537
+ " linked_data = pd.concat([clinical_df, genetic_df], axis=0).T\n"
538
+ ]
539
+ },
540
+ {
541
+ "name": "stderr",
542
+ "output_type": "stream",
543
+ "text": [
544
+ "/media/techt/DATA/GenoAgent/tools/preprocess.py:455: FutureWarning: Downcasting object dtype arrays on .fillna, .ffill, .bfill is deprecated and will change in a future version. Call result.infer_objects(copy=False) instead. To opt-in to the future behavior, set `pd.set_option('future.no_silent_downcasting', True)`\n",
545
+ " df[gene_cols] = df[gene_cols].fillna(df[gene_cols].mean())\n"
546
+ ]
547
+ },
548
+ {
549
+ "name": "stdout",
550
+ "output_type": "stream",
551
+ "text": [
552
+ "Linked data shape after handling missing values: (35, 21279)\n",
553
+ "Quartiles for 'Chronic_obstructive_pulmonary_disease_(COPD)':\n",
554
+ " 25%: 1.0\n",
555
+ " 50% (Median): 1.0\n",
556
+ " 75%: 1.0\n",
557
+ "Min: 1\n",
558
+ "Max: 1\n",
559
+ "The distribution of the feature 'Chronic_obstructive_pulmonary_disease_(COPD)' in this dataset is severely biased.\n",
560
+ "\n",
561
+ "Dataset deemed not usable due to quality issues - linked data not saved\n"
562
+ ]
563
+ }
564
+ ],
565
+ "source": [
566
+ "# 1. Normalize gene symbols in the gene expression data \n",
567
+ "# (This was already done in the previous step, so no need to repeat)\n",
568
+ "print(f\"Normalized gene data shape: {gene_data.shape}\")\n",
569
+ "\n",
570
+ "# 2. Examine the sample IDs in the gene expression data to understand the structure\n",
571
+ "print(\"Gene data column names (sample IDs):\")\n",
572
+ "print(gene_data.columns[:5]) # Print first 5 for brevity\n",
573
+ "\n",
574
+ "# Inspect the clinical data format from the matrix file directly\n",
575
+ "background_info, clinical_data = get_background_and_clinical_data(matrix_file)\n",
576
+ "print(\"\\nRaw clinical data structure:\")\n",
577
+ "print(f\"Clinical data shape: {clinical_data.shape}\")\n",
578
+ "print(f\"Clinical data columns: {clinical_data.columns[:5]}\")\n",
579
+ "\n",
580
+ "# Get the sample characteristics to re-extract the disease information\n",
581
+ "sample_characteristics_dict = get_unique_values_by_row(clinical_data)\n",
582
+ "print(\"\\nSample characteristics dictionary:\")\n",
583
+ "print(sample_characteristics_dict)\n",
584
+ "\n",
585
+ "# 3. Directly create clinical features from the raw data again\n",
586
+ "# Verify trait row contains the disease information (OA vs RA)\n",
587
+ "print(\"\\nValues in trait row:\")\n",
588
+ "trait_values = clinical_data.iloc[trait_row].values\n",
589
+ "print(trait_values[:5])\n",
590
+ "\n",
591
+ "# Create clinical dataframe with proper structure\n",
592
+ "# First get the sample IDs from gene data as these are our actual sample identifiers\n",
593
+ "sample_ids = gene_data.columns.tolist()\n",
594
+ "\n",
595
+ "# Create the clinical features dataframe with those sample IDs\n",
596
+ "clinical_features = pd.DataFrame(index=[trait], columns=sample_ids)\n",
597
+ "\n",
598
+ "# Fill the clinical features with our trait values by mapping GSM IDs to actual values\n",
599
+ "for col in clinical_data.columns:\n",
600
+ " if col in sample_ids:\n",
601
+ " # Extract the disease value and convert it\n",
602
+ " disease_val = clinical_data.iloc[trait_row][col]\n",
603
+ " clinical_features.loc[trait, col] = convert_trait(disease_val)\n",
604
+ "\n",
605
+ "print(\"\\nCreated clinical features dataframe:\")\n",
606
+ "print(f\"Shape: {clinical_features.shape}\")\n",
607
+ "print(clinical_features.iloc[:, :5]) # Show first 5 columns\n",
608
+ "\n",
609
+ "# 4. Link clinical and genetic data\n",
610
+ "linked_data = geo_link_clinical_genetic_data(clinical_features, gene_data)\n",
611
+ "print(f\"\\nLinked data shape before handling missing values: {linked_data.shape}\")\n",
612
+ "\n",
613
+ "# 5. Handle missing values - we need to use the actual column name, not the trait variable\n",
614
+ "# First identify the actual trait column name in the linked data\n",
615
+ "trait_column = clinical_features.index[0] # This should be 'Osteoarthritis'\n",
616
+ "print(f\"Actual trait column in linked data: {trait_column}\")\n",
617
+ "\n",
618
+ "# Now handle missing values with the correct column name\n",
619
+ "linked_data_clean = handle_missing_values(linked_data, trait_column)\n",
620
+ "print(f\"Linked data shape after handling missing values: {linked_data_clean.shape}\")\n",
621
+ "\n",
622
+ "# 6. Evaluate bias in trait and demographic features\n",
623
+ "is_biased, linked_data_clean = judge_and_remove_biased_features(linked_data_clean, trait_column)\n",
624
+ "\n",
625
+ "# 7. Conduct final quality validation\n",
626
+ "note = \"Dataset contains gene expression data from synovial fibroblasts of RA and OA patients. Data includes high serum and low serum responses.\"\n",
627
+ "is_usable = validate_and_save_cohort_info(\n",
628
+ " is_final=True,\n",
629
+ " cohort=cohort,\n",
630
+ " info_path=json_path,\n",
631
+ " is_gene_available=True,\n",
632
+ " is_trait_available=(linked_data_clean.shape[0] > 0),\n",
633
+ " is_biased=is_biased,\n",
634
+ " df=linked_data_clean,\n",
635
+ " note=note\n",
636
+ ")\n",
637
+ "\n",
638
+ "# 8. Save linked data if usable\n",
639
+ "if is_usable:\n",
640
+ " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n",
641
+ " linked_data_clean.to_csv(out_data_file)\n",
642
+ " print(f\"Linked data saved to {out_data_file}\")\n",
643
+ "else:\n",
644
+ " print(\"Dataset deemed not usable due to quality issues - linked data not saved\")"
645
+ ]
646
+ }
647
+ ],
648
+ "metadata": {
649
+ "language_info": {
650
+ "codemirror_mode": {
651
+ "name": "ipython",
652
+ "version": 3
653
+ },
654
+ "file_extension": ".py",
655
+ "mimetype": "text/x-python",
656
+ "name": "python",
657
+ "nbconvert_exporter": "python",
658
+ "pygments_lexer": "ipython3",
659
+ "version": "3.10.16"
660
+ }
661
+ },
662
+ "nbformat": 4,
663
+ "nbformat_minor": 5
664
+ }
code/Chronic_obstructive_pulmonary_disease_(COPD)/GSE64593.ipynb ADDED
@@ -0,0 +1,529 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": 1,
6
+ "id": "5a5987d4",
7
+ "metadata": {
8
+ "execution": {
9
+ "iopub.execute_input": "2025-03-25T08:21:55.041771Z",
10
+ "iopub.status.busy": "2025-03-25T08:21:55.041591Z",
11
+ "iopub.status.idle": "2025-03-25T08:21:55.203259Z",
12
+ "shell.execute_reply": "2025-03-25T08:21:55.202918Z"
13
+ }
14
+ },
15
+ "outputs": [],
16
+ "source": [
17
+ "import sys\n",
18
+ "import os\n",
19
+ "sys.path.append(os.path.abspath(os.path.join(os.getcwd(), '../..')))\n",
20
+ "\n",
21
+ "# Path Configuration\n",
22
+ "from tools.preprocess import *\n",
23
+ "\n",
24
+ "# Processing context\n",
25
+ "trait = \"Chronic_obstructive_pulmonary_disease_(COPD)\"\n",
26
+ "cohort = \"GSE64593\"\n",
27
+ "\n",
28
+ "# Input paths\n",
29
+ "in_trait_dir = \"../../input/GEO/Chronic_obstructive_pulmonary_disease_(COPD)\"\n",
30
+ "in_cohort_dir = \"../../input/GEO/Chronic_obstructive_pulmonary_disease_(COPD)/GSE64593\"\n",
31
+ "\n",
32
+ "# Output paths\n",
33
+ "out_data_file = \"../../output/preprocess/Chronic_obstructive_pulmonary_disease_(COPD)/GSE64593.csv\"\n",
34
+ "out_gene_data_file = \"../../output/preprocess/Chronic_obstructive_pulmonary_disease_(COPD)/gene_data/GSE64593.csv\"\n",
35
+ "out_clinical_data_file = \"../../output/preprocess/Chronic_obstructive_pulmonary_disease_(COPD)/clinical_data/GSE64593.csv\"\n",
36
+ "json_path = \"../../output/preprocess/Chronic_obstructive_pulmonary_disease_(COPD)/cohort_info.json\"\n"
37
+ ]
38
+ },
39
+ {
40
+ "cell_type": "markdown",
41
+ "id": "abad30f0",
42
+ "metadata": {},
43
+ "source": [
44
+ "### Step 1: Initial Data Loading"
45
+ ]
46
+ },
47
+ {
48
+ "cell_type": "code",
49
+ "execution_count": 2,
50
+ "id": "65286817",
51
+ "metadata": {
52
+ "execution": {
53
+ "iopub.execute_input": "2025-03-25T08:21:55.204618Z",
54
+ "iopub.status.busy": "2025-03-25T08:21:55.204480Z",
55
+ "iopub.status.idle": "2025-03-25T08:21:55.371089Z",
56
+ "shell.execute_reply": "2025-03-25T08:21:55.370775Z"
57
+ }
58
+ },
59
+ "outputs": [
60
+ {
61
+ "name": "stdout",
62
+ "output_type": "stream",
63
+ "text": [
64
+ "Background Information:\n",
65
+ "!Series_title\t\"The Role of Interleukin-23 in the Early Development of Emphysema in HIV1+ Smokers [Affymetrix]\"\n",
66
+ "!Series_summary\t\"Matrix metalloproteinase-9 (MMP-9) expression is up-regulated in alveolar macrophages (AM) of HIV1+ smokers who develop emphysema. Based on the knowledge that lung epithelial lining fluid (ELF) of HIV1+ smokers has increased levels of inflammatory cytokines compared to HIV1- smokers, we hypothesized up-regulation of lung cytokines in HIV1+ smokers may be functionally related to increased MMP-9 expression. Cytokine arrays evaluated cytokine protein levels in ELF obtained from 5 groups of individuals: HIV1‾ healthy nonsmokers, HIV1‾ healthy smokers, HIV1‾ smokers with low diffusing capacity (DLCO) , HIV1 + nonsmokers, and HIV1 + smokers with low DLCO. Among several pro-inflammatory cytokines elevated in ELF associated with smoking and HIV1+, increased levels of the Th17-related cytokine IL-23 were found in HIV1- smokers with low DLCO and HIV1+ smokers and nonsmokers. Relative IL-23 gene expression was significantly increased in AM of HIV1+ individuals, with greater expression in AM of HIV1+ smokers with low DLCO. Infection with HIV1 in vitro induced IL-23 expression in normal AM. Since AM purified by adherence contain a small number of lymphocytes, we hy-pothesized that in an AM/lymphocyte co-culture system, IL-23 would up-regulate MMP-9. IL-23 stimulation of AM/lymphocyte co-cultures in vitro induced increased MMP-9 mRNA levels and protein. AM of healthy individuals did not express IL-23 receptors (IL-23R), lung T lymphocytes express IL-23R and interact with AM in order to up-regulate MMP-9. This mechanism may contribute to the increased tissue destruction in the lungs of HIV1+ smokers and suggests that Th-17 related inflammation may play a role.\"\n",
67
+ "!Series_summary\t\"IL-23 upregulates MMP-9 expression in human alveolar macrophages via a T lymphocyte/alveolar macrophage interaction, suggesting a possible role for Th-17 related inflammation in accelerated emphysema in HIV1+ smokers.\"\n",
68
+ "!Series_overall_design\t\"Array-based expression profiling of alveolar macrophages from HIV1+ smokers and HIV1- smokers.\"\n",
69
+ "Sample Characteristics Dictionary:\n",
70
+ "{0: ['smoking status: smoker'], 1: ['disease state: HIV+', 'disease state: HIV-'], 2: ['cell type: alveolar macrophage']}\n"
71
+ ]
72
+ }
73
+ ],
74
+ "source": [
75
+ "from tools.preprocess import *\n",
76
+ "# 1. Identify the paths to the SOFT file and the matrix file\n",
77
+ "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
78
+ "\n",
79
+ "# 2. Read the matrix file to obtain background information and sample characteristics data\n",
80
+ "background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']\n",
81
+ "clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']\n",
82
+ "background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)\n",
83
+ "\n",
84
+ "# 3. Obtain the sample characteristics dictionary from the clinical dataframe\n",
85
+ "sample_characteristics_dict = get_unique_values_by_row(clinical_data)\n",
86
+ "\n",
87
+ "# 4. Explicitly print out all the background information and the sample characteristics dictionary\n",
88
+ "print(\"Background Information:\")\n",
89
+ "print(background_info)\n",
90
+ "print(\"Sample Characteristics Dictionary:\")\n",
91
+ "print(sample_characteristics_dict)\n"
92
+ ]
93
+ },
94
+ {
95
+ "cell_type": "markdown",
96
+ "id": "9f5afa08",
97
+ "metadata": {},
98
+ "source": [
99
+ "### Step 2: Dataset Analysis and Clinical Feature Extraction"
100
+ ]
101
+ },
102
+ {
103
+ "cell_type": "code",
104
+ "execution_count": 3,
105
+ "id": "ddf66cf5",
106
+ "metadata": {
107
+ "execution": {
108
+ "iopub.execute_input": "2025-03-25T08:21:55.372223Z",
109
+ "iopub.status.busy": "2025-03-25T08:21:55.372110Z",
110
+ "iopub.status.idle": "2025-03-25T08:21:55.375306Z",
111
+ "shell.execute_reply": "2025-03-25T08:21:55.375014Z"
112
+ }
113
+ },
114
+ "outputs": [
115
+ {
116
+ "name": "stdout",
117
+ "output_type": "stream",
118
+ "text": [
119
+ "No COPD/emphysema trait data available for extraction.\n"
120
+ ]
121
+ }
122
+ ],
123
+ "source": [
124
+ "# 1. Gene Expression Data Analysis\n",
125
+ "# Based on the background information, this dataset appears to be analyzing gene expression\n",
126
+ "# specifically for MMP-9 in alveolar macrophages using Affymetrix arrays.\n",
127
+ "is_gene_available = True\n",
128
+ "\n",
129
+ "# 2. Variable Availability and Data Type Conversion\n",
130
+ "# For COPD/emphysema trait:\n",
131
+ "# Looking at the sample characteristics, there's no direct mention of COPD, emphysema, or DLCO status\n",
132
+ "# The study examines HIV+ smokers with low DLCO as having emphysema, but we don't have this info in the characteristics\n",
133
+ "# We cannot reliably infer COPD status from just HIV status without DLCO measurements\n",
134
+ "trait_row = None # No direct or reliably inferable COPD trait data\n",
135
+ "\n",
136
+ "# Age data - Not available in the sample characteristics\n",
137
+ "age_row = None\n",
138
+ "\n",
139
+ "# Gender data - Not available in the sample characteristics\n",
140
+ "gender_row = None\n",
141
+ "\n",
142
+ "# Conversion functions defined for completeness\n",
143
+ "def convert_trait(value):\n",
144
+ " return None # Not applicable since we don't have COPD trait data\n",
145
+ "\n",
146
+ "def convert_age(value):\n",
147
+ " return None # Not used but included for completeness\n",
148
+ "\n",
149
+ "def convert_gender(value):\n",
150
+ " return None # Not used but included for completeness\n",
151
+ "\n",
152
+ "# 3. Save Metadata\n",
153
+ "# Determine trait data availability\n",
154
+ "is_trait_available = trait_row is not None # Will be False\n",
155
+ "\n",
156
+ "# Initial filtering validation\n",
157
+ "validate_and_save_cohort_info(\n",
158
+ " is_final=False,\n",
159
+ " cohort=cohort,\n",
160
+ " info_path=json_path,\n",
161
+ " is_gene_available=is_gene_available,\n",
162
+ " is_trait_available=is_trait_available\n",
163
+ ")\n",
164
+ "\n",
165
+ "# 4. Clinical Feature Extraction\n",
166
+ "# Skip this step as trait_row is None (no reliable COPD trait data available)\n",
167
+ "print(\"No COPD/emphysema trait data available for extraction.\")\n"
168
+ ]
169
+ },
170
+ {
171
+ "cell_type": "markdown",
172
+ "id": "d2e668b5",
173
+ "metadata": {},
174
+ "source": [
175
+ "### Step 3: Gene Data Extraction"
176
+ ]
177
+ },
178
+ {
179
+ "cell_type": "code",
180
+ "execution_count": 4,
181
+ "id": "42043d08",
182
+ "metadata": {
183
+ "execution": {
184
+ "iopub.execute_input": "2025-03-25T08:21:55.376353Z",
185
+ "iopub.status.busy": "2025-03-25T08:21:55.376243Z",
186
+ "iopub.status.idle": "2025-03-25T08:21:55.538484Z",
187
+ "shell.execute_reply": "2025-03-25T08:21:55.538109Z"
188
+ }
189
+ },
190
+ "outputs": [
191
+ {
192
+ "name": "stdout",
193
+ "output_type": "stream",
194
+ "text": [
195
+ "Matrix file found: ../../input/GEO/Chronic_obstructive_pulmonary_disease_(COPD)/GSE64593/GSE64593_series_matrix.txt.gz\n",
196
+ "Gene data shape: (54675, 34)\n",
197
+ "First 20 gene/probe identifiers:\n",
198
+ "Index(['1007_s_at', '1053_at', '117_at', '121_at', '1255_g_at', '1294_at',\n",
199
+ " '1316_at', '1320_at', '1405_i_at', '1431_at', '1438_at', '1487_at',\n",
200
+ " '1494_f_at', '1552256_a_at', '1552257_a_at', '1552258_at', '1552261_at',\n",
201
+ " '1552263_at', '1552264_a_at', '1552266_at'],\n",
202
+ " dtype='object', name='ID')\n"
203
+ ]
204
+ }
205
+ ],
206
+ "source": [
207
+ "# 1. Get the SOFT and matrix file paths again \n",
208
+ "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
209
+ "print(f\"Matrix file found: {matrix_file}\")\n",
210
+ "\n",
211
+ "# 2. Use the get_genetic_data function from the library to get the gene_data\n",
212
+ "try:\n",
213
+ " gene_data = get_genetic_data(matrix_file)\n",
214
+ " print(f\"Gene data shape: {gene_data.shape}\")\n",
215
+ " \n",
216
+ " # 3. Print the first 20 row IDs (gene or probe identifiers)\n",
217
+ " print(\"First 20 gene/probe identifiers:\")\n",
218
+ " print(gene_data.index[:20])\n",
219
+ "except Exception as e:\n",
220
+ " print(f\"Error extracting gene data: {e}\")\n"
221
+ ]
222
+ },
223
+ {
224
+ "cell_type": "markdown",
225
+ "id": "7cf0c5c8",
226
+ "metadata": {},
227
+ "source": [
228
+ "### Step 4: Gene Identifier Review"
229
+ ]
230
+ },
231
+ {
232
+ "cell_type": "code",
233
+ "execution_count": 5,
234
+ "id": "c9832ad8",
235
+ "metadata": {
236
+ "execution": {
237
+ "iopub.execute_input": "2025-03-25T08:21:55.539763Z",
238
+ "iopub.status.busy": "2025-03-25T08:21:55.539653Z",
239
+ "iopub.status.idle": "2025-03-25T08:21:55.541465Z",
240
+ "shell.execute_reply": "2025-03-25T08:21:55.541194Z"
241
+ }
242
+ },
243
+ "outputs": [],
244
+ "source": [
245
+ "# These identifiers like '1007_s_at', '1053_at', etc. are Affymetrix probe IDs\n",
246
+ "# They are not human gene symbols and need to be mapped to gene symbols\n",
247
+ "\n",
248
+ "requires_gene_mapping = True\n"
249
+ ]
250
+ },
251
+ {
252
+ "cell_type": "markdown",
253
+ "id": "2434e9f3",
254
+ "metadata": {},
255
+ "source": [
256
+ "### Step 5: Gene Annotation"
257
+ ]
258
+ },
259
+ {
260
+ "cell_type": "code",
261
+ "execution_count": 6,
262
+ "id": "b2354645",
263
+ "metadata": {
264
+ "execution": {
265
+ "iopub.execute_input": "2025-03-25T08:21:55.542535Z",
266
+ "iopub.status.busy": "2025-03-25T08:21:55.542438Z",
267
+ "iopub.status.idle": "2025-03-25T08:21:58.961088Z",
268
+ "shell.execute_reply": "2025-03-25T08:21:58.960751Z"
269
+ }
270
+ },
271
+ "outputs": [
272
+ {
273
+ "name": "stdout",
274
+ "output_type": "stream",
275
+ "text": [
276
+ "\n",
277
+ "Gene annotation preview:\n",
278
+ "Columns in gene annotation: ['ID', 'GB_ACC', 'SPOT_ID', 'Species Scientific Name', 'Annotation Date', 'Sequence Type', 'Sequence Source', 'Target Description', 'Representative Public ID', 'Gene Title', 'Gene Symbol', 'ENTREZ_GENE_ID', 'RefSeq Transcript ID', 'Gene Ontology Biological Process', 'Gene Ontology Cellular Component', 'Gene Ontology Molecular Function']\n",
279
+ "{'ID': ['1007_s_at', '1053_at', '117_at', '121_at', '1255_g_at'], 'GB_ACC': ['U48705', 'M87338', 'X51757', 'X69699', 'L36861'], 'SPOT_ID': [nan, nan, nan, nan, nan], 'Species Scientific Name': ['Homo sapiens', 'Homo sapiens', 'Homo sapiens', 'Homo sapiens', 'Homo sapiens'], 'Annotation Date': ['Oct 6, 2014', 'Oct 6, 2014', 'Oct 6, 2014', 'Oct 6, 2014', 'Oct 6, 2014'], 'Sequence Type': ['Exemplar sequence', 'Exemplar sequence', 'Exemplar sequence', 'Exemplar sequence', 'Exemplar sequence'], 'Sequence Source': ['Affymetrix Proprietary Database', 'GenBank', 'Affymetrix Proprietary Database', 'GenBank', 'Affymetrix Proprietary Database'], 'Target Description': ['U48705 /FEATURE=mRNA /DEFINITION=HSU48705 Human receptor tyrosine kinase DDR gene, complete cds', 'M87338 /FEATURE= /DEFINITION=HUMA1SBU Human replication factor C, 40-kDa subunit (A1) mRNA, complete cds', \"X51757 /FEATURE=cds /DEFINITION=HSP70B Human heat-shock protein HSP70B' gene\", 'X69699 /FEATURE= /DEFINITION=HSPAX8A H.sapiens Pax8 mRNA', 'L36861 /FEATURE=expanded_cds /DEFINITION=HUMGCAPB Homo sapiens guanylate cyclase activating protein (GCAP) gene exons 1-4, complete cds'], 'Representative Public ID': ['U48705', 'M87338', 'X51757', 'X69699', 'L36861'], 'Gene Title': ['discoidin domain receptor tyrosine kinase 1 /// microRNA 4640', 'replication factor C (activator 1) 2, 40kDa', \"heat shock 70kDa protein 6 (HSP70B')\", 'paired box 8', 'guanylate cyclase activator 1A (retina)'], 'Gene Symbol': ['DDR1 /// MIR4640', 'RFC2', 'HSPA6', 'PAX8', 'GUCA1A'], 'ENTREZ_GENE_ID': ['780 /// 100616237', '5982', '3310', '7849', '2978'], 'RefSeq Transcript ID': ['NM_001202521 /// NM_001202522 /// NM_001202523 /// NM_001954 /// NM_013993 /// NM_013994 /// NR_039783 /// XM_005249385 /// XM_005249386 /// XM_005249387 /// XM_005249389 /// XM_005272873 /// XM_005272874 /// XM_005272875 /// XM_005272877 /// XM_005275027 /// XM_005275028 /// XM_005275030 /// XM_005275031 /// XM_005275162 /// XM_005275163 /// XM_005275164 /// XM_005275166 /// XM_005275457 /// XM_005275458 /// XM_005275459 /// XM_005275461 /// XM_006715185 /// XM_006715186 /// XM_006715187 /// XM_006715188 /// XM_006715189 /// XM_006715190 /// XM_006725501 /// XM_006725502 /// XM_006725503 /// XM_006725504 /// XM_006725505 /// XM_006725506 /// XM_006725714 /// XM_006725715 /// XM_006725716 /// XM_006725717 /// XM_006725718 /// XM_006725719 /// XM_006725720 /// XM_006725721 /// XM_006725722 /// XM_006725827 /// XM_006725828 /// XM_006725829 /// XM_006725830 /// XM_006725831 /// XM_006725832 /// XM_006726017 /// XM_006726018 /// XM_006726019 /// XM_006726020 /// XM_006726021 /// XM_006726022 /// XR_427836 /// XR_430858 /// XR_430938 /// XR_430974 /// XR_431015', 'NM_001278791 /// NM_001278792 /// NM_001278793 /// NM_002914 /// NM_181471 /// XM_006716080', 'NM_002155', 'NM_003466 /// NM_013951 /// NM_013952 /// NM_013953 /// NM_013992', 'NM_000409 /// XM_006715073'], 'Gene Ontology Biological Process': ['0001558 // regulation of cell growth // inferred from electronic annotation /// 0001952 // regulation of cell-matrix adhesion // inferred from electronic annotation /// 0006468 // protein phosphorylation // inferred from electronic annotation /// 0007155 // cell adhesion // traceable author statement /// 0007169 // transmembrane receptor protein tyrosine kinase signaling pathway // inferred from electronic annotation /// 0007565 // female pregnancy // inferred from electronic annotation /// 0007566 // embryo implantation // inferred from electronic annotation /// 0007595 // lactation // inferred from electronic annotation /// 0008285 // negative regulation of cell proliferation // inferred from electronic annotation /// 0010715 // regulation of extracellular matrix disassembly // inferred from mutant phenotype /// 0014909 // smooth muscle cell migration // inferred from mutant phenotype /// 0016310 // phosphorylation // inferred from electronic annotation /// 0018108 // peptidyl-tyrosine phosphorylation // inferred from electronic annotation /// 0030198 // extracellular matrix organization // traceable author statement /// 0038063 // collagen-activated tyrosine kinase receptor signaling pathway // inferred from direct assay /// 0038063 // collagen-activated tyrosine kinase receptor signaling pathway // inferred from mutant phenotype /// 0038083 // peptidyl-tyrosine autophosphorylation // inferred from direct assay /// 0043583 // ear development // inferred from electronic annotation /// 0044319 // wound healing, spreading of cells // inferred from mutant phenotype /// 0046777 // protein autophosphorylation // inferred from direct assay /// 0060444 // branching involved in mammary gland duct morphogenesis // inferred from electronic annotation /// 0060749 // mammary gland alveolus development // inferred from electronic annotation /// 0061302 // smooth muscle cell-matrix adhesion // inferred from mutant phenotype', '0000278 // mitotic cell cycle // traceable author statement /// 0000722 // telomere maintenance via recombination // traceable author statement /// 0000723 // telomere maintenance // traceable author statement /// 0006260 // DNA replication // traceable author statement /// 0006271 // DNA strand elongation involved in DNA replication // traceable author statement /// 0006281 // DNA repair // traceable author statement /// 0006283 // transcription-coupled nucleotide-excision repair // traceable author statement /// 0006289 // nucleotide-excision repair // traceable author statement /// 0006297 // nucleotide-excision repair, DNA gap filling // traceable author statement /// 0015979 // photosynthesis // inferred from electronic annotation /// 0015995 // chlorophyll biosynthetic process // inferred from electronic annotation /// 0032201 // telomere maintenance via semi-conservative replication // traceable author statement', '0000902 // cell morphogenesis // inferred from electronic annotation /// 0006200 // ATP catabolic process // inferred from direct assay /// 0006950 // response to stress // inferred from electronic annotation /// 0006986 // response to unfolded protein // traceable author statement /// 0034605 // cellular response to heat // inferred from direct assay /// 0042026 // protein refolding // inferred from direct assay /// 0070370 // cellular heat acclimation // inferred from mutant phenotype', '0001655 // urogenital system development // inferred from sequence or structural similarity /// 0001656 // metanephros development // inferred from electronic annotation /// 0001658 // branching involved in ureteric bud morphogenesis // inferred from expression pattern /// 0001822 // kidney development // inferred from expression pattern /// 0001823 // mesonephros development // inferred from sequence or structural similarity /// 0003337 // mesenchymal to epithelial transition involved in metanephros morphogenesis // inferred from expression pattern /// 0006351 // transcription, DNA-templated // inferred from direct assay /// 0006355 // regulation of transcription, DNA-templated // inferred from electronic annotation /// 0007275 // multicellular organismal development // inferred from electronic annotation /// 0007417 // central nervous system development // inferred from expression pattern /// 0009653 // anatomical structure morphogenesis // traceable author statement /// 0030154 // cell differentiation // inferred from electronic annotation /// 0030878 // thyroid gland development // inferred from expression pattern /// 0030878 // thyroid gland development // inferred from mutant phenotype /// 0038194 // thyroid-stimulating hormone signaling pathway // traceable author statement /// 0039003 // pronephric field specification // inferred from sequence or structural similarity /// 0042472 // inner ear morphogenesis // inferred from sequence or structural similarity /// 0042981 // regulation of apoptotic process // inferred from sequence or structural similarity /// 0045893 // positive regulation of transcription, DNA-templated // inferred from direct assay /// 0045893 // positive regulation of transcription, DNA-templated // inferred from sequence or structural similarity /// 0045944 // positive regulation of transcription from RNA polymerase II promoter // inferred from direct assay /// 0048793 // pronephros development // inferred from sequence or structural similarity /// 0071371 // cellular response to gonadotropin stimulus // inferred from direct assay /// 0071599 // otic vesicle development // inferred from expression pattern /// 0072050 // S-shaped body morphogenesis // inferred from electronic annotation /// 0072073 // kidney epithelium development // inferred from electronic annotation /// 0072108 // positive regulation of mesenchymal to epithelial transition involved in metanephros morphogenesis // inferred from sequence or structural similarity /// 0072164 // mesonephric tubule development // inferred from electronic annotation /// 0072207 // metanephric epithelium development // inferred from expression pattern /// 0072221 // metanephric distal convoluted tubule development // inferred from sequence or structural similarity /// 0072278 // metanephric comma-shaped body morphogenesis // inferred from expression pattern /// 0072284 // metanephric S-shaped body morphogenesis // inferred from expression pattern /// 0072289 // metanephric nephron tubule formation // inferred from sequence or structural similarity /// 0072305 // negative regulation of mesenchymal cell apoptotic process involved in metanephric nephron morphogenesis // inferred from sequence or structural similarity /// 0072307 // regulation of metanephric nephron tubule epithelial cell differentiation // inferred from sequence or structural similarity /// 0090190 // positive regulation of branching involved in ureteric bud morphogenesis // inferred from sequence or structural similarity /// 1900212 // negative regulation of mesenchymal cell apoptotic process involved in metanephros development // inferred from sequence or structural similarity /// 1900215 // negative regulation of apoptotic process involved in metanephric collecting duct development // inferred from sequence or structural similarity /// 1900218 // negative regulation of apoptotic process involved in metanephric nephron tubule development // inferred from sequence or structural similarity /// 2000594 // positive regulation of metanephric DCT cell differentiation // inferred from sequence or structural similarity /// 2000611 // positive regulation of thyroid hormone generation // inferred from mutant phenotype /// 2000612 // regulation of thyroid-stimulating hormone secretion // inferred from mutant phenotype', '0007165 // signal transduction // non-traceable author statement /// 0007601 // visual perception // inferred from electronic annotation /// 0007602 // phototransduction // inferred from electronic annotation /// 0007603 // phototransduction, visible light // traceable author statement /// 0016056 // rhodopsin mediated signaling pathway // traceable author statement /// 0022400 // regulation of rhodopsin mediated signaling pathway // traceable author statement /// 0030828 // positive regulation of cGMP biosynthetic process // inferred from electronic annotation /// 0031282 // regulation of guanylate cyclase activity // inferred from electronic annotation /// 0031284 // positive regulation of guanylate cyclase activity // inferred from electronic annotation /// 0050896 // response to stimulus // inferred from electronic annotation'], 'Gene Ontology Cellular Component': ['0005576 // extracellular region // inferred from electronic annotation /// 0005615 // extracellular space // inferred from direct assay /// 0005886 // plasma membrane // traceable author statement /// 0005887 // integral component of plasma membrane // traceable author statement /// 0016020 // membrane // inferred from electronic annotation /// 0016021 // integral component of membrane // inferred from electronic annotation /// 0043235 // receptor complex // inferred from direct assay /// 0070062 // extracellular vesicular exosome // inferred from direct assay', '0005634 // nucleus // inferred from electronic annotation /// 0005654 // nucleoplasm // traceable author statement /// 0005663 // DNA replication factor C complex // inferred from direct assay', '0005737 // cytoplasm // inferred from direct assay /// 0005814 // centriole // inferred from direct assay /// 0005829 // cytosol // inferred from direct assay /// 0008180 // COP9 signalosome // inferred from direct assay /// 0070062 // extracellular vesicular exosome // inferred from direct assay /// 0072562 // blood microparticle // inferred from direct assay', '0005634 // nucleus // inferred from direct assay /// 0005654 // nucleoplasm // inferred from sequence or structural similarity /// 0005730 // nucleolus // inferred from direct assay', '0001750 // photoreceptor outer segment // inferred from electronic annotation /// 0001917 // photoreceptor inner segment // inferred from electronic annotation /// 0005578 // proteinaceous extracellular matrix // inferred from electronic annotation /// 0005886 // plasma membrane // inferred from direct assay /// 0016020 // membrane // inferred from electronic annotation /// 0097381 // photoreceptor disc membrane // traceable author statement'], 'Gene Ontology Molecular Function': ['0000166 // nucleotide binding // inferred from electronic annotation /// 0004672 // protein kinase activity // inferred from electronic annotation /// 0004713 // protein tyrosine kinase activity // inferred from electronic annotation /// 0004714 // transmembrane receptor protein tyrosine kinase activity // traceable author statement /// 0005515 // protein binding // inferred from physical interaction /// 0005518 // collagen binding // inferred from direct assay /// 0005518 // collagen binding // inferred from mutant phenotype /// 0005524 // ATP binding // inferred from electronic annotation /// 0016301 // kinase activity // inferred from electronic annotation /// 0016740 // transferase activity // inferred from electronic annotation /// 0016772 // transferase activity, transferring phosphorus-containing groups // inferred from electronic annotation /// 0038062 // protein tyrosine kinase collagen receptor activity // inferred from direct assay /// 0046872 // metal ion binding // inferred from electronic annotation', '0000166 // nucleotide binding // inferred from electronic annotation /// 0003677 // DNA binding // inferred from electronic annotation /// 0005515 // protein binding // inferred from physical interaction /// 0005524 // ATP binding // inferred from electronic annotation /// 0016851 // magnesium chelatase activity // inferred from electronic annotation /// 0017111 // nucleoside-triphosphatase activity // inferred from electronic annotation', '0000166 // nucleotide binding // inferred from electronic annotation /// 0005524 // ATP binding // inferred from electronic annotation /// 0019899 // enzyme binding // inferred from physical interaction /// 0031072 // heat shock protein binding // inferred from physical interaction /// 0042623 // ATPase activity, coupled // inferred from direct assay /// 0051082 // unfolded protein binding // inferred from direct assay', '0000979 // RNA polymerase II core promoter sequence-specific DNA binding // inferred from direct assay /// 0003677 // DNA binding // inferred from direct assay /// 0003677 // DNA binding // inferred from mutant phenotype /// 0003700 // sequence-specific DNA binding transcription factor activity // inferred from direct assay /// 0004996 // thyroid-stimulating hormone receptor activity // traceable author statement /// 0005515 // protein binding // inferred from physical interaction /// 0044212 // transcription regulatory region DNA binding // inferred from direct assay', '0005509 // calcium ion binding // inferred from electronic annotation /// 0008048 // calcium sensitive guanylate cyclase activator activity // inferred from electronic annotation /// 0030249 // guanylate cyclase regulator activity // inferred from electronic annotation /// 0046872 // metal ion binding // inferred from electronic annotation']}\n",
280
+ "\n",
281
+ "Searching for platform information in SOFT file:\n",
282
+ "!Series_platform_id = GPL570\n",
283
+ "\n",
284
+ "Searching for gene symbol information in SOFT file:\n",
285
+ "Found references to gene symbols:\n",
286
+ "!Platform_relation = Alternative to: GPL19918 (Gene symbol version, 10K)\n",
287
+ "!Platform_relation = Alternative to: GPL20182 (Gene Symbol Version)\n",
288
+ "#Gene Symbol = A gene symbol, when one is available (from UniGene).\n",
289
+ "ID\tGB_ACC\tSPOT_ID\tSpecies Scientific Name\tAnnotation Date\tSequence Type\tSequence Source\tTarget Description\tRepresentative Public ID\tGene Title\tGene Symbol\tENTREZ_GENE_ID\tRefSeq Transcript ID\tGene Ontology Biological Process\tGene Ontology Cellular Component\tGene Ontology Molecular Function\n",
290
+ "\n",
291
+ "Checking for additional annotation files in the directory:\n",
292
+ "[]\n"
293
+ ]
294
+ }
295
+ ],
296
+ "source": [
297
+ "# 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.\n",
298
+ "gene_annotation = get_gene_annotation(soft_file)\n",
299
+ "\n",
300
+ "# 2. Analyze the gene annotation dataframe to identify which columns contain the gene identifiers and gene symbols\n",
301
+ "print(\"\\nGene annotation preview:\")\n",
302
+ "print(f\"Columns in gene annotation: {gene_annotation.columns.tolist()}\")\n",
303
+ "print(preview_df(gene_annotation, n=5))\n",
304
+ "\n",
305
+ "# Let's look for platform information in the SOFT file to understand the annotation better\n",
306
+ "print(\"\\nSearching for platform information in SOFT file:\")\n",
307
+ "with gzip.open(soft_file, 'rt') as f:\n",
308
+ " for i, line in enumerate(f):\n",
309
+ " if '!Series_platform_id' in line:\n",
310
+ " print(line.strip())\n",
311
+ " break\n",
312
+ " if i > 100: # Limit search to first 100 lines\n",
313
+ " print(\"Platform ID not found in first 100 lines\")\n",
314
+ " break\n",
315
+ "\n",
316
+ "# Check if the SOFT file includes any reference to gene symbols\n",
317
+ "print(\"\\nSearching for gene symbol information in SOFT file:\")\n",
318
+ "with gzip.open(soft_file, 'rt') as f:\n",
319
+ " gene_symbol_lines = []\n",
320
+ " for i, line in enumerate(f):\n",
321
+ " if 'GENE_SYMBOL' in line or 'gene_symbol' in line.lower() or 'symbol' in line.lower():\n",
322
+ " gene_symbol_lines.append(line.strip())\n",
323
+ " if i > 1000 and len(gene_symbol_lines) > 0: # Limit search but ensure we found something\n",
324
+ " break\n",
325
+ " \n",
326
+ " if gene_symbol_lines:\n",
327
+ " print(\"Found references to gene symbols:\")\n",
328
+ " for line in gene_symbol_lines[:5]: # Show just first 5 matches\n",
329
+ " print(line)\n",
330
+ " else:\n",
331
+ " print(\"No explicit gene symbol references found in first 1000 lines\")\n",
332
+ "\n",
333
+ "# Look for alternative annotation files or references in the directory\n",
334
+ "print(\"\\nChecking for additional annotation files in the directory:\")\n",
335
+ "all_files = os.listdir(in_cohort_dir)\n",
336
+ "print([f for f in all_files if 'annotation' in f.lower() or 'platform' in f.lower() or 'gpl' in f.lower()])\n"
337
+ ]
338
+ },
339
+ {
340
+ "cell_type": "markdown",
341
+ "id": "2dac0b60",
342
+ "metadata": {},
343
+ "source": [
344
+ "### Step 6: Gene Identifier Mapping"
345
+ ]
346
+ },
347
+ {
348
+ "cell_type": "code",
349
+ "execution_count": 7,
350
+ "id": "92605ae1",
351
+ "metadata": {
352
+ "execution": {
353
+ "iopub.execute_input": "2025-03-25T08:21:58.962389Z",
354
+ "iopub.status.busy": "2025-03-25T08:21:58.962272Z",
355
+ "iopub.status.idle": "2025-03-25T08:21:59.167825Z",
356
+ "shell.execute_reply": "2025-03-25T08:21:59.167507Z"
357
+ }
358
+ },
359
+ "outputs": [
360
+ {
361
+ "name": "stdout",
362
+ "output_type": "stream",
363
+ "text": [
364
+ "Gene mapping dataframe shape: (45782, 2)\n",
365
+ "Sample of gene mapping:\n",
366
+ " ID Gene\n",
367
+ "0 1007_s_at DDR1 /// MIR4640\n",
368
+ "1 1053_at RFC2\n",
369
+ "2 117_at HSPA6\n",
370
+ "3 121_at PAX8\n",
371
+ "4 1255_g_at GUCA1A\n"
372
+ ]
373
+ },
374
+ {
375
+ "name": "stdout",
376
+ "output_type": "stream",
377
+ "text": [
378
+ "Gene expression data shape after mapping: (21278, 34)\n",
379
+ "Sample of gene expression data:\n",
380
+ " GSM1575085 GSM1575086 GSM1575087 GSM1575088 GSM1575089 \\\n",
381
+ "Gene \n",
382
+ "A1BG 92.13980 87.1394 136.8800 169.79900 149.5720 \n",
383
+ "A1BG-AS1 79.08870 29.9709 26.5951 97.24380 10.3971 \n",
384
+ "A1CF 65.27392 146.8920 157.2644 117.82857 98.7029 \n",
385
+ "A2M 5640.59000 10535.9921 5956.3960 4601.38610 10920.6929 \n",
386
+ "A2M-AS1 95.51210 66.9938 72.5051 78.37100 102.9160 \n",
387
+ "\n",
388
+ " GSM1575090 GSM1575091 GSM1575092 GSM1575093 GSM1575094 ... \\\n",
389
+ "Gene ... \n",
390
+ "A1BG 137.5130 110.3330 180.97400 198.45200 292.8590 ... \n",
391
+ "A1BG-AS1 86.5203 100.2560 14.18130 20.68470 98.5018 ... \n",
392
+ "A1CF 93.7718 174.4951 122.40554 38.26969 186.8891 ... \n",
393
+ "A2M 2494.5275 8309.0367 4087.66620 19431.86100 1693.5690 ... \n",
394
+ "A2M-AS1 68.8274 51.4439 66.17640 63.74770 179.6830 ... \n",
395
+ "\n",
396
+ " GSM1575109 GSM1575110 GSM1575111 GSM1575112 GSM1575113 \\\n",
397
+ "Gene \n",
398
+ "A1BG 153.24700 321.1850 132.0920 202.59000 164.71600 \n",
399
+ "A1BG-AS1 44.13270 4.8377 27.0553 143.29600 125.52800 \n",
400
+ "A1CF 80.53890 84.5798 36.5748 88.72113 106.35991 \n",
401
+ "A2M 5912.15264 3208.1601 14937.8089 5214.23420 2478.62510 \n",
402
+ "A2M-AS1 161.38500 141.2550 74.8281 73.06360 158.03000 \n",
403
+ "\n",
404
+ " GSM1575114 GSM1575115 GSM1575116 GSM1575117 GSM1575118 \n",
405
+ "Gene \n",
406
+ "A1BG 188.7050 169.86000 144.15400 196.4090 189.3030 \n",
407
+ "A1BG-AS1 17.7108 67.09200 18.29160 17.2501 14.6572 \n",
408
+ "A1CF 163.9334 149.91933 283.41040 208.1441 136.5545 \n",
409
+ "A2M 6350.7761 1336.01740 2184.26181 3854.5369 1826.5803 \n",
410
+ "A2M-AS1 81.9210 51.26120 77.60570 75.1390 58.2430 \n",
411
+ "\n",
412
+ "[5 rows x 34 columns]\n",
413
+ "Number of unique genes after mapping: 21278\n"
414
+ ]
415
+ }
416
+ ],
417
+ "source": [
418
+ "# 1. Identify which columns contain the gene identifiers and gene symbols\n",
419
+ "# The column 'ID' in gene_annotation contains identifiers that match the gene expression data index\n",
420
+ "# The column 'Gene Symbol' contains the gene symbols we need to map to\n",
421
+ "prob_col = 'ID'\n",
422
+ "gene_col = 'Gene Symbol'\n",
423
+ "\n",
424
+ "# 2. Extract the mapping dataframe using the get_gene_mapping function\n",
425
+ "gene_mapping = get_gene_mapping(gene_annotation, prob_col, gene_col)\n",
426
+ "print(f\"Gene mapping dataframe shape: {gene_mapping.shape}\")\n",
427
+ "print(\"Sample of gene mapping:\")\n",
428
+ "print(gene_mapping.head())\n",
429
+ "\n",
430
+ "# 3. Apply the gene mapping to convert probe-level measurements to gene expression data\n",
431
+ "gene_data = apply_gene_mapping(gene_data, gene_mapping)\n",
432
+ "print(f\"Gene expression data shape after mapping: {gene_data.shape}\")\n",
433
+ "print(\"Sample of gene expression data:\")\n",
434
+ "print(gene_data.head())\n",
435
+ "\n",
436
+ "# Check how many unique genes we have after mapping\n",
437
+ "print(f\"Number of unique genes after mapping: {len(gene_data.index)}\")\n"
438
+ ]
439
+ },
440
+ {
441
+ "cell_type": "markdown",
442
+ "id": "ceb0ed36",
443
+ "metadata": {},
444
+ "source": [
445
+ "### Step 7: Data Normalization and Linking"
446
+ ]
447
+ },
448
+ {
449
+ "cell_type": "code",
450
+ "execution_count": 8,
451
+ "id": "a4949585",
452
+ "metadata": {
453
+ "execution": {
454
+ "iopub.execute_input": "2025-03-25T08:21:59.169152Z",
455
+ "iopub.status.busy": "2025-03-25T08:21:59.169049Z",
456
+ "iopub.status.idle": "2025-03-25T08:21:59.594809Z",
457
+ "shell.execute_reply": "2025-03-25T08:21:59.594444Z"
458
+ }
459
+ },
460
+ "outputs": [
461
+ {
462
+ "name": "stdout",
463
+ "output_type": "stream",
464
+ "text": [
465
+ "Gene data shape after normalization: (19845, 34)\n"
466
+ ]
467
+ },
468
+ {
469
+ "name": "stdout",
470
+ "output_type": "stream",
471
+ "text": [
472
+ "Gene data saved to ../../output/preprocess/Chronic_obstructive_pulmonary_disease_(COPD)/gene_data/GSE64593.csv\n",
473
+ "\n",
474
+ "No COPD trait data available for this cohort.\n",
475
+ "Dataset usability status: Not usable\n",
476
+ "Dataset deemed not usable for COPD analysis due to missing trait data - linked data not created\n"
477
+ ]
478
+ }
479
+ ],
480
+ "source": [
481
+ "# 1. Normalize gene symbols in the gene expression data\n",
482
+ "try:\n",
483
+ " normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n",
484
+ " print(f\"Gene data shape after normalization: {normalized_gene_data.shape}\")\n",
485
+ " \n",
486
+ " # Save normalized gene data\n",
487
+ " os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
488
+ " normalized_gene_data.to_csv(out_gene_data_file)\n",
489
+ " print(f\"Gene data saved to {out_gene_data_file}\")\n",
490
+ "except Exception as e:\n",
491
+ " print(f\"Error during gene symbol normalization: {e}\")\n",
492
+ " normalized_gene_data = gene_data\n",
493
+ " print(\"Using original gene data (without normalization).\")\n",
494
+ "\n",
495
+ "# 2. Since we identified in step 2 that there's no COPD trait information available,\n",
496
+ "# we cannot create clinical features or link the data\n",
497
+ "print(\"\\nNo COPD trait data available for this cohort.\")\n",
498
+ "\n",
499
+ "# 3. Conduct initial validation since we can't do final validation without trait data\n",
500
+ "is_usable = validate_and_save_cohort_info(\n",
501
+ " is_final=False, # Use initial validation when trait data is unavailable\n",
502
+ " cohort=cohort,\n",
503
+ " info_path=json_path,\n",
504
+ " is_gene_available=True,\n",
505
+ " is_trait_available=False # We determined there's no COPD trait data in step 2\n",
506
+ ")\n",
507
+ "\n",
508
+ "print(f\"Dataset usability status: {'Usable' if is_usable else 'Not usable'}\")\n",
509
+ "print(\"Dataset deemed not usable for COPD analysis due to missing trait data - linked data not created\")"
510
+ ]
511
+ }
512
+ ],
513
+ "metadata": {
514
+ "language_info": {
515
+ "codemirror_mode": {
516
+ "name": "ipython",
517
+ "version": 3
518
+ },
519
+ "file_extension": ".py",
520
+ "mimetype": "text/x-python",
521
+ "name": "python",
522
+ "nbconvert_exporter": "python",
523
+ "pygments_lexer": "ipython3",
524
+ "version": "3.10.16"
525
+ }
526
+ },
527
+ "nbformat": 4,
528
+ "nbformat_minor": 5
529
+ }
code/Chronic_obstructive_pulmonary_disease_(COPD)/GSE84046.ipynb ADDED
@@ -0,0 +1,584 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": 1,
6
+ "id": "88f7fb0f",
7
+ "metadata": {
8
+ "execution": {
9
+ "iopub.execute_input": "2025-03-25T08:22:06.112362Z",
10
+ "iopub.status.busy": "2025-03-25T08:22:06.112165Z",
11
+ "iopub.status.idle": "2025-03-25T08:22:06.279887Z",
12
+ "shell.execute_reply": "2025-03-25T08:22:06.279493Z"
13
+ }
14
+ },
15
+ "outputs": [],
16
+ "source": [
17
+ "import sys\n",
18
+ "import os\n",
19
+ "sys.path.append(os.path.abspath(os.path.join(os.getcwd(), '../..')))\n",
20
+ "\n",
21
+ "# Path Configuration\n",
22
+ "from tools.preprocess import *\n",
23
+ "\n",
24
+ "# Processing context\n",
25
+ "trait = \"Chronic_obstructive_pulmonary_disease_(COPD)\"\n",
26
+ "cohort = \"GSE84046\"\n",
27
+ "\n",
28
+ "# Input paths\n",
29
+ "in_trait_dir = \"../../input/GEO/Chronic_obstructive_pulmonary_disease_(COPD)\"\n",
30
+ "in_cohort_dir = \"../../input/GEO/Chronic_obstructive_pulmonary_disease_(COPD)/GSE84046\"\n",
31
+ "\n",
32
+ "# Output paths\n",
33
+ "out_data_file = \"../../output/preprocess/Chronic_obstructive_pulmonary_disease_(COPD)/GSE84046.csv\"\n",
34
+ "out_gene_data_file = \"../../output/preprocess/Chronic_obstructive_pulmonary_disease_(COPD)/gene_data/GSE84046.csv\"\n",
35
+ "out_clinical_data_file = \"../../output/preprocess/Chronic_obstructive_pulmonary_disease_(COPD)/clinical_data/GSE84046.csv\"\n",
36
+ "json_path = \"../../output/preprocess/Chronic_obstructive_pulmonary_disease_(COPD)/cohort_info.json\"\n"
37
+ ]
38
+ },
39
+ {
40
+ "cell_type": "markdown",
41
+ "id": "bd9fc991",
42
+ "metadata": {},
43
+ "source": [
44
+ "### Step 1: Initial Data Loading"
45
+ ]
46
+ },
47
+ {
48
+ "cell_type": "code",
49
+ "execution_count": 2,
50
+ "id": "8c4af887",
51
+ "metadata": {
52
+ "execution": {
53
+ "iopub.execute_input": "2025-03-25T08:22:06.281211Z",
54
+ "iopub.status.busy": "2025-03-25T08:22:06.281061Z",
55
+ "iopub.status.idle": "2025-03-25T08:22:06.401410Z",
56
+ "shell.execute_reply": "2025-03-25T08:22:06.401073Z"
57
+ }
58
+ },
59
+ "outputs": [
60
+ {
61
+ "name": "stdout",
62
+ "output_type": "stream",
63
+ "text": [
64
+ "Background Information:\n",
65
+ "!Series_title\t\"The impact of protein quantity during energy restriction on genome-wide gene expression analysis in human adipose tissue\"\n",
66
+ "!Series_summary\t\"Overweight is a growing health problem worldwide. The most effective strategy to reduce weight is energy restriction (ER): restriction of food intake without malnutrition. ER has been shown to be beneficial in disease prevention, healthy aging, and inflammation. Recent studies suggest that reducing the protein content of a diet contributes to the beneficial effects by ER. The first objective of our study was to assess the effect of energy restriction on changes in gene expression in adipose tissue. Secondly, the changes in gene expression were compared between a high protein diet and a normal protein diet during energy restriction. In a parallel double-blinded study, overweight older subjects adhered to a 25% ER diet, either combined with high protein intake (HP-ER, 1.7 g/kg per day), or with normal protein intake (NP-ER, 0.9 g/kg per day) for 12 weeks. From 10 HP-ER subjects and 12 NP-ER subjects subcutaneous adipose tissue biopsies were collected before and after the diet. Adipose tissue was used to isolate total RNA and to evaluate whole genome gene expression changes upon a HP-ER and NP-ER diet. Upon 25% ER, clusters of gene sets in energy metabolism, such as lipid metabolism and PPARα targets, NRF2 targets, glucose metabolism, and TCA cycle, as well as gene sets in oxidative phosphorylation, adaptive immune response, immune cell infiltration, and cell cycle were decreased, and RNA translation and processing gene sets were increased. A different gene expression response between HP-ER and NP-ER was observed for 530 genes. Pathway analysis revealed that after NP-ER a downregulation in expression of genes involved in adaptive immune response was present. HP-ER resulted in an upregulation of pathways involved in cell cycle, GPCR signalling, olfactory signalling and nitrogen metabolism. Based on the gene expression changes, we concluded that HP seems to be less beneficial for ER’s effect on immune-related gene expression in adipose tissue.\"\n",
67
+ "!Series_overall_design\t\"In a parallel double-blinded study, overweight middle-aged subjects adhered to a 25% ER diet, either combined with high protein (HP-ER, 1.5 g/kg-bw/d), or with standard protein (SP-ER, 0.8 g/kg-bw/d) for 12 weeks. From 10 HP-ER subjects and 12 SP-ER subjects subcutaneous adipose tissue biopsies were collected before and after the diet. Adipose tissue was used to isolate total RNA and to evaluate whole genome gene expression changes upon a HP-ER and SP-ER diet.\"\n",
68
+ "Sample Characteristics Dictionary:\n",
69
+ "{0: ['subjectid: 6053', 'subjectid: 6076', 'subjectid: 6039', 'subjectid: 6054', 'subjectid: 6077', 'subjectid: 6044', 'subjectid: 6055', 'subjectid: 6078', 'subjectid: 6064', 'subjectid: 6080', 'subjectid: 6084', 'subjectid: 6107', 'subjectid: 6124', 'subjectid: 6086', 'subjectid: 6108', 'subjectid: 6129', 'subjectid: 6087', 'subjectid: 6112', 'subjectid: 6012', 'subjectid: 6092', 'subjectid: 6121', 'subjectid: 6047'], 1: ['protein content restricted diet: high', 'protein content restricted diet: normal'], 2: ['time of sampling (before/after): before', 'time of sampling (before/after): after'], 3: ['time of sampling (wk): t=0 (baseline)', 'time of sampling (wk): t=12'], 4: ['sexe: Male', 'sexe: Female'], 5: ['date of birth (dd-mm-yyyy): 1952-06-17', 'date of birth (dd-mm-yyyy): 1944-12-11', 'date of birth (dd-mm-yyyy): 1955-07-23', 'date of birth (dd-mm-yyyy): 1947-11-29', 'date of birth (dd-mm-yyyy): 1944-07-19', 'date of birth (dd-mm-yyyy): 1943-02-09', 'date of birth (dd-mm-yyyy): 1952-07-07', 'date of birth (dd-mm-yyyy): 1954-06-07', 'date of birth (dd-mm-yyyy): 1944-03-17', 'date of birth (dd-mm-yyyy): 1951-03-09', 'date of birth (dd-mm-yyyy): 1953-10-01', 'date of birth (dd-mm-yyyy): 1952-12-04', 'date of birth (dd-mm-yyyy): 1944-02-01', 'date of birth (dd-mm-yyyy): 1955-04-30', 'date of birth (dd-mm-yyyy): 1946-03-25', 'date of birth (dd-mm-yyyy): 1954-12-12', 'date of birth (dd-mm-yyyy): 1954-05-04', 'date of birth (dd-mm-yyyy): 1946-06-04', 'date of birth (dd-mm-yyyy): 1947-07-14', 'date of birth (dd-mm-yyyy): 1952-09-30', 'date of birth (dd-mm-yyyy): 1946-12-13', 'date of birth (dd-mm-yyyy): 1953-04-25'], 6: ['screening bmi (kg/m2): 30.0', 'screening bmi (kg/m2): 30.3', 'screening bmi (kg/m2): 32.4', 'screening bmi (kg/m2): 29.2', 'screening bmi (kg/m2): 34.7', 'screening bmi (kg/m2): 33.0', 'screening bmi (kg/m2): 27.6', 'screening bmi (kg/m2): 33.1', 'screening bmi (kg/m2): 30.4', 'screening bmi (kg/m2): 30.5', 'screening bmi (kg/m2): 28.4', 'screening bmi (kg/m2): 28.9', 'screening bmi (kg/m2): 29.7', 'screening bmi (kg/m2): 28.8', 'screening bmi (kg/m2): 29.8', 'screening bmi (kg/m2): 35.2', 'screening bmi (kg/m2): 30.6', 'screening bmi (kg/m2): 28.2', 'screening bmi (kg/m2): 34.8'], 7: ['screening body fat percentage (fm): 32.9', 'screening body fat percentage (fm): 31.8', 'screening body fat percentage (fm): 46.8', 'screening body fat percentage (fm): 37.1', 'screening body fat percentage (fm): 28.2', 'screening body fat percentage (fm): 25.6', 'screening body fat percentage (fm): 31.5', 'screening body fat percentage (fm): 48.1', 'screening body fat percentage (fm): 32.1', 'screening body fat percentage (fm): 30.2', 'screening body fat percentage (fm): 29.4', 'screening body fat percentage (fm): 45', 'screening body fat percentage (fm): 32.2', 'screening body fat percentage (fm): 31.2', 'screening body fat percentage (fm): 48', 'screening body fat percentage (fm): 30.7', 'screening body fat percentage (fm): 47.3', 'screening body fat percentage (fm): 42.1', 'screening body fat percentage (fm): 46.7', 'screening body fat percentage (fm): 34.2'], 8: ['screening glucose (mmol/l): 6.28', 'screening glucose (mmol/l): 6.95', 'screening glucose (mmol/l): 6.34', 'screening glucose (mmol/l): 5.45', 'screening glucose (mmol/l): 5.67', 'screening glucose (mmol/l): 7.62', 'screening glucose (mmol/l): 5.78', 'screening glucose (mmol/l): 5.95', 'screening glucose (mmol/l): 6.23', 'screening glucose (mmol/l): 5.89', 'screening glucose (mmol/l): 5.62', 'screening glucose (mmol/l): 5.56', 'screening glucose (mmol/l): 6.56', 'screening glucose (mmol/l): 5.00', 'screening glucose (mmol/l): 5.50', 'screening glucose (mmol/l): 5.84']}\n"
70
+ ]
71
+ }
72
+ ],
73
+ "source": [
74
+ "from tools.preprocess import *\n",
75
+ "# 1. Identify the paths to the SOFT file and the matrix file\n",
76
+ "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
77
+ "\n",
78
+ "# 2. Read the matrix file to obtain background information and sample characteristics data\n",
79
+ "background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']\n",
80
+ "clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']\n",
81
+ "background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)\n",
82
+ "\n",
83
+ "# 3. Obtain the sample characteristics dictionary from the clinical dataframe\n",
84
+ "sample_characteristics_dict = get_unique_values_by_row(clinical_data)\n",
85
+ "\n",
86
+ "# 4. Explicitly print out all the background information and the sample characteristics dictionary\n",
87
+ "print(\"Background Information:\")\n",
88
+ "print(background_info)\n",
89
+ "print(\"Sample Characteristics Dictionary:\")\n",
90
+ "print(sample_characteristics_dict)\n"
91
+ ]
92
+ },
93
+ {
94
+ "cell_type": "markdown",
95
+ "id": "44c2c984",
96
+ "metadata": {},
97
+ "source": [
98
+ "### Step 2: Dataset Analysis and Clinical Feature Extraction"
99
+ ]
100
+ },
101
+ {
102
+ "cell_type": "code",
103
+ "execution_count": 3,
104
+ "id": "1e3a12f8",
105
+ "metadata": {
106
+ "execution": {
107
+ "iopub.execute_input": "2025-03-25T08:22:06.402809Z",
108
+ "iopub.status.busy": "2025-03-25T08:22:06.402691Z",
109
+ "iopub.status.idle": "2025-03-25T08:22:06.409092Z",
110
+ "shell.execute_reply": "2025-03-25T08:22:06.408764Z"
111
+ }
112
+ },
113
+ "outputs": [
114
+ {
115
+ "data": {
116
+ "text/plain": [
117
+ "False"
118
+ ]
119
+ },
120
+ "execution_count": 3,
121
+ "metadata": {},
122
+ "output_type": "execute_result"
123
+ }
124
+ ],
125
+ "source": [
126
+ "# Review data availability and determine preprocessing approach\n",
127
+ "\n",
128
+ "# 1. Gene Expression Data Availability\n",
129
+ "# Based on the background information, this study conducts genome-wide gene \n",
130
+ "# expression analysis on adipose tissue\n",
131
+ "is_gene_available = True # This is gene expression data, not just miRNA or methylation\n",
132
+ "\n",
133
+ "# 2. Variable Availability and Data Type Conversion\n",
134
+ "\n",
135
+ "# 2.1 Trait (COPD) Availability\n",
136
+ "# This study is about protein content in diet during energy restriction\n",
137
+ "# Not related to COPD, so trait data is not available\n",
138
+ "trait_row = None\n",
139
+ "\n",
140
+ "# 2.2 Gender Availability\n",
141
+ "# Gender is available in row 4, labeled as 'sexe'\n",
142
+ "gender_row = 4\n",
143
+ "\n",
144
+ "def convert_gender(value):\n",
145
+ " if value is None:\n",
146
+ " return None\n",
147
+ " if ':' in value:\n",
148
+ " value = value.split(': ')[1].strip()\n",
149
+ " if value.lower() == 'female':\n",
150
+ " return 0\n",
151
+ " elif value.lower() == 'male':\n",
152
+ " return 1\n",
153
+ " return None\n",
154
+ "\n",
155
+ "# 2.3 Age Availability\n",
156
+ "# Age is not directly given but can be inferred from date of birth in row 5\n",
157
+ "age_row = 5\n",
158
+ "\n",
159
+ "def convert_age(value):\n",
160
+ " if value is None:\n",
161
+ " return None\n",
162
+ " if ':' in value:\n",
163
+ " value = value.split(': ')[1].strip()\n",
164
+ " \n",
165
+ " # Extract birth year from format \"date of birth (dd-mm-yyyy): YYYY-MM-DD\"\n",
166
+ " if '-' in value:\n",
167
+ " try:\n",
168
+ " birth_year = int(value.split('-')[0])\n",
169
+ " # Assuming study was conducted around 2014 (based on context)\n",
170
+ " # Most people in study are from 1940s-1950s which would make them ~60-70 years old\n",
171
+ " study_year = 2014\n",
172
+ " age = study_year - birth_year\n",
173
+ " return age\n",
174
+ " except:\n",
175
+ " return None\n",
176
+ " return None\n",
177
+ "\n",
178
+ "# No conversion function for trait since it's not available\n",
179
+ "def convert_trait(value):\n",
180
+ " return None\n",
181
+ "\n",
182
+ "# 3. Save Metadata - Initial filtering\n",
183
+ "is_trait_available = trait_row is not None\n",
184
+ "validate_and_save_cohort_info(\n",
185
+ " is_final=False,\n",
186
+ " cohort=cohort,\n",
187
+ " info_path=json_path,\n",
188
+ " is_gene_available=is_gene_available,\n",
189
+ " is_trait_available=is_trait_available\n",
190
+ ")\n",
191
+ "\n",
192
+ "# 4. Skip clinical feature extraction since trait data is not available\n",
193
+ "# The function will return False since is_trait_available is False\n"
194
+ ]
195
+ },
196
+ {
197
+ "cell_type": "markdown",
198
+ "id": "5334e93f",
199
+ "metadata": {},
200
+ "source": [
201
+ "### Step 3: Gene Data Extraction"
202
+ ]
203
+ },
204
+ {
205
+ "cell_type": "code",
206
+ "execution_count": 4,
207
+ "id": "59d1b1b5",
208
+ "metadata": {
209
+ "execution": {
210
+ "iopub.execute_input": "2025-03-25T08:22:06.410413Z",
211
+ "iopub.status.busy": "2025-03-25T08:22:06.410299Z",
212
+ "iopub.status.idle": "2025-03-25T08:22:06.581269Z",
213
+ "shell.execute_reply": "2025-03-25T08:22:06.580897Z"
214
+ }
215
+ },
216
+ "outputs": [
217
+ {
218
+ "name": "stdout",
219
+ "output_type": "stream",
220
+ "text": [
221
+ "Matrix file found: ../../input/GEO/Chronic_obstructive_pulmonary_disease_(COPD)/GSE84046/GSE84046_series_matrix.txt.gz\n",
222
+ "Gene data shape: (33297, 44)\n",
223
+ "First 20 gene/probe identifiers:\n",
224
+ "Index(['7892501', '7892502', '7892503', '7892504', '7892505', '7892506',\n",
225
+ " '7892507', '7892508', '7892509', '7892510', '7892511', '7892512',\n",
226
+ " '7892513', '7892514', '7892515', '7892516', '7892517', '7892518',\n",
227
+ " '7892519', '7892520'],\n",
228
+ " dtype='object', name='ID')\n"
229
+ ]
230
+ }
231
+ ],
232
+ "source": [
233
+ "# 1. Get the SOFT and matrix file paths again \n",
234
+ "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
235
+ "print(f\"Matrix file found: {matrix_file}\")\n",
236
+ "\n",
237
+ "# 2. Use the get_genetic_data function from the library to get the gene_data\n",
238
+ "try:\n",
239
+ " gene_data = get_genetic_data(matrix_file)\n",
240
+ " print(f\"Gene data shape: {gene_data.shape}\")\n",
241
+ " \n",
242
+ " # 3. Print the first 20 row IDs (gene or probe identifiers)\n",
243
+ " print(\"First 20 gene/probe identifiers:\")\n",
244
+ " print(gene_data.index[:20])\n",
245
+ "except Exception as e:\n",
246
+ " print(f\"Error extracting gene data: {e}\")\n"
247
+ ]
248
+ },
249
+ {
250
+ "cell_type": "markdown",
251
+ "id": "b27a093b",
252
+ "metadata": {},
253
+ "source": [
254
+ "### Step 4: Gene Identifier Review"
255
+ ]
256
+ },
257
+ {
258
+ "cell_type": "code",
259
+ "execution_count": 5,
260
+ "id": "95605f74",
261
+ "metadata": {
262
+ "execution": {
263
+ "iopub.execute_input": "2025-03-25T08:22:06.582731Z",
264
+ "iopub.status.busy": "2025-03-25T08:22:06.582610Z",
265
+ "iopub.status.idle": "2025-03-25T08:22:06.584520Z",
266
+ "shell.execute_reply": "2025-03-25T08:22:06.584204Z"
267
+ }
268
+ },
269
+ "outputs": [],
270
+ "source": [
271
+ "# The gene identifiers are microarray probe IDs, not human gene symbols\n",
272
+ "requires_gene_mapping = True\n"
273
+ ]
274
+ },
275
+ {
276
+ "cell_type": "markdown",
277
+ "id": "ec7dc819",
278
+ "metadata": {},
279
+ "source": [
280
+ "### Step 5: Gene Annotation"
281
+ ]
282
+ },
283
+ {
284
+ "cell_type": "code",
285
+ "execution_count": 6,
286
+ "id": "a6dc0de1",
287
+ "metadata": {
288
+ "execution": {
289
+ "iopub.execute_input": "2025-03-25T08:22:06.586071Z",
290
+ "iopub.status.busy": "2025-03-25T08:22:06.585954Z",
291
+ "iopub.status.idle": "2025-03-25T08:22:09.861706Z",
292
+ "shell.execute_reply": "2025-03-25T08:22:09.861331Z"
293
+ }
294
+ },
295
+ "outputs": [
296
+ {
297
+ "name": "stdout",
298
+ "output_type": "stream",
299
+ "text": [
300
+ "\n",
301
+ "Gene annotation preview:\n",
302
+ "Columns in gene annotation: ['ID', 'GB_LIST', 'SPOT_ID', 'seqname', 'RANGE_GB', 'RANGE_STRAND', 'RANGE_START', 'RANGE_STOP', 'total_probes', 'gene_assignment', 'mrna_assignment', 'category']\n",
303
+ "{'ID': ['7896736', '7896738', '7896740', '7896742', '7896744'], 'GB_LIST': [nan, nan, 'NM_001005240,NM_001004195,NM_001005484,BC136848,BC136907', 'BC118988,AL137655', 'NM_001005277,NM_001005221,NM_001005224,NM_001005504,BC137547'], 'SPOT_ID': ['chr1:53049-54936', 'chr1:63015-63887', 'chr1:69091-70008', 'chr1:334129-334296', 'chr1:367659-368597'], 'seqname': ['chr1', 'chr1', 'chr1', 'chr1', 'chr1'], 'RANGE_GB': ['NC_000001.10', 'NC_000001.10', 'NC_000001.10', 'NC_000001.10', 'NC_000001.10'], 'RANGE_STRAND': ['+', '+', '+', '+', '+'], 'RANGE_START': [53049.0, 63015.0, 69091.0, 334129.0, 367659.0], 'RANGE_STOP': [54936.0, 63887.0, 70008.0, 334296.0, 368597.0], 'total_probes': [7.0, 31.0, 24.0, 6.0, 36.0], 'gene_assignment': ['---', '---', 'NM_001005240 // OR4F17 // olfactory receptor, family 4, subfamily F, member 17 // 19p13.3 // 81099 /// NM_001004195 // OR4F4 // olfactory receptor, family 4, subfamily F, member 4 // 15q26.3 // 26682 /// NM_001005484 // OR4F5 // olfactory receptor, family 4, subfamily F, member 5 // 1p36.33 // 79501 /// ENST00000318050 // OR4F17 // olfactory receptor, family 4, subfamily F, member 17 // 19p13.3 // 81099 /// ENST00000335137 // OR4F4 // olfactory receptor, family 4, subfamily F, member 4 // 15q26.3 // 26682 /// ENST00000326183 // OR4F5 // olfactory receptor, family 4, subfamily F, member 5 // 1p36.33 // 79501 /// BC136848 // OR4F17 // olfactory receptor, family 4, subfamily F, member 17 // 19p13.3 // 81099 /// BC136907 // OR4F4 // olfactory receptor, family 4, subfamily F, member 4 // 15q26.3 // 26682 /// ENST00000442916 // OR4F17 // olfactory receptor, family 4, subfamily F, member 17 // 19p13.3 // 81099', 'ENST00000388975 // SEPT14 // septin 14 // 7p11.2 // 346288 /// BC118988 // NCRNA00266 // non-protein coding RNA 266 // --- // 140849 /// AL137655 // LOC100134822 // similar to hCG1739109 // --- // 100134822', 'NM_001005277 // OR4F16 // olfactory receptor, family 4, subfamily F, member 16 // 1p36.33 // 81399 /// NM_001005221 // OR4F29 // olfactory receptor, family 4, subfamily F, member 29 // 1p36.33 // 729759 /// NM_001005224 // OR4F3 // olfactory receptor, family 4, subfamily F, member 3 // 5q35.3 // 26683 /// NM_001005504 // OR4F21 // olfactory receptor, family 4, subfamily F, member 21 // 8p23.3 // 441308 /// ENST00000320901 // OR4F21 // olfactory receptor, family 4, subfamily F, member 21 // 8p23.3 // 441308 /// BC137547 // OR4F3 // olfactory receptor, family 4, subfamily F, member 3 // 5q35.3 // 26683 /// BC137547 // OR4F16 // olfactory receptor, family 4, subfamily F, member 16 // 1p36.33 // 81399 /// BC137547 // OR4F29 // olfactory receptor, family 4, subfamily F, member 29 // 1p36.33 // 729759'], 'mrna_assignment': ['---', 'ENST00000328113 // ENSEMBL // cdna:pseudogene chromosome:GRCh37:15:102467008:102467910:-1 gene:ENSG00000183909 // chr1 // 100 // 100 // 31 // 31 // 0 /// ENST00000318181 // ENSEMBL // cdna:pseudogene chromosome:GRCh37:19:104601:105256:1 gene:ENSG00000176705 // chr1 // 100 // 100 // 31 // 31 // 0 /// ENST00000492842 // ENSEMBL // cdna:pseudogene chromosome:GRCh37:1:62948:63887:1 gene:ENSG00000240361 // chr1 // 100 // 100 // 31 // 31 // 0', 'NM_001005240 // RefSeq // Homo sapiens olfactory receptor, family 4, subfamily F, member 17 (OR4F17), mRNA. // chr1 // 100 // 100 // 24 // 24 // 0 /// NM_001004195 // RefSeq // Homo sapiens olfactory receptor, family 4, subfamily F, member 4 (OR4F4), mRNA. // chr1 // 100 // 100 // 24 // 24 // 0 /// NM_001005484 // RefSeq // Homo sapiens olfactory receptor, family 4, subfamily F, member 5 (OR4F5), mRNA. // chr1 // 100 // 100 // 24 // 24 // 0 /// ENST00000318050 // ENSEMBL // Olfactory receptor 4F17 gene:ENSG00000176695 // chr1 // 100 // 100 // 24 // 24 // 0 /// ENST00000335137 // ENSEMBL // Olfactory receptor 4F4 gene:ENSG00000186092 // chr1 // 100 // 100 // 24 // 24 // 0 /// ENST00000326183 // ENSEMBL // Olfactory receptor 4F5 gene:ENSG00000177693 // chr1 // 100 // 100 // 24 // 24 // 0 /// BC136848 // GenBank // Homo sapiens olfactory receptor, family 4, subfamily F, member 17, mRNA (cDNA clone MGC:168462 IMAGE:9020839), complete cds. // chr1 // 100 // 100 // 24 // 24 // 0 /// BC136907 // GenBank // Homo sapiens olfactory receptor, family 4, subfamily F, member 4, mRNA (cDNA clone MGC:168521 IMAGE:9020898), complete cds. // chr1 // 100 // 100 // 24 // 24 // 0 /// ENST00000442916 // ENSEMBL // OR4F4 (Fragment) gene:ENSG00000176695 // chr1 // 100 // 88 // 21 // 21 // 0', 'ENST00000388975 // ENSEMBL // Septin-14 gene:ENSG00000154997 // chr1 // 50 // 100 // 3 // 6 // 0 /// BC118988 // GenBank // Homo sapiens chromosome 20 open reading frame 69, mRNA (cDNA clone MGC:141807 IMAGE:40035995), complete cds. // chr1 // 100 // 100 // 6 // 6 // 0 /// AL137655 // GenBank // Homo sapiens mRNA; cDNA DKFZp434B2016 (from clone DKFZp434B2016). // chr1 // 100 // 100 // 6 // 6 // 0 /// ENST00000428915 // ENSEMBL // cdna:known chromosome:GRCh37:10:38742109:38755311:1 gene:ENSG00000203496 // chr1 // 100 // 100 // 6 // 6 // 0 /// ENST00000455207 // ENSEMBL // cdna:known chromosome:GRCh37:1:334129:446155:1 gene:ENSG00000224813 // chr1 // 100 // 100 // 6 // 6 // 0 /// ENST00000455464 // ENSEMBL // cdna:known chromosome:GRCh37:1:334140:342806:1 gene:ENSG00000224813 // chr1 // 100 // 100 // 6 // 6 // 0 /// ENST00000440200 // ENSEMBL // cdna:known chromosome:GRCh37:1:536816:655580:-1 gene:ENSG00000230021 // chr1 // 100 // 100 // 6 // 6 // 0 /// ENST00000279067 // ENSEMBL // cdna:known chromosome:GRCh37:20:62921738:62934912:1 gene:ENSG00000149656 // chr1 // 100 // 100 // 6 // 6 // 0 /// ENST00000499986 // ENSEMBL // cdna:known chromosome:GRCh37:5:180717576:180761371:1 gene:ENSG00000248628 // chr1 // 100 // 100 // 6 // 6 // 0 /// ENST00000436899 // ENSEMBL // cdna:known chromosome:GRCh37:6:131910:144885:-1 gene:ENSG00000170590 // chr1 // 100 // 100 // 6 // 6 // 0 /// ENST00000432557 // ENSEMBL // cdna:known chromosome:GRCh37:8:132324:150572:-1 gene:ENSG00000250210 // chr1 // 100 // 100 // 6 // 6 // 0 /// ENST00000523795 // ENSEMBL // cdna:known chromosome:GRCh37:8:141690:150563:-1 gene:ENSG00000250210 // chr1 // 100 // 100 // 6 // 6 // 0 /// ENST00000490482 // ENSEMBL // cdna:known chromosome:GRCh37:8:149942:163324:-1 gene:ENSG00000223508 // chr1 // 100 // 100 // 6 // 6 // 0 /// ENST00000307499 // ENSEMBL // cdna:known supercontig::GL000227.1:57780:70752:-1 gene:ENSG00000229450 // chr1 // 100 // 100 // 6 // 6 // 0 /// ENST00000441245 // ENSEMBL // cdna:known chromosome:GRCh37:1:637316:655530:-1 gene:ENSG00000230021 // chr1 // 100 // 67 // 4 // 4 // 0 /// ENST00000425473 // ENSEMBL // cdna:known chromosome:GRCh37:20:62926294:62944485:1 gene:ENSG00000149656 // chr1 // 100 // 67 // 4 // 4 // 0 /// ENST00000471248 // ENSEMBL // cdna:known chromosome:GRCh37:1:110953:129173:-1 gene:ENSG00000238009 // chr1 // 75 // 67 // 3 // 4 // 0', 'NM_001005277 // RefSeq // Homo sapiens olfactory receptor, family 4, subfamily F, member 16 (OR4F16), mRNA. // chr1 // 100 // 100 // 36 // 36 // 0 /// NM_001005221 // RefSeq // Homo sapiens olfactory receptor, family 4, subfamily F, member 29 (OR4F29), mRNA. // chr1 // 100 // 100 // 36 // 36 // 0 /// NM_001005224 // RefSeq // Homo sapiens olfactory receptor, family 4, subfamily F, member 3 (OR4F3), mRNA. // chr1 // 100 // 100 // 36 // 36 // 0 /// NM_001005504 // RefSeq // Homo sapiens olfactory receptor, family 4, subfamily F, member 21 (OR4F21), mRNA. // chr1 // 89 // 100 // 32 // 36 // 0 /// ENST00000320901 // ENSEMBL // Olfactory receptor 4F21 gene:ENSG00000176269 // chr1 // 89 // 100 // 32 // 36 // 0 /// BC137547 // GenBank // Homo sapiens olfactory receptor, family 4, subfamily F, member 3, mRNA (cDNA clone MGC:169170 IMAGE:9021547), complete cds. // chr1 // 100 // 100 // 36 // 36 // 0 /// ENST00000426406 // ENSEMBL // cdna:known chromosome:GRCh37:1:367640:368634:1 gene:ENSG00000235249 // chr1 // 100 // 100 // 36 // 36 // 0 /// ENST00000332831 // ENSEMBL // cdna:known chromosome:GRCh37:1:621096:622034:-1 gene:ENSG00000185097 // chr1 // 100 // 100 // 36 // 36 // 0 /// ENST00000456475 // ENSEMBL // cdna:known chromosome:GRCh37:5:180794269:180795263:1 gene:ENSG00000230178 // chr1 // 100 // 100 // 36 // 36 // 0 /// ENST00000521196 // ENSEMBL // cdna:known chromosome:GRCh37:11:86612:87605:-1 gene:ENSG00000224777 // chr1 // 78 // 100 // 28 // 36 // 0'], 'category': ['---', 'main', 'main', 'main', 'main']}\n",
304
+ "\n",
305
+ "Searching for platform information in SOFT file:\n",
306
+ "!Series_platform_id = GPL11532\n",
307
+ "\n",
308
+ "Searching for gene symbol information in SOFT file:\n"
309
+ ]
310
+ },
311
+ {
312
+ "name": "stdout",
313
+ "output_type": "stream",
314
+ "text": [
315
+ "No explicit gene symbol references found in first 1000 lines\n",
316
+ "\n",
317
+ "Checking for additional annotation files in the directory:\n",
318
+ "[]\n"
319
+ ]
320
+ }
321
+ ],
322
+ "source": [
323
+ "# 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.\n",
324
+ "gene_annotation = get_gene_annotation(soft_file)\n",
325
+ "\n",
326
+ "# 2. Analyze the gene annotation dataframe to identify which columns contain the gene identifiers and gene symbols\n",
327
+ "print(\"\\nGene annotation preview:\")\n",
328
+ "print(f\"Columns in gene annotation: {gene_annotation.columns.tolist()}\")\n",
329
+ "print(preview_df(gene_annotation, n=5))\n",
330
+ "\n",
331
+ "# Let's look for platform information in the SOFT file to understand the annotation better\n",
332
+ "print(\"\\nSearching for platform information in SOFT file:\")\n",
333
+ "with gzip.open(soft_file, 'rt') as f:\n",
334
+ " for i, line in enumerate(f):\n",
335
+ " if '!Series_platform_id' in line:\n",
336
+ " print(line.strip())\n",
337
+ " break\n",
338
+ " if i > 100: # Limit search to first 100 lines\n",
339
+ " print(\"Platform ID not found in first 100 lines\")\n",
340
+ " break\n",
341
+ "\n",
342
+ "# Check if the SOFT file includes any reference to gene symbols\n",
343
+ "print(\"\\nSearching for gene symbol information in SOFT file:\")\n",
344
+ "with gzip.open(soft_file, 'rt') as f:\n",
345
+ " gene_symbol_lines = []\n",
346
+ " for i, line in enumerate(f):\n",
347
+ " if 'GENE_SYMBOL' in line or 'gene_symbol' in line.lower() or 'symbol' in line.lower():\n",
348
+ " gene_symbol_lines.append(line.strip())\n",
349
+ " if i > 1000 and len(gene_symbol_lines) > 0: # Limit search but ensure we found something\n",
350
+ " break\n",
351
+ " \n",
352
+ " if gene_symbol_lines:\n",
353
+ " print(\"Found references to gene symbols:\")\n",
354
+ " for line in gene_symbol_lines[:5]: # Show just first 5 matches\n",
355
+ " print(line)\n",
356
+ " else:\n",
357
+ " print(\"No explicit gene symbol references found in first 1000 lines\")\n",
358
+ "\n",
359
+ "# Look for alternative annotation files or references in the directory\n",
360
+ "print(\"\\nChecking for additional annotation files in the directory:\")\n",
361
+ "all_files = os.listdir(in_cohort_dir)\n",
362
+ "print([f for f in all_files if 'annotation' in f.lower() or 'platform' in f.lower() or 'gpl' in f.lower()])\n"
363
+ ]
364
+ },
365
+ {
366
+ "cell_type": "markdown",
367
+ "id": "5754b1c8",
368
+ "metadata": {},
369
+ "source": [
370
+ "### Step 6: Gene Identifier Mapping"
371
+ ]
372
+ },
373
+ {
374
+ "cell_type": "code",
375
+ "execution_count": 7,
376
+ "id": "ac2698b4",
377
+ "metadata": {
378
+ "execution": {
379
+ "iopub.execute_input": "2025-03-25T08:22:09.863574Z",
380
+ "iopub.status.busy": "2025-03-25T08:22:09.863419Z",
381
+ "iopub.status.idle": "2025-03-25T08:22:10.361249Z",
382
+ "shell.execute_reply": "2025-03-25T08:22:10.360875Z"
383
+ }
384
+ },
385
+ "outputs": [
386
+ {
387
+ "name": "stdout",
388
+ "output_type": "stream",
389
+ "text": [
390
+ "First 5 IDs from gene expression data: ['7892501', '7892502', '7892503', '7892504', '7892505']\n",
391
+ "First 5 IDs from gene annotation: ['7896736', '7896738', '7896740', '7896742', '7896744']\n",
392
+ "\n",
393
+ "Sample gene_assignment entries:\n",
394
+ "---...\n",
395
+ "---...\n",
396
+ "NM_001005240 // OR4F17 // olfactory receptor, family 4, subfamily F, member 17 // 19p13.3 // 81099 /// NM_001004195 // OR4F4 // olfactory receptor, family 4, subfamily F, member 4 // 15q26.3 // 26682 ...\n",
397
+ "\n",
398
+ "Creating gene mapping dataframe...\n",
399
+ "Original mapping shape: (33297, 2)\n",
400
+ "Sample mapped entries:\n",
401
+ " ID Gene\n",
402
+ "0 7896736 ---\n",
403
+ "1 7896738 ---\n",
404
+ "2 7896740 NM_001005240 // OR4F17 // olfactory receptor, ...\n",
405
+ "\n",
406
+ "Applying gene mapping to gene expression data...\n"
407
+ ]
408
+ },
409
+ {
410
+ "name": "stdout",
411
+ "output_type": "stream",
412
+ "text": [
413
+ "Gene-level expression data shape: (56391, 44)\n",
414
+ "First 10 gene symbols after mapping:\n",
415
+ "['A-', 'A-2', 'A-52', 'A-E', 'A-I', 'A-II', 'A-IV', 'A-V', 'A0', 'A1']\n",
416
+ "\n",
417
+ "Preview of gene expression data:\n",
418
+ "{'GSM2226420': [33.68976687768011, 1.9937525379999999, 3.3021436486666667], 'GSM2226421': [33.80631276691363, 1.8987550603333334, 3.3720884666666664], 'GSM2226422': [34.00824614293309, 1.929899198, 3.3661534399999997], 'GSM2226423': [33.61255679126494, 1.9025789763333334, 3.3930164499999997], 'GSM2226424': [33.662630774239126, 2.024719238, 3.3526896666666666]}\n"
419
+ ]
420
+ }
421
+ ],
422
+ "source": [
423
+ "# Analyze the gene annotation dataframe to determine the mapping from probe IDs to gene symbols\n",
424
+ "# First, confirm the columns containing probe IDs \n",
425
+ "print(\"First 5 IDs from gene expression data:\", gene_data.index[:5].tolist())\n",
426
+ "print(\"First 5 IDs from gene annotation:\", gene_annotation['ID'][:5].tolist())\n",
427
+ "\n",
428
+ "# Looking at the gene_assignment column which contains gene symbols\n",
429
+ "gene_assignment_sample = gene_annotation['gene_assignment'].head(3).tolist()\n",
430
+ "print(\"\\nSample gene_assignment entries:\")\n",
431
+ "for entry in gene_assignment_sample:\n",
432
+ " print(f\"{entry[:200]}...\")\n",
433
+ "\n",
434
+ "# Extract gene mapping from annotation\n",
435
+ "# The ID column contains the probe identifiers\n",
436
+ "# The gene_assignment column contains gene symbols but needs parsing\n",
437
+ "print(\"\\nCreating gene mapping dataframe...\")\n",
438
+ "mapping_df = get_gene_mapping(gene_annotation, 'ID', 'gene_assignment')\n",
439
+ "print(f\"Original mapping shape: {mapping_df.shape}\")\n",
440
+ "print(\"Sample mapped entries:\")\n",
441
+ "print(mapping_df.head(3))\n",
442
+ "\n",
443
+ "# Apply the gene mapping to convert probe-level measurements to gene-level expression\n",
444
+ "print(\"\\nApplying gene mapping to gene expression data...\")\n",
445
+ "gene_data = apply_gene_mapping(gene_data, mapping_df)\n",
446
+ "print(f\"Gene-level expression data shape: {gene_data.shape}\")\n",
447
+ "print(\"First 10 gene symbols after mapping:\")\n",
448
+ "print(list(gene_data.index[:10]))\n",
449
+ "\n",
450
+ "# Preview the gene expression data\n",
451
+ "print(\"\\nPreview of gene expression data:\")\n",
452
+ "preview_sample = preview_df(gene_data, n=3)\n",
453
+ "preview_cols = list(preview_sample.keys())[:5] # Show only first 5 columns to avoid clutter\n",
454
+ "preview_data = {col: preview_sample[col] for col in preview_cols}\n",
455
+ "print(preview_data)\n"
456
+ ]
457
+ },
458
+ {
459
+ "cell_type": "markdown",
460
+ "id": "88369521",
461
+ "metadata": {},
462
+ "source": [
463
+ "### Step 7: Data Normalization and Linking"
464
+ ]
465
+ },
466
+ {
467
+ "cell_type": "code",
468
+ "execution_count": 8,
469
+ "id": "629a3a19",
470
+ "metadata": {
471
+ "execution": {
472
+ "iopub.execute_input": "2025-03-25T08:22:10.363074Z",
473
+ "iopub.status.busy": "2025-03-25T08:22:10.362942Z",
474
+ "iopub.status.idle": "2025-03-25T08:22:11.074587Z",
475
+ "shell.execute_reply": "2025-03-25T08:22:11.074220Z"
476
+ }
477
+ },
478
+ "outputs": [
479
+ {
480
+ "name": "stdout",
481
+ "output_type": "stream",
482
+ "text": [
483
+ "Normalized gene data shape: (20124, 44)\n"
484
+ ]
485
+ },
486
+ {
487
+ "name": "stdout",
488
+ "output_type": "stream",
489
+ "text": [
490
+ "Gene expression data saved to ../../output/preprocess/Chronic_obstructive_pulmonary_disease_(COPD)/gene_data/GSE84046.csv\n",
491
+ "\n",
492
+ "No COPD-related trait data available in this dataset.\n",
493
+ "Clinical data (demographic only) saved to ../../output/preprocess/Chronic_obstructive_pulmonary_disease_(COPD)/clinical_data/GSE84046.csv\n",
494
+ "\n",
495
+ "Clinical data preview:\n",
496
+ " Gender Age\n",
497
+ "GSM2226420 1 62\n",
498
+ "GSM2226421 1 70\n",
499
+ "GSM2226422 1 62\n",
500
+ "\n",
501
+ "Dataset usability assessment: Not usable for COPD analysis\n",
502
+ "Assessment details saved to ../../output/preprocess/Chronic_obstructive_pulmonary_disease_(COPD)/cohort_info.json\n"
503
+ ]
504
+ }
505
+ ],
506
+ "source": [
507
+ "# 1. Normalize gene symbols in the gene expression data\n",
508
+ "normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n",
509
+ "print(f\"Normalized gene data shape: {normalized_gene_data.shape}\")\n",
510
+ "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
511
+ "normalized_gene_data.to_csv(out_gene_data_file)\n",
512
+ "print(f\"Gene expression data saved to {out_gene_data_file}\")\n",
513
+ "\n",
514
+ "# 2. Since we previously determined that trait data is not available (trait_row = None),\n",
515
+ "# we can't create clinical features or linked data for this cohort\n",
516
+ "print(\"\\nNo COPD-related trait data available in this dataset.\")\n",
517
+ "\n",
518
+ "# 3. Create a minimal clinical dataframe with just the demographic information\n",
519
+ "# Get the sample IDs from gene data\n",
520
+ "sample_ids = normalized_gene_data.columns.tolist()\n",
521
+ "\n",
522
+ "# Create clinical dataframe with gender and age if available\n",
523
+ "clinical_features_list = []\n",
524
+ "\n",
525
+ "# Add gender information if available\n",
526
+ "if gender_row is not None:\n",
527
+ " gender_series = clinical_data.iloc[gender_row].drop('!Sample_geo_accession', errors='ignore')\n",
528
+ " gender_series = gender_series.map(convert_gender)\n",
529
+ " gender_series.name = 'Gender'\n",
530
+ " clinical_features_list.append(gender_series)\n",
531
+ "\n",
532
+ "# Add age information if available\n",
533
+ "if age_row is not None:\n",
534
+ " age_series = clinical_data.iloc[age_row].drop('!Sample_geo_accession', errors='ignore') \n",
535
+ " age_series = age_series.map(convert_age)\n",
536
+ " age_series.name = 'Age'\n",
537
+ " clinical_features_list.append(age_series)\n",
538
+ "\n",
539
+ "# Create clinical dataframe if we have features\n",
540
+ "if clinical_features_list:\n",
541
+ " clinical_df = pd.concat(clinical_features_list, axis=1)\n",
542
+ " \n",
543
+ " # Save clinical data\n",
544
+ " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
545
+ " clinical_df.to_csv(out_clinical_data_file)\n",
546
+ " print(f\"Clinical data (demographic only) saved to {out_clinical_data_file}\")\n",
547
+ " \n",
548
+ " print(\"\\nClinical data preview:\")\n",
549
+ " print(clinical_df.head(3))\n",
550
+ "else:\n",
551
+ " print(\"No usable clinical features found.\")\n",
552
+ "\n",
553
+ "# 4. Final validation - use is_final=False since this is an initial filter-out case\n",
554
+ "note = \"This dataset contains gene expression from adipose tissue in a protein diet study, not related to COPD.\"\n",
555
+ "is_usable = validate_and_save_cohort_info(\n",
556
+ " is_final=False,\n",
557
+ " cohort=cohort,\n",
558
+ " info_path=json_path,\n",
559
+ " is_gene_available=True,\n",
560
+ " is_trait_available=False # No COPD trait data\n",
561
+ ")\n",
562
+ "\n",
563
+ "print(f\"\\nDataset usability assessment: {'Usable' if is_usable else 'Not usable'} for COPD analysis\")\n",
564
+ "print(f\"Assessment details saved to {json_path}\")"
565
+ ]
566
+ }
567
+ ],
568
+ "metadata": {
569
+ "language_info": {
570
+ "codemirror_mode": {
571
+ "name": "ipython",
572
+ "version": 3
573
+ },
574
+ "file_extension": ".py",
575
+ "mimetype": "text/x-python",
576
+ "name": "python",
577
+ "nbconvert_exporter": "python",
578
+ "pygments_lexer": "ipython3",
579
+ "version": "3.10.16"
580
+ }
581
+ },
582
+ "nbformat": 4,
583
+ "nbformat_minor": 5
584
+ }
code/Chronic_obstructive_pulmonary_disease_(COPD)/TCGA.ipynb ADDED
@@ -0,0 +1,551 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": 1,
6
+ "id": "c8a34fca",
7
+ "metadata": {
8
+ "execution": {
9
+ "iopub.execute_input": "2025-03-25T08:22:11.763991Z",
10
+ "iopub.status.busy": "2025-03-25T08:22:11.763887Z",
11
+ "iopub.status.idle": "2025-03-25T08:22:11.925875Z",
12
+ "shell.execute_reply": "2025-03-25T08:22:11.925545Z"
13
+ }
14
+ },
15
+ "outputs": [],
16
+ "source": [
17
+ "import sys\n",
18
+ "import os\n",
19
+ "sys.path.append(os.path.abspath(os.path.join(os.getcwd(), '../..')))\n",
20
+ "\n",
21
+ "# Path Configuration\n",
22
+ "from tools.preprocess import *\n",
23
+ "\n",
24
+ "# Processing context\n",
25
+ "trait = \"Chronic_obstructive_pulmonary_disease_(COPD)\"\n",
26
+ "\n",
27
+ "# Input paths\n",
28
+ "tcga_root_dir = \"../../input/TCGA\"\n",
29
+ "\n",
30
+ "# Output paths\n",
31
+ "out_data_file = \"../../output/preprocess/Chronic_obstructive_pulmonary_disease_(COPD)/TCGA.csv\"\n",
32
+ "out_gene_data_file = \"../../output/preprocess/Chronic_obstructive_pulmonary_disease_(COPD)/gene_data/TCGA.csv\"\n",
33
+ "out_clinical_data_file = \"../../output/preprocess/Chronic_obstructive_pulmonary_disease_(COPD)/clinical_data/TCGA.csv\"\n",
34
+ "json_path = \"../../output/preprocess/Chronic_obstructive_pulmonary_disease_(COPD)/cohort_info.json\"\n"
35
+ ]
36
+ },
37
+ {
38
+ "cell_type": "markdown",
39
+ "id": "92228018",
40
+ "metadata": {},
41
+ "source": [
42
+ "### Step 1: Initial Data Loading"
43
+ ]
44
+ },
45
+ {
46
+ "cell_type": "code",
47
+ "execution_count": 2,
48
+ "id": "c82c699f",
49
+ "metadata": {
50
+ "execution": {
51
+ "iopub.execute_input": "2025-03-25T08:22:11.927157Z",
52
+ "iopub.status.busy": "2025-03-25T08:22:11.927014Z",
53
+ "iopub.status.idle": "2025-03-25T08:22:14.586823Z",
54
+ "shell.execute_reply": "2025-03-25T08:22:14.586434Z"
55
+ }
56
+ },
57
+ "outputs": [
58
+ {
59
+ "name": "stdout",
60
+ "output_type": "stream",
61
+ "text": [
62
+ "Looking for a relevant cohort directory for Chronic_obstructive_pulmonary_disease_(COPD)...\n",
63
+ "Available cohorts: ['TCGA_Liver_Cancer_(LIHC)', 'TCGA_Lower_Grade_Glioma_(LGG)', 'TCGA_lower_grade_glioma_and_glioblastoma_(GBMLGG)', 'TCGA_Lung_Adenocarcinoma_(LUAD)', 'TCGA_Lung_Cancer_(LUNG)', 'TCGA_Lung_Squamous_Cell_Carcinoma_(LUSC)', 'TCGA_Melanoma_(SKCM)', 'TCGA_Mesothelioma_(MESO)', 'TCGA_Ocular_melanomas_(UVM)', 'TCGA_Ovarian_Cancer_(OV)', 'TCGA_Pancreatic_Cancer_(PAAD)', 'TCGA_Pheochromocytoma_Paraganglioma_(PCPG)', 'TCGA_Prostate_Cancer_(PRAD)', 'TCGA_Rectal_Cancer_(READ)', 'TCGA_Sarcoma_(SARC)', 'TCGA_Stomach_Cancer_(STAD)', 'TCGA_Testicular_Cancer_(TGCT)', 'TCGA_Thymoma_(THYM)', 'TCGA_Thyroid_Cancer_(THCA)', 'TCGA_Uterine_Carcinosarcoma_(UCS)', '.DS_Store', 'CrawlData.ipynb', 'TCGA_Acute_Myeloid_Leukemia_(LAML)', 'TCGA_Adrenocortical_Cancer_(ACC)', 'TCGA_Bile_Duct_Cancer_(CHOL)', 'TCGA_Bladder_Cancer_(BLCA)', 'TCGA_Breast_Cancer_(BRCA)', 'TCGA_Cervical_Cancer_(CESC)', 'TCGA_Colon_and_Rectal_Cancer_(COADREAD)', 'TCGA_Colon_Cancer_(COAD)', 'TCGA_Endometrioid_Cancer_(UCEC)', 'TCGA_Esophageal_Cancer_(ESCA)', 'TCGA_Glioblastoma_(GBM)', 'TCGA_Head_and_Neck_Cancer_(HNSC)', 'TCGA_Kidney_Chromophobe_(KICH)', 'TCGA_Kidney_Clear_Cell_Carcinoma_(KIRC)', 'TCGA_Kidney_Papillary_Cell_Carcinoma_(KIRP)', 'TCGA_Large_Bcell_Lymphoma_(DLBC)']\n",
64
+ "COPD related cohorts: ['TCGA_Lung_Adenocarcinoma_(LUAD)', 'TCGA_Lung_Cancer_(LUNG)', 'TCGA_Lung_Squamous_Cell_Carcinoma_(LUSC)']\n",
65
+ "Selected cohort: TCGA_Lung_Cancer_(LUNG)\n",
66
+ "Clinical data file: TCGA.LUNG.sampleMap_LUNG_clinicalMatrix\n",
67
+ "Genetic data file: TCGA.LUNG.sampleMap_HiSeqV2_PANCAN.gz\n"
68
+ ]
69
+ },
70
+ {
71
+ "name": "stdout",
72
+ "output_type": "stream",
73
+ "text": [
74
+ "\n",
75
+ "Clinical data columns:\n",
76
+ "['ABSOLUTE_Ploidy', 'ABSOLUTE_Purity', 'AKT1', 'ALK_translocation', 'BRAF', 'CBL', 'CTNNB1', 'Canonical_mut_in_KRAS_EGFR_ALK', 'Cnncl_mt_n_KRAS_EGFR_ALK_RET_ROS1_BRAF_ERBB2_HRAS_NRAS_AKT1_MAP2', 'EGFR', 'ERBB2', 'ERBB4', 'Estimated_allele_fraction_of_a_clonal_varnt_prsnt_t_1_cpy_pr_cll', 'Expression_Subtype', 'HRAS', 'KRAS', 'MAP2K1', 'MET', 'NRAS', 'PIK3CA', 'PTPN11', 'Pathology', 'Pathology_Updated', 'RET_translocation', 'ROS1_translocation', 'STK11', 'WGS_as_of_20120731_0_no_1_yes', '_INTEGRATION', '_PANCAN_CNA_PANCAN_K8', '_PANCAN_Cluster_Cluster_PANCAN', '_PANCAN_DNAMethyl_PANCAN', '_PANCAN_RPPA_PANCAN_K8', '_PANCAN_UNC_RNAseq_PANCAN_K16', '_PANCAN_miRNA_PANCAN', '_PANCAN_mutation_PANCAN', '_PATIENT', '_cohort', '_primary_disease', '_primary_site', 'additional_pharmaceutical_therapy', 'additional_radiation_therapy', 'additional_surgery_locoregional_procedure', 'additional_surgery_metastatic_procedure', 'age_at_initial_pathologic_diagnosis', 'anatomic_neoplasm_subdivision', 'anatomic_neoplasm_subdivision_other', 'bcr_followup_barcode', 'bcr_patient_barcode', 'bcr_sample_barcode', 'days_to_additional_surgery_locoregional_procedure', 'days_to_additional_surgery_metastatic_procedure', 'days_to_birth', 'days_to_collection', 'days_to_death', 'days_to_initial_pathologic_diagnosis', 'days_to_last_followup', 'days_to_new_tumor_event_after_initial_treatment', 'disease_code', 'dlco_predictive_percent', 'eastern_cancer_oncology_group', 'egfr_mutation_performed', 'egfr_mutation_result', 'eml4_alk_translocation_method', 'eml4_alk_translocation_performed', 'followup_case_report_form_submission_reason', 'followup_treatment_success', 'form_completion_date', 'gender', 'histological_type', 'history_of_neoadjuvant_treatment', 'icd_10', 'icd_o_3_histology', 'icd_o_3_site', 'informed_consent_verified', 'initial_weight', 'intermediate_dimension', 'is_ffpe', 'karnofsky_performance_score', 'kras_gene_analysis_performed', 'kras_mutation_found', 'kras_mutation_result', 'location_in_lung_parenchyma', 'longest_dimension', 'lost_follow_up', 'new_neoplasm_event_type', 'new_tumor_event_after_initial_treatment', 'number_pack_years_smoked', 'oct_embedded', 'other_dx', 'pathologic_M', 'pathologic_N', 'pathologic_T', 'pathologic_stage', 'pathology_report_file_name', 'patient_id', 'performance_status_scale_timing', 'person_neoplasm_cancer_status', 'post_bronchodilator_fev1_fvc_percent', 'post_bronchodilator_fev1_percent', 'pre_bronchodilator_fev1_fvc_percent', 'pre_bronchodilator_fev1_percent', 'primary_therapy_outcome_success', 'progression_determined_by', 'project_code', 'pulmonary_function_test_performed', 'radiation_therapy', 'residual_tumor', 'sample_type', 'sample_type_id', 'shortest_dimension', 'stopped_smoking_year', 'system_version', 'targeted_molecular_therapy', 'tissue_prospective_collection_indicator', 'tissue_retrospective_collection_indicator', 'tissue_source_site', 'tobacco_smoking_history', 'tobacco_smoking_history_indicator', 'tumor_tissue_site', 'vial_number', 'vital_status', 'year_of_initial_pathologic_diagnosis', 'year_of_tobacco_smoking_onset', '_GENOMIC_ID_TCGA_LUNG_exp_HiSeqV2_exon', '_GENOMIC_ID_TCGA_LUNG_hMethyl27', '_GENOMIC_ID_TCGA_LUNG_mutation', '_GENOMIC_ID_TCGA_LUNG_exp_HiSeqV2_PANCAN', '_GENOMIC_ID_TCGA_LUNG_hMethyl450', '_GENOMIC_ID_TCGA_LUNG_gistic2thd', '_GENOMIC_ID_TCGA_LUNG_G4502A_07_3', '_GENOMIC_ID_TCGA_LUNG_exp_HiSeqV2', '_GENOMIC_ID_TCGA_LUNG_gistic2', '_GENOMIC_ID_TCGA_LUNG_RPPA_RBN']\n",
77
+ "\n",
78
+ "Clinical data shape: (1299, 133)\n",
79
+ "Genetic data shape: (20530, 1129)\n"
80
+ ]
81
+ }
82
+ ],
83
+ "source": [
84
+ "import os\n",
85
+ "\n",
86
+ "# Check if there's a suitable cohort directory for COPD\n",
87
+ "print(f\"Looking for a relevant cohort directory for {trait}...\")\n",
88
+ "\n",
89
+ "# Check available cohorts\n",
90
+ "available_dirs = os.listdir(tcga_root_dir)\n",
91
+ "print(f\"Available cohorts: {available_dirs}\")\n",
92
+ "\n",
93
+ "# COPD-related keywords\n",
94
+ "copd_related_keywords = ['lung', 'pulmonary', 'respiratory', 'copd', 'bronchitis', 'emphysema', 'airway']\n",
95
+ "\n",
96
+ "# Look for COPD related directories\n",
97
+ "copd_related_dirs = []\n",
98
+ "for d in available_dirs:\n",
99
+ " if any(keyword in d.lower() for keyword in copd_related_keywords):\n",
100
+ " copd_related_dirs.append(d)\n",
101
+ "\n",
102
+ "print(f\"COPD related cohorts: {copd_related_dirs}\")\n",
103
+ "\n",
104
+ "if not copd_related_dirs:\n",
105
+ " print(f\"No suitable cohort found for {trait}.\")\n",
106
+ " # Mark the task as completed by recording the unavailability\n",
107
+ " validate_and_save_cohort_info(\n",
108
+ " is_final=False,\n",
109
+ " cohort=\"TCGA\",\n",
110
+ " info_path=json_path,\n",
111
+ " is_gene_available=False,\n",
112
+ " is_trait_available=False\n",
113
+ " )\n",
114
+ " # Exit the script early since no suitable cohort was found\n",
115
+ " selected_cohort = None\n",
116
+ "else:\n",
117
+ " # For COPD, the general lung cancer cohort would be most relevant\n",
118
+ " # Prioritize general lung cancer over specific subtypes if available\n",
119
+ " if 'TCGA_Lung_Cancer_(LUNG)' in copd_related_dirs:\n",
120
+ " selected_cohort = 'TCGA_Lung_Cancer_(LUNG)'\n",
121
+ " else:\n",
122
+ " selected_cohort = copd_related_dirs[0]\n",
123
+ "\n",
124
+ "if selected_cohort:\n",
125
+ " print(f\"Selected cohort: {selected_cohort}\")\n",
126
+ " \n",
127
+ " # Get the full path to the selected cohort directory\n",
128
+ " cohort_dir = os.path.join(tcga_root_dir, selected_cohort)\n",
129
+ " \n",
130
+ " # Get the clinical and genetic data file paths\n",
131
+ " clinical_file_path, genetic_file_path = tcga_get_relevant_filepaths(cohort_dir)\n",
132
+ " \n",
133
+ " print(f\"Clinical data file: {os.path.basename(clinical_file_path)}\")\n",
134
+ " print(f\"Genetic data file: {os.path.basename(genetic_file_path)}\")\n",
135
+ " \n",
136
+ " # Load the clinical and genetic data\n",
137
+ " clinical_df = pd.read_csv(clinical_file_path, index_col=0, sep='\\t')\n",
138
+ " genetic_df = pd.read_csv(genetic_file_path, index_col=0, sep='\\t')\n",
139
+ " \n",
140
+ " # Print the column names of the clinical data\n",
141
+ " print(\"\\nClinical data columns:\")\n",
142
+ " print(clinical_df.columns.tolist())\n",
143
+ " \n",
144
+ " # Basic info about the datasets\n",
145
+ " print(f\"\\nClinical data shape: {clinical_df.shape}\")\n",
146
+ " print(f\"Genetic data shape: {genetic_df.shape}\")\n"
147
+ ]
148
+ },
149
+ {
150
+ "cell_type": "markdown",
151
+ "id": "c7e08ede",
152
+ "metadata": {},
153
+ "source": [
154
+ "### Step 2: Find Candidate Demographic Features"
155
+ ]
156
+ },
157
+ {
158
+ "cell_type": "code",
159
+ "execution_count": 3,
160
+ "id": "b0c32a55",
161
+ "metadata": {
162
+ "execution": {
163
+ "iopub.execute_input": "2025-03-25T08:22:14.588684Z",
164
+ "iopub.status.busy": "2025-03-25T08:22:14.588540Z",
165
+ "iopub.status.idle": "2025-03-25T08:22:14.605180Z",
166
+ "shell.execute_reply": "2025-03-25T08:22:14.604861Z"
167
+ }
168
+ },
169
+ "outputs": [
170
+ {
171
+ "name": "stdout",
172
+ "output_type": "stream",
173
+ "text": [
174
+ "Age columns preview:\n",
175
+ "{'age_at_initial_pathologic_diagnosis': [70.0, 67.0, 79.0, 68.0, 66.0], 'days_to_birth': [-25752.0, -24532.0, -29068.0, -24868.0, -24411.0]}\n",
176
+ "Gender columns preview:\n",
177
+ "{'gender': ['MALE', 'MALE', 'FEMALE', 'MALE', 'MALE']}\n"
178
+ ]
179
+ }
180
+ ],
181
+ "source": [
182
+ "# Identify candidate columns for age\n",
183
+ "candidate_age_cols = ['age_at_initial_pathologic_diagnosis', 'days_to_birth']\n",
184
+ "\n",
185
+ "# Identify candidate columns for gender\n",
186
+ "candidate_gender_cols = ['gender']\n",
187
+ "\n",
188
+ "# Load the clinical data file\n",
189
+ "cohort_dir = os.path.join(tcga_root_dir, 'TCGA_Lung_Cancer_(LUNG)')\n",
190
+ "clinical_file_path, _ = tcga_get_relevant_filepaths(cohort_dir)\n",
191
+ "clinical_df = pd.read_csv(clinical_file_path, sep='\\t', index_col=0)\n",
192
+ "\n",
193
+ "# Extract and preview age columns\n",
194
+ "if candidate_age_cols:\n",
195
+ " age_preview = {col: clinical_df[col].head(5).tolist() for col in candidate_age_cols}\n",
196
+ " print(\"Age columns preview:\")\n",
197
+ " print(age_preview)\n",
198
+ "\n",
199
+ "# Extract and preview gender columns\n",
200
+ "if candidate_gender_cols:\n",
201
+ " gender_preview = {col: clinical_df[col].head(5).tolist() for col in candidate_gender_cols}\n",
202
+ " print(\"Gender columns preview:\")\n",
203
+ " print(gender_preview)\n"
204
+ ]
205
+ },
206
+ {
207
+ "cell_type": "markdown",
208
+ "id": "14b79852",
209
+ "metadata": {},
210
+ "source": [
211
+ "### Step 3: Select Demographic Features"
212
+ ]
213
+ },
214
+ {
215
+ "cell_type": "code",
216
+ "execution_count": 4,
217
+ "id": "61a54339",
218
+ "metadata": {
219
+ "execution": {
220
+ "iopub.execute_input": "2025-03-25T08:22:14.606935Z",
221
+ "iopub.status.busy": "2025-03-25T08:22:14.606794Z",
222
+ "iopub.status.idle": "2025-03-25T08:22:14.610531Z",
223
+ "shell.execute_reply": "2025-03-25T08:22:14.610237Z"
224
+ }
225
+ },
226
+ "outputs": [
227
+ {
228
+ "name": "stdout",
229
+ "output_type": "stream",
230
+ "text": [
231
+ "Age columns evaluation:\n",
232
+ " age_at_initial_pathologic_diagnosis: 5/5 non-null values\n",
233
+ " Values represent age in years directly: [70.0, 67.0, 79.0, 68.0, 66.0]\n",
234
+ " days_to_birth: 5/5 non-null values\n",
235
+ " Values represent negative days from birth (needs conversion): [-25752.0, -24532.0, -29068.0, -24868.0, -24411.0]\n",
236
+ "\n",
237
+ "Gender columns evaluation:\n",
238
+ " gender: 5/5 non-null values, values: ['MALE', 'MALE', 'FEMALE', 'MALE', 'MALE']\n",
239
+ "\n",
240
+ "Chosen demographic columns:\n",
241
+ "Age column: age_at_initial_pathologic_diagnosis\n",
242
+ "Gender column: gender\n"
243
+ ]
244
+ }
245
+ ],
246
+ "source": [
247
+ "# Inspect the age columns\n",
248
+ "print(\"Age columns evaluation:\")\n",
249
+ "for col, values in {'age_at_initial_pathologic_diagnosis': [70.0, 67.0, 79.0, 68.0, 66.0], 'days_to_birth': [-25752.0, -24532.0, -29068.0, -24868.0, -24411.0]}.items():\n",
250
+ " non_null_count = sum(1 for v in values if v is not None)\n",
251
+ " print(f\" {col}: {non_null_count}/5 non-null values\")\n",
252
+ " if col == 'age_at_initial_pathologic_diagnosis':\n",
253
+ " print(f\" Values represent age in years directly: {values}\")\n",
254
+ " elif col == 'days_to_birth':\n",
255
+ " print(f\" Values represent negative days from birth (needs conversion): {values}\")\n",
256
+ "\n",
257
+ "# Inspect the gender columns\n",
258
+ "print(\"\\nGender columns evaluation:\")\n",
259
+ "for col, values in {'gender': ['MALE', 'MALE', 'FEMALE', 'MALE', 'MALE']}.items():\n",
260
+ " non_null_count = sum(1 for v in values if v is not None and v != '')\n",
261
+ " print(f\" {col}: {non_null_count}/5 non-null values, values: {values}\")\n",
262
+ "\n",
263
+ "# Select appropriate columns\n",
264
+ "age_col = \"age_at_initial_pathologic_diagnosis\" # Direct age is easier to work with than days_to_birth\n",
265
+ "gender_col = \"gender\" # Only one option available and it has valid values\n",
266
+ "\n",
267
+ "# Print chosen columns\n",
268
+ "print(\"\\nChosen demographic columns:\")\n",
269
+ "print(f\"Age column: {age_col}\")\n",
270
+ "print(f\"Gender column: {gender_col}\")\n"
271
+ ]
272
+ },
273
+ {
274
+ "cell_type": "markdown",
275
+ "id": "cf235b83",
276
+ "metadata": {},
277
+ "source": [
278
+ "### Step 4: Feature Engineering and Validation"
279
+ ]
280
+ },
281
+ {
282
+ "cell_type": "code",
283
+ "execution_count": 5,
284
+ "id": "e1bd422b",
285
+ "metadata": {
286
+ "execution": {
287
+ "iopub.execute_input": "2025-03-25T08:22:14.612295Z",
288
+ "iopub.status.busy": "2025-03-25T08:22:14.612189Z",
289
+ "iopub.status.idle": "2025-03-25T08:24:08.293123Z",
290
+ "shell.execute_reply": "2025-03-25T08:24:08.292730Z"
291
+ }
292
+ },
293
+ "outputs": [
294
+ {
295
+ "name": "stdout",
296
+ "output_type": "stream",
297
+ "text": [
298
+ "Clinical features (first 5 rows):\n",
299
+ " Chronic_obstructive_pulmonary_disease_(COPD) Age Gender\n",
300
+ "sampleID \n",
301
+ "TCGA-05-4244-01 1 70.0 1.0\n",
302
+ "TCGA-05-4249-01 1 67.0 1.0\n",
303
+ "TCGA-05-4250-01 1 79.0 0.0\n",
304
+ "TCGA-05-4382-01 1 68.0 1.0\n",
305
+ "TCGA-05-4384-01 1 66.0 1.0\n",
306
+ "\n",
307
+ "Processing gene expression data...\n"
308
+ ]
309
+ },
310
+ {
311
+ "name": "stdout",
312
+ "output_type": "stream",
313
+ "text": [
314
+ "Original gene data shape: (20530, 1129)\n"
315
+ ]
316
+ },
317
+ {
318
+ "name": "stdout",
319
+ "output_type": "stream",
320
+ "text": [
321
+ "Attempting to normalize gene symbols...\n"
322
+ ]
323
+ },
324
+ {
325
+ "name": "stdout",
326
+ "output_type": "stream",
327
+ "text": [
328
+ "Gene data shape after normalization: (19848, 1129)\n"
329
+ ]
330
+ },
331
+ {
332
+ "name": "stdout",
333
+ "output_type": "stream",
334
+ "text": [
335
+ "Gene data saved to: ../../output/preprocess/Chronic_obstructive_pulmonary_disease_(COPD)/gene_data/TCGA.csv\n",
336
+ "\n",
337
+ "Linking clinical and genetic data...\n",
338
+ "Clinical data shape: (1299, 3)\n",
339
+ "Genetic data shape: (19848, 1129)\n",
340
+ "Number of common samples: 1129\n",
341
+ "\n",
342
+ "Linked data shape: (1129, 19851)\n",
343
+ "Linked data preview (first 5 rows, first few columns):\n",
344
+ " Chronic_obstructive_pulmonary_disease_(COPD) Age Gender \\\n",
345
+ "TCGA-78-7147-01 1 67.0 0.0 \n",
346
+ "TCGA-55-7227-01 1 77.0 1.0 \n",
347
+ "TCGA-44-7661-01 1 69.0 0.0 \n",
348
+ "TCGA-85-A4PA-01 1 61.0 1.0 \n",
349
+ "TCGA-38-A44F-01 1 80.0 1.0 \n",
350
+ "\n",
351
+ " A1BG A1BG-AS1 \n",
352
+ "TCGA-78-7147-01 0.034026 0.522917 \n",
353
+ "TCGA-55-7227-01 -1.308274 -0.304083 \n",
354
+ "TCGA-44-7661-01 -0.353574 0.199017 \n",
355
+ "TCGA-85-A4PA-01 1.474026 2.069817 \n",
356
+ "TCGA-38-A44F-01 0.196826 1.340917 \n"
357
+ ]
358
+ },
359
+ {
360
+ "name": "stdout",
361
+ "output_type": "stream",
362
+ "text": [
363
+ "\n",
364
+ "Data shape after handling missing values: (1129, 19851)\n",
365
+ "\n",
366
+ "Checking for bias in features:\n",
367
+ "For the feature 'Chronic_obstructive_pulmonary_disease_(COPD)', the least common label is '0' with 110 occurrences. This represents 9.74% of the dataset.\n",
368
+ "The distribution of the feature 'Chronic_obstructive_pulmonary_disease_(COPD)' in this dataset is fine.\n",
369
+ "\n",
370
+ "Quartiles for 'Age':\n",
371
+ " 25%: 60.0\n",
372
+ " 50% (Median): 67.0\n",
373
+ " 75%: 73.0\n",
374
+ "Min: 38.0\n",
375
+ "Max: 90.0\n",
376
+ "The distribution of the feature 'Age' in this dataset is fine.\n",
377
+ "\n",
378
+ "For the feature 'Gender', the least common label is '0.0' with 455 occurrences. This represents 40.30% of the dataset.\n",
379
+ "The distribution of the feature 'Gender' in this dataset is fine.\n",
380
+ "\n",
381
+ "\n",
382
+ "Performing final validation...\n"
383
+ ]
384
+ },
385
+ {
386
+ "name": "stdout",
387
+ "output_type": "stream",
388
+ "text": [
389
+ "Linked data saved to: ../../output/preprocess/Chronic_obstructive_pulmonary_disease_(COPD)/TCGA.csv\n",
390
+ "Clinical data saved to: ../../output/preprocess/Chronic_obstructive_pulmonary_disease_(COPD)/clinical_data/TCGA.csv\n"
391
+ ]
392
+ }
393
+ ],
394
+ "source": [
395
+ "# 1. Extract and standardize clinical features\n",
396
+ "# Use tcga_select_clinical_features which will automatically create the trait variable and add age/gender if provided\n",
397
+ "cohort_dir = os.path.join(tcga_root_dir, 'TCGA_Lung_Cancer_(LUNG)')\n",
398
+ "clinical_file_path, genetic_file_path = tcga_get_relevant_filepaths(cohort_dir)\n",
399
+ "\n",
400
+ "# Load the clinical data if not already loaded\n",
401
+ "clinical_df = pd.read_csv(clinical_file_path, sep='\\t', index_col=0)\n",
402
+ "\n",
403
+ "linked_clinical_df = tcga_select_clinical_features(\n",
404
+ " clinical_df, \n",
405
+ " trait=trait, \n",
406
+ " age_col=age_col, \n",
407
+ " gender_col=gender_col\n",
408
+ ")\n",
409
+ "\n",
410
+ "# Print preview of clinical features\n",
411
+ "print(\"Clinical features (first 5 rows):\")\n",
412
+ "print(linked_clinical_df.head())\n",
413
+ "\n",
414
+ "# 2. Process gene expression data\n",
415
+ "print(\"\\nProcessing gene expression data...\")\n",
416
+ "# Load genetic data from the same cohort directory\n",
417
+ "genetic_df = pd.read_csv(genetic_file_path, sep='\\t', index_col=0)\n",
418
+ "\n",
419
+ "# Check gene data shape\n",
420
+ "print(f\"Original gene data shape: {genetic_df.shape}\")\n",
421
+ "\n",
422
+ "# Save a version of the gene data before normalization (as a backup)\n",
423
+ "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
424
+ "genetic_df.to_csv(out_gene_data_file.replace('.csv', '_original.csv'))\n",
425
+ "\n",
426
+ "# We need to transpose genetic data so genes are rows and samples are columns for normalization\n",
427
+ "gene_df_for_norm = genetic_df.copy() # Keep original orientation for now\n",
428
+ "\n",
429
+ "# Try to normalize gene symbols - adding debug output to understand what's happening\n",
430
+ "print(\"Attempting to normalize gene symbols...\")\n",
431
+ "try:\n",
432
+ " # First check if we need to transpose based on the data format\n",
433
+ " # In TCGA data, typically genes are rows and samples are columns\n",
434
+ " if gene_df_for_norm.shape[0] > gene_df_for_norm.shape[1]:\n",
435
+ " # More rows than columns, likely genes are rows already\n",
436
+ " normalized_gene_df = normalize_gene_symbols_in_index(gene_df_for_norm)\n",
437
+ " else:\n",
438
+ " # Need to transpose first\n",
439
+ " normalized_gene_df = normalize_gene_symbols_in_index(gene_df_for_norm.T)\n",
440
+ " \n",
441
+ " print(f\"Gene data shape after normalization: {normalized_gene_df.shape}\")\n",
442
+ " \n",
443
+ " # Check if normalization returned empty DataFrame\n",
444
+ " if normalized_gene_df.shape[0] == 0:\n",
445
+ " print(\"WARNING: Gene symbol normalization returned an empty DataFrame.\")\n",
446
+ " print(\"Using original gene data instead of normalized data.\")\n",
447
+ " # Use original data\n",
448
+ " normalized_gene_df = genetic_df\n",
449
+ " \n",
450
+ "except Exception as e:\n",
451
+ " print(f\"Error during gene symbol normalization: {e}\")\n",
452
+ " print(\"Using original gene data instead.\")\n",
453
+ " normalized_gene_df = genetic_df\n",
454
+ "\n",
455
+ "# Save gene data\n",
456
+ "normalized_gene_df.to_csv(out_gene_data_file)\n",
457
+ "print(f\"Gene data saved to: {out_gene_data_file}\")\n",
458
+ "\n",
459
+ "# 3. Link clinical and genetic data\n",
460
+ "# TCGA data uses the same sample IDs in both datasets\n",
461
+ "print(\"\\nLinking clinical and genetic data...\")\n",
462
+ "print(f\"Clinical data shape: {linked_clinical_df.shape}\")\n",
463
+ "print(f\"Genetic data shape: {normalized_gene_df.shape}\")\n",
464
+ "\n",
465
+ "# Find common samples between clinical and genetic data\n",
466
+ "# In TCGA, samples are typically columns in the gene data and index in the clinical data\n",
467
+ "common_samples = set(linked_clinical_df.index).intersection(set(normalized_gene_df.columns))\n",
468
+ "print(f\"Number of common samples: {len(common_samples)}\")\n",
469
+ "\n",
470
+ "if len(common_samples) == 0:\n",
471
+ " print(\"ERROR: No common samples found between clinical and genetic data.\")\n",
472
+ " # Try the alternative orientation\n",
473
+ " common_samples = set(linked_clinical_df.index).intersection(set(normalized_gene_df.index))\n",
474
+ " print(f\"Checking alternative orientation: {len(common_samples)} common samples found.\")\n",
475
+ " \n",
476
+ " if len(common_samples) == 0:\n",
477
+ " # Use is_final=False mode which doesn't require df and is_biased\n",
478
+ " validate_and_save_cohort_info(\n",
479
+ " is_final=False,\n",
480
+ " cohort=\"TCGA\",\n",
481
+ " info_path=json_path,\n",
482
+ " is_gene_available=True,\n",
483
+ " is_trait_available=True\n",
484
+ " )\n",
485
+ " print(\"The dataset was determined to be unusable for this trait due to no common samples. No data files were saved.\")\n",
486
+ "else:\n",
487
+ " # Filter clinical data to only include common samples\n",
488
+ " linked_clinical_df = linked_clinical_df.loc[list(common_samples)]\n",
489
+ " \n",
490
+ " # Create linked data by merging\n",
491
+ " linked_data = pd.concat([linked_clinical_df, normalized_gene_df[list(common_samples)].T], axis=1)\n",
492
+ " \n",
493
+ " print(f\"\\nLinked data shape: {linked_data.shape}\")\n",
494
+ " print(\"Linked data preview (first 5 rows, first few columns):\")\n",
495
+ " display_cols = [trait, 'Age', 'Gender'] + list(linked_data.columns[3:5])\n",
496
+ " print(linked_data[display_cols].head())\n",
497
+ " \n",
498
+ " # 4. Handle missing values\n",
499
+ " linked_data = handle_missing_values(linked_data, trait)\n",
500
+ " print(f\"\\nData shape after handling missing values: {linked_data.shape}\")\n",
501
+ " \n",
502
+ " # 5. Check for bias in trait and demographic features\n",
503
+ " print(\"\\nChecking for bias in features:\")\n",
504
+ " is_trait_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n",
505
+ " \n",
506
+ " # 6. Validate and save cohort info\n",
507
+ " print(\"\\nPerforming final validation...\")\n",
508
+ " is_usable = validate_and_save_cohort_info(\n",
509
+ " is_final=True,\n",
510
+ " cohort=\"TCGA\",\n",
511
+ " info_path=json_path,\n",
512
+ " is_gene_available=len(linked_data.columns) > 3, # More than just trait/age/gender columns\n",
513
+ " is_trait_available=trait in linked_data.columns,\n",
514
+ " is_biased=is_trait_biased,\n",
515
+ " df=linked_data,\n",
516
+ " note=\"Data from TCGA Lung Cancer cohort used for COPD gene expression analysis.\"\n",
517
+ " )\n",
518
+ " \n",
519
+ " # 7. Save linked data if usable\n",
520
+ " if is_usable:\n",
521
+ " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n",
522
+ " linked_data.to_csv(out_data_file)\n",
523
+ " print(f\"Linked data saved to: {out_data_file}\")\n",
524
+ " \n",
525
+ " # Also save clinical data separately\n",
526
+ " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
527
+ " clinical_columns = [col for col in linked_data.columns if col in [trait, 'Age', 'Gender']]\n",
528
+ " linked_data[clinical_columns].to_csv(out_clinical_data_file)\n",
529
+ " print(f\"Clinical data saved to: {out_clinical_data_file}\")\n",
530
+ " else:\n",
531
+ " print(\"The dataset was determined to be unusable for this trait. No data files were saved.\")"
532
+ ]
533
+ }
534
+ ],
535
+ "metadata": {
536
+ "language_info": {
537
+ "codemirror_mode": {
538
+ "name": "ipython",
539
+ "version": 3
540
+ },
541
+ "file_extension": ".py",
542
+ "mimetype": "text/x-python",
543
+ "name": "python",
544
+ "nbconvert_exporter": "python",
545
+ "pygments_lexer": "ipython3",
546
+ "version": "3.10.16"
547
+ }
548
+ },
549
+ "nbformat": 4,
550
+ "nbformat_minor": 5
551
+ }
code/Colon_and_Rectal_Cancer/GSE56699.ipynb ADDED
@@ -0,0 +1,718 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": 1,
6
+ "id": "22ca9fad",
7
+ "metadata": {
8
+ "execution": {
9
+ "iopub.execute_input": "2025-03-25T08:24:26.164713Z",
10
+ "iopub.status.busy": "2025-03-25T08:24:26.164297Z",
11
+ "iopub.status.idle": "2025-03-25T08:24:26.335116Z",
12
+ "shell.execute_reply": "2025-03-25T08:24:26.334660Z"
13
+ }
14
+ },
15
+ "outputs": [],
16
+ "source": [
17
+ "import sys\n",
18
+ "import os\n",
19
+ "sys.path.append(os.path.abspath(os.path.join(os.getcwd(), '../..')))\n",
20
+ "\n",
21
+ "# Path Configuration\n",
22
+ "from tools.preprocess import *\n",
23
+ "\n",
24
+ "# Processing context\n",
25
+ "trait = \"Colon_and_Rectal_Cancer\"\n",
26
+ "cohort = \"GSE56699\"\n",
27
+ "\n",
28
+ "# Input paths\n",
29
+ "in_trait_dir = \"../../input/GEO/Colon_and_Rectal_Cancer\"\n",
30
+ "in_cohort_dir = \"../../input/GEO/Colon_and_Rectal_Cancer/GSE56699\"\n",
31
+ "\n",
32
+ "# Output paths\n",
33
+ "out_data_file = \"../../output/preprocess/Colon_and_Rectal_Cancer/GSE56699.csv\"\n",
34
+ "out_gene_data_file = \"../../output/preprocess/Colon_and_Rectal_Cancer/gene_data/GSE56699.csv\"\n",
35
+ "out_clinical_data_file = \"../../output/preprocess/Colon_and_Rectal_Cancer/clinical_data/GSE56699.csv\"\n",
36
+ "json_path = \"../../output/preprocess/Colon_and_Rectal_Cancer/cohort_info.json\"\n"
37
+ ]
38
+ },
39
+ {
40
+ "cell_type": "markdown",
41
+ "id": "7aefe1fc",
42
+ "metadata": {},
43
+ "source": [
44
+ "### Step 1: Initial Data Loading"
45
+ ]
46
+ },
47
+ {
48
+ "cell_type": "code",
49
+ "execution_count": 2,
50
+ "id": "9689d924",
51
+ "metadata": {
52
+ "execution": {
53
+ "iopub.execute_input": "2025-03-25T08:24:26.336433Z",
54
+ "iopub.status.busy": "2025-03-25T08:24:26.336276Z",
55
+ "iopub.status.idle": "2025-03-25T08:24:26.478423Z",
56
+ "shell.execute_reply": "2025-03-25T08:24:26.477951Z"
57
+ }
58
+ },
59
+ "outputs": [
60
+ {
61
+ "name": "stdout",
62
+ "output_type": "stream",
63
+ "text": [
64
+ "Background Information:\n",
65
+ "!Series_title\t\"Stromal contribution to expression signatures of colorectal cancer (rectal samples)\"\n",
66
+ "!Series_summary\t\"We noticed that a recently identified poor prognosis stem/serrated molecular subtype of colorectal cancer (CRC) is characterized by up-regulation of transcripts known to be also expressed by stromal cells. To better define the origin of such transcripts, we analyzed RNAseq and microarray datasets from CRC mouse xenografts, where human cancer cells are supported by murine stroma. The analysis revealed that mRNA levels of stem/serrated subtype genes are mostly due to stromal expression, even when the stromal fraction is below 5%. Indeed, a classifier based on genes exclusively expressed by cancer-associated fibroblasts was significantly associated, in multiple datasets, to poor prognosis of CRC and to radioresistance of rectal cancer.\"\n",
67
+ "!Series_summary\t\"\"\n",
68
+ "!Series_summary\t\"\"\n",
69
+ "!Series_overall_design\t\"Molecular Characterization of 72 primary rectal cancer formalin-fixed, paraffin-embedded (FFPE) specimens including 58 pretreatment specimens, 14 surgical specimens.\"\n",
70
+ "!Series_overall_design\t\"\"\n",
71
+ "!Series_overall_design\t\"The study was approved by the ethic institutional review board for \"\"Biobanking and use of human tissues for experimental studies\"\" of the Pathology Service of the Azienda Ospedaliera Città della Salute e della Scienza di Torino, Torino, Italy. The project provided a verbal informed consent from the patients due to the retrospective approach of the study, which did not impact on their treatment. All the cases were anonymously recorded. The IRB approved this consent procedure.\"\n",
72
+ "Sample Characteristics Dictionary:\n",
73
+ "{0: ['patient code: RCa0001', 'patient code: RCa0002', 'patient code: RCa0003', 'patient code: RCa0004', 'patient code: RCa0005', 'patient code: RCa0006', 'patient code: RCa0007', 'patient code: RCa0008', 'patient code: RCa0009', 'patient code: RCa0010', 'patient code: RCa0011', 'patient code: RCa0012', 'patient code: RCa0013', 'patient code: RCa0014', 'patient code: RCa0015', 'patient code: RCa0016', 'patient code: RCa0024', 'patient code: RCa0026', 'patient code: RCa0027', 'patient code: RCa0028', 'patient code: RCa0029', 'patient code: RCa0030', 'patient code: RCa0031', 'patient code: RCa0032', 'patient code: RCa0033', 'patient code: RCa0034', 'patient code: RCa0035', 'patient code: RCa0036', 'patient code: RCa0037', 'patient code: RCa0038'], 1: ['sample type: SS', 'sample type: PB'], 2: ['origin: Brussel: UZ Brussel Oncologisch Centrum', 'origin: Candiolo: Institute for Cancer Research, University of Turin', 'origin: Turin: Deparment of Medical Science, University of Turin', 'origin: Cluj-Napaca: University of Medicine and Pharmacology'], 3: ['mandard: 3', 'mandard: 4', 'mandard: 1', 'mandard: NA', 'mandard: 5', 'mandard: 2'], 4: ['response 3 classes: CR', 'response 3 classes: RES', 'response 3 classes: PR'], 5: ['diagnosis: Invasive low grade adenocarcinoma of the rectum', 'diagnosis: Tubulovilleus adenoma', 'diagnosis: Transmural invasive moderately differentiated adenocarcinoma', 'diagnosis: Invasive moederately differentiated adeocarcinoma', 'diagnosis: Moderately differentiated adenocarcinoma', 'diagnosis: Transmural scare, without any residual vital tumor tissue', 'diagnosis: Transmural invasive moderately to bad differentiated adenocarcinoma', 'diagnosis: Invasive, moderately to bad differentiated adenocarcinoma', 'diagnosis: Low-grade adenocarcinoma', 'diagnosis: Maderately differentiated adenocarcinoma', 'diagnosis: Poorly differentiated invasive adenocarcinoma (no surgical specimen available)', 'diagnosis: Low-grade adenocarcinoma with invasion of the perirectal fat', 'diagnosis: Poorly differentiated invasive adenocarcinoma', 'diagnosis: Invasive adenocarcinoma', 'diagnosis: Adenocarcinom, at least intramucosaal (no surgical specimen available)', 'diagnosis: Invasive adenocarcinoma (grade op invasion not to be determined)', 'diagnosis: The major part of the tumor is a tubular villus adenoma, with limited parts of well differantiated intramucosaal invasive adenocarcinoma', 'diagnosis: Tubular adenoma with moderate dysplasia', 'diagnosis: Invasive, moderately differentiated adenocarcinoma', 'diagnosis: Invasive, moderately differentiated adenorcarcinoma, at least intramucosaal', 'diagnosis: Transmural invasive moderately differentiated adenocarcinoma (cilinder cells)', 'diagnosis: invasive, moderately differentiated adenocarcinoma (cilinder cells)', 'diagnosis: Transmural invasive moderately differentiated adenocarcinoma (intestinal type)', 'diagnosis: Invasive well differentiated adenocarcinoma (cilinder cells)', 'diagnosis: Tubulovilleus adenoma with invasion in the submucosa (at least pT1)', 'diagnosis: No residual tumorcells found in ulcus', 'diagnosis: NA', 'diagnosis: adenocarcinoma', 'diagnosis: Adenocarcinoma Tubulare G2', 'diagnosis: 1) Polipo valvola ileo-cecale; 2) Micropolipi colon trasverso; 3) Polipo; 4) Adenocarcinoma moderatamente differenziato (G2)'], 6: ['recurrence: 0', 'recurrence: 1', 'note: Mucosa', 'recurrence: NA'], 7: ['df: 35', 'df: 44', 'df: 63', 'df: 54', 'df: 79', 'df: 16', 'df: 74', 'df: 62', 'df: 58', 'df: 56', 'df: 25', 'df: 20', 'df: 12', 'recurrence: NA', 'df: NA', 'df: 31', 'df: 32', 'df: 24', 'df: 37', 'df: 53', 'df: 55', 'df: 69', 'df: 77', 'df: 26', 'df: 29', 'df: 17', 'df: 13', 'df: 27', 'df: 11', 'df: 4'], 8: ['death: 0', 'death: 1', 'df: NA', 'death: NA'], 9: ['dsf: 35', 'dsf: 44', 'dsf: 63', 'dsf: 54', 'dsf: 79', 'dsf: 16', 'dsf: 74', 'dsf: 62', 'dsf: 58', 'dsf: 56', 'dsf: 36', 'dsf: 27', 'dsf: 13', 'death: NA', 'dsf: NA', 'dsf: 31', 'dsf: 32', 'dsf: 33', 'dsf: 39', 'dsf: 53', 'dsf: 55', 'dsf: 69', 'dsf: 77', 'dsf: 26', 'dsf: 17', 'dsf: 20', 'dsf: 71', 'dsf: 18', 'dsf: 4', 'dsf: 15'], 10: [nan, 'dsf: NA']}\n"
74
+ ]
75
+ }
76
+ ],
77
+ "source": [
78
+ "from tools.preprocess import *\n",
79
+ "# 1. Identify the paths to the SOFT file and the matrix file\n",
80
+ "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
81
+ "\n",
82
+ "# 2. Read the matrix file to obtain background information and sample characteristics data\n",
83
+ "background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']\n",
84
+ "clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']\n",
85
+ "background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)\n",
86
+ "\n",
87
+ "# 3. Obtain the sample characteristics dictionary from the clinical dataframe\n",
88
+ "sample_characteristics_dict = get_unique_values_by_row(clinical_data)\n",
89
+ "\n",
90
+ "# 4. Explicitly print out all the background information and the sample characteristics dictionary\n",
91
+ "print(\"Background Information:\")\n",
92
+ "print(background_info)\n",
93
+ "print(\"Sample Characteristics Dictionary:\")\n",
94
+ "print(sample_characteristics_dict)\n"
95
+ ]
96
+ },
97
+ {
98
+ "cell_type": "markdown",
99
+ "id": "ddb0d045",
100
+ "metadata": {},
101
+ "source": [
102
+ "### Step 2: Dataset Analysis and Clinical Feature Extraction"
103
+ ]
104
+ },
105
+ {
106
+ "cell_type": "code",
107
+ "execution_count": 3,
108
+ "id": "16cc24dd",
109
+ "metadata": {
110
+ "execution": {
111
+ "iopub.execute_input": "2025-03-25T08:24:26.479923Z",
112
+ "iopub.status.busy": "2025-03-25T08:24:26.479800Z",
113
+ "iopub.status.idle": "2025-03-25T08:24:26.488827Z",
114
+ "shell.execute_reply": "2025-03-25T08:24:26.488380Z"
115
+ }
116
+ },
117
+ "outputs": [
118
+ {
119
+ "name": "stdout",
120
+ "output_type": "stream",
121
+ "text": [
122
+ "Preview of selected clinical features:\n",
123
+ "{4: [1.0]}\n",
124
+ "Clinical data saved to: ../../output/preprocess/Colon_and_Rectal_Cancer/clinical_data/GSE56699.csv\n"
125
+ ]
126
+ }
127
+ ],
128
+ "source": [
129
+ "import pandas as pd\n",
130
+ "import numpy as np\n",
131
+ "import os\n",
132
+ "import json\n",
133
+ "from typing import Callable, Optional, Dict, Any\n",
134
+ "\n",
135
+ "# 1. Analyze Gene Expression Data Availability\n",
136
+ "# Based on the background information, this dataset contains gene expression data from rectal cancer specimens\n",
137
+ "is_gene_available = True\n",
138
+ "\n",
139
+ "# 2. Variable Availability and Data Type Conversion\n",
140
+ "# 2.1 Data Availability\n",
141
+ "# Analyzing the sample characteristics dictionary:\n",
142
+ "\n",
143
+ "# For trait (Colon_and_Rectal_Cancer):\n",
144
+ "# Row 4 has \"response 3 classes\" which indicates cancer response to treatment\n",
145
+ "trait_row = 4 \n",
146
+ "\n",
147
+ "# For age:\n",
148
+ "# No explicit age information in the sample characteristics\n",
149
+ "age_row = None\n",
150
+ "\n",
151
+ "# For gender:\n",
152
+ "# No gender information in the sample characteristics\n",
153
+ "gender_row = None\n",
154
+ "\n",
155
+ "# 2.2 Data Type Conversion Functions\n",
156
+ "def convert_trait(value: str) -> int:\n",
157
+ " \"\"\"Convert cancer response value to binary format (0 for complete response, 1 for others).\"\"\"\n",
158
+ " if pd.isna(value):\n",
159
+ " return None\n",
160
+ " \n",
161
+ " # Extract the value after the colon and strip whitespace\n",
162
+ " if isinstance(value, str) and \":\" in value:\n",
163
+ " value = value.split(\":\", 1)[1].strip()\n",
164
+ " \n",
165
+ " # Convert values based on \"response 3 classes\"\n",
166
+ " if value == \"CR\": # Complete Response\n",
167
+ " return 0\n",
168
+ " elif value in [\"RES\", \"PR\"]: # Resistant or Partial Response\n",
169
+ " return 1\n",
170
+ " else:\n",
171
+ " return None\n",
172
+ "\n",
173
+ "def convert_age(value: str) -> Optional[float]:\n",
174
+ " \"\"\"Convert age value to continuous format.\"\"\"\n",
175
+ " # This function is defined but not used since age data is not available\n",
176
+ " return None\n",
177
+ "\n",
178
+ "def convert_gender(value: str) -> Optional[int]:\n",
179
+ " \"\"\"Convert gender value to binary format (0 for female, 1 for male).\"\"\"\n",
180
+ " # This function is defined but not used since gender data is not available\n",
181
+ " return None\n",
182
+ "\n",
183
+ "# 3. Save Metadata\n",
184
+ "# Determine if trait data is available\n",
185
+ "is_trait_available = trait_row is not None\n",
186
+ "\n",
187
+ "# Validate and save cohort info (initial filtering)\n",
188
+ "validate_and_save_cohort_info(\n",
189
+ " is_final=False,\n",
190
+ " cohort=cohort,\n",
191
+ " info_path=json_path,\n",
192
+ " is_gene_available=is_gene_available,\n",
193
+ " is_trait_available=is_trait_available\n",
194
+ ")\n",
195
+ "\n",
196
+ "# 4. Clinical Feature Extraction (if trait_row is not None)\n",
197
+ "if trait_row is not None:\n",
198
+ " # We need to create the clinical data DataFrame from the sample characteristics dictionary\n",
199
+ " # The sample characteristics dictionary is provided in the previous output\n",
200
+ " \n",
201
+ " # Create a dictionary mapping sample IDs to their characteristics\n",
202
+ " sample_ids = ['GSM1369681', 'GSM1369682', 'GSM1369683', 'GSM1369684', 'GSM1369685',\n",
203
+ " 'GSM1369686', 'GSM1369687', 'GSM1369688', 'GSM1369689', 'GSM1369690',\n",
204
+ " 'GSM1369691', 'GSM1369692', 'GSM1369693', 'GSM1369694', 'GSM1369695',\n",
205
+ " 'GSM1369696', 'GSM1369697', 'GSM1369698', 'GSM1369699', 'GSM1369700',\n",
206
+ " 'GSM1369701', 'GSM1369702', 'GSM1369703', 'GSM1369704', 'GSM1369705',\n",
207
+ " 'GSM1369706', 'GSM1369707', 'GSM1369708', 'GSM1369709', 'GSM1369710']\n",
208
+ " \n",
209
+ " # Create the clinical data DataFrame with sample characteristics\n",
210
+ " clinical_data = pd.DataFrame(index=sample_ids)\n",
211
+ " \n",
212
+ " # Fill in the trait values from row 4\n",
213
+ " trait_values = [\n",
214
+ " 'response 3 classes: CR',\n",
215
+ " 'response 3 classes: RES',\n",
216
+ " 'response 3 classes: PR',\n",
217
+ " 'response 3 classes: PR',\n",
218
+ " 'response 3 classes: PR',\n",
219
+ " 'response 3 classes: PR',\n",
220
+ " 'response 3 classes: PR',\n",
221
+ " 'response 3 classes: PR',\n",
222
+ " 'response 3 classes: PR',\n",
223
+ " 'response 3 classes: PR',\n",
224
+ " 'response 3 classes: PR',\n",
225
+ " 'response 3 classes: PR',\n",
226
+ " 'response 3 classes: PR',\n",
227
+ " 'response 3 classes: PR',\n",
228
+ " 'response 3 classes: PR',\n",
229
+ " 'response 3 classes: PR',\n",
230
+ " 'response 3 classes: PR',\n",
231
+ " 'response 3 classes: PR',\n",
232
+ " 'response 3 classes: PR',\n",
233
+ " 'response 3 classes: PR',\n",
234
+ " 'response 3 classes: PR',\n",
235
+ " 'response 3 classes: PR',\n",
236
+ " 'response 3 classes: PR',\n",
237
+ " 'response 3 classes: PR',\n",
238
+ " 'response 3 classes: PR',\n",
239
+ " 'response 3 classes: PR',\n",
240
+ " 'response 3 classes: PR',\n",
241
+ " 'response 3 classes: PR',\n",
242
+ " 'response 3 classes: PR',\n",
243
+ " 'response 3 classes: PR'\n",
244
+ " ]\n",
245
+ " \n",
246
+ " # Add traits to the DataFrame\n",
247
+ " clinical_data[trait_row] = trait_values\n",
248
+ " \n",
249
+ " # Extract clinical features using the function from the library\n",
250
+ " selected_clinical_df = geo_select_clinical_features(\n",
251
+ " clinical_df=clinical_data,\n",
252
+ " trait=trait,\n",
253
+ " trait_row=trait_row,\n",
254
+ " convert_trait=convert_trait,\n",
255
+ " age_row=age_row,\n",
256
+ " convert_age=convert_age,\n",
257
+ " gender_row=gender_row,\n",
258
+ " convert_gender=convert_gender\n",
259
+ " )\n",
260
+ " \n",
261
+ " # Preview the extracted clinical features\n",
262
+ " print(\"Preview of selected clinical features:\")\n",
263
+ " preview = preview_df(selected_clinical_df)\n",
264
+ " print(preview)\n",
265
+ " \n",
266
+ " # Create directory if it doesn't exist\n",
267
+ " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
268
+ " \n",
269
+ " # Save the extracted clinical features to CSV\n",
270
+ " selected_clinical_df.to_csv(out_clinical_data_file)\n",
271
+ " print(f\"Clinical data saved to: {out_clinical_data_file}\")\n"
272
+ ]
273
+ },
274
+ {
275
+ "cell_type": "markdown",
276
+ "id": "562015bd",
277
+ "metadata": {},
278
+ "source": [
279
+ "### Step 3: Gene Data Extraction"
280
+ ]
281
+ },
282
+ {
283
+ "cell_type": "code",
284
+ "execution_count": 4,
285
+ "id": "65c66afc",
286
+ "metadata": {
287
+ "execution": {
288
+ "iopub.execute_input": "2025-03-25T08:24:26.490295Z",
289
+ "iopub.status.busy": "2025-03-25T08:24:26.490176Z",
290
+ "iopub.status.idle": "2025-03-25T08:24:26.750724Z",
291
+ "shell.execute_reply": "2025-03-25T08:24:26.750080Z"
292
+ }
293
+ },
294
+ "outputs": [
295
+ {
296
+ "name": "stdout",
297
+ "output_type": "stream",
298
+ "text": [
299
+ "Found data marker at line 79\n",
300
+ "Header line: \"ID_REF\"\t\"GSM1366951\"\t\"GSM1366952\"\t\"GSM1366953\"\t\"GSM1366954\"\t\"GSM1366955\"\t\"GSM1366956\"\t\"GSM1366957\"\t\"GSM1366958\"\t\"GSM1366959\"\t\"GSM1366960\"\t\"GSM1366961\"\t\"GSM1366962\"\t\"GSM1366963\"\t\"GSM1366964\"\t\"GSM1366965\"\t\"GSM1366966\"\t\"GSM1366967\"\t\"GSM1366968\"\t\"GSM1366969\"\t\"GSM1366970\"\t\"GSM1366971\"\t\"GSM1366972\"\t\"GSM1366973\"\t\"GSM1366974\"\t\"GSM1366975\"\t\"GSM1366976\"\t\"GSM1366977\"\t\"GSM1366978\"\t\"GSM1366979\"\t\"GSM1366980\"\t\"GSM1366981\"\t\"GSM1366982\"\t\"GSM1366983\"\t\"GSM1366984\"\t\"GSM1366985\"\t\"GSM1366986\"\t\"GSM1366987\"\t\"GSM1366988\"\t\"GSM1366989\"\t\"GSM1366990\"\t\"GSM1366991\"\t\"GSM1366992\"\t\"GSM1366993\"\t\"GSM1366994\"\t\"GSM1366995\"\t\"GSM1366996\"\t\"GSM1366997\"\t\"GSM1366998\"\t\"GSM1366999\"\t\"GSM1367000\"\t\"GSM1367001\"\t\"GSM1367002\"\t\"GSM1367003\"\t\"GSM1367004\"\t\"GSM1367005\"\t\"GSM1367006\"\t\"GSM1367007\"\t\"GSM1367008\"\t\"GSM1367009\"\t\"GSM1367010\"\t\"GSM1367011\"\t\"GSM1367012\"\t\"GSM1367013\"\t\"GSM1367014\"\t\"GSM1367015\"\t\"GSM1367016\"\t\"GSM1367017\"\t\"GSM1367018\"\t\"GSM1367019\"\t\"GSM1367020\"\t\"GSM1367021\"\t\"GSM1367022\"\n",
301
+ "First data line: \"ILMN_1343291\"\t3521.337305\t3165.43762\t3154.461427\t3153.589722\t3082.240701\t3132.744699\t2764.465751\t3297.647817\t3795.286897\t2748.380793\t3646.884134\t3234.991847\t3171.999862\t4648.063313\t2632.995659\t4120.122372\t1226.915629\t3693.853979\t2649.18146\t2477.394289\t2652.917804\t3103.096928\t2791.580976\t3554.031087\t3277.268916\t2167.371162\t3246.750878\t3446.867221\t3153.268646\t3009.96851\t3235.171861\t2602.726147\t2829.568991\t3624.203926\t3327.716293\t3138.459625\t2702.411971\t4339.685511\t5083.082607\t3103.883442\t3210.789587\t3087.855255\t2961.470727\t2809.480122\t2870.398121\t3160.124177\t3319.004415\t2778.061373\t3245.315998\t3111.446953\t3055.442459\t2950.264135\t3548.106566\t2926.373742\t3110.400044\t2719.532334\t3002.041161\t3876.147573\t3274.895153\t2692.229621\t3169.830871\t1977.782997\t2734.231265\t3216.918021\t3351.124023\t3027.703371\t3229.380938\t2690.50499\t4538.705237\t3031.497553\t3906.734941\t3599.313062\n"
302
+ ]
303
+ },
304
+ {
305
+ "name": "stdout",
306
+ "output_type": "stream",
307
+ "text": [
308
+ "Index(['ILMN_1343291', 'ILMN_1651209', 'ILMN_1651228', 'ILMN_1651229',\n",
309
+ " 'ILMN_1651235', 'ILMN_1651236', 'ILMN_1651237', 'ILMN_1651238',\n",
310
+ " 'ILMN_1651254', 'ILMN_1651260', 'ILMN_1651262', 'ILMN_1651268',\n",
311
+ " 'ILMN_1651278', 'ILMN_1651282', 'ILMN_1651285', 'ILMN_1651286',\n",
312
+ " 'ILMN_1651292', 'ILMN_1651303', 'ILMN_1651309', 'ILMN_1651315'],\n",
313
+ " dtype='object', name='ID')\n"
314
+ ]
315
+ }
316
+ ],
317
+ "source": [
318
+ "# 1. Get the file paths for the SOFT file and matrix file\n",
319
+ "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
320
+ "\n",
321
+ "# 2. First, let's examine the structure of the matrix file to understand its format\n",
322
+ "import gzip\n",
323
+ "\n",
324
+ "# Peek at the first few lines of the file to understand its structure\n",
325
+ "with gzip.open(matrix_file, 'rt') as file:\n",
326
+ " # Read first 100 lines to find the header structure\n",
327
+ " for i, line in enumerate(file):\n",
328
+ " if '!series_matrix_table_begin' in line:\n",
329
+ " print(f\"Found data marker at line {i}\")\n",
330
+ " # Read the next line which should be the header\n",
331
+ " header_line = next(file)\n",
332
+ " print(f\"Header line: {header_line.strip()}\")\n",
333
+ " # And the first data line\n",
334
+ " first_data_line = next(file)\n",
335
+ " print(f\"First data line: {first_data_line.strip()}\")\n",
336
+ " break\n",
337
+ " if i > 100: # Limit search to first 100 lines\n",
338
+ " print(\"Matrix table marker not found in first 100 lines\")\n",
339
+ " break\n",
340
+ "\n",
341
+ "# 3. Now try to get the genetic data with better error handling\n",
342
+ "try:\n",
343
+ " gene_data = get_genetic_data(matrix_file)\n",
344
+ " print(gene_data.index[:20])\n",
345
+ "except KeyError as e:\n",
346
+ " print(f\"KeyError: {e}\")\n",
347
+ " \n",
348
+ " # Alternative approach: manually extract the data\n",
349
+ " print(\"\\nTrying alternative approach to read the gene data:\")\n",
350
+ " with gzip.open(matrix_file, 'rt') as file:\n",
351
+ " # Find the start of the data\n",
352
+ " for line in file:\n",
353
+ " if '!series_matrix_table_begin' in line:\n",
354
+ " break\n",
355
+ " \n",
356
+ " # Read the headers and data\n",
357
+ " import pandas as pd\n",
358
+ " df = pd.read_csv(file, sep='\\t', index_col=0)\n",
359
+ " print(f\"Column names: {df.columns[:5]}\")\n",
360
+ " print(f\"First 20 row IDs: {df.index[:20]}\")\n",
361
+ " gene_data = df\n"
362
+ ]
363
+ },
364
+ {
365
+ "cell_type": "markdown",
366
+ "id": "b726a634",
367
+ "metadata": {},
368
+ "source": [
369
+ "### Step 4: Gene Identifier Review"
370
+ ]
371
+ },
372
+ {
373
+ "cell_type": "code",
374
+ "execution_count": 5,
375
+ "id": "8a0c2e5f",
376
+ "metadata": {
377
+ "execution": {
378
+ "iopub.execute_input": "2025-03-25T08:24:26.752524Z",
379
+ "iopub.status.busy": "2025-03-25T08:24:26.752388Z",
380
+ "iopub.status.idle": "2025-03-25T08:24:26.754750Z",
381
+ "shell.execute_reply": "2025-03-25T08:24:26.754308Z"
382
+ }
383
+ },
384
+ "outputs": [],
385
+ "source": [
386
+ "# Looking at the identifiers, they start with \"ILMN_\" which indicates they are Illumina probe IDs\n",
387
+ "# These are not standard human gene symbols and will need to be mapped to gene symbols\n",
388
+ "\n",
389
+ "# Illumina IDs (ILMN_) are microarray probe identifiers from Illumina BeadArray platforms\n",
390
+ "# They need to be converted to standard gene symbols for biological interpretation\n",
391
+ "\n",
392
+ "requires_gene_mapping = True\n"
393
+ ]
394
+ },
395
+ {
396
+ "cell_type": "markdown",
397
+ "id": "b76b6b4c",
398
+ "metadata": {},
399
+ "source": [
400
+ "### Step 5: Gene Annotation"
401
+ ]
402
+ },
403
+ {
404
+ "cell_type": "code",
405
+ "execution_count": 6,
406
+ "id": "9429fc51",
407
+ "metadata": {
408
+ "execution": {
409
+ "iopub.execute_input": "2025-03-25T08:24:26.756391Z",
410
+ "iopub.status.busy": "2025-03-25T08:24:26.756273Z",
411
+ "iopub.status.idle": "2025-03-25T08:24:31.756466Z",
412
+ "shell.execute_reply": "2025-03-25T08:24:31.755820Z"
413
+ }
414
+ },
415
+ "outputs": [
416
+ {
417
+ "name": "stdout",
418
+ "output_type": "stream",
419
+ "text": [
420
+ "Gene annotation preview:\n",
421
+ "{'ID': ['ILMN_3166687', 'ILMN_3165566', 'ILMN_3164811', 'ILMN_3165363', 'ILMN_3166511'], 'Transcript': ['ILMN_333737', 'ILMN_333646', 'ILMN_333584', 'ILMN_333628', 'ILMN_333719'], 'Species': ['ILMN Controls', 'ILMN Controls', 'ILMN Controls', 'ILMN Controls', 'ILMN Controls'], 'Source': ['ILMN_Controls', 'ILMN_Controls', 'ILMN_Controls', 'ILMN_Controls', 'ILMN_Controls'], 'Search_Key': ['ERCC-00162', 'ERCC-00071', 'ERCC-00009', 'ERCC-00053', 'ERCC-00144'], 'ILMN_Gene': ['ERCC-00162', 'ERCC-00071', 'ERCC-00009', 'ERCC-00053', 'ERCC-00144'], 'Source_Reference_ID': ['ERCC-00162', 'ERCC-00071', 'ERCC-00009', 'ERCC-00053', 'ERCC-00144'], 'RefSeq_ID': [nan, nan, nan, nan, nan], 'Entrez_Gene_ID': [nan, nan, nan, nan, nan], 'GI': [nan, nan, nan, nan, nan], 'Accession': ['DQ516750', 'DQ883654', 'DQ668364', 'DQ516785', 'DQ854995'], 'Symbol': ['ERCC-00162', 'ERCC-00071', 'ERCC-00009', 'ERCC-00053', 'ERCC-00144'], 'Protein_Product': [nan, nan, nan, nan, nan], 'Array_Address_Id': [5270161.0, 4260594.0, 7610424.0, 5260356.0, 2030196.0], 'Probe_Type': ['S', 'S', 'S', 'S', 'S'], 'Probe_Start': [12.0, 224.0, 868.0, 873.0, 130.0], 'SEQUENCE': ['CCCATGTGTCCAATTCTGAATATCTTTCCAGCTAAGTGCTTCTGCCCACC', 'GGATTAACTGCTGTGGTGTGTCATACTCGGCTACCTCCTGGTTTGGCGTC', 'GACCACGCCTTGTAATCGTATGACACGCGCTTGACACGACTGAATCCAGC', 'CTGCAATGCCATTAACAACCTTAGCACGGTATTTCCAGTAGCTGGTGAGC', 'CGTGCAGACAGGGATCGTAAGGCGATCCAGCCGGTATACCTTAGTCACAT'], 'Chromosome': [nan, nan, nan, nan, nan], 'Probe_Chr_Orientation': [nan, nan, nan, nan, nan], 'Probe_Coordinates': [nan, nan, nan, nan, nan], 'Cytoband': [nan, nan, nan, nan, nan], 'Definition': ['Methanocaldococcus jannaschii spike-in control MJ-500-33 genomic sequence', 'Synthetic construct clone NISTag13 external RNA control sequence', 'Synthetic construct clone TagJ microarray control', 'Methanocaldococcus jannaschii spike-in control MJ-1000-68 genomic sequence', 'Synthetic construct clone AG006.1100 external RNA control sequence'], 'Ontology_Component': [nan, nan, nan, nan, nan], 'Ontology_Process': [nan, nan, nan, nan, nan], 'Ontology_Function': [nan, nan, nan, nan, nan], 'Synonyms': [nan, nan, nan, nan, nan], 'Obsolete_Probe_Id': [nan, nan, nan, nan, nan], 'GB_ACC': ['DQ516750', 'DQ883654', 'DQ668364', 'DQ516785', 'DQ854995']}\n"
422
+ ]
423
+ }
424
+ ],
425
+ "source": [
426
+ "# 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.\n",
427
+ "gene_annotation = get_gene_annotation(soft_file)\n",
428
+ "\n",
429
+ "# 2. Use the 'preview_df' function from the library to preview the data and print out the results.\n",
430
+ "print(\"Gene annotation preview:\")\n",
431
+ "print(preview_df(gene_annotation))\n"
432
+ ]
433
+ },
434
+ {
435
+ "cell_type": "markdown",
436
+ "id": "87ccaaee",
437
+ "metadata": {},
438
+ "source": [
439
+ "### Step 6: Gene Identifier Mapping"
440
+ ]
441
+ },
442
+ {
443
+ "cell_type": "code",
444
+ "execution_count": 7,
445
+ "id": "edbeae2b",
446
+ "metadata": {
447
+ "execution": {
448
+ "iopub.execute_input": "2025-03-25T08:24:31.758369Z",
449
+ "iopub.status.busy": "2025-03-25T08:24:31.758229Z",
450
+ "iopub.status.idle": "2025-03-25T08:24:32.868158Z",
451
+ "shell.execute_reply": "2025-03-25T08:24:32.867452Z"
452
+ }
453
+ },
454
+ "outputs": [
455
+ {
456
+ "name": "stdout",
457
+ "output_type": "stream",
458
+ "text": [
459
+ "Gene mapping preview (first 5 rows):\n",
460
+ " ID Gene\n",
461
+ "0 ILMN_3166687 ERCC-00162\n",
462
+ "1 ILMN_3165566 ERCC-00071\n",
463
+ "2 ILMN_3164811 ERCC-00009\n",
464
+ "3 ILMN_3165363 ERCC-00053\n",
465
+ "4 ILMN_3166511 ERCC-00144\n"
466
+ ]
467
+ },
468
+ {
469
+ "name": "stdout",
470
+ "output_type": "stream",
471
+ "text": [
472
+ "Dimensions of gene expression data after mapping: (20211, 72)\n",
473
+ "Preview of gene expression data after mapping (first 5 genes):\n",
474
+ " GSM1366951 GSM1366952 GSM1366953 GSM1366954 GSM1366955 \\\n",
475
+ "Gene \n",
476
+ "A1BG 118.389670 144.600702 122.886608 133.022756 142.476847 \n",
477
+ "A1CF 759.060159 1817.612371 808.235136 977.351679 1207.345218 \n",
478
+ "A26C3 113.607415 106.275437 123.190609 119.261428 116.022301 \n",
479
+ "A2BP1 531.492788 700.987161 602.783304 657.927725 789.555525 \n",
480
+ "A2LD1 148.447316 153.643459 300.927913 420.407326 164.404106 \n",
481
+ "\n",
482
+ " GSM1366956 GSM1366957 GSM1366958 GSM1366959 GSM1366960 ... \\\n",
483
+ "Gene ... \n",
484
+ "A1BG 131.775939 128.508176 135.696979 119.674105 129.621366 ... \n",
485
+ "A1CF 1821.464618 1854.497192 1744.429754 770.568048 488.976178 ... \n",
486
+ "A26C3 105.967047 110.855337 112.252253 116.457441 112.159092 ... \n",
487
+ "A2BP1 454.391780 444.731300 472.251329 1049.291007 463.863503 ... \n",
488
+ "A2LD1 427.324463 366.442160 447.262945 175.492016 219.622057 ... \n",
489
+ "\n",
490
+ " GSM1367013 GSM1367014 GSM1367015 GSM1367016 GSM1367017 \\\n",
491
+ "Gene \n",
492
+ "A1BG 122.885849 129.478171 130.077685 123.582661 122.097605 \n",
493
+ "A1CF 1313.168194 2087.190080 1531.901017 850.247611 1475.088604 \n",
494
+ "A26C3 104.261978 975.991830 112.836137 138.884464 111.234431 \n",
495
+ "A2BP1 559.150127 458.203412 499.167731 449.171124 582.178155 \n",
496
+ "A2LD1 207.479132 298.380885 425.806037 325.345643 263.939011 \n",
497
+ "\n",
498
+ " GSM1367018 GSM1367019 GSM1367020 GSM1367021 GSM1367022 \n",
499
+ "Gene \n",
500
+ "A1BG 140.354502 133.022162 139.057344 126.619216 117.106583 \n",
501
+ "A1CF 963.882272 671.401800 1200.167478 671.711028 1104.967884 \n",
502
+ "A26C3 123.574498 143.116296 123.057562 126.327795 113.804219 \n",
503
+ "A2BP1 466.418865 1734.946029 470.169792 486.859132 449.555070 \n",
504
+ "A2LD1 268.233347 163.154391 313.292936 195.617996 284.338040 \n",
505
+ "\n",
506
+ "[5 rows x 72 columns]\n"
507
+ ]
508
+ },
509
+ {
510
+ "name": "stdout",
511
+ "output_type": "stream",
512
+ "text": [
513
+ "Gene expression data saved to: ../../output/preprocess/Colon_and_Rectal_Cancer/gene_data/GSE56699.csv\n"
514
+ ]
515
+ }
516
+ ],
517
+ "source": [
518
+ "# 1. Analyze the gene annotation and expression data to determine the mapping columns\n",
519
+ "# Based on the output, 'ID' in gene_annotation corresponds to 'ILMN_xxxxx' identifiers in gene_data\n",
520
+ "# 'Symbol' is the column containing gene symbols in gene_annotation\n",
521
+ "\n",
522
+ "# 2. Get gene mapping dataframe by extracting ID and Symbol columns\n",
523
+ "gene_mapping = get_gene_mapping(gene_annotation, prob_col=\"ID\", gene_col=\"Symbol\")\n",
524
+ "\n",
525
+ "print(\"Gene mapping preview (first 5 rows):\")\n",
526
+ "print(gene_mapping.head())\n",
527
+ "\n",
528
+ "# 3. Apply gene mapping to convert probe-level measurements to gene expression data\n",
529
+ "# This will handle the many-to-many relations by dividing probe values equally among mapped genes\n",
530
+ "# and then summing up all probe values for each gene\n",
531
+ "gene_data = apply_gene_mapping(gene_data, gene_mapping)\n",
532
+ "\n",
533
+ "print(f\"Dimensions of gene expression data after mapping: {gene_data.shape}\")\n",
534
+ "print(\"Preview of gene expression data after mapping (first 5 genes):\")\n",
535
+ "print(gene_data.head())\n",
536
+ "\n",
537
+ "# Create directory if it doesn't exist\n",
538
+ "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
539
+ "\n",
540
+ "# Save gene expression data to CSV\n",
541
+ "gene_data.to_csv(out_gene_data_file)\n",
542
+ "print(f\"Gene expression data saved to: {out_gene_data_file}\")\n"
543
+ ]
544
+ },
545
+ {
546
+ "cell_type": "markdown",
547
+ "id": "7f4eeafa",
548
+ "metadata": {},
549
+ "source": [
550
+ "### Step 7: Data Normalization and Linking"
551
+ ]
552
+ },
553
+ {
554
+ "cell_type": "code",
555
+ "execution_count": 8,
556
+ "id": "6a0f69f6",
557
+ "metadata": {
558
+ "execution": {
559
+ "iopub.execute_input": "2025-03-25T08:24:32.870082Z",
560
+ "iopub.status.busy": "2025-03-25T08:24:32.869943Z",
561
+ "iopub.status.idle": "2025-03-25T08:24:33.135414Z",
562
+ "shell.execute_reply": "2025-03-25T08:24:33.134773Z"
563
+ }
564
+ },
565
+ "outputs": [
566
+ {
567
+ "name": "stdout",
568
+ "output_type": "stream",
569
+ "text": [
570
+ "Clinical data structure:\n",
571
+ "{0: ['patient code: RCa0001', 'patient code: RCa0002', 'patient code: RCa0003', 'patient code: RCa0004', 'patient code: RCa0005', 'patient code: RCa0006', 'patient code: RCa0007', 'patient code: RCa0008', 'patient code: RCa0009', 'patient code: RCa0010', 'patient code: RCa0011', 'patient code: RCa0012', 'patient code: RCa0013', 'patient code: RCa0014', 'patient code: RCa0015', 'patient code: RCa0016', 'patient code: RCa0024', 'patient code: RCa0026', 'patient code: RCa0027', 'patient code: RCa0028', 'patient code: RCa0029', 'patient code: RCa0030', 'patient code: RCa0031', 'patient code: RCa0032', 'patient code: RCa0033', 'patient code: RCa0034', 'patient code: RCa0035', 'patient code: RCa0036', 'patient code: RCa0037', 'patient code: RCa0038'], 1: ['sample type: SS', 'sample type: PB'], 2: ['origin: Brussel: UZ Brussel Oncologisch Centrum', 'origin: Candiolo: Institute for Cancer Research, University of Turin', 'origin: Turin: Deparment of Medical Science, University of Turin', 'origin: Cluj-Napaca: University of Medicine and Pharmacology'], 3: ['mandard: 3', 'mandard: 4', 'mandard: 1', 'mandard: NA', 'mandard: 5', 'mandard: 2'], 4: ['response 3 classes: CR', 'response 3 classes: RES', 'response 3 classes: PR'], 5: ['diagnosis: Invasive low grade adenocarcinoma of the rectum', 'diagnosis: Tubulovilleus adenoma', 'diagnosis: Transmural invasive moderately differentiated adenocarcinoma', 'diagnosis: Invasive moederately differentiated adeocarcinoma', 'diagnosis: Moderately differentiated adenocarcinoma', 'diagnosis: Transmural scare, without any residual vital tumor tissue', 'diagnosis: Transmural invasive moderately to bad differentiated adenocarcinoma', 'diagnosis: Invasive, moderately to bad differentiated adenocarcinoma', 'diagnosis: Low-grade adenocarcinoma', 'diagnosis: Maderately differentiated adenocarcinoma', 'diagnosis: Poorly differentiated invasive adenocarcinoma (no surgical specimen available)', 'diagnosis: Low-grade adenocarcinoma with invasion of the perirectal fat', 'diagnosis: Poorly differentiated invasive adenocarcinoma', 'diagnosis: Invasive adenocarcinoma', 'diagnosis: Adenocarcinom, at least intramucosaal (no surgical specimen available)', 'diagnosis: Invasive adenocarcinoma (grade op invasion not to be determined)', 'diagnosis: The major part of the tumor is a tubular villus adenoma, with limited parts of well differantiated intramucosaal invasive adenocarcinoma', 'diagnosis: Tubular adenoma with moderate dysplasia', 'diagnosis: Invasive, moderately differentiated adenocarcinoma', 'diagnosis: Invasive, moderately differentiated adenorcarcinoma, at least intramucosaal', 'diagnosis: Transmural invasive moderately differentiated adenocarcinoma (cilinder cells)', 'diagnosis: invasive, moderately differentiated adenocarcinoma (cilinder cells)', 'diagnosis: Transmural invasive moderately differentiated adenocarcinoma (intestinal type)', 'diagnosis: Invasive well differentiated adenocarcinoma (cilinder cells)', 'diagnosis: Tubulovilleus adenoma with invasion in the submucosa (at least pT1)', 'diagnosis: No residual tumorcells found in ulcus', 'diagnosis: NA', 'diagnosis: adenocarcinoma', 'diagnosis: Adenocarcinoma Tubulare G2', 'diagnosis: 1) Polipo valvola ileo-cecale; 2) Micropolipi colon trasverso; 3) Polipo; 4) Adenocarcinoma moderatamente differenziato (G2)'], 6: ['recurrence: 0', 'recurrence: 1', 'note: Mucosa', 'recurrence: NA'], 7: ['df: 35', 'df: 44', 'df: 63', 'df: 54', 'df: 79', 'df: 16', 'df: 74', 'df: 62', 'df: 58', 'df: 56', 'df: 25', 'df: 20', 'df: 12', 'recurrence: NA', 'df: NA', 'df: 31', 'df: 32', 'df: 24', 'df: 37', 'df: 53', 'df: 55', 'df: 69', 'df: 77', 'df: 26', 'df: 29', 'df: 17', 'df: 13', 'df: 27', 'df: 11', 'df: 4'], 8: ['death: 0', 'death: 1', 'df: NA', 'death: NA'], 9: ['dsf: 35', 'dsf: 44', 'dsf: 63', 'dsf: 54', 'dsf: 79', 'dsf: 16', 'dsf: 74', 'dsf: 62', 'dsf: 58', 'dsf: 56', 'dsf: 36', 'dsf: 27', 'dsf: 13', 'death: NA', 'dsf: NA', 'dsf: 31', 'dsf: 32', 'dsf: 33', 'dsf: 39', 'dsf: 53', 'dsf: 55', 'dsf: 69', 'dsf: 77', 'dsf: 26', 'dsf: 17', 'dsf: 20', 'dsf: 71', 'dsf: 18', 'dsf: 4', 'dsf: 15'], 10: [nan, 'dsf: NA']}\n",
572
+ "Corrected clinical data saved to ../../output/preprocess/Colon_and_Rectal_Cancer/clinical_data/GSE56699.csv\n",
573
+ "Linked data shape: (72, 20212)\n",
574
+ "Data after handling missing values: (0, 1)\n",
575
+ "Quartiles for 'Colon_and_Rectal_Cancer':\n",
576
+ " 25%: nan\n",
577
+ " 50% (Median): nan\n",
578
+ " 75%: nan\n",
579
+ "Min: nan\n",
580
+ "Max: nan\n",
581
+ "The distribution of the feature 'Colon_and_Rectal_Cancer' in this dataset is fine.\n",
582
+ "\n",
583
+ "Abnormality detected in the cohort: GSE56699. Preprocessing failed.\n",
584
+ "Data was determined to be unusable and was not saved\n"
585
+ ]
586
+ }
587
+ ],
588
+ "source": [
589
+ "# 1. Load the normalized gene data \n",
590
+ "gene_data = pd.read_csv(out_gene_data_file, index_col=0)\n",
591
+ "\n",
592
+ "# 2. Re-extract clinical features from the SOFT file to get proper clinical data\n",
593
+ "# Use the actual clinical data from the matrix file properly\n",
594
+ "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
595
+ "background_info, clinical_data = get_background_and_clinical_data(matrix_file)\n",
596
+ "\n",
597
+ "# 3. Create a correct clinical features dataframe\n",
598
+ "# First inspect what's in the clinical data\n",
599
+ "clinical_data_dict = get_unique_values_by_row(clinical_data)\n",
600
+ "print(\"Clinical data structure:\")\n",
601
+ "print(clinical_data_dict)\n",
602
+ "\n",
603
+ "# Based on the sample characteristics dictionary shown previously, \n",
604
+ "# extract and process clinical features\n",
605
+ "selected_clinical_df = pd.DataFrame()\n",
606
+ "\n",
607
+ "# Process disease state row manually to ensure correct mapping\n",
608
+ "disease_row = clinical_data.iloc[trait_row]\n",
609
+ "samples = [col for col in disease_row.index if col != \"!Sample_geo_accession\"]\n",
610
+ "trait_values = []\n",
611
+ "\n",
612
+ "for sample in samples:\n",
613
+ " value = disease_row[sample]\n",
614
+ " if pd.isna(value):\n",
615
+ " trait_values.append(None)\n",
616
+ " else:\n",
617
+ " if \":\" in value:\n",
618
+ " value = value.split(\":\", 1)[1].strip()\n",
619
+ " \n",
620
+ " if \"IBS\" in value:\n",
621
+ " trait_values.append(1) # IBS is our target trait\n",
622
+ " elif \"IBD\" in value:\n",
623
+ " trait_values.append(0) # IBD is the control\n",
624
+ " else:\n",
625
+ " trait_values.append(None)\n",
626
+ "\n",
627
+ "# Create dataframe with processed values\n",
628
+ "selected_clinical_df[trait] = trait_values\n",
629
+ "selected_clinical_df.index = samples\n",
630
+ "\n",
631
+ "# Save the corrected clinical data\n",
632
+ "os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
633
+ "selected_clinical_df.to_csv(out_clinical_data_file)\n",
634
+ "print(f\"Corrected clinical data saved to {out_clinical_data_file}\")\n",
635
+ "\n",
636
+ "# 4. Link the clinical and genetic data\n",
637
+ "linked_data = pd.DataFrame()\n",
638
+ "# Transpose gene data to have samples as rows and genes as columns\n",
639
+ "gene_data_t = gene_data.T\n",
640
+ "# Verify alignment of sample IDs between clinical and gene data\n",
641
+ "common_samples = list(set(selected_clinical_df.index) & set(gene_data_t.index))\n",
642
+ "if common_samples:\n",
643
+ " gene_data_filtered = gene_data_t.loc[common_samples]\n",
644
+ " clinical_data_filtered = selected_clinical_df.loc[common_samples]\n",
645
+ " # Join the data\n",
646
+ " linked_data = pd.concat([clinical_data_filtered, gene_data_filtered], axis=1)\n",
647
+ " print(f\"Linked data shape: {linked_data.shape}\")\n",
648
+ "else:\n",
649
+ " # Alternative linking approach if sample IDs don't directly match\n",
650
+ " print(\"No common sample IDs found. Attempting alternative linking...\")\n",
651
+ " # The GSM ids in gene data columns may correspond to the sample IDs\n",
652
+ " clinical_data_reset = selected_clinical_df.reset_index()\n",
653
+ " clinical_data_reset.columns = [\"Sample\"] + list(clinical_data_reset.columns[1:])\n",
654
+ " gene_data_cols = list(gene_data.columns)\n",
655
+ " \n",
656
+ " # Create merged dataframe\n",
657
+ " data_dict = {trait: []}\n",
658
+ " # Add trait values\n",
659
+ " for col in gene_data_cols:\n",
660
+ " sample_idx = clinical_data_reset.index[clinical_data_reset[\"Sample\"] == col] if \"Sample\" in clinical_data_reset.columns else []\n",
661
+ " if len(sample_idx) > 0:\n",
662
+ " data_dict[trait].append(clinical_data_reset.loc[sample_idx[0], trait])\n",
663
+ " else:\n",
664
+ " data_dict[trait].append(None)\n",
665
+ " \n",
666
+ " # Add gene expression values\n",
667
+ " for gene in gene_data.index:\n",
668
+ " data_dict[gene] = list(gene_data.loc[gene])\n",
669
+ " \n",
670
+ " linked_data = pd.DataFrame(data_dict, index=gene_data_cols)\n",
671
+ " print(f\"Alternative linked data shape: {linked_data.shape}\")\n",
672
+ "\n",
673
+ "# 5. Handle missing values in the linked data\n",
674
+ "linked_data = handle_missing_values(linked_data, trait)\n",
675
+ "print(f\"Data after handling missing values: {linked_data.shape}\")\n",
676
+ "\n",
677
+ "# 6. Determine whether the trait and some demographic features are severely biased\n",
678
+ "is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)\n",
679
+ "\n",
680
+ "# 7. Conduct quality check and save the cohort information\n",
681
+ "is_usable = validate_and_save_cohort_info(\n",
682
+ " is_final=True, \n",
683
+ " cohort=cohort, \n",
684
+ " info_path=json_path, \n",
685
+ " is_gene_available=True, \n",
686
+ " is_trait_available=True, \n",
687
+ " is_biased=is_trait_biased, \n",
688
+ " df=unbiased_linked_data,\n",
689
+ " note=\"Dataset contains gene expression data from patients with IBS and IBD, examining effects of relaxation response mind-body intervention.\"\n",
690
+ ")\n",
691
+ "\n",
692
+ "# 8. If the linked data is usable, save it as a CSV file\n",
693
+ "if is_usable:\n",
694
+ " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n",
695
+ " unbiased_linked_data.to_csv(out_data_file)\n",
696
+ " print(f\"Linked data saved to {out_data_file}\")\n",
697
+ "else:\n",
698
+ " print(\"Data was determined to be unusable and was not saved\")"
699
+ ]
700
+ }
701
+ ],
702
+ "metadata": {
703
+ "language_info": {
704
+ "codemirror_mode": {
705
+ "name": "ipython",
706
+ "version": 3
707
+ },
708
+ "file_extension": ".py",
709
+ "mimetype": "text/x-python",
710
+ "name": "python",
711
+ "nbconvert_exporter": "python",
712
+ "pygments_lexer": "ipython3",
713
+ "version": "3.10.16"
714
+ }
715
+ },
716
+ "nbformat": 4,
717
+ "nbformat_minor": 5
718
+ }
code/Colon_and_Rectal_Cancer/TCGA.ipynb ADDED
@@ -0,0 +1,436 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": 1,
6
+ "id": "1c558516",
7
+ "metadata": {
8
+ "execution": {
9
+ "iopub.execute_input": "2025-03-25T08:24:34.027298Z",
10
+ "iopub.status.busy": "2025-03-25T08:24:34.027192Z",
11
+ "iopub.status.idle": "2025-03-25T08:24:34.191533Z",
12
+ "shell.execute_reply": "2025-03-25T08:24:34.191191Z"
13
+ }
14
+ },
15
+ "outputs": [],
16
+ "source": [
17
+ "import sys\n",
18
+ "import os\n",
19
+ "sys.path.append(os.path.abspath(os.path.join(os.getcwd(), '../..')))\n",
20
+ "\n",
21
+ "# Path Configuration\n",
22
+ "from tools.preprocess import *\n",
23
+ "\n",
24
+ "# Processing context\n",
25
+ "trait = \"Colon_and_Rectal_Cancer\"\n",
26
+ "\n",
27
+ "# Input paths\n",
28
+ "tcga_root_dir = \"../../input/TCGA\"\n",
29
+ "\n",
30
+ "# Output paths\n",
31
+ "out_data_file = \"../../output/preprocess/Colon_and_Rectal_Cancer/TCGA.csv\"\n",
32
+ "out_gene_data_file = \"../../output/preprocess/Colon_and_Rectal_Cancer/gene_data/TCGA.csv\"\n",
33
+ "out_clinical_data_file = \"../../output/preprocess/Colon_and_Rectal_Cancer/clinical_data/TCGA.csv\"\n",
34
+ "json_path = \"../../output/preprocess/Colon_and_Rectal_Cancer/cohort_info.json\"\n"
35
+ ]
36
+ },
37
+ {
38
+ "cell_type": "markdown",
39
+ "id": "3d3e1f61",
40
+ "metadata": {},
41
+ "source": [
42
+ "### Step 1: Initial Data Loading"
43
+ ]
44
+ },
45
+ {
46
+ "cell_type": "code",
47
+ "execution_count": 2,
48
+ "id": "e1bc4a32",
49
+ "metadata": {
50
+ "execution": {
51
+ "iopub.execute_input": "2025-03-25T08:24:34.192902Z",
52
+ "iopub.status.busy": "2025-03-25T08:24:34.192764Z",
53
+ "iopub.status.idle": "2025-03-25T08:24:35.172682Z",
54
+ "shell.execute_reply": "2025-03-25T08:24:35.172316Z"
55
+ }
56
+ },
57
+ "outputs": [
58
+ {
59
+ "name": "stdout",
60
+ "output_type": "stream",
61
+ "text": [
62
+ "Found potential match: TCGA_Liver_Cancer_(LIHC) (score: 1)\n",
63
+ "Found potential match: TCGA_Rectal_Cancer_(READ) (score: 2)\n",
64
+ "Found potential match: TCGA_Colon_and_Rectal_Cancer_(COADREAD) (score: 4)\n",
65
+ "Selected directory: TCGA_Colon_and_Rectal_Cancer_(COADREAD)\n",
66
+ "Clinical file: TCGA.COADREAD.sampleMap_COADREAD_clinicalMatrix\n",
67
+ "Genetic file: TCGA.COADREAD.sampleMap_HiSeqV2_PANCAN.gz\n"
68
+ ]
69
+ },
70
+ {
71
+ "name": "stdout",
72
+ "output_type": "stream",
73
+ "text": [
74
+ "\n",
75
+ "Clinical data columns:\n",
76
+ "['AWG_MLH1_silencing', 'AWG_cancer_type_Oct62011', 'CDE_ID_3226963', 'CIMP', 'MSI_updated_Oct62011', '_INTEGRATION', '_PANCAN_CNA_PANCAN_K8', '_PANCAN_Cluster_Cluster_PANCAN', '_PANCAN_DNAMethyl_COADREAD', '_PANCAN_DNAMethyl_PANCAN', '_PANCAN_RPPA_PANCAN_K8', '_PANCAN_UNC_RNAseq_PANCAN_K16', '_PANCAN_miRNA_PANCAN', '_PANCAN_mutation_PANCAN', '_PATIENT', '_cohort', '_primary_disease', '_primary_site', 'additional_pharmaceutical_therapy', 'additional_radiation_therapy', 'age_at_initial_pathologic_diagnosis', 'anatomic_neoplasm_subdivision', 'bcr_followup_barcode', 'bcr_patient_barcode', 'bcr_sample_barcode', 'braf_gene_analysis_performed', 'braf_gene_analysis_result', 'circumferential_resection_margin', 'colon_polyps_present', 'days_to_birth', 'days_to_collection', 'days_to_death', 'days_to_initial_pathologic_diagnosis', 'days_to_last_followup', 'days_to_new_tumor_event_additional_surgery_procedure', 'days_to_new_tumor_event_after_initial_treatment', 'disease_code', 'followup_case_report_form_submission_reason', 'followup_treatment_success', 'form_completion_date', 'gender', 'height', 'histological_type', 'history_of_colon_polyps', 'history_of_neoadjuvant_treatment', 'hypermutation', 'icd_10', 'icd_o_3_histology', 'icd_o_3_site', 'informed_consent_verified', 'initial_weight', 'intermediate_dimension', 'is_ffpe', 'kras_gene_analysis_performed', 'kras_mutation_codon', 'kras_mutation_found', 'longest_dimension', 'loss_expression_of_mismatch_repair_proteins_by_ihc', 'loss_expression_of_mismatch_repair_proteins_by_ihc_result', 'lost_follow_up', 'lymph_node_examined_count', 'lymphatic_invasion', 'microsatellite_instability', 'new_neoplasm_event_type', 'new_tumor_event_additional_surgery_procedure', 'new_tumor_event_after_initial_treatment', 'non_nodal_tumor_deposits', 'non_silent_mutation', 'non_silent_rate_per_Mb', 'number_of_abnormal_loci', 'number_of_first_degree_relatives_with_cancer_diagnosis', 'number_of_loci_tested', 'number_of_lymphnodes_positive_by_he', 'number_of_lymphnodes_positive_by_ihc', 'oct_embedded', 'pathologic_M', 'pathologic_N', 'pathologic_T', 'pathologic_stage', 'pathology_report_file_name', 'patient_id', 'perineural_invasion_present', 'person_neoplasm_cancer_status', 'postoperative_rx_tx', 'preoperative_pretreatment_cea_level', 'primary_lymph_node_presentation_assessment', 'primary_therapy_outcome_success', 'project_code', 'radiation_therapy', 'residual_disease_post_new_tumor_event_margin_status', 'residual_tumor', 'sample_type', 'sample_type_id', 'shortest_dimension', 'silent_mutation', 'silent_rate_per_Mb', 'site_of_additional_surgery_new_tumor_event_mets', 'synchronous_colon_cancer_present', 'system_version', 'tissue_prospective_collection_indicator', 'tissue_retrospective_collection_indicator', 'tissue_source_site', 'total_mutation', 'tumor_tissue_site', 'venous_invasion', 'vial_number', 'vital_status', 'weight', 'year_of_initial_pathologic_diagnosis', '_GENOMIC_ID_TCGA_COADREAD_exp_HiSeqV2_exon', '_GENOMIC_ID_TCGA_COADREAD_PDMRNAseq', '_GENOMIC_ID_TCGA_COADREAD_exp_HiSeqV2_PANCAN', '_GENOMIC_ID_TCGA_COADREAD_hMethyl450', '_GENOMIC_ID_TCGA_COADREAD_gistic2thd', '_GENOMIC_ID_TCGA_COADREAD_hMethyl27', '_GENOMIC_ID_TCGA_COADREAD_G4502A_07_3', '_GENOMIC_ID_TCGA_COADREAD_PDMarrayCNV', '_GENOMIC_ID_TCGA_COADREAD_exp_HiSeqV2', '_GENOMIC_ID_TCGA_COADREAD_PDMarray', '_GENOMIC_ID_TCGA_COADREAD_gistic2', '_GENOMIC_ID_TCGA_COADREAD_mutation', '_GENOMIC_ID_TCGA_COADREAD_RPPA_RBN', '_GENOMIC_ID_TCGA_COADREAD_PDMRNAseqCNV']\n",
77
+ "\n",
78
+ "Clinical data shape: (736, 123)\n",
79
+ "Genetic data shape: (20530, 434)\n"
80
+ ]
81
+ }
82
+ ],
83
+ "source": [
84
+ "import os\n",
85
+ "import pandas as pd\n",
86
+ "\n",
87
+ "# 1. Find the most relevant directory for Colon and Rectal Cancer\n",
88
+ "subdirectories = os.listdir(tcga_root_dir)\n",
89
+ "target_trait = trait.lower().replace(\"_\", \" \") # Convert to lowercase for case-insensitive matching\n",
90
+ "\n",
91
+ "# Start with no match, then find the best match based on similarity to target trait\n",
92
+ "best_match = None\n",
93
+ "best_match_score = 0\n",
94
+ "\n",
95
+ "for subdir in subdirectories:\n",
96
+ " subdir_lower = subdir.lower()\n",
97
+ " \n",
98
+ " # Calculate a simple similarity score - more matching words = better match\n",
99
+ " # This prioritizes exact matches over partial matches\n",
100
+ " score = 0\n",
101
+ " for word in target_trait.split():\n",
102
+ " if word in subdir_lower:\n",
103
+ " score += 1\n",
104
+ " \n",
105
+ " # Track the best match\n",
106
+ " if score > best_match_score:\n",
107
+ " best_match_score = score\n",
108
+ " best_match = subdir\n",
109
+ " print(f\"Found potential match: {subdir} (score: {score})\")\n",
110
+ "\n",
111
+ "# Use the best match if found\n",
112
+ "if best_match:\n",
113
+ " print(f\"Selected directory: {best_match}\")\n",
114
+ " \n",
115
+ " # 2. Get the clinical and genetic data file paths\n",
116
+ " cohort_dir = os.path.join(tcga_root_dir, best_match)\n",
117
+ " clinical_file_path, genetic_file_path = tcga_get_relevant_filepaths(cohort_dir)\n",
118
+ " \n",
119
+ " print(f\"Clinical file: {os.path.basename(clinical_file_path)}\")\n",
120
+ " print(f\"Genetic file: {os.path.basename(genetic_file_path)}\")\n",
121
+ " \n",
122
+ " # 3. Load the data files\n",
123
+ " clinical_df = pd.read_csv(clinical_file_path, sep='\\t', index_col=0)\n",
124
+ " genetic_df = pd.read_csv(genetic_file_path, sep='\\t', index_col=0)\n",
125
+ " \n",
126
+ " # 4. Print clinical data columns for inspection\n",
127
+ " print(\"\\nClinical data columns:\")\n",
128
+ " print(clinical_df.columns.tolist())\n",
129
+ " \n",
130
+ " # Print basic information about the datasets\n",
131
+ " print(f\"\\nClinical data shape: {clinical_df.shape}\")\n",
132
+ " print(f\"Genetic data shape: {genetic_df.shape}\")\n",
133
+ " \n",
134
+ " # Check if we have both gene and trait data\n",
135
+ " is_gene_available = genetic_df.shape[0] > 0\n",
136
+ " is_trait_available = clinical_df.shape[0] > 0\n",
137
+ " \n",
138
+ "else:\n",
139
+ " print(f\"No suitable directory found for {trait}.\")\n",
140
+ " is_gene_available = False\n",
141
+ " is_trait_available = False\n",
142
+ "\n",
143
+ "# Record the data availability\n",
144
+ "validate_and_save_cohort_info(\n",
145
+ " is_final=False,\n",
146
+ " cohort=\"TCGA\",\n",
147
+ " info_path=json_path,\n",
148
+ " is_gene_available=is_gene_available,\n",
149
+ " is_trait_available=is_trait_available\n",
150
+ ")\n",
151
+ "\n",
152
+ "# Exit if no suitable directory was found\n",
153
+ "if not best_match:\n",
154
+ " print(\"Skipping this trait as no suitable data was found.\")\n"
155
+ ]
156
+ },
157
+ {
158
+ "cell_type": "markdown",
159
+ "id": "709cd3d3",
160
+ "metadata": {},
161
+ "source": [
162
+ "### Step 2: Find Candidate Demographic Features"
163
+ ]
164
+ },
165
+ {
166
+ "cell_type": "code",
167
+ "execution_count": 3,
168
+ "id": "5933e2a7",
169
+ "metadata": {
170
+ "execution": {
171
+ "iopub.execute_input": "2025-03-25T08:24:35.174114Z",
172
+ "iopub.status.busy": "2025-03-25T08:24:35.174008Z",
173
+ "iopub.status.idle": "2025-03-25T08:24:35.185666Z",
174
+ "shell.execute_reply": "2025-03-25T08:24:35.185376Z"
175
+ }
176
+ },
177
+ "outputs": [
178
+ {
179
+ "name": "stdout",
180
+ "output_type": "stream",
181
+ "text": [
182
+ "Age columns preview:\n",
183
+ "{'age_at_initial_pathologic_diagnosis': [61.0, 67.0, 42.0, 74.0, nan], 'days_to_birth': [-22379.0, -24523.0, -15494.0, -27095.0, nan]}\n",
184
+ "\n",
185
+ "Gender columns preview:\n",
186
+ "{'gender': ['FEMALE', 'MALE', 'FEMALE', 'MALE', nan]}\n"
187
+ ]
188
+ }
189
+ ],
190
+ "source": [
191
+ "# Identify columns that might contain age information\n",
192
+ "candidate_age_cols = [\n",
193
+ " 'age_at_initial_pathologic_diagnosis',\n",
194
+ " 'days_to_birth' # Negative days to birth can represent age\n",
195
+ "]\n",
196
+ "\n",
197
+ "# Identify columns that might contain gender information\n",
198
+ "candidate_gender_cols = [\n",
199
+ " 'gender'\n",
200
+ "]\n",
201
+ "\n",
202
+ "# Load the clinical data to examine these columns\n",
203
+ "cohort_dir = os.path.join(tcga_root_dir, \"TCGA_Colon_and_Rectal_Cancer_(COADREAD)\")\n",
204
+ "clinical_file_path, _ = tcga_get_relevant_filepaths(cohort_dir)\n",
205
+ "clinical_df = pd.read_csv(clinical_file_path, sep='\\t', index_col=0)\n",
206
+ "\n",
207
+ "# Extract and preview age-related columns\n",
208
+ "if candidate_age_cols:\n",
209
+ " age_df = clinical_df[candidate_age_cols]\n",
210
+ " print(\"Age columns preview:\")\n",
211
+ " print(preview_df(age_df))\n",
212
+ "\n",
213
+ "# Extract and preview gender-related columns\n",
214
+ "if candidate_gender_cols:\n",
215
+ " gender_df = clinical_df[candidate_gender_cols]\n",
216
+ " print(\"\\nGender columns preview:\")\n",
217
+ " print(preview_df(gender_df))\n"
218
+ ]
219
+ },
220
+ {
221
+ "cell_type": "markdown",
222
+ "id": "37d99797",
223
+ "metadata": {},
224
+ "source": [
225
+ "### Step 3: Select Demographic Features"
226
+ ]
227
+ },
228
+ {
229
+ "cell_type": "code",
230
+ "execution_count": 4,
231
+ "id": "88b72458",
232
+ "metadata": {
233
+ "execution": {
234
+ "iopub.execute_input": "2025-03-25T08:24:35.186985Z",
235
+ "iopub.status.busy": "2025-03-25T08:24:35.186885Z",
236
+ "iopub.status.idle": "2025-03-25T08:24:35.190161Z",
237
+ "shell.execute_reply": "2025-03-25T08:24:35.189875Z"
238
+ }
239
+ },
240
+ "outputs": [
241
+ {
242
+ "name": "stdout",
243
+ "output_type": "stream",
244
+ "text": [
245
+ "Age column candidates:\n",
246
+ "Column: age_at_initial_pathologic_diagnosis, Values: [61.0, 67.0, 42.0, 74.0, None], Missing: 20.0%\n",
247
+ "Column: days_to_birth, Values: [-22379.0, -24523.0, -15494.0, -27095.0, None], Missing: 20.0%\n",
248
+ "\n",
249
+ "Gender column candidates:\n",
250
+ "Column: gender, Values: ['FEMALE', 'MALE', 'FEMALE', 'MALE', None], Missing: 20.0%\n",
251
+ "\n",
252
+ "Selected columns:\n",
253
+ "Age column: age_at_initial_pathologic_diagnosis\n",
254
+ "Gender column: gender\n"
255
+ ]
256
+ }
257
+ ],
258
+ "source": [
259
+ "# Check the age columns\n",
260
+ "print(\"Age column candidates:\")\n",
261
+ "for col, values in {'age_at_initial_pathologic_diagnosis': [61.0, 67.0, 42.0, 74.0, None], \n",
262
+ " 'days_to_birth': [-22379.0, -24523.0, -15494.0, -27095.0, None]}.items():\n",
263
+ " missing_count = sum(1 for v in values if v is None or pd.isna(v))\n",
264
+ " missing_percentage = missing_count / len(values) * 100\n",
265
+ " print(f\"Column: {col}, Values: {values}, Missing: {missing_percentage:.1f}%\")\n",
266
+ "\n",
267
+ "# Check the gender columns\n",
268
+ "print(\"\\nGender column candidates:\")\n",
269
+ "for col, values in {'gender': ['FEMALE', 'MALE', 'FEMALE', 'MALE', None]}.items():\n",
270
+ " missing_count = sum(1 for v in values if v is None or pd.isna(v))\n",
271
+ " missing_percentage = missing_count / len(values) * 100\n",
272
+ " print(f\"Column: {col}, Values: {values}, Missing: {missing_percentage:.1f}%\")\n",
273
+ "\n",
274
+ "# Select the columns\n",
275
+ "age_col = 'age_at_initial_pathologic_diagnosis' # Clear age values in years\n",
276
+ "gender_col = 'gender' # Standard gender labels\n",
277
+ "\n",
278
+ "print(\"\\nSelected columns:\")\n",
279
+ "print(f\"Age column: {age_col}\")\n",
280
+ "print(f\"Gender column: {gender_col}\")\n"
281
+ ]
282
+ },
283
+ {
284
+ "cell_type": "markdown",
285
+ "id": "a3d7c8f6",
286
+ "metadata": {},
287
+ "source": [
288
+ "### Step 4: Feature Engineering and Validation"
289
+ ]
290
+ },
291
+ {
292
+ "cell_type": "code",
293
+ "execution_count": 5,
294
+ "id": "342d196e",
295
+ "metadata": {
296
+ "execution": {
297
+ "iopub.execute_input": "2025-03-25T08:24:35.191386Z",
298
+ "iopub.status.busy": "2025-03-25T08:24:35.191287Z",
299
+ "iopub.status.idle": "2025-03-25T08:25:13.819637Z",
300
+ "shell.execute_reply": "2025-03-25T08:25:13.818967Z"
301
+ }
302
+ },
303
+ "outputs": [
304
+ {
305
+ "name": "stdout",
306
+ "output_type": "stream",
307
+ "text": [
308
+ "Normalized gene expression data saved to ../../output/preprocess/Colon_and_Rectal_Cancer/gene_data/TCGA.csv\n",
309
+ "Gene expression data shape after normalization: (19848, 434)\n",
310
+ "Clinical data saved to ../../output/preprocess/Colon_and_Rectal_Cancer/clinical_data/TCGA.csv\n",
311
+ "Clinical data shape: (736, 3)\n",
312
+ "Number of samples in clinical data: 736\n",
313
+ "Number of samples in genetic data: 434\n",
314
+ "Number of common samples: 434\n",
315
+ "Linked data shape: (434, 19851)\n"
316
+ ]
317
+ },
318
+ {
319
+ "name": "stdout",
320
+ "output_type": "stream",
321
+ "text": [
322
+ "Data shape after handling missing values: (434, 19851)\n",
323
+ "For the feature 'Colon_and_Rectal_Cancer', the least common label is '0' with 51 occurrences. This represents 11.75% of the dataset.\n",
324
+ "The distribution of the feature 'Colon_and_Rectal_Cancer' in this dataset is fine.\n",
325
+ "\n",
326
+ "Quartiles for 'Age':\n",
327
+ " 25%: 56.0\n",
328
+ " 50% (Median): 66.0\n",
329
+ " 75%: 75.0\n",
330
+ "Min: 31.0\n",
331
+ "Max: 90.0\n",
332
+ "The distribution of the feature 'Age' in this dataset is fine.\n",
333
+ "\n",
334
+ "For the feature 'Gender', the least common label is '0.0' with 199 occurrences. This represents 45.85% of the dataset.\n",
335
+ "The distribution of the feature 'Gender' in this dataset is fine.\n",
336
+ "\n"
337
+ ]
338
+ },
339
+ {
340
+ "name": "stdout",
341
+ "output_type": "stream",
342
+ "text": [
343
+ "Linked data saved to ../../output/preprocess/Colon_and_Rectal_Cancer/TCGA.csv\n",
344
+ "Preprocessing completed.\n"
345
+ ]
346
+ }
347
+ ],
348
+ "source": [
349
+ "# Step 1: Extract and standardize clinical features\n",
350
+ "# Create clinical features dataframe with trait (Canavan Disease) using patient IDs\n",
351
+ "clinical_features = tcga_select_clinical_features(\n",
352
+ " clinical_df, \n",
353
+ " trait=trait, \n",
354
+ " age_col=age_col, \n",
355
+ " gender_col=gender_col\n",
356
+ ")\n",
357
+ "\n",
358
+ "# Step 2: Normalize gene symbols in the gene expression data\n",
359
+ "# The gene symbols in TCGA genetic data are already standardized, but we'll normalize them for consistency\n",
360
+ "normalized_gene_df = normalize_gene_symbols_in_index(genetic_df)\n",
361
+ "\n",
362
+ "# Save the normalized gene data\n",
363
+ "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
364
+ "normalized_gene_df.to_csv(out_gene_data_file)\n",
365
+ "print(f\"Normalized gene expression data saved to {out_gene_data_file}\")\n",
366
+ "print(f\"Gene expression data shape after normalization: {normalized_gene_df.shape}\")\n",
367
+ "\n",
368
+ "# Step 3: Link clinical and genetic data\n",
369
+ "# Transpose genetic data to have samples as rows and genes as columns\n",
370
+ "genetic_df_t = normalized_gene_df.T\n",
371
+ "# Save the clinical data for reference\n",
372
+ "os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
373
+ "clinical_features.to_csv(out_clinical_data_file)\n",
374
+ "print(f\"Clinical data saved to {out_clinical_data_file}\")\n",
375
+ "print(f\"Clinical data shape: {clinical_features.shape}\")\n",
376
+ "\n",
377
+ "# Verify common indices between clinical and genetic data\n",
378
+ "clinical_indices = set(clinical_features.index)\n",
379
+ "genetic_indices = set(genetic_df_t.index)\n",
380
+ "common_indices = clinical_indices.intersection(genetic_indices)\n",
381
+ "print(f\"Number of samples in clinical data: {len(clinical_indices)}\")\n",
382
+ "print(f\"Number of samples in genetic data: {len(genetic_indices)}\")\n",
383
+ "print(f\"Number of common samples: {len(common_indices)}\")\n",
384
+ "\n",
385
+ "# Link the data by using the common indices\n",
386
+ "linked_data = pd.concat([clinical_features.loc[list(common_indices)], genetic_df_t.loc[list(common_indices)]], axis=1)\n",
387
+ "print(f\"Linked data shape: {linked_data.shape}\")\n",
388
+ "\n",
389
+ "# Step 4: Handle missing values in the linked data\n",
390
+ "linked_data = handle_missing_values(linked_data, trait_col=trait)\n",
391
+ "print(f\"Data shape after handling missing values: {linked_data.shape}\")\n",
392
+ "\n",
393
+ "# Step 5: Determine whether the trait and demographic features are severely biased\n",
394
+ "trait_biased, linked_data = judge_and_remove_biased_features(linked_data, trait=trait)\n",
395
+ "\n",
396
+ "# Step 6: Conduct final quality validation and save information\n",
397
+ "is_usable = validate_and_save_cohort_info(\n",
398
+ " is_final=True,\n",
399
+ " cohort=\"TCGA\",\n",
400
+ " info_path=json_path,\n",
401
+ " is_gene_available=True,\n",
402
+ " is_trait_available=True,\n",
403
+ " is_biased=trait_biased,\n",
404
+ " df=linked_data,\n",
405
+ " note=f\"Dataset contains TCGA glioma and brain tumor samples with gene expression and clinical information for {trait}.\"\n",
406
+ ")\n",
407
+ "\n",
408
+ "# Step 7: Save linked data if usable\n",
409
+ "if is_usable:\n",
410
+ " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n",
411
+ " linked_data.to_csv(out_data_file)\n",
412
+ " print(f\"Linked data saved to {out_data_file}\")\n",
413
+ "else:\n",
414
+ " print(\"Dataset deemed not usable based on validation criteria. Data not saved.\")\n",
415
+ "\n",
416
+ "print(\"Preprocessing completed.\")"
417
+ ]
418
+ }
419
+ ],
420
+ "metadata": {
421
+ "language_info": {
422
+ "codemirror_mode": {
423
+ "name": "ipython",
424
+ "version": 3
425
+ },
426
+ "file_extension": ".py",
427
+ "mimetype": "text/x-python",
428
+ "name": "python",
429
+ "nbconvert_exporter": "python",
430
+ "pygments_lexer": "ipython3",
431
+ "version": "3.10.16"
432
+ }
433
+ },
434
+ "nbformat": 4,
435
+ "nbformat_minor": 5
436
+ }
code/Congestive_heart_failure/GSE182600.ipynb ADDED
@@ -0,0 +1,846 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": 1,
6
+ "id": "935d8b27",
7
+ "metadata": {
8
+ "execution": {
9
+ "iopub.execute_input": "2025-03-25T08:25:14.800886Z",
10
+ "iopub.status.busy": "2025-03-25T08:25:14.800776Z",
11
+ "iopub.status.idle": "2025-03-25T08:25:14.970087Z",
12
+ "shell.execute_reply": "2025-03-25T08:25:14.969718Z"
13
+ }
14
+ },
15
+ "outputs": [],
16
+ "source": [
17
+ "import sys\n",
18
+ "import os\n",
19
+ "sys.path.append(os.path.abspath(os.path.join(os.getcwd(), '../..')))\n",
20
+ "\n",
21
+ "# Path Configuration\n",
22
+ "from tools.preprocess import *\n",
23
+ "\n",
24
+ "# Processing context\n",
25
+ "trait = \"Congestive_heart_failure\"\n",
26
+ "cohort = \"GSE182600\"\n",
27
+ "\n",
28
+ "# Input paths\n",
29
+ "in_trait_dir = \"../../input/GEO/Congestive_heart_failure\"\n",
30
+ "in_cohort_dir = \"../../input/GEO/Congestive_heart_failure/GSE182600\"\n",
31
+ "\n",
32
+ "# Output paths\n",
33
+ "out_data_file = \"../../output/preprocess/Congestive_heart_failure/GSE182600.csv\"\n",
34
+ "out_gene_data_file = \"../../output/preprocess/Congestive_heart_failure/gene_data/GSE182600.csv\"\n",
35
+ "out_clinical_data_file = \"../../output/preprocess/Congestive_heart_failure/clinical_data/GSE182600.csv\"\n",
36
+ "json_path = \"../../output/preprocess/Congestive_heart_failure/cohort_info.json\"\n"
37
+ ]
38
+ },
39
+ {
40
+ "cell_type": "markdown",
41
+ "id": "58903b36",
42
+ "metadata": {},
43
+ "source": [
44
+ "### Step 1: Initial Data Loading"
45
+ ]
46
+ },
47
+ {
48
+ "cell_type": "code",
49
+ "execution_count": 2,
50
+ "id": "65c5fd50",
51
+ "metadata": {
52
+ "execution": {
53
+ "iopub.execute_input": "2025-03-25T08:25:14.971552Z",
54
+ "iopub.status.busy": "2025-03-25T08:25:14.971403Z",
55
+ "iopub.status.idle": "2025-03-25T08:25:15.163888Z",
56
+ "shell.execute_reply": "2025-03-25T08:25:15.163481Z"
57
+ }
58
+ },
59
+ "outputs": [
60
+ {
61
+ "name": "stdout",
62
+ "output_type": "stream",
63
+ "text": [
64
+ "Background Information:\n",
65
+ "!Series_title\t\"Gene Expression of Cardiogenic Shock Patients under Extracorporeal Membrane Oxygenation\"\n",
66
+ "!Series_summary\t\"Prognosis for cardiogenic shock patients under ECMO was our study goal. Success defined as survived more than 7 days after ECMO installation and failure died or had multiple organ failure in 7 days. Total 34 cases were enrolled, 17 success and 17 failure.\"\n",
67
+ "!Series_summary\t\"Peripheral blood mononuclear cells collected at ECMO installation 0hr, 2hr and removal were used analyzed.\"\n",
68
+ "!Series_overall_design\t\"Analysis of the cardiogenic shock patients at extracorporeal membrane oxygenation treatment by genome-wide gene expression. Transcriptomic profiling between successful and failure groups were analyzed.\"\n",
69
+ "Sample Characteristics Dictionary:\n",
70
+ "{0: ['disease state: Acute myocarditis', 'disease state: Acute myocardial infarction', 'disease state: Dilated cardiomyopathy, DCMP', 'disease state: Congestive heart failure', 'disease state: Dilated cardiomyopathy', 'disease state: Arrhythmia', 'disease state: Aortic dissection'], 1: ['age: 33.4', 'age: 51.2', 'age: 51.9', 'age: 47.8', 'age: 41.5', 'age: 67.3', 'age: 52.8', 'age: 16.1', 'age: 78.9', 'age: 53.2', 'age: 70.9', 'age: 59.9', 'age: 21.9', 'age: 45.2', 'age: 52.4', 'age: 32.3', 'age: 55.8', 'age: 47', 'age: 57.3', 'age: 31.7', 'age: 49.3', 'age: 66.1', 'age: 55.9', 'age: 49.1', 'age: 63', 'age: 21', 'age: 53.6', 'age: 50.1', 'age: 37.4', 'age: 71.5'], 2: ['gender: F', 'gender: M'], 3: ['outcome: Success', 'outcome: Failure', 'outcome: failure'], 4: ['cell type: PBMC'], 5: ['time: 0hr', 'time: 2hr', 'time: Removal']}\n"
71
+ ]
72
+ }
73
+ ],
74
+ "source": [
75
+ "from tools.preprocess import *\n",
76
+ "# 1. Identify the paths to the SOFT file and the matrix file\n",
77
+ "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
78
+ "\n",
79
+ "# 2. Read the matrix file to obtain background information and sample characteristics data\n",
80
+ "background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']\n",
81
+ "clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']\n",
82
+ "background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)\n",
83
+ "\n",
84
+ "# 3. Obtain the sample characteristics dictionary from the clinical dataframe\n",
85
+ "sample_characteristics_dict = get_unique_values_by_row(clinical_data)\n",
86
+ "\n",
87
+ "# 4. Explicitly print out all the background information and the sample characteristics dictionary\n",
88
+ "print(\"Background Information:\")\n",
89
+ "print(background_info)\n",
90
+ "print(\"Sample Characteristics Dictionary:\")\n",
91
+ "print(sample_characteristics_dict)\n"
92
+ ]
93
+ },
94
+ {
95
+ "cell_type": "markdown",
96
+ "id": "936da96f",
97
+ "metadata": {},
98
+ "source": [
99
+ "### Step 2: Dataset Analysis and Clinical Feature Extraction"
100
+ ]
101
+ },
102
+ {
103
+ "cell_type": "code",
104
+ "execution_count": 3,
105
+ "id": "0f6ebafa",
106
+ "metadata": {
107
+ "execution": {
108
+ "iopub.execute_input": "2025-03-25T08:25:15.165382Z",
109
+ "iopub.status.busy": "2025-03-25T08:25:15.165264Z",
110
+ "iopub.status.idle": "2025-03-25T08:25:15.171480Z",
111
+ "shell.execute_reply": "2025-03-25T08:25:15.171192Z"
112
+ }
113
+ },
114
+ "outputs": [
115
+ {
116
+ "data": {
117
+ "text/plain": [
118
+ "False"
119
+ ]
120
+ },
121
+ "execution_count": 3,
122
+ "metadata": {},
123
+ "output_type": "execute_result"
124
+ }
125
+ ],
126
+ "source": [
127
+ "# 1. Gene Expression Data Availability\n",
128
+ "# Based on the background information, this dataset appears to contain gene expression data\n",
129
+ "is_gene_available = True\n",
130
+ "\n",
131
+ "# 2. Variable Availability and Data Type Conversion\n",
132
+ "# For trait (Congestive heart failure)\n",
133
+ "# Looking at the sample characteristics, outcome (row 3) indicates success or failure of ECMO treatment\n",
134
+ "# which is directly related to the trait of congestive heart failure\n",
135
+ "trait_row = 3\n",
136
+ "\n",
137
+ "def convert_trait(value):\n",
138
+ " if value is None:\n",
139
+ " return None\n",
140
+ " \n",
141
+ " # Extract value after colon if present\n",
142
+ " if ':' in value:\n",
143
+ " value = value.split(':', 1)[1].strip()\n",
144
+ " \n",
145
+ " # Convert to binary: 1 for failure (worse outcome), 0 for success\n",
146
+ " if value.lower() in ['failure']:\n",
147
+ " return 1\n",
148
+ " elif value.lower() == 'success':\n",
149
+ " return 0\n",
150
+ " return None\n",
151
+ "\n",
152
+ "# For age\n",
153
+ "age_row = 1\n",
154
+ "\n",
155
+ "def convert_age(value):\n",
156
+ " if value is None:\n",
157
+ " return None\n",
158
+ " \n",
159
+ " # Extract value after colon if present\n",
160
+ " if ':' in value:\n",
161
+ " value = value.split(':', 1)[1].strip()\n",
162
+ " \n",
163
+ " try:\n",
164
+ " return float(value)\n",
165
+ " except:\n",
166
+ " return None\n",
167
+ "\n",
168
+ "# For gender\n",
169
+ "gender_row = 2\n",
170
+ "\n",
171
+ "def convert_gender(value):\n",
172
+ " if value is None:\n",
173
+ " return None\n",
174
+ " \n",
175
+ " # Extract value after colon if present\n",
176
+ " if ':' in value:\n",
177
+ " value = value.split(':', 1)[1].strip()\n",
178
+ " \n",
179
+ " # Convert to binary: 0 for female, 1 for male\n",
180
+ " if value.upper() == 'F':\n",
181
+ " return 0\n",
182
+ " elif value.upper() == 'M':\n",
183
+ " return 1\n",
184
+ " return None\n",
185
+ "\n",
186
+ "# 3. Save Metadata\n",
187
+ "# Initial filtering - check if both gene and trait data are available\n",
188
+ "is_trait_available = trait_row is not None\n",
189
+ "validate_and_save_cohort_info(\n",
190
+ " is_final=False, \n",
191
+ " cohort=cohort, \n",
192
+ " info_path=json_path, \n",
193
+ " is_gene_available=is_gene_available, \n",
194
+ " is_trait_available=is_trait_available\n",
195
+ ")\n",
196
+ "\n",
197
+ "# 4. Clinical Feature Extraction\n",
198
+ "# I'll skip this part for now as we don't have the proper clinical data structure\n",
199
+ "# This will be handled in the next step when we have the appropriate data format\n"
200
+ ]
201
+ },
202
+ {
203
+ "cell_type": "markdown",
204
+ "id": "fcdc3b78",
205
+ "metadata": {},
206
+ "source": [
207
+ "### Step 3: Gene Data Extraction"
208
+ ]
209
+ },
210
+ {
211
+ "cell_type": "code",
212
+ "execution_count": 4,
213
+ "id": "41dc21d1",
214
+ "metadata": {
215
+ "execution": {
216
+ "iopub.execute_input": "2025-03-25T08:25:15.172614Z",
217
+ "iopub.status.busy": "2025-03-25T08:25:15.172505Z",
218
+ "iopub.status.idle": "2025-03-25T08:25:15.520121Z",
219
+ "shell.execute_reply": "2025-03-25T08:25:15.519718Z"
220
+ }
221
+ },
222
+ "outputs": [
223
+ {
224
+ "name": "stdout",
225
+ "output_type": "stream",
226
+ "text": [
227
+ "Matrix file found: ../../input/GEO/Congestive_heart_failure/GSE182600/GSE182600_series_matrix.txt.gz\n"
228
+ ]
229
+ },
230
+ {
231
+ "name": "stdout",
232
+ "output_type": "stream",
233
+ "text": [
234
+ "Gene data shape: (29363, 78)\n",
235
+ "First 20 gene/probe identifiers:\n",
236
+ "Index(['ILMN_1343291', 'ILMN_1651209', 'ILMN_1651228', 'ILMN_1651229',\n",
237
+ " 'ILMN_1651235', 'ILMN_1651236', 'ILMN_1651237', 'ILMN_1651238',\n",
238
+ " 'ILMN_1651254', 'ILMN_1651260', 'ILMN_1651262', 'ILMN_1651268',\n",
239
+ " 'ILMN_1651278', 'ILMN_1651282', 'ILMN_1651285', 'ILMN_1651286',\n",
240
+ " 'ILMN_1651292', 'ILMN_1651303', 'ILMN_1651309', 'ILMN_1651315'],\n",
241
+ " dtype='object', name='ID')\n"
242
+ ]
243
+ }
244
+ ],
245
+ "source": [
246
+ "# 1. Get the SOFT and matrix file paths again \n",
247
+ "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
248
+ "print(f\"Matrix file found: {matrix_file}\")\n",
249
+ "\n",
250
+ "# 2. Use the get_genetic_data function from the library to get the gene_data\n",
251
+ "try:\n",
252
+ " gene_data = get_genetic_data(matrix_file)\n",
253
+ " print(f\"Gene data shape: {gene_data.shape}\")\n",
254
+ " \n",
255
+ " # 3. Print the first 20 row IDs (gene or probe identifiers)\n",
256
+ " print(\"First 20 gene/probe identifiers:\")\n",
257
+ " print(gene_data.index[:20])\n",
258
+ "except Exception as e:\n",
259
+ " print(f\"Error extracting gene data: {e}\")\n"
260
+ ]
261
+ },
262
+ {
263
+ "cell_type": "markdown",
264
+ "id": "b3230465",
265
+ "metadata": {},
266
+ "source": [
267
+ "### Step 4: Gene Identifier Review"
268
+ ]
269
+ },
270
+ {
271
+ "cell_type": "code",
272
+ "execution_count": 5,
273
+ "id": "35182ced",
274
+ "metadata": {
275
+ "execution": {
276
+ "iopub.execute_input": "2025-03-25T08:25:15.521489Z",
277
+ "iopub.status.busy": "2025-03-25T08:25:15.521363Z",
278
+ "iopub.status.idle": "2025-03-25T08:25:15.523304Z",
279
+ "shell.execute_reply": "2025-03-25T08:25:15.523017Z"
280
+ }
281
+ },
282
+ "outputs": [],
283
+ "source": [
284
+ "# The gene identifiers start with 'ILMN_', which indicates these are Illumina array probe IDs,\n",
285
+ "# not standard human gene symbols. These IDs need to be mapped to official gene symbols\n",
286
+ "# for proper biological interpretation.\n",
287
+ "\n",
288
+ "# Illumina probe IDs like ILMN_1343291 need to be converted to their corresponding gene symbols\n",
289
+ "# using annotation information typically provided in platform files or through bioinformatics\n",
290
+ "# databases.\n",
291
+ "\n",
292
+ "requires_gene_mapping = True\n"
293
+ ]
294
+ },
295
+ {
296
+ "cell_type": "markdown",
297
+ "id": "b394d6e1",
298
+ "metadata": {},
299
+ "source": [
300
+ "### Step 5: Gene Annotation"
301
+ ]
302
+ },
303
+ {
304
+ "cell_type": "code",
305
+ "execution_count": 6,
306
+ "id": "4729ed07",
307
+ "metadata": {
308
+ "execution": {
309
+ "iopub.execute_input": "2025-03-25T08:25:15.524558Z",
310
+ "iopub.status.busy": "2025-03-25T08:25:15.524446Z",
311
+ "iopub.status.idle": "2025-03-25T08:25:41.315718Z",
312
+ "shell.execute_reply": "2025-03-25T08:25:41.315342Z"
313
+ }
314
+ },
315
+ "outputs": [
316
+ {
317
+ "name": "stdout",
318
+ "output_type": "stream",
319
+ "text": [
320
+ "\n",
321
+ "Gene annotation preview:\n",
322
+ "Columns in gene annotation: ['ID', 'Transcript', 'Species', 'Source', 'Search_Key', 'ILMN_Gene', 'Source_Reference_ID', 'RefSeq_ID', 'Entrez_Gene_ID', 'GI', 'Accession', 'Symbol', 'Protein_Product', 'Array_Address_Id', 'Probe_Type', 'Probe_Start', 'SEQUENCE', 'Chromosome', 'Probe_Chr_Orientation', 'Probe_Coordinates', 'Cytoband', 'Definition', 'Ontology_Component', 'Ontology_Process', 'Ontology_Function', 'Synonyms', 'Obsolete_Probe_Id', 'GB_ACC']\n",
323
+ "{'ID': ['ILMN_3166687', 'ILMN_3165566', 'ILMN_3164811', 'ILMN_3165363', 'ILMN_3166511'], 'Transcript': ['ILMN_333737', 'ILMN_333646', 'ILMN_333584', 'ILMN_333628', 'ILMN_333719'], 'Species': ['ILMN Controls', 'ILMN Controls', 'ILMN Controls', 'ILMN Controls', 'ILMN Controls'], 'Source': ['ILMN_Controls', 'ILMN_Controls', 'ILMN_Controls', 'ILMN_Controls', 'ILMN_Controls'], 'Search_Key': ['ERCC-00162', 'ERCC-00071', 'ERCC-00009', 'ERCC-00053', 'ERCC-00144'], 'ILMN_Gene': ['ERCC-00162', 'ERCC-00071', 'ERCC-00009', 'ERCC-00053', 'ERCC-00144'], 'Source_Reference_ID': ['ERCC-00162', 'ERCC-00071', 'ERCC-00009', 'ERCC-00053', 'ERCC-00144'], 'RefSeq_ID': [nan, nan, nan, nan, nan], 'Entrez_Gene_ID': [nan, nan, nan, nan, nan], 'GI': [nan, nan, nan, nan, nan], 'Accession': ['DQ516750', 'DQ883654', 'DQ668364', 'DQ516785', 'DQ854995'], 'Symbol': ['ERCC-00162', 'ERCC-00071', 'ERCC-00009', 'ERCC-00053', 'ERCC-00144'], 'Protein_Product': [nan, nan, nan, nan, nan], 'Array_Address_Id': [5270161.0, 4260594.0, 7610424.0, 5260356.0, 2030196.0], 'Probe_Type': ['S', 'S', 'S', 'S', 'S'], 'Probe_Start': [12.0, 224.0, 868.0, 873.0, 130.0], 'SEQUENCE': ['CCCATGTGTCCAATTCTGAATATCTTTCCAGCTAAGTGCTTCTGCCCACC', 'GGATTAACTGCTGTGGTGTGTCATACTCGGCTACCTCCTGGTTTGGCGTC', 'GACCACGCCTTGTAATCGTATGACACGCGCTTGACACGACTGAATCCAGC', 'CTGCAATGCCATTAACAACCTTAGCACGGTATTTCCAGTAGCTGGTGAGC', 'CGTGCAGACAGGGATCGTAAGGCGATCCAGCCGGTATACCTTAGTCACAT'], 'Chromosome': [nan, nan, nan, nan, nan], 'Probe_Chr_Orientation': [nan, nan, nan, nan, nan], 'Probe_Coordinates': [nan, nan, nan, nan, nan], 'Cytoband': [nan, nan, nan, nan, nan], 'Definition': ['Methanocaldococcus jannaschii spike-in control MJ-500-33 genomic sequence', 'Synthetic construct clone NISTag13 external RNA control sequence', 'Synthetic construct clone TagJ microarray control', 'Methanocaldococcus jannaschii spike-in control MJ-1000-68 genomic sequence', 'Synthetic construct clone AG006.1100 external RNA control sequence'], 'Ontology_Component': [nan, nan, nan, nan, nan], 'Ontology_Process': [nan, nan, nan, nan, nan], 'Ontology_Function': [nan, nan, nan, nan, nan], 'Synonyms': [nan, nan, nan, nan, nan], 'Obsolete_Probe_Id': [nan, nan, nan, nan, nan], 'GB_ACC': ['DQ516750', 'DQ883654', 'DQ668364', 'DQ516785', 'DQ854995']}\n",
324
+ "\n",
325
+ "Analyzing SPOT_ID.1 column for gene symbols:\n",
326
+ "\n",
327
+ "Gene data ID prefix: ILMN\n"
328
+ ]
329
+ },
330
+ {
331
+ "name": "stdout",
332
+ "output_type": "stream",
333
+ "text": [
334
+ "Column 'ID' contains values matching gene data ID pattern\n"
335
+ ]
336
+ },
337
+ {
338
+ "name": "stdout",
339
+ "output_type": "stream",
340
+ "text": [
341
+ "Column 'Transcript' contains values matching gene data ID pattern\n"
342
+ ]
343
+ },
344
+ {
345
+ "name": "stdout",
346
+ "output_type": "stream",
347
+ "text": [
348
+ "Column 'Species' contains values matching gene data ID pattern\n"
349
+ ]
350
+ },
351
+ {
352
+ "name": "stdout",
353
+ "output_type": "stream",
354
+ "text": [
355
+ "Column 'Source' contains values matching gene data ID pattern\n"
356
+ ]
357
+ },
358
+ {
359
+ "name": "stdout",
360
+ "output_type": "stream",
361
+ "text": [
362
+ "\n",
363
+ "Checking for columns containing transcript or gene related terms:\n",
364
+ "Column 'Transcript' may contain gene-related information\n",
365
+ "Sample values: ['ILMN_333737', 'ILMN_333646', 'ILMN_333584']\n",
366
+ "Column 'ILMN_Gene' may contain gene-related information\n",
367
+ "Sample values: ['ERCC-00162', 'ERCC-00071', 'ERCC-00009']\n",
368
+ "Column 'Entrez_Gene_ID' may contain gene-related information\n",
369
+ "Sample values: [nan, nan, nan]\n",
370
+ "Column 'Symbol' may contain gene-related information\n",
371
+ "Sample values: ['ERCC-00162', 'ERCC-00071', 'ERCC-00009']\n"
372
+ ]
373
+ }
374
+ ],
375
+ "source": [
376
+ "# 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.\n",
377
+ "gene_annotation = get_gene_annotation(soft_file)\n",
378
+ "\n",
379
+ "# 2. Analyze the gene annotation dataframe to identify which columns contain the gene identifiers and gene symbols\n",
380
+ "print(\"\\nGene annotation preview:\")\n",
381
+ "print(f\"Columns in gene annotation: {gene_annotation.columns.tolist()}\")\n",
382
+ "print(preview_df(gene_annotation, n=5))\n",
383
+ "\n",
384
+ "# Check for gene information in the SPOT_ID.1 column which appears to contain gene names\n",
385
+ "print(\"\\nAnalyzing SPOT_ID.1 column for gene symbols:\")\n",
386
+ "if 'SPOT_ID.1' in gene_annotation.columns:\n",
387
+ " # Extract a few sample values\n",
388
+ " sample_values = gene_annotation['SPOT_ID.1'].head(3).tolist()\n",
389
+ " for i, value in enumerate(sample_values):\n",
390
+ " print(f\"Sample {i+1} excerpt: {value[:200]}...\") # Print first 200 chars\n",
391
+ " # Test the extract_human_gene_symbols function on these values\n",
392
+ " symbols = extract_human_gene_symbols(value)\n",
393
+ " print(f\" Extracted gene symbols: {symbols}\")\n",
394
+ "\n",
395
+ "# Try to find the probe IDs in the gene annotation\n",
396
+ "gene_data_id_prefix = gene_data.index[0].split('_')[0] # Get prefix of first gene ID\n",
397
+ "print(f\"\\nGene data ID prefix: {gene_data_id_prefix}\")\n",
398
+ "\n",
399
+ "# Look for columns that might match the gene data IDs\n",
400
+ "for col in gene_annotation.columns:\n",
401
+ " if gene_annotation[col].astype(str).str.contains(gene_data_id_prefix).any():\n",
402
+ " print(f\"Column '{col}' contains values matching gene data ID pattern\")\n",
403
+ "\n",
404
+ "# Check if there's any column that might contain transcript or gene IDs\n",
405
+ "print(\"\\nChecking for columns containing transcript or gene related terms:\")\n",
406
+ "for col in gene_annotation.columns:\n",
407
+ " if any(term in col.upper() for term in ['GENE', 'TRANSCRIPT', 'SYMBOL', 'NAME', 'DESCRIPTION']):\n",
408
+ " print(f\"Column '{col}' may contain gene-related information\")\n",
409
+ " # Show sample values\n",
410
+ " print(f\"Sample values: {gene_annotation[col].head(3).tolist()}\")\n"
411
+ ]
412
+ },
413
+ {
414
+ "cell_type": "markdown",
415
+ "id": "0e6cfa72",
416
+ "metadata": {},
417
+ "source": [
418
+ "### Step 6: Gene Identifier Mapping"
419
+ ]
420
+ },
421
+ {
422
+ "cell_type": "code",
423
+ "execution_count": 7,
424
+ "id": "714c6291",
425
+ "metadata": {
426
+ "execution": {
427
+ "iopub.execute_input": "2025-03-25T08:25:41.317128Z",
428
+ "iopub.status.busy": "2025-03-25T08:25:41.316994Z",
429
+ "iopub.status.idle": "2025-03-25T08:25:42.898238Z",
430
+ "shell.execute_reply": "2025-03-25T08:25:42.897830Z"
431
+ }
432
+ },
433
+ "outputs": [
434
+ {
435
+ "name": "stdout",
436
+ "output_type": "stream",
437
+ "text": [
438
+ "Gene mapping dataframe sample:\n",
439
+ " ID Gene\n",
440
+ "0 ILMN_3166687 ERCC-00162\n",
441
+ "1 ILMN_3165566 ERCC-00071\n",
442
+ "2 ILMN_3164811 ERCC-00009\n",
443
+ "3 ILMN_3165363 ERCC-00053\n",
444
+ "4 ILMN_3166511 ERCC-00144\n",
445
+ "Mapping dataframe shape: (29377, 2)\n"
446
+ ]
447
+ },
448
+ {
449
+ "name": "stdout",
450
+ "output_type": "stream",
451
+ "text": [
452
+ "\n",
453
+ "Gene expression data shape after mapping: (20206, 78)\n",
454
+ "First 10 gene symbols after mapping:\n",
455
+ "['A1BG', 'A1CF', 'A26C3', 'A2BP1', 'A2LD1', 'A2M', 'A2ML1', 'A3GALT2', 'A4GALT', 'A4GNT']\n"
456
+ ]
457
+ },
458
+ {
459
+ "name": "stdout",
460
+ "output_type": "stream",
461
+ "text": [
462
+ "Gene expression data saved to: ../../output/preprocess/Congestive_heart_failure/gene_data/GSE182600.csv\n"
463
+ ]
464
+ }
465
+ ],
466
+ "source": [
467
+ "# 1. Identify the columns in gene_annotation that correspond to gene identifiers and gene symbols\n",
468
+ "# From the previous output, we can see:\n",
469
+ "# - The 'ID' column contains values matching the ILMN_ pattern used in gene_data index\n",
470
+ "# - The 'Symbol' column appears to contain gene symbols\n",
471
+ "\n",
472
+ "# 2. Get a gene mapping dataframe using the get_gene_mapping function\n",
473
+ "probe_col = 'ID'\n",
474
+ "gene_col = 'Symbol'\n",
475
+ "gene_mapping = get_gene_mapping(gene_annotation, probe_col, gene_col)\n",
476
+ "\n",
477
+ "# Preview the mapping dataframe\n",
478
+ "print(\"Gene mapping dataframe sample:\")\n",
479
+ "print(gene_mapping.head())\n",
480
+ "print(f\"Mapping dataframe shape: {gene_mapping.shape}\")\n",
481
+ "\n",
482
+ "# 3. Apply the gene mapping to convert probe-level data to gene-level data\n",
483
+ "# The apply_gene_mapping function handles the many-to-many mapping as specified\n",
484
+ "gene_data = apply_gene_mapping(gene_data, gene_mapping)\n",
485
+ "\n",
486
+ "# Print information about the resulting gene expression dataframe\n",
487
+ "print(f\"\\nGene expression data shape after mapping: {gene_data.shape}\")\n",
488
+ "print(\"First 10 gene symbols after mapping:\")\n",
489
+ "print(gene_data.index[:10].tolist())\n",
490
+ "\n",
491
+ "# Save the gene data to a CSV file\n",
492
+ "gene_data.to_csv(out_gene_data_file)\n",
493
+ "print(f\"Gene expression data saved to: {out_gene_data_file}\")\n"
494
+ ]
495
+ },
496
+ {
497
+ "cell_type": "markdown",
498
+ "id": "aa84763a",
499
+ "metadata": {},
500
+ "source": [
501
+ "### Step 7: Data Normalization and Linking"
502
+ ]
503
+ },
504
+ {
505
+ "cell_type": "code",
506
+ "execution_count": 8,
507
+ "id": "260a86ff",
508
+ "metadata": {
509
+ "execution": {
510
+ "iopub.execute_input": "2025-03-25T08:25:42.899819Z",
511
+ "iopub.status.busy": "2025-03-25T08:25:42.899604Z",
512
+ "iopub.status.idle": "2025-03-25T08:25:55.500301Z",
513
+ "shell.execute_reply": "2025-03-25T08:25:55.499894Z"
514
+ }
515
+ },
516
+ "outputs": [
517
+ {
518
+ "name": "stdout",
519
+ "output_type": "stream",
520
+ "text": [
521
+ "Gene data shape before normalization: (20206, 78)\n",
522
+ "Gene data shape after normalization: (19445, 78)\n"
523
+ ]
524
+ },
525
+ {
526
+ "name": "stdout",
527
+ "output_type": "stream",
528
+ "text": [
529
+ "Normalized gene expression data saved to ../../output/preprocess/Congestive_heart_failure/gene_data/GSE182600.csv\n",
530
+ "Original clinical data preview:\n",
531
+ " !Sample_geo_accession GSM5532093 \\\n",
532
+ "0 !Sample_characteristics_ch1 disease state: Acute myocarditis \n",
533
+ "1 !Sample_characteristics_ch1 age: 33.4 \n",
534
+ "2 !Sample_characteristics_ch1 gender: F \n",
535
+ "3 !Sample_characteristics_ch1 outcome: Success \n",
536
+ "4 !Sample_characteristics_ch1 cell type: PBMC \n",
537
+ "\n",
538
+ " GSM5532094 GSM5532095 \\\n",
539
+ "0 disease state: Acute myocarditis disease state: Acute myocarditis \n",
540
+ "1 age: 51.2 age: 51.9 \n",
541
+ "2 gender: M gender: F \n",
542
+ "3 outcome: Success outcome: Failure \n",
543
+ "4 cell type: PBMC cell type: PBMC \n",
544
+ "\n",
545
+ " GSM5532096 \\\n",
546
+ "0 disease state: Acute myocardial infarction \n",
547
+ "1 age: 47.8 \n",
548
+ "2 gender: M \n",
549
+ "3 outcome: Success \n",
550
+ "4 cell type: PBMC \n",
551
+ "\n",
552
+ " GSM5532097 \\\n",
553
+ "0 disease state: Acute myocarditis \n",
554
+ "1 age: 41.5 \n",
555
+ "2 gender: F \n",
556
+ "3 outcome: Failure \n",
557
+ "4 cell type: PBMC \n",
558
+ "\n",
559
+ " GSM5532098 \\\n",
560
+ "0 disease state: Acute myocardial infarction \n",
561
+ "1 age: 67.3 \n",
562
+ "2 gender: M \n",
563
+ "3 outcome: Failure \n",
564
+ "4 cell type: PBMC \n",
565
+ "\n",
566
+ " GSM5532099 \\\n",
567
+ "0 disease state: Acute myocardial infarction \n",
568
+ "1 age: 52.8 \n",
569
+ "2 gender: M \n",
570
+ "3 outcome: Success \n",
571
+ "4 cell type: PBMC \n",
572
+ "\n",
573
+ " GSM5532100 \\\n",
574
+ "0 disease state: Dilated cardiomyopathy, DCMP \n",
575
+ "1 age: 16.1 \n",
576
+ "2 gender: M \n",
577
+ "3 outcome: Failure \n",
578
+ "4 cell type: PBMC \n",
579
+ "\n",
580
+ " GSM5532101 ... \\\n",
581
+ "0 disease state: Acute myocardial infarction ... \n",
582
+ "1 age: 78.9 ... \n",
583
+ "2 gender: M ... \n",
584
+ "3 outcome: Failure ... \n",
585
+ "4 cell type: PBMC ... \n",
586
+ "\n",
587
+ " GSM5532161 \\\n",
588
+ "0 disease state: Acute myocardial infarction \n",
589
+ "1 age: 52.8 \n",
590
+ "2 gender: M \n",
591
+ "3 outcome: Success \n",
592
+ "4 cell type: PBMC \n",
593
+ "\n",
594
+ " GSM5532162 \\\n",
595
+ "0 disease state: Acute myocardial infarction \n",
596
+ "1 age: 53.2 \n",
597
+ "2 gender: M \n",
598
+ "3 outcome: Success \n",
599
+ "4 cell type: PBMC \n",
600
+ "\n",
601
+ " GSM5532163 GSM5532164 \\\n",
602
+ "0 disease state: Acute myocarditis disease state: Arrhythmia \n",
603
+ "1 age: 21.9 age: 55.8 \n",
604
+ "2 gender: F gender: M \n",
605
+ "3 outcome: Success outcome: Success \n",
606
+ "4 cell type: PBMC cell type: PBMC \n",
607
+ "\n",
608
+ " GSM5532165 \\\n",
609
+ "0 disease state: Dilated cardiomyopathy \n",
610
+ "1 age: 47 \n",
611
+ "2 gender: M \n",
612
+ "3 outcome: Success \n",
613
+ "4 cell type: PBMC \n",
614
+ "\n",
615
+ " GSM5532166 \\\n",
616
+ "0 disease state: Acute myocardial infarction \n",
617
+ "1 age: 49.3 \n",
618
+ "2 gender: M \n",
619
+ "3 outcome: Success \n",
620
+ "4 cell type: PBMC \n",
621
+ "\n",
622
+ " GSM5532167 \\\n",
623
+ "0 disease state: Congestive heart failure \n",
624
+ "1 age: 66.1 \n",
625
+ "2 gender: M \n",
626
+ "3 outcome: Success \n",
627
+ "4 cell type: PBMC \n",
628
+ "\n",
629
+ " GSM5532168 \\\n",
630
+ "0 disease state: Acute myocardial infarction \n",
631
+ "1 age: 53.6 \n",
632
+ "2 gender: M \n",
633
+ "3 outcome: Success \n",
634
+ "4 cell type: PBMC \n",
635
+ "\n",
636
+ " GSM5532169 \\\n",
637
+ "0 disease state: Acute myocardial infarction \n",
638
+ "1 age: 50.1 \n",
639
+ "2 gender: F \n",
640
+ "3 outcome: Success \n",
641
+ "4 cell type: PBMC \n",
642
+ "\n",
643
+ " GSM5532170 \n",
644
+ "0 disease state: Congestive heart failure \n",
645
+ "1 age: 56.5 \n",
646
+ "2 gender: M \n",
647
+ "3 outcome: Success \n",
648
+ "4 cell type: PBMC \n",
649
+ "\n",
650
+ "[5 rows x 79 columns]\n",
651
+ "Selected clinical data shape: (3, 78)\n",
652
+ "Clinical data preview:\n",
653
+ " GSM5532093 GSM5532094 GSM5532095 GSM5532096 \\\n",
654
+ "Congestive_heart_failure 0.0 0.0 1.0 0.0 \n",
655
+ "Age 33.4 51.2 51.9 47.8 \n",
656
+ "Gender 0.0 1.0 0.0 1.0 \n",
657
+ "\n",
658
+ " GSM5532097 GSM5532098 GSM5532099 GSM5532100 \\\n",
659
+ "Congestive_heart_failure 1.0 1.0 0.0 1.0 \n",
660
+ "Age 41.5 67.3 52.8 16.1 \n",
661
+ "Gender 0.0 1.0 1.0 1.0 \n",
662
+ "\n",
663
+ " GSM5532101 GSM5532102 ... GSM5532161 GSM5532162 \\\n",
664
+ "Congestive_heart_failure 1.0 0.0 ... 0.0 0.0 \n",
665
+ "Age 78.9 53.2 ... 52.8 53.2 \n",
666
+ "Gender 1.0 1.0 ... 1.0 1.0 \n",
667
+ "\n",
668
+ " GSM5532163 GSM5532164 GSM5532165 GSM5532166 \\\n",
669
+ "Congestive_heart_failure 0.0 0.0 0.0 0.0 \n",
670
+ "Age 21.9 55.8 47.0 49.3 \n",
671
+ "Gender 0.0 1.0 1.0 1.0 \n",
672
+ "\n",
673
+ " GSM5532167 GSM5532168 GSM5532169 GSM5532170 \n",
674
+ "Congestive_heart_failure 0.0 0.0 0.0 0.0 \n",
675
+ "Age 66.1 53.6 50.1 56.5 \n",
676
+ "Gender 1.0 1.0 0.0 1.0 \n",
677
+ "\n",
678
+ "[3 rows x 78 columns]\n",
679
+ "Linked data shape before processing: (78, 19448)\n",
680
+ "Linked data preview (first 5 rows, 5 columns):\n",
681
+ " Congestive_heart_failure Age Gender A1BG A1BG-AS1\n",
682
+ "GSM5532093 0.0 33.4 0.0 123.145500 1284.286536\n",
683
+ "GSM5532094 0.0 51.2 1.0 134.323626 2123.843378\n",
684
+ "GSM5532095 1.0 51.9 0.0 100.294706 1088.857429\n",
685
+ "GSM5532096 0.0 47.8 1.0 130.315854 1074.517347\n",
686
+ "GSM5532097 1.0 41.5 0.0 106.890941 1070.809003\n"
687
+ ]
688
+ },
689
+ {
690
+ "name": "stdout",
691
+ "output_type": "stream",
692
+ "text": [
693
+ "Data shape after handling missing values: (78, 19448)\n",
694
+ "For the feature 'Congestive_heart_failure', the least common label is '1.0' with 31 occurrences. This represents 39.74% of the dataset.\n",
695
+ "Quartiles for 'Age':\n",
696
+ " 25%: 47.0\n",
697
+ " 50% (Median): 52.15\n",
698
+ " 75%: 56.35\n",
699
+ "Min: 16.1\n",
700
+ "Max: 78.9\n",
701
+ "For the feature 'Gender', the least common label is '0.0' with 24 occurrences. This represents 30.77% of the dataset.\n",
702
+ "A new JSON file was created at: ../../output/preprocess/Congestive_heart_failure/cohort_info.json\n"
703
+ ]
704
+ },
705
+ {
706
+ "name": "stdout",
707
+ "output_type": "stream",
708
+ "text": [
709
+ "Linked data saved to ../../output/preprocess/Congestive_heart_failure/GSE182600.csv\n"
710
+ ]
711
+ }
712
+ ],
713
+ "source": [
714
+ "# 1. Normalize gene symbols in the gene expression data\n",
715
+ "# Use normalize_gene_symbols_in_index to standardize gene symbols\n",
716
+ "normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n",
717
+ "print(f\"Gene data shape before normalization: {gene_data.shape}\")\n",
718
+ "print(f\"Gene data shape after normalization: {normalized_gene_data.shape}\")\n",
719
+ "\n",
720
+ "# Save the normalized gene data to file\n",
721
+ "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
722
+ "normalized_gene_data.to_csv(out_gene_data_file)\n",
723
+ "print(f\"Normalized gene expression data saved to {out_gene_data_file}\")\n",
724
+ "\n",
725
+ "# Load the actual clinical data from the matrix file that was previously obtained in Step 1\n",
726
+ "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
727
+ "background_info, clinical_data = get_background_and_clinical_data(matrix_file)\n",
728
+ "\n",
729
+ "# Get preview of clinical data to understand its structure\n",
730
+ "print(\"Original clinical data preview:\")\n",
731
+ "print(clinical_data.head())\n",
732
+ "\n",
733
+ "# 2. If we have trait data available, proceed with linking\n",
734
+ "if trait_row is not None:\n",
735
+ " # Extract clinical features using the original clinical data\n",
736
+ " selected_clinical_df = geo_select_clinical_features(\n",
737
+ " clinical_df=clinical_data,\n",
738
+ " trait=trait,\n",
739
+ " trait_row=trait_row,\n",
740
+ " convert_trait=convert_trait,\n",
741
+ " age_row=age_row,\n",
742
+ " convert_age=convert_age,\n",
743
+ " gender_row=gender_row,\n",
744
+ " convert_gender=convert_gender\n",
745
+ " )\n",
746
+ "\n",
747
+ " print(f\"Selected clinical data shape: {selected_clinical_df.shape}\")\n",
748
+ " print(\"Clinical data preview:\")\n",
749
+ " print(selected_clinical_df.head())\n",
750
+ "\n",
751
+ " # Link the clinical and genetic data\n",
752
+ " linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)\n",
753
+ " print(f\"Linked data shape before processing: {linked_data.shape}\")\n",
754
+ " print(\"Linked data preview (first 5 rows, 5 columns):\")\n",
755
+ " print(linked_data.iloc[:5, :5] if not linked_data.empty else \"Empty dataframe\")\n",
756
+ "\n",
757
+ " # 3. Handle missing values\n",
758
+ " try:\n",
759
+ " linked_data = handle_missing_values(linked_data, trait)\n",
760
+ " print(f\"Data shape after handling missing values: {linked_data.shape}\")\n",
761
+ " except Exception as e:\n",
762
+ " print(f\"Error handling missing values: {e}\")\n",
763
+ " linked_data = pd.DataFrame() # Create empty dataframe if error occurs\n",
764
+ "\n",
765
+ " # 4. Check for bias in features\n",
766
+ " if not linked_data.empty and linked_data.shape[0] > 0:\n",
767
+ " # Check if trait is biased\n",
768
+ " trait_type = 'binary' if len(linked_data[trait].unique()) <= 2 else 'continuous'\n",
769
+ " if trait_type == \"binary\":\n",
770
+ " is_biased = judge_binary_variable_biased(linked_data, trait)\n",
771
+ " else:\n",
772
+ " is_biased = judge_continuous_variable_biased(linked_data, trait)\n",
773
+ " \n",
774
+ " # Remove biased demographic features\n",
775
+ " if \"Age\" in linked_data.columns:\n",
776
+ " age_biased = judge_continuous_variable_biased(linked_data, 'Age')\n",
777
+ " if age_biased:\n",
778
+ " linked_data = linked_data.drop(columns='Age')\n",
779
+ " \n",
780
+ " if \"Gender\" in linked_data.columns:\n",
781
+ " gender_biased = judge_binary_variable_biased(linked_data, 'Gender')\n",
782
+ " if gender_biased:\n",
783
+ " linked_data = linked_data.drop(columns='Gender')\n",
784
+ " else:\n",
785
+ " is_biased = True\n",
786
+ " print(\"Cannot check for bias as dataframe is empty or has no rows after missing value handling\")\n",
787
+ "\n",
788
+ " # 5. Validate and save cohort information\n",
789
+ " note = \"\"\n",
790
+ " if linked_data.empty or linked_data.shape[0] == 0:\n",
791
+ " note = \"Dataset contains gene expression data related to atrial fibrillation after cardiac surgery, but linking clinical and genetic data failed, possibly due to mismatched sample IDs.\"\n",
792
+ " else:\n",
793
+ " note = \"Dataset contains gene expression data for atrial fibrillation after cardiac surgery, which is relevant to arrhythmia research.\"\n",
794
+ " \n",
795
+ " is_usable = validate_and_save_cohort_info(\n",
796
+ " is_final=True,\n",
797
+ " cohort=cohort,\n",
798
+ " info_path=json_path,\n",
799
+ " is_gene_available=True,\n",
800
+ " is_trait_available=True,\n",
801
+ " is_biased=is_biased,\n",
802
+ " df=linked_data,\n",
803
+ " note=note\n",
804
+ " )\n",
805
+ "\n",
806
+ " # 6. Save the linked data if usable\n",
807
+ " if is_usable:\n",
808
+ " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n",
809
+ " linked_data.to_csv(out_data_file)\n",
810
+ " print(f\"Linked data saved to {out_data_file}\")\n",
811
+ " else:\n",
812
+ " print(\"Dataset is not usable for analysis. No linked data file saved.\")\n",
813
+ "else:\n",
814
+ " # If no trait data available, validate with trait_available=False\n",
815
+ " is_usable = validate_and_save_cohort_info(\n",
816
+ " is_final=True,\n",
817
+ " cohort=cohort,\n",
818
+ " info_path=json_path,\n",
819
+ " is_gene_available=True,\n",
820
+ " is_trait_available=False,\n",
821
+ " is_biased=True, # Set to True since we can't use data without trait\n",
822
+ " df=pd.DataFrame(), # Empty DataFrame\n",
823
+ " note=\"Dataset contains gene expression data but lacks proper clinical trait information for arrhythmia analysis.\"\n",
824
+ " )\n",
825
+ " \n",
826
+ " print(\"Dataset is not usable for arrhythmia analysis due to lack of clinical trait data. No linked data file saved.\")"
827
+ ]
828
+ }
829
+ ],
830
+ "metadata": {
831
+ "language_info": {
832
+ "codemirror_mode": {
833
+ "name": "ipython",
834
+ "version": 3
835
+ },
836
+ "file_extension": ".py",
837
+ "mimetype": "text/x-python",
838
+ "name": "python",
839
+ "nbconvert_exporter": "python",
840
+ "pygments_lexer": "ipython3",
841
+ "version": "3.10.16"
842
+ }
843
+ },
844
+ "nbformat": 4,
845
+ "nbformat_minor": 5
846
+ }
code/Congestive_heart_failure/GSE93101.ipynb ADDED
@@ -0,0 +1,785 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": 1,
6
+ "id": "147aed01",
7
+ "metadata": {
8
+ "execution": {
9
+ "iopub.execute_input": "2025-03-25T08:25:56.548956Z",
10
+ "iopub.status.busy": "2025-03-25T08:25:56.548720Z",
11
+ "iopub.status.idle": "2025-03-25T08:25:56.716341Z",
12
+ "shell.execute_reply": "2025-03-25T08:25:56.716010Z"
13
+ }
14
+ },
15
+ "outputs": [],
16
+ "source": [
17
+ "import sys\n",
18
+ "import os\n",
19
+ "sys.path.append(os.path.abspath(os.path.join(os.getcwd(), '../..')))\n",
20
+ "\n",
21
+ "# Path Configuration\n",
22
+ "from tools.preprocess import *\n",
23
+ "\n",
24
+ "# Processing context\n",
25
+ "trait = \"Congestive_heart_failure\"\n",
26
+ "cohort = \"GSE93101\"\n",
27
+ "\n",
28
+ "# Input paths\n",
29
+ "in_trait_dir = \"../../input/GEO/Congestive_heart_failure\"\n",
30
+ "in_cohort_dir = \"../../input/GEO/Congestive_heart_failure/GSE93101\"\n",
31
+ "\n",
32
+ "# Output paths\n",
33
+ "out_data_file = \"../../output/preprocess/Congestive_heart_failure/GSE93101.csv\"\n",
34
+ "out_gene_data_file = \"../../output/preprocess/Congestive_heart_failure/gene_data/GSE93101.csv\"\n",
35
+ "out_clinical_data_file = \"../../output/preprocess/Congestive_heart_failure/clinical_data/GSE93101.csv\"\n",
36
+ "json_path = \"../../output/preprocess/Congestive_heart_failure/cohort_info.json\"\n"
37
+ ]
38
+ },
39
+ {
40
+ "cell_type": "markdown",
41
+ "id": "6f2b768c",
42
+ "metadata": {},
43
+ "source": [
44
+ "### Step 1: Initial Data Loading"
45
+ ]
46
+ },
47
+ {
48
+ "cell_type": "code",
49
+ "execution_count": 2,
50
+ "id": "09762be8",
51
+ "metadata": {
52
+ "execution": {
53
+ "iopub.execute_input": "2025-03-25T08:25:56.717676Z",
54
+ "iopub.status.busy": "2025-03-25T08:25:56.717543Z",
55
+ "iopub.status.idle": "2025-03-25T08:25:56.804283Z",
56
+ "shell.execute_reply": "2025-03-25T08:25:56.803993Z"
57
+ }
58
+ },
59
+ "outputs": [
60
+ {
61
+ "name": "stdout",
62
+ "output_type": "stream",
63
+ "text": [
64
+ "Background Information:\n",
65
+ "!Series_title\t\"Molecular Prognosis of Cardiogenic Shock Patients under Extracorporeal Membrane Oxygenation\"\n",
66
+ "!Series_summary\t\"Prognosis for cardiogenic shock patients under ECMO was our study goal. Success defined as survived more than 7 days after ECMO installation and failure died or had multiple organ failure in 7 days. Total 34 cases were enrolled, 17 success and 17 failure.\"\n",
67
+ "!Series_summary\t\"Peripheral blood mononuclear cells collected at ECMO installation were used analyzed.\"\n",
68
+ "!Series_overall_design\t\"Analysis of the cardiogenic shock patients at extracorporeal membrane oxygenation treatment by genome-wide expression and methylation. Transcriptomic profiling and DNA methylation between successful and failure groups were analyzed.\"\n",
69
+ "!Series_overall_design\t\"This submission represents the transcriptome data.\"\n",
70
+ "Sample Characteristics Dictionary:\n",
71
+ "{0: ['course: Acute myocarditis', 'course: Acute myocardial infarction', 'course: Dilated cardiomyopathy, DCMP', 'course: Congestive heart failure', 'course: Dilated cardiomyopathy', 'course: Arrhythmia', 'course: Aortic dissection'], 1: ['age: 33.4', 'age: 51.2', 'age: 51.9', 'age: 47.8', 'age: 41.5', 'age: 67.3', 'age: 52.8', 'age: 16.1', 'age: 78.9', 'age: 53.2', 'age: 70.9', 'age: 59.9', 'age: 21.9', 'age: 45.2', 'age: 52.4', 'age: 32.3', 'age: 55.8', 'age: 47', 'age: 57.3', 'age: 31.7', 'age: 49.3', 'age: 66.1', 'age: 55.9', 'age: 49.1', 'age: 63', 'age: 21', 'age: 53.6', 'age: 50.1', 'age: 37.4', 'age: 71.5'], 2: ['gender: F', 'gender: M'], 3: ['outcome: Success', 'outcome: Failure', 'outcome: failure']}\n"
72
+ ]
73
+ }
74
+ ],
75
+ "source": [
76
+ "from tools.preprocess import *\n",
77
+ "# 1. Identify the paths to the SOFT file and the matrix file\n",
78
+ "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
79
+ "\n",
80
+ "# 2. Read the matrix file to obtain background information and sample characteristics data\n",
81
+ "background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']\n",
82
+ "clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']\n",
83
+ "background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)\n",
84
+ "\n",
85
+ "# 3. Obtain the sample characteristics dictionary from the clinical dataframe\n",
86
+ "sample_characteristics_dict = get_unique_values_by_row(clinical_data)\n",
87
+ "\n",
88
+ "# 4. Explicitly print out all the background information and the sample characteristics dictionary\n",
89
+ "print(\"Background Information:\")\n",
90
+ "print(background_info)\n",
91
+ "print(\"Sample Characteristics Dictionary:\")\n",
92
+ "print(sample_characteristics_dict)\n"
93
+ ]
94
+ },
95
+ {
96
+ "cell_type": "markdown",
97
+ "id": "7add2ced",
98
+ "metadata": {},
99
+ "source": [
100
+ "### Step 2: Dataset Analysis and Clinical Feature Extraction"
101
+ ]
102
+ },
103
+ {
104
+ "cell_type": "code",
105
+ "execution_count": 3,
106
+ "id": "f8c921ed",
107
+ "metadata": {
108
+ "execution": {
109
+ "iopub.execute_input": "2025-03-25T08:25:56.805483Z",
110
+ "iopub.status.busy": "2025-03-25T08:25:56.805381Z",
111
+ "iopub.status.idle": "2025-03-25T08:25:56.815153Z",
112
+ "shell.execute_reply": "2025-03-25T08:25:56.814866Z"
113
+ }
114
+ },
115
+ "outputs": [
116
+ {
117
+ "name": "stdout",
118
+ "output_type": "stream",
119
+ "text": [
120
+ "Preview of clinical features:\n",
121
+ "{'GSM2443799': [0.0, 33.4, 0.0], 'GSM2443800': [0.0, 51.2, 1.0], 'GSM2443801': [0.0, 51.9, 0.0], 'GSM2443802': [0.0, 47.8, 1.0], 'GSM2443803': [0.0, 41.5, 0.0], 'GSM2443804': [0.0, 67.3, 1.0], 'GSM2443805': [0.0, 52.8, 1.0], 'GSM2443806': [0.0, 16.1, 1.0], 'GSM2443807': [0.0, 78.9, 1.0], 'GSM2443808': [0.0, 53.2, 1.0], 'GSM2443809': [0.0, 70.9, 1.0], 'GSM2443810': [0.0, 59.9, 1.0], 'GSM2443811': [0.0, 21.9, 0.0], 'GSM2443812': [1.0, 45.2, 0.0], 'GSM2443813': [0.0, 52.4, 1.0], 'GSM2443814': [0.0, 32.3, 1.0], 'GSM2443815': [0.0, 52.8, 1.0], 'GSM2443816': [0.0, 55.8, 1.0], 'GSM2443817': [0.0, 47.0, 1.0], 'GSM2443818': [0.0, 55.8, 1.0], 'GSM2443819': [0.0, 57.3, 0.0], 'GSM2443820': [0.0, 31.7, 0.0], 'GSM2443821': [0.0, 49.3, 1.0], 'GSM2443822': [1.0, 66.1, 1.0], 'GSM2443823': [0.0, 55.9, 1.0], 'GSM2443824': [0.0, 49.1, 0.0], 'GSM2443825': [0.0, 63.0, 1.0], 'GSM2443826': [0.0, 21.0, 1.0], 'GSM2443827': [0.0, 53.6, 1.0], 'GSM2443828': [0.0, 50.1, 0.0], 'GSM2443829': [0.0, 37.4, 1.0], 'GSM2443830': [0.0, 71.5, 0.0], 'GSM2443831': [1.0, 56.5, 1.0]}\n",
122
+ "Clinical data saved to ../../output/preprocess/Congestive_heart_failure/clinical_data/GSE93101.csv\n"
123
+ ]
124
+ }
125
+ ],
126
+ "source": [
127
+ "# 1. Gene Expression Data Availability\n",
128
+ "# Based on the background information, this dataset contains transcriptome data\n",
129
+ "# \"This submission represents the transcriptome data.\"\n",
130
+ "is_gene_available = True\n",
131
+ "\n",
132
+ "# 2. Variable Availability and Data Type Conversion\n",
133
+ "\n",
134
+ "# 2.1 Data Availability\n",
135
+ "\n",
136
+ "# Trait: Congestive heart failure\n",
137
+ "# Looking at the sample characteristics, key 0 contains \"course: Congestive heart failure\"\n",
138
+ "# This suggests patients have different conditions, and we're interested in those with CHF\n",
139
+ "trait_row = 0\n",
140
+ "\n",
141
+ "# Age: Available in key 1\n",
142
+ "age_row = 1\n",
143
+ "\n",
144
+ "# Gender: Available in key 2\n",
145
+ "gender_row = 2\n",
146
+ "\n",
147
+ "# 2.2 Data Type Conversion Functions\n",
148
+ "\n",
149
+ "def convert_trait(value):\n",
150
+ " \"\"\"Convert trait value to binary (0 or 1)\"\"\"\n",
151
+ " if value is None:\n",
152
+ " return None\n",
153
+ " \n",
154
+ " # Extract the value after the colon\n",
155
+ " if \":\" in value:\n",
156
+ " condition = value.split(\":\", 1)[1].strip()\n",
157
+ " else:\n",
158
+ " condition = value.strip()\n",
159
+ " \n",
160
+ " # Check if the condition is congestive heart failure (case insensitive)\n",
161
+ " if condition.lower() == \"congestive heart failure\":\n",
162
+ " return 1\n",
163
+ " else:\n",
164
+ " return 0\n",
165
+ "\n",
166
+ "def convert_age(value):\n",
167
+ " \"\"\"Convert age value to continuous (float)\"\"\"\n",
168
+ " if value is None:\n",
169
+ " return None\n",
170
+ " \n",
171
+ " # Extract the value after the colon\n",
172
+ " if \":\" in value:\n",
173
+ " age_str = value.split(\":\", 1)[1].strip()\n",
174
+ " else:\n",
175
+ " age_str = value.strip()\n",
176
+ " \n",
177
+ " try:\n",
178
+ " return float(age_str)\n",
179
+ " except (ValueError, TypeError):\n",
180
+ " return None\n",
181
+ "\n",
182
+ "def convert_gender(value):\n",
183
+ " \"\"\"Convert gender value to binary (0 for female, 1 for male)\"\"\"\n",
184
+ " if value is None:\n",
185
+ " return None\n",
186
+ " \n",
187
+ " # Extract the value after the colon\n",
188
+ " if \":\" in value:\n",
189
+ " gender = value.split(\":\", 1)[1].strip()\n",
190
+ " else:\n",
191
+ " gender = value.strip()\n",
192
+ " \n",
193
+ " if gender.upper() == \"F\":\n",
194
+ " return 0\n",
195
+ " elif gender.upper() == \"M\":\n",
196
+ " return 1\n",
197
+ " else:\n",
198
+ " return None\n",
199
+ "\n",
200
+ "# 3. Save Metadata\n",
201
+ "# Check if trait data is available (trait_row is not None)\n",
202
+ "is_trait_available = trait_row is not None\n",
203
+ "\n",
204
+ "# Validate and save cohort info for initial filtering\n",
205
+ "validate_and_save_cohort_info(\n",
206
+ " is_final=False,\n",
207
+ " cohort=cohort,\n",
208
+ " info_path=json_path,\n",
209
+ " is_gene_available=is_gene_available,\n",
210
+ " is_trait_available=is_trait_available\n",
211
+ ")\n",
212
+ "\n",
213
+ "# 4. Clinical Feature Extraction (if trait_row is not None)\n",
214
+ "if trait_row is not None:\n",
215
+ " # Extract clinical features\n",
216
+ " clinical_features_df = geo_select_clinical_features(\n",
217
+ " clinical_df=clinical_data,\n",
218
+ " trait=trait,\n",
219
+ " trait_row=trait_row,\n",
220
+ " convert_trait=convert_trait,\n",
221
+ " age_row=age_row,\n",
222
+ " convert_age=convert_age,\n",
223
+ " gender_row=gender_row,\n",
224
+ " convert_gender=convert_gender\n",
225
+ " )\n",
226
+ " \n",
227
+ " # Preview the extracted clinical features\n",
228
+ " preview = preview_df(clinical_features_df)\n",
229
+ " print(\"Preview of clinical features:\")\n",
230
+ " print(preview)\n",
231
+ " \n",
232
+ " # Save clinical data to CSV\n",
233
+ " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
234
+ " clinical_features_df.to_csv(out_clinical_data_file, index=False)\n",
235
+ " print(f\"Clinical data saved to {out_clinical_data_file}\")\n"
236
+ ]
237
+ },
238
+ {
239
+ "cell_type": "markdown",
240
+ "id": "1fac0d62",
241
+ "metadata": {},
242
+ "source": [
243
+ "### Step 3: Gene Data Extraction"
244
+ ]
245
+ },
246
+ {
247
+ "cell_type": "code",
248
+ "execution_count": 4,
249
+ "id": "1e627a09",
250
+ "metadata": {
251
+ "execution": {
252
+ "iopub.execute_input": "2025-03-25T08:25:56.816289Z",
253
+ "iopub.status.busy": "2025-03-25T08:25:56.816191Z",
254
+ "iopub.status.idle": "2025-03-25T08:25:56.940057Z",
255
+ "shell.execute_reply": "2025-03-25T08:25:56.939619Z"
256
+ }
257
+ },
258
+ "outputs": [
259
+ {
260
+ "name": "stdout",
261
+ "output_type": "stream",
262
+ "text": [
263
+ "Matrix file found: ../../input/GEO/Congestive_heart_failure/GSE93101/GSE93101_series_matrix.txt.gz\n",
264
+ "Gene data shape: (29363, 33)\n",
265
+ "First 20 gene/probe identifiers:\n",
266
+ "Index(['ILMN_1343291', 'ILMN_1651209', 'ILMN_1651228', 'ILMN_1651229',\n",
267
+ " 'ILMN_1651235', 'ILMN_1651236', 'ILMN_1651237', 'ILMN_1651238',\n",
268
+ " 'ILMN_1651254', 'ILMN_1651260', 'ILMN_1651262', 'ILMN_1651268',\n",
269
+ " 'ILMN_1651278', 'ILMN_1651282', 'ILMN_1651285', 'ILMN_1651286',\n",
270
+ " 'ILMN_1651292', 'ILMN_1651303', 'ILMN_1651309', 'ILMN_1651315'],\n",
271
+ " dtype='object', name='ID')\n"
272
+ ]
273
+ }
274
+ ],
275
+ "source": [
276
+ "# 1. Get the SOFT and matrix file paths again \n",
277
+ "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
278
+ "print(f\"Matrix file found: {matrix_file}\")\n",
279
+ "\n",
280
+ "# 2. Use the get_genetic_data function from the library to get the gene_data\n",
281
+ "try:\n",
282
+ " gene_data = get_genetic_data(matrix_file)\n",
283
+ " print(f\"Gene data shape: {gene_data.shape}\")\n",
284
+ " \n",
285
+ " # 3. Print the first 20 row IDs (gene or probe identifiers)\n",
286
+ " print(\"First 20 gene/probe identifiers:\")\n",
287
+ " print(gene_data.index[:20])\n",
288
+ "except Exception as e:\n",
289
+ " print(f\"Error extracting gene data: {e}\")\n"
290
+ ]
291
+ },
292
+ {
293
+ "cell_type": "markdown",
294
+ "id": "50eb9800",
295
+ "metadata": {},
296
+ "source": [
297
+ "### Step 4: Gene Identifier Review"
298
+ ]
299
+ },
300
+ {
301
+ "cell_type": "code",
302
+ "execution_count": 5,
303
+ "id": "97245137",
304
+ "metadata": {
305
+ "execution": {
306
+ "iopub.execute_input": "2025-03-25T08:25:56.941465Z",
307
+ "iopub.status.busy": "2025-03-25T08:25:56.941358Z",
308
+ "iopub.status.idle": "2025-03-25T08:25:56.943231Z",
309
+ "shell.execute_reply": "2025-03-25T08:25:56.942947Z"
310
+ }
311
+ },
312
+ "outputs": [],
313
+ "source": [
314
+ "# The identifiers starting with \"ILMN_\" are Illumina probe IDs, not human gene symbols.\n",
315
+ "# These are specific to Illumina microarray platforms and need to be mapped to standard gene symbols.\n",
316
+ "# ILMN_ prefix indicates Illumina's proprietary probe identifiers from their microarray platforms.\n",
317
+ "\n",
318
+ "requires_gene_mapping = True\n"
319
+ ]
320
+ },
321
+ {
322
+ "cell_type": "markdown",
323
+ "id": "49d4be7c",
324
+ "metadata": {},
325
+ "source": [
326
+ "### Step 5: Gene Annotation"
327
+ ]
328
+ },
329
+ {
330
+ "cell_type": "code",
331
+ "execution_count": 6,
332
+ "id": "9dfc797f",
333
+ "metadata": {
334
+ "execution": {
335
+ "iopub.execute_input": "2025-03-25T08:25:56.944586Z",
336
+ "iopub.status.busy": "2025-03-25T08:25:56.944487Z",
337
+ "iopub.status.idle": "2025-03-25T08:26:07.851780Z",
338
+ "shell.execute_reply": "2025-03-25T08:26:07.851336Z"
339
+ }
340
+ },
341
+ "outputs": [
342
+ {
343
+ "name": "stdout",
344
+ "output_type": "stream",
345
+ "text": [
346
+ "\n",
347
+ "Gene annotation preview:\n",
348
+ "Columns in gene annotation: ['ID', 'Transcript', 'Species', 'Source', 'Search_Key', 'ILMN_Gene', 'Source_Reference_ID', 'RefSeq_ID', 'Entrez_Gene_ID', 'GI', 'Accession', 'Symbol', 'Protein_Product', 'Array_Address_Id', 'Probe_Type', 'Probe_Start', 'SEQUENCE', 'Chromosome', 'Probe_Chr_Orientation', 'Probe_Coordinates', 'Cytoband', 'Definition', 'Ontology_Component', 'Ontology_Process', 'Ontology_Function', 'Synonyms', 'Obsolete_Probe_Id', 'GB_ACC']\n",
349
+ "{'ID': ['ILMN_3166687', 'ILMN_3165566', 'ILMN_3164811', 'ILMN_3165363', 'ILMN_3166511'], 'Transcript': ['ILMN_333737', 'ILMN_333646', 'ILMN_333584', 'ILMN_333628', 'ILMN_333719'], 'Species': ['ILMN Controls', 'ILMN Controls', 'ILMN Controls', 'ILMN Controls', 'ILMN Controls'], 'Source': ['ILMN_Controls', 'ILMN_Controls', 'ILMN_Controls', 'ILMN_Controls', 'ILMN_Controls'], 'Search_Key': ['ERCC-00162', 'ERCC-00071', 'ERCC-00009', 'ERCC-00053', 'ERCC-00144'], 'ILMN_Gene': ['ERCC-00162', 'ERCC-00071', 'ERCC-00009', 'ERCC-00053', 'ERCC-00144'], 'Source_Reference_ID': ['ERCC-00162', 'ERCC-00071', 'ERCC-00009', 'ERCC-00053', 'ERCC-00144'], 'RefSeq_ID': [nan, nan, nan, nan, nan], 'Entrez_Gene_ID': [nan, nan, nan, nan, nan], 'GI': [nan, nan, nan, nan, nan], 'Accession': ['DQ516750', 'DQ883654', 'DQ668364', 'DQ516785', 'DQ854995'], 'Symbol': ['ERCC-00162', 'ERCC-00071', 'ERCC-00009', 'ERCC-00053', 'ERCC-00144'], 'Protein_Product': [nan, nan, nan, nan, nan], 'Array_Address_Id': [5270161.0, 4260594.0, 7610424.0, 5260356.0, 2030196.0], 'Probe_Type': ['S', 'S', 'S', 'S', 'S'], 'Probe_Start': [12.0, 224.0, 868.0, 873.0, 130.0], 'SEQUENCE': ['CCCATGTGTCCAATTCTGAATATCTTTCCAGCTAAGTGCTTCTGCCCACC', 'GGATTAACTGCTGTGGTGTGTCATACTCGGCTACCTCCTGGTTTGGCGTC', 'GACCACGCCTTGTAATCGTATGACACGCGCTTGACACGACTGAATCCAGC', 'CTGCAATGCCATTAACAACCTTAGCACGGTATTTCCAGTAGCTGGTGAGC', 'CGTGCAGACAGGGATCGTAAGGCGATCCAGCCGGTATACCTTAGTCACAT'], 'Chromosome': [nan, nan, nan, nan, nan], 'Probe_Chr_Orientation': [nan, nan, nan, nan, nan], 'Probe_Coordinates': [nan, nan, nan, nan, nan], 'Cytoband': [nan, nan, nan, nan, nan], 'Definition': ['Methanocaldococcus jannaschii spike-in control MJ-500-33 genomic sequence', 'Synthetic construct clone NISTag13 external RNA control sequence', 'Synthetic construct clone TagJ microarray control', 'Methanocaldococcus jannaschii spike-in control MJ-1000-68 genomic sequence', 'Synthetic construct clone AG006.1100 external RNA control sequence'], 'Ontology_Component': [nan, nan, nan, nan, nan], 'Ontology_Process': [nan, nan, nan, nan, nan], 'Ontology_Function': [nan, nan, nan, nan, nan], 'Synonyms': [nan, nan, nan, nan, nan], 'Obsolete_Probe_Id': [nan, nan, nan, nan, nan], 'GB_ACC': ['DQ516750', 'DQ883654', 'DQ668364', 'DQ516785', 'DQ854995']}\n",
350
+ "\n",
351
+ "Analyzing SPOT_ID.1 column for gene symbols:\n",
352
+ "\n",
353
+ "Gene data ID prefix: ILMN\n",
354
+ "Column 'ID' contains values matching gene data ID pattern\n"
355
+ ]
356
+ },
357
+ {
358
+ "name": "stdout",
359
+ "output_type": "stream",
360
+ "text": [
361
+ "Column 'Transcript' contains values matching gene data ID pattern\n"
362
+ ]
363
+ },
364
+ {
365
+ "name": "stdout",
366
+ "output_type": "stream",
367
+ "text": [
368
+ "Column 'Species' contains values matching gene data ID pattern\n"
369
+ ]
370
+ },
371
+ {
372
+ "name": "stdout",
373
+ "output_type": "stream",
374
+ "text": [
375
+ "Column 'Source' contains values matching gene data ID pattern\n"
376
+ ]
377
+ },
378
+ {
379
+ "name": "stdout",
380
+ "output_type": "stream",
381
+ "text": [
382
+ "\n",
383
+ "Checking for columns containing transcript or gene related terms:\n",
384
+ "Column 'Transcript' may contain gene-related information\n",
385
+ "Sample values: ['ILMN_333737', 'ILMN_333646', 'ILMN_333584']\n",
386
+ "Column 'ILMN_Gene' may contain gene-related information\n",
387
+ "Sample values: ['ERCC-00162', 'ERCC-00071', 'ERCC-00009']\n",
388
+ "Column 'Entrez_Gene_ID' may contain gene-related information\n",
389
+ "Sample values: [nan, nan, nan]\n",
390
+ "Column 'Symbol' may contain gene-related information\n",
391
+ "Sample values: ['ERCC-00162', 'ERCC-00071', 'ERCC-00009']\n"
392
+ ]
393
+ }
394
+ ],
395
+ "source": [
396
+ "# 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.\n",
397
+ "gene_annotation = get_gene_annotation(soft_file)\n",
398
+ "\n",
399
+ "# 2. Analyze the gene annotation dataframe to identify which columns contain the gene identifiers and gene symbols\n",
400
+ "print(\"\\nGene annotation preview:\")\n",
401
+ "print(f\"Columns in gene annotation: {gene_annotation.columns.tolist()}\")\n",
402
+ "print(preview_df(gene_annotation, n=5))\n",
403
+ "\n",
404
+ "# Check for gene information in the SPOT_ID.1 column which appears to contain gene names\n",
405
+ "print(\"\\nAnalyzing SPOT_ID.1 column for gene symbols:\")\n",
406
+ "if 'SPOT_ID.1' in gene_annotation.columns:\n",
407
+ " # Extract a few sample values\n",
408
+ " sample_values = gene_annotation['SPOT_ID.1'].head(3).tolist()\n",
409
+ " for i, value in enumerate(sample_values):\n",
410
+ " print(f\"Sample {i+1} excerpt: {value[:200]}...\") # Print first 200 chars\n",
411
+ " # Test the extract_human_gene_symbols function on these values\n",
412
+ " symbols = extract_human_gene_symbols(value)\n",
413
+ " print(f\" Extracted gene symbols: {symbols}\")\n",
414
+ "\n",
415
+ "# Try to find the probe IDs in the gene annotation\n",
416
+ "gene_data_id_prefix = gene_data.index[0].split('_')[0] # Get prefix of first gene ID\n",
417
+ "print(f\"\\nGene data ID prefix: {gene_data_id_prefix}\")\n",
418
+ "\n",
419
+ "# Look for columns that might match the gene data IDs\n",
420
+ "for col in gene_annotation.columns:\n",
421
+ " if gene_annotation[col].astype(str).str.contains(gene_data_id_prefix).any():\n",
422
+ " print(f\"Column '{col}' contains values matching gene data ID pattern\")\n",
423
+ "\n",
424
+ "# Check if there's any column that might contain transcript or gene IDs\n",
425
+ "print(\"\\nChecking for columns containing transcript or gene related terms:\")\n",
426
+ "for col in gene_annotation.columns:\n",
427
+ " if any(term in col.upper() for term in ['GENE', 'TRANSCRIPT', 'SYMBOL', 'NAME', 'DESCRIPTION']):\n",
428
+ " print(f\"Column '{col}' may contain gene-related information\")\n",
429
+ " # Show sample values\n",
430
+ " print(f\"Sample values: {gene_annotation[col].head(3).tolist()}\")\n"
431
+ ]
432
+ },
433
+ {
434
+ "cell_type": "markdown",
435
+ "id": "57195f28",
436
+ "metadata": {},
437
+ "source": [
438
+ "### Step 6: Gene Identifier Mapping"
439
+ ]
440
+ },
441
+ {
442
+ "cell_type": "code",
443
+ "execution_count": 7,
444
+ "id": "4fd8c11e",
445
+ "metadata": {
446
+ "execution": {
447
+ "iopub.execute_input": "2025-03-25T08:26:07.853300Z",
448
+ "iopub.status.busy": "2025-03-25T08:26:07.853179Z",
449
+ "iopub.status.idle": "2025-03-25T08:26:08.030849Z",
450
+ "shell.execute_reply": "2025-03-25T08:26:08.030477Z"
451
+ }
452
+ },
453
+ "outputs": [
454
+ {
455
+ "name": "stdout",
456
+ "output_type": "stream",
457
+ "text": [
458
+ "\n",
459
+ "Gene mapping preview:\n",
460
+ "Gene mapping shape: (29377, 2)\n",
461
+ "{'ID': ['ILMN_3166687', 'ILMN_3165566', 'ILMN_3164811', 'ILMN_3165363', 'ILMN_3166511'], 'Gene': ['ERCC-00162', 'ERCC-00071', 'ERCC-00009', 'ERCC-00053', 'ERCC-00144']}\n",
462
+ "\n",
463
+ "Gene expression data after mapping:\n",
464
+ "Shape: (20206, 33)\n",
465
+ "First 5 gene symbols: ['A1BG', 'A1CF', 'A26C3', 'A2BP1', 'A2LD1']\n",
466
+ "Number of unique gene symbols: 20206\n",
467
+ "Common genes found: ['TP53', 'BRCA1', 'EGFR', 'TNF', 'IL6']\n"
468
+ ]
469
+ }
470
+ ],
471
+ "source": [
472
+ "# 1. Based on the preview, we can see that:\n",
473
+ "# - 'ID' column in the gene annotation contains the same ILMN_ identifiers used in gene expression data\n",
474
+ "# - 'Symbol' column contains gene symbols we need to map to\n",
475
+ "\n",
476
+ "# 2. Get gene mapping dataframe using the function from the library\n",
477
+ "gene_mapping = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='Symbol')\n",
478
+ "\n",
479
+ "# Examine the mapping to verify it has the expected format\n",
480
+ "print(\"\\nGene mapping preview:\")\n",
481
+ "print(f\"Gene mapping shape: {gene_mapping.shape}\")\n",
482
+ "print(preview_df(gene_mapping, n=5))\n",
483
+ "\n",
484
+ "# 3. Apply gene mapping to convert probe-level expression to gene-level expression\n",
485
+ "gene_data = apply_gene_mapping(gene_data, gene_mapping)\n",
486
+ "\n",
487
+ "# Preview the resulting gene expression data\n",
488
+ "print(\"\\nGene expression data after mapping:\")\n",
489
+ "print(f\"Shape: {gene_data.shape}\")\n",
490
+ "print(f\"First 5 gene symbols: {gene_data.index[:5].tolist()}\")\n",
491
+ "\n",
492
+ "# Examine number of unique gene symbols\n",
493
+ "print(f\"Number of unique gene symbols: {len(gene_data.index.unique())}\")\n",
494
+ "\n",
495
+ "# Check if standard gene symbols are present by looking for common genes\n",
496
+ "common_genes = [\"TP53\", \"BRCA1\", \"EGFR\", \"TNF\", \"IL6\"]\n",
497
+ "found_genes = [gene for gene in common_genes if gene in gene_data.index]\n",
498
+ "print(f\"Common genes found: {found_genes}\")\n"
499
+ ]
500
+ },
501
+ {
502
+ "cell_type": "markdown",
503
+ "id": "a23bc703",
504
+ "metadata": {},
505
+ "source": [
506
+ "### Step 7: Data Normalization and Linking"
507
+ ]
508
+ },
509
+ {
510
+ "cell_type": "code",
511
+ "execution_count": 8,
512
+ "id": "24420a29",
513
+ "metadata": {
514
+ "execution": {
515
+ "iopub.execute_input": "2025-03-25T08:26:08.032641Z",
516
+ "iopub.status.busy": "2025-03-25T08:26:08.032528Z",
517
+ "iopub.status.idle": "2025-03-25T08:26:14.377772Z",
518
+ "shell.execute_reply": "2025-03-25T08:26:14.377224Z"
519
+ }
520
+ },
521
+ "outputs": [
522
+ {
523
+ "name": "stdout",
524
+ "output_type": "stream",
525
+ "text": [
526
+ "Gene data shape before normalization: (20206, 33)\n",
527
+ "Gene data shape after normalization: (19445, 33)\n"
528
+ ]
529
+ },
530
+ {
531
+ "name": "stdout",
532
+ "output_type": "stream",
533
+ "text": [
534
+ "Normalized gene expression data saved to ../../output/preprocess/Congestive_heart_failure/gene_data/GSE93101.csv\n",
535
+ "Original clinical data preview:\n",
536
+ " !Sample_geo_accession GSM2443799 \\\n",
537
+ "0 !Sample_characteristics_ch1 course: Acute myocarditis \n",
538
+ "1 !Sample_characteristics_ch1 age: 33.4 \n",
539
+ "2 !Sample_characteristics_ch1 gender: F \n",
540
+ "3 !Sample_characteristics_ch1 outcome: Success \n",
541
+ "\n",
542
+ " GSM2443800 GSM2443801 \\\n",
543
+ "0 course: Acute myocarditis course: Acute myocarditis \n",
544
+ "1 age: 51.2 age: 51.9 \n",
545
+ "2 gender: M gender: F \n",
546
+ "3 outcome: Success outcome: Failure \n",
547
+ "\n",
548
+ " GSM2443802 GSM2443803 \\\n",
549
+ "0 course: Acute myocardial infarction course: Acute myocarditis \n",
550
+ "1 age: 47.8 age: 41.5 \n",
551
+ "2 gender: M gender: F \n",
552
+ "3 outcome: Success outcome: Failure \n",
553
+ "\n",
554
+ " GSM2443804 GSM2443805 \\\n",
555
+ "0 course: Acute myocardial infarction course: Acute myocardial infarction \n",
556
+ "1 age: 67.3 age: 52.8 \n",
557
+ "2 gender: M gender: M \n",
558
+ "3 outcome: Failure outcome: Success \n",
559
+ "\n",
560
+ " GSM2443806 GSM2443807 \\\n",
561
+ "0 course: Dilated cardiomyopathy, DCMP course: Acute myocardial infarction \n",
562
+ "1 age: 16.1 age: 78.9 \n",
563
+ "2 gender: M gender: M \n",
564
+ "3 outcome: Failure outcome: Failure \n",
565
+ "\n",
566
+ " ... GSM2443822 GSM2443823 \\\n",
567
+ "0 ... course: Congestive heart failure course: Aortic dissection \n",
568
+ "1 ... age: 66.1 age: 55.9 \n",
569
+ "2 ... gender: M gender: M \n",
570
+ "3 ... outcome: Success outcome: Failure \n",
571
+ "\n",
572
+ " GSM2443824 GSM2443825 \\\n",
573
+ "0 course: Dilated cardiomyopathy, DCMP course: Acute myocardial infarction \n",
574
+ "1 age: 49.1 age: 63 \n",
575
+ "2 gender: F gender: M \n",
576
+ "3 outcome: Failure outcome: Failure \n",
577
+ "\n",
578
+ " GSM2443826 GSM2443827 \\\n",
579
+ "0 course: Dilated cardiomyopathy, DCMP course: Acute myocardial infarction \n",
580
+ "1 age: 21 age: 53.6 \n",
581
+ "2 gender: M gender: M \n",
582
+ "3 outcome: Failure outcome: Success \n",
583
+ "\n",
584
+ " GSM2443828 GSM2443829 \\\n",
585
+ "0 course: Acute myocardial infarction course: Acute myocardial infarction \n",
586
+ "1 age: 50.1 age: 37.4 \n",
587
+ "2 gender: F gender: M \n",
588
+ "3 outcome: Success outcome: Failure \n",
589
+ "\n",
590
+ " GSM2443830 GSM2443831 \n",
591
+ "0 course: Acute myocarditis course: Congestive heart failure \n",
592
+ "1 age: 71.5 age: 56.5 \n",
593
+ "2 gender: F gender: M \n",
594
+ "3 outcome: Success outcome: Success \n",
595
+ "\n",
596
+ "[4 rows x 34 columns]\n",
597
+ "Selected clinical data shape: (3, 33)\n",
598
+ "Clinical data preview:\n",
599
+ " GSM2443799 GSM2443800 GSM2443801 GSM2443802 \\\n",
600
+ "Congestive_heart_failure 0.0 0.0 0.0 0.0 \n",
601
+ "Age 33.4 51.2 51.9 47.8 \n",
602
+ "Gender 0.0 1.0 0.0 1.0 \n",
603
+ "\n",
604
+ " GSM2443803 GSM2443804 GSM2443805 GSM2443806 \\\n",
605
+ "Congestive_heart_failure 0.0 0.0 0.0 0.0 \n",
606
+ "Age 41.5 67.3 52.8 16.1 \n",
607
+ "Gender 0.0 1.0 1.0 1.0 \n",
608
+ "\n",
609
+ " GSM2443807 GSM2443808 ... GSM2443822 GSM2443823 \\\n",
610
+ "Congestive_heart_failure 0.0 0.0 ... 1.0 0.0 \n",
611
+ "Age 78.9 53.2 ... 66.1 55.9 \n",
612
+ "Gender 1.0 1.0 ... 1.0 1.0 \n",
613
+ "\n",
614
+ " GSM2443824 GSM2443825 GSM2443826 GSM2443827 \\\n",
615
+ "Congestive_heart_failure 0.0 0.0 0.0 0.0 \n",
616
+ "Age 49.1 63.0 21.0 53.6 \n",
617
+ "Gender 0.0 1.0 1.0 1.0 \n",
618
+ "\n",
619
+ " GSM2443828 GSM2443829 GSM2443830 GSM2443831 \n",
620
+ "Congestive_heart_failure 0.0 0.0 0.0 1.0 \n",
621
+ "Age 50.1 37.4 71.5 56.5 \n",
622
+ "Gender 0.0 1.0 0.0 1.0 \n",
623
+ "\n",
624
+ "[3 rows x 33 columns]\n",
625
+ "Linked data shape before processing: (33, 19448)\n",
626
+ "Linked data preview (first 5 rows, 5 columns):\n",
627
+ " Congestive_heart_failure Age Gender A1BG A1BG-AS1\n",
628
+ "GSM2443799 0.0 33.4 0.0 129.442547 1330.542639\n",
629
+ "GSM2443800 0.0 51.2 1.0 142.061233 2177.610030\n",
630
+ "GSM2443801 0.0 51.9 0.0 103.958331 1130.866630\n",
631
+ "GSM2443802 0.0 47.8 1.0 137.556161 1116.450458\n",
632
+ "GSM2443803 0.0 41.5 0.0 111.260768 1112.964973\n"
633
+ ]
634
+ },
635
+ {
636
+ "name": "stdout",
637
+ "output_type": "stream",
638
+ "text": [
639
+ "Data shape after handling missing values: (33, 19448)\n",
640
+ "For the feature 'Congestive_heart_failure', the least common label is '1.0' with 3 occurrences. This represents 9.09% of the dataset.\n",
641
+ "Quartiles for 'Age':\n",
642
+ " 25%: 45.2\n",
643
+ " 50% (Median): 52.4\n",
644
+ " 75%: 56.5\n",
645
+ "Min: 16.1\n",
646
+ "Max: 78.9\n",
647
+ "For the feature 'Gender', the least common label is '0.0' with 10 occurrences. This represents 30.30% of the dataset.\n",
648
+ "Dataset is not usable for analysis. No linked data file saved.\n"
649
+ ]
650
+ }
651
+ ],
652
+ "source": [
653
+ "# 1. Normalize gene symbols in the gene expression data\n",
654
+ "# Use normalize_gene_symbols_in_index to standardize gene symbols\n",
655
+ "normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n",
656
+ "print(f\"Gene data shape before normalization: {gene_data.shape}\")\n",
657
+ "print(f\"Gene data shape after normalization: {normalized_gene_data.shape}\")\n",
658
+ "\n",
659
+ "# Save the normalized gene data to file\n",
660
+ "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
661
+ "normalized_gene_data.to_csv(out_gene_data_file)\n",
662
+ "print(f\"Normalized gene expression data saved to {out_gene_data_file}\")\n",
663
+ "\n",
664
+ "# Load the actual clinical data from the matrix file that was previously obtained in Step 1\n",
665
+ "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
666
+ "background_info, clinical_data = get_background_and_clinical_data(matrix_file)\n",
667
+ "\n",
668
+ "# Get preview of clinical data to understand its structure\n",
669
+ "print(\"Original clinical data preview:\")\n",
670
+ "print(clinical_data.head())\n",
671
+ "\n",
672
+ "# 2. If we have trait data available, proceed with linking\n",
673
+ "if trait_row is not None:\n",
674
+ " # Extract clinical features using the original clinical data\n",
675
+ " selected_clinical_df = geo_select_clinical_features(\n",
676
+ " clinical_df=clinical_data,\n",
677
+ " trait=trait,\n",
678
+ " trait_row=trait_row,\n",
679
+ " convert_trait=convert_trait,\n",
680
+ " age_row=age_row,\n",
681
+ " convert_age=convert_age,\n",
682
+ " gender_row=gender_row,\n",
683
+ " convert_gender=convert_gender\n",
684
+ " )\n",
685
+ "\n",
686
+ " print(f\"Selected clinical data shape: {selected_clinical_df.shape}\")\n",
687
+ " print(\"Clinical data preview:\")\n",
688
+ " print(selected_clinical_df.head())\n",
689
+ "\n",
690
+ " # Link the clinical and genetic data\n",
691
+ " linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)\n",
692
+ " print(f\"Linked data shape before processing: {linked_data.shape}\")\n",
693
+ " print(\"Linked data preview (first 5 rows, 5 columns):\")\n",
694
+ " print(linked_data.iloc[:5, :5] if not linked_data.empty else \"Empty dataframe\")\n",
695
+ "\n",
696
+ " # 3. Handle missing values\n",
697
+ " try:\n",
698
+ " linked_data = handle_missing_values(linked_data, trait)\n",
699
+ " print(f\"Data shape after handling missing values: {linked_data.shape}\")\n",
700
+ " except Exception as e:\n",
701
+ " print(f\"Error handling missing values: {e}\")\n",
702
+ " linked_data = pd.DataFrame() # Create empty dataframe if error occurs\n",
703
+ "\n",
704
+ " # 4. Check for bias in features\n",
705
+ " if not linked_data.empty and linked_data.shape[0] > 0:\n",
706
+ " # Check if trait is biased\n",
707
+ " trait_type = 'binary' if len(linked_data[trait].unique()) <= 2 else 'continuous'\n",
708
+ " if trait_type == \"binary\":\n",
709
+ " is_biased = judge_binary_variable_biased(linked_data, trait)\n",
710
+ " else:\n",
711
+ " is_biased = judge_continuous_variable_biased(linked_data, trait)\n",
712
+ " \n",
713
+ " # Remove biased demographic features\n",
714
+ " if \"Age\" in linked_data.columns:\n",
715
+ " age_biased = judge_continuous_variable_biased(linked_data, 'Age')\n",
716
+ " if age_biased:\n",
717
+ " linked_data = linked_data.drop(columns='Age')\n",
718
+ " \n",
719
+ " if \"Gender\" in linked_data.columns:\n",
720
+ " gender_biased = judge_binary_variable_biased(linked_data, 'Gender')\n",
721
+ " if gender_biased:\n",
722
+ " linked_data = linked_data.drop(columns='Gender')\n",
723
+ " else:\n",
724
+ " is_biased = True\n",
725
+ " print(\"Cannot check for bias as dataframe is empty or has no rows after missing value handling\")\n",
726
+ "\n",
727
+ " # 5. Validate and save cohort information\n",
728
+ " note = \"\"\n",
729
+ " if linked_data.empty or linked_data.shape[0] == 0:\n",
730
+ " note = \"Dataset contains gene expression data related to atrial fibrillation after cardiac surgery, but linking clinical and genetic data failed, possibly due to mismatched sample IDs.\"\n",
731
+ " else:\n",
732
+ " note = \"Dataset contains gene expression data for atrial fibrillation after cardiac surgery, which is relevant to arrhythmia research.\"\n",
733
+ " \n",
734
+ " is_usable = validate_and_save_cohort_info(\n",
735
+ " is_final=True,\n",
736
+ " cohort=cohort,\n",
737
+ " info_path=json_path,\n",
738
+ " is_gene_available=True,\n",
739
+ " is_trait_available=True,\n",
740
+ " is_biased=is_biased,\n",
741
+ " df=linked_data,\n",
742
+ " note=note\n",
743
+ " )\n",
744
+ "\n",
745
+ " # 6. Save the linked data if usable\n",
746
+ " if is_usable:\n",
747
+ " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n",
748
+ " linked_data.to_csv(out_data_file)\n",
749
+ " print(f\"Linked data saved to {out_data_file}\")\n",
750
+ " else:\n",
751
+ " print(\"Dataset is not usable for analysis. No linked data file saved.\")\n",
752
+ "else:\n",
753
+ " # If no trait data available, validate with trait_available=False\n",
754
+ " is_usable = validate_and_save_cohort_info(\n",
755
+ " is_final=True,\n",
756
+ " cohort=cohort,\n",
757
+ " info_path=json_path,\n",
758
+ " is_gene_available=True,\n",
759
+ " is_trait_available=False,\n",
760
+ " is_biased=True, # Set to True since we can't use data without trait\n",
761
+ " df=pd.DataFrame(), # Empty DataFrame\n",
762
+ " note=\"Dataset contains gene expression data but lacks proper clinical trait information for arrhythmia analysis.\"\n",
763
+ " )\n",
764
+ " \n",
765
+ " print(\"Dataset is not usable for arrhythmia analysis due to lack of clinical trait data. No linked data file saved.\")"
766
+ ]
767
+ }
768
+ ],
769
+ "metadata": {
770
+ "language_info": {
771
+ "codemirror_mode": {
772
+ "name": "ipython",
773
+ "version": 3
774
+ },
775
+ "file_extension": ".py",
776
+ "mimetype": "text/x-python",
777
+ "name": "python",
778
+ "nbconvert_exporter": "python",
779
+ "pygments_lexer": "ipython3",
780
+ "version": "3.10.16"
781
+ }
782
+ },
783
+ "nbformat": 4,
784
+ "nbformat_minor": 5
785
+ }
code/Congestive_heart_failure/TCGA.ipynb ADDED
@@ -0,0 +1,520 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": 1,
6
+ "id": "a6af35d1",
7
+ "metadata": {
8
+ "execution": {
9
+ "iopub.execute_input": "2025-03-25T08:26:15.291399Z",
10
+ "iopub.status.busy": "2025-03-25T08:26:15.291182Z",
11
+ "iopub.status.idle": "2025-03-25T08:26:15.463517Z",
12
+ "shell.execute_reply": "2025-03-25T08:26:15.463161Z"
13
+ }
14
+ },
15
+ "outputs": [],
16
+ "source": [
17
+ "import sys\n",
18
+ "import os\n",
19
+ "sys.path.append(os.path.abspath(os.path.join(os.getcwd(), '../..')))\n",
20
+ "\n",
21
+ "# Path Configuration\n",
22
+ "from tools.preprocess import *\n",
23
+ "\n",
24
+ "# Processing context\n",
25
+ "trait = \"Congestive_heart_failure\"\n",
26
+ "\n",
27
+ "# Input paths\n",
28
+ "tcga_root_dir = \"../../input/TCGA\"\n",
29
+ "\n",
30
+ "# Output paths\n",
31
+ "out_data_file = \"../../output/preprocess/Congestive_heart_failure/TCGA.csv\"\n",
32
+ "out_gene_data_file = \"../../output/preprocess/Congestive_heart_failure/gene_data/TCGA.csv\"\n",
33
+ "out_clinical_data_file = \"../../output/preprocess/Congestive_heart_failure/clinical_data/TCGA.csv\"\n",
34
+ "json_path = \"../../output/preprocess/Congestive_heart_failure/cohort_info.json\"\n"
35
+ ]
36
+ },
37
+ {
38
+ "cell_type": "markdown",
39
+ "id": "45628af4",
40
+ "metadata": {},
41
+ "source": [
42
+ "### Step 1: Initial Data Loading"
43
+ ]
44
+ },
45
+ {
46
+ "cell_type": "code",
47
+ "execution_count": 2,
48
+ "id": "13c3fb1f",
49
+ "metadata": {
50
+ "execution": {
51
+ "iopub.execute_input": "2025-03-25T08:26:15.464986Z",
52
+ "iopub.status.busy": "2025-03-25T08:26:15.464835Z",
53
+ "iopub.status.idle": "2025-03-25T08:26:16.959279Z",
54
+ "shell.execute_reply": "2025-03-25T08:26:16.958916Z"
55
+ }
56
+ },
57
+ "outputs": [
58
+ {
59
+ "name": "stdout",
60
+ "output_type": "stream",
61
+ "text": [
62
+ "Looking for a relevant cohort directory for Congestive_heart_failure...\n",
63
+ "Available cohorts: ['TCGA_Liver_Cancer_(LIHC)', 'TCGA_Lower_Grade_Glioma_(LGG)', 'TCGA_lower_grade_glioma_and_glioblastoma_(GBMLGG)', 'TCGA_Lung_Adenocarcinoma_(LUAD)', 'TCGA_Lung_Cancer_(LUNG)', 'TCGA_Lung_Squamous_Cell_Carcinoma_(LUSC)', 'TCGA_Melanoma_(SKCM)', 'TCGA_Mesothelioma_(MESO)', 'TCGA_Ocular_melanomas_(UVM)', 'TCGA_Ovarian_Cancer_(OV)', 'TCGA_Pancreatic_Cancer_(PAAD)', 'TCGA_Pheochromocytoma_Paraganglioma_(PCPG)', 'TCGA_Prostate_Cancer_(PRAD)', 'TCGA_Rectal_Cancer_(READ)', 'TCGA_Sarcoma_(SARC)', 'TCGA_Stomach_Cancer_(STAD)', 'TCGA_Testicular_Cancer_(TGCT)', 'TCGA_Thymoma_(THYM)', 'TCGA_Thyroid_Cancer_(THCA)', 'TCGA_Uterine_Carcinosarcoma_(UCS)', '.DS_Store', 'CrawlData.ipynb', 'TCGA_Acute_Myeloid_Leukemia_(LAML)', 'TCGA_Adrenocortical_Cancer_(ACC)', 'TCGA_Bile_Duct_Cancer_(CHOL)', 'TCGA_Bladder_Cancer_(BLCA)', 'TCGA_Breast_Cancer_(BRCA)', 'TCGA_Cervical_Cancer_(CESC)', 'TCGA_Colon_and_Rectal_Cancer_(COADREAD)', 'TCGA_Colon_Cancer_(COAD)', 'TCGA_Endometrioid_Cancer_(UCEC)', 'TCGA_Esophageal_Cancer_(ESCA)', 'TCGA_Glioblastoma_(GBM)', 'TCGA_Head_and_Neck_Cancer_(HNSC)', 'TCGA_Kidney_Chromophobe_(KICH)', 'TCGA_Kidney_Clear_Cell_Carcinoma_(KIRC)', 'TCGA_Kidney_Papillary_Cell_Carcinoma_(KIRP)', 'TCGA_Large_Bcell_Lymphoma_(DLBC)']\n",
64
+ "Cardiac-related cohorts: []\n",
65
+ "No direct cardiac cohorts found. Looking for possible related cohorts...\n",
66
+ "Possible related cohorts: ['TCGA_Lung_Adenocarcinoma_(LUAD)', 'TCGA_Lung_Cancer_(LUNG)', 'TCGA_Lung_Squamous_Cell_Carcinoma_(LUSC)', 'TCGA_Thymoma_(THYM)']\n",
67
+ "Selected cohort: TCGA_Lung_Adenocarcinoma_(LUAD)\n",
68
+ "Clinical data file: TCGA.LUAD.sampleMap_LUAD_clinicalMatrix\n",
69
+ "Genetic data file: TCGA.LUAD.sampleMap_HiSeqV2_PANCAN.gz\n"
70
+ ]
71
+ },
72
+ {
73
+ "name": "stdout",
74
+ "output_type": "stream",
75
+ "text": [
76
+ "\n",
77
+ "Clinical data columns:\n",
78
+ "['ABSOLUTE_Ploidy', 'ABSOLUTE_Purity', 'AKT1', 'ALK_translocation', 'BRAF', 'CBL', 'CTNNB1', 'Canonical_mut_in_KRAS_EGFR_ALK', 'Cnncl_mt_n_KRAS_EGFR_ALK_RET_ROS1_BRAF_ERBB2_HRAS_NRAS_AKT1_MAP2', 'EGFR', 'ERBB2', 'ERBB4', 'Estimated_allele_fraction_of_a_clonal_varnt_prsnt_t_1_cpy_pr_cll', 'Expression_Subtype', 'HRAS', 'KRAS', 'MAP2K1', 'MET', 'NRAS', 'PIK3CA', 'PTPN11', 'Pathology', 'Pathology_Updated', 'RET_translocation', 'ROS1_translocation', 'STK11', 'WGS_as_of_20120731_0_no_1_yes', '_INTEGRATION', '_PANCAN_CNA_PANCAN_K8', '_PANCAN_Cluster_Cluster_PANCAN', '_PANCAN_DNAMethyl_LUAD', '_PANCAN_DNAMethyl_PANCAN', '_PANCAN_RPPA_PANCAN_K8', '_PANCAN_UNC_RNAseq_PANCAN_K16', '_PANCAN_miRNA_PANCAN', '_PANCAN_mirna_LUAD', '_PANCAN_mutation_PANCAN', '_PATIENT', '_cohort', '_primary_disease', '_primary_site', 'additional_pharmaceutical_therapy', 'additional_radiation_therapy', 'additional_surgery_locoregional_procedure', 'additional_surgery_metastatic_procedure', 'age_at_initial_pathologic_diagnosis', 'anatomic_neoplasm_subdivision', 'anatomic_neoplasm_subdivision_other', 'bcr_followup_barcode', 'bcr_patient_barcode', 'bcr_sample_barcode', 'days_to_additional_surgery_locoregional_procedure', 'days_to_additional_surgery_metastatic_procedure', 'days_to_birth', 'days_to_collection', 'days_to_death', 'days_to_initial_pathologic_diagnosis', 'days_to_last_followup', 'days_to_new_tumor_event_after_initial_treatment', 'disease_code', 'dlco_predictive_percent', 'eastern_cancer_oncology_group', 'egfr_mutation_performed', 'egfr_mutation_result', 'eml4_alk_translocation_method', 'eml4_alk_translocation_performed', 'followup_case_report_form_submission_reason', 'followup_treatment_success', 'form_completion_date', 'gender', 'histological_type', 'history_of_neoadjuvant_treatment', 'icd_10', 'icd_o_3_histology', 'icd_o_3_site', 'informed_consent_verified', 'initial_weight', 'intermediate_dimension', 'is_ffpe', 'karnofsky_performance_score', 'kras_gene_analysis_performed', 'kras_mutation_found', 'kras_mutation_result', 'location_in_lung_parenchyma', 'longest_dimension', 'lost_follow_up', 'new_neoplasm_event_type', 'new_tumor_event_after_initial_treatment', 'number_pack_years_smoked', 'oct_embedded', 'other_dx', 'pathologic_M', 'pathologic_N', 'pathologic_T', 'pathologic_stage', 'pathology_report_file_name', 'patient_id', 'performance_status_scale_timing', 'person_neoplasm_cancer_status', 'post_bronchodilator_fev1_fvc_percent', 'post_bronchodilator_fev1_percent', 'pre_bronchodilator_fev1_fvc_percent', 'pre_bronchodilator_fev1_percent', 'primary_therapy_outcome_success', 'progression_determined_by', 'project_code', 'pulmonary_function_test_performed', 'radiation_therapy', 'residual_tumor', 'sample_type', 'sample_type_id', 'shortest_dimension', 'stopped_smoking_year', 'system_version', 'targeted_molecular_therapy', 'tissue_prospective_collection_indicator', 'tissue_retrospective_collection_indicator', 'tissue_source_site', 'tobacco_smoking_history', 'tobacco_smoking_history_indicator', 'tumor_tissue_site', 'vial_number', 'vital_status', 'year_of_initial_pathologic_diagnosis', 'year_of_tobacco_smoking_onset', '_GENOMIC_ID_TCGA_LUAD_mutation', '_GENOMIC_ID_TCGA_LUAD_mutation_curated_broad_gene', '_GENOMIC_ID_TCGA_LUAD_PDMarray', '_GENOMIC_ID_TCGA_LUAD_exp_HiSeqV2', '_GENOMIC_ID_TCGA_LUAD_G4502A_07_3', '_GENOMIC_ID_TCGA_LUAD_hMethyl27', '_GENOMIC_ID_data/public/TCGA/LUAD/miRNA_GA_gene', '_GENOMIC_ID_TCGA_LUAD_gistic2', '_GENOMIC_ID_TCGA_LUAD_hMethyl450', '_GENOMIC_ID_TCGA_LUAD_PDMRNAseqCNV', '_GENOMIC_ID_TCGA_LUAD_gistic2thd', '_GENOMIC_ID_TCGA_LUAD_PDMarrayCNV', '_GENOMIC_ID_TCGA_LUAD_exp_HiSeqV2_exon', '_GENOMIC_ID_TCGA_LUAD_miRNA_HiSeq', '_GENOMIC_ID_TCGA_LUAD_RPPA_RBN', '_GENOMIC_ID_TCGA_LUAD_exp_HiSeqV2_PANCAN', '_GENOMIC_ID_TCGA_LUAD_PDMRNAseq', '_GENOMIC_ID_TCGA_LUAD_RPPA', '_GENOMIC_ID_TCGA_LUAD_exp_HiSeqV2_percentile', '_GENOMIC_ID_TCGA_LUAD_mutation_broad_gene', '_GENOMIC_ID_data/public/TCGA/LUAD/miRNA_HiSeq_gene', '_GENOMIC_ID_TCGA_LUAD_miRNA_GA']\n",
79
+ "\n",
80
+ "Clinical data shape: (706, 147)\n",
81
+ "Genetic data shape: (20530, 576)\n"
82
+ ]
83
+ }
84
+ ],
85
+ "source": [
86
+ "import os\n",
87
+ "\n",
88
+ "# Check if there's a suitable cohort directory for Arrhythmia\n",
89
+ "print(f\"Looking for a relevant cohort directory for {trait}...\")\n",
90
+ "\n",
91
+ "# Check available cohorts\n",
92
+ "available_dirs = os.listdir(tcga_root_dir)\n",
93
+ "print(f\"Available cohorts: {available_dirs}\")\n",
94
+ "\n",
95
+ "# Arrhythmia is a cardiac condition, so we should look for heart/cardiac-related cohorts\n",
96
+ "cardiac_related_terms = ['heart', 'cardiac', 'cardiovascular', 'thoracic', 'chest']\n",
97
+ "\n",
98
+ "# First check for direct heart/cardiac related cohorts\n",
99
+ "cardiac_related_dirs = [d for d in available_dirs if any(term in d.lower() for term in cardiac_related_terms)]\n",
100
+ "print(f\"Cardiac-related cohorts: {cardiac_related_dirs}\")\n",
101
+ "\n",
102
+ "# If no direct heart-related cohorts, we might need to look at:\n",
103
+ "# 1. General datasets that might include cardiac data\n",
104
+ "# 2. Datasets that affect organs near the heart\n",
105
+ "# 3. Datasets where cardiac function might be measured as part of standard evaluation\n",
106
+ "if not cardiac_related_dirs:\n",
107
+ " print(\"No direct cardiac cohorts found. Looking for possible related cohorts...\")\n",
108
+ " # Lung, thoracic, or chest area studies might include cardiac data\n",
109
+ " possible_related_cohorts = [d for d in available_dirs \n",
110
+ " if any(term in d.lower() for term in ['lung', 'thoracic', 'chest', 'thymoma'])]\n",
111
+ " print(f\"Possible related cohorts: {possible_related_cohorts}\")\n",
112
+ " \n",
113
+ " if possible_related_cohorts:\n",
114
+ " # Lung studies often include cardiac measures\n",
115
+ " selected_cohort = [d for d in possible_related_cohorts if 'lung' in d.lower()][0] if any('lung' in d.lower() for d in possible_related_cohorts) else possible_related_cohorts[0]\n",
116
+ " else:\n",
117
+ " print(f\"No suitable cohort found for {trait}.\")\n",
118
+ " # Mark the task as completed by recording the unavailability\n",
119
+ " validate_and_save_cohort_info(\n",
120
+ " is_final=False,\n",
121
+ " cohort=\"TCGA\",\n",
122
+ " info_path=json_path,\n",
123
+ " is_gene_available=False,\n",
124
+ " is_trait_available=False\n",
125
+ " )\n",
126
+ " # Exit the script early since no suitable cohort was found\n",
127
+ " selected_cohort = None\n",
128
+ "else:\n",
129
+ " selected_cohort = cardiac_related_dirs[0]\n",
130
+ "\n",
131
+ "if selected_cohort:\n",
132
+ " print(f\"Selected cohort: {selected_cohort}\")\n",
133
+ " \n",
134
+ " # Get the full path to the selected cohort directory\n",
135
+ " cohort_dir = os.path.join(tcga_root_dir, selected_cohort)\n",
136
+ " \n",
137
+ " # Get the clinical and genetic data file paths\n",
138
+ " clinical_file_path, genetic_file_path = tcga_get_relevant_filepaths(cohort_dir)\n",
139
+ " \n",
140
+ " print(f\"Clinical data file: {os.path.basename(clinical_file_path)}\")\n",
141
+ " print(f\"Genetic data file: {os.path.basename(genetic_file_path)}\")\n",
142
+ " \n",
143
+ " # Load the clinical and genetic data\n",
144
+ " clinical_df = pd.read_csv(clinical_file_path, index_col=0, sep='\\t')\n",
145
+ " genetic_df = pd.read_csv(genetic_file_path, index_col=0, sep='\\t')\n",
146
+ " \n",
147
+ " # Print the column names of the clinical data\n",
148
+ " print(\"\\nClinical data columns:\")\n",
149
+ " print(clinical_df.columns.tolist())\n",
150
+ " \n",
151
+ " # Basic info about the datasets\n",
152
+ " print(f\"\\nClinical data shape: {clinical_df.shape}\")\n",
153
+ " print(f\"Genetic data shape: {genetic_df.shape}\")\n"
154
+ ]
155
+ },
156
+ {
157
+ "cell_type": "markdown",
158
+ "id": "fc9ce7ea",
159
+ "metadata": {},
160
+ "source": [
161
+ "### Step 2: Find Candidate Demographic Features"
162
+ ]
163
+ },
164
+ {
165
+ "cell_type": "code",
166
+ "execution_count": 3,
167
+ "id": "604bf2f2",
168
+ "metadata": {
169
+ "execution": {
170
+ "iopub.execute_input": "2025-03-25T08:26:16.960644Z",
171
+ "iopub.status.busy": "2025-03-25T08:26:16.960529Z",
172
+ "iopub.status.idle": "2025-03-25T08:26:16.986743Z",
173
+ "shell.execute_reply": "2025-03-25T08:26:16.986393Z"
174
+ }
175
+ },
176
+ "outputs": [
177
+ {
178
+ "name": "stdout",
179
+ "output_type": "stream",
180
+ "text": [
181
+ "Age columns preview:\n",
182
+ "{'age_at_initial_pathologic_diagnosis': [67.0, 67.0, 72.0, 72.0, 77.0], 'days_to_birth': [-24477.0, -24477.0, -26615.0, -26615.0, -28171.0]}\n",
183
+ "Gender columns preview:\n",
184
+ "{'gender': ['MALE', 'MALE', 'MALE', 'MALE', 'FEMALE']}\n"
185
+ ]
186
+ }
187
+ ],
188
+ "source": [
189
+ "# Step 1: Identify candidate columns for age and gender\n",
190
+ "candidate_age_cols = ['age_at_initial_pathologic_diagnosis', 'days_to_birth']\n",
191
+ "candidate_gender_cols = ['gender']\n",
192
+ "\n",
193
+ "# Step 2: Load clinical data and preview the candidate columns\n",
194
+ "clinical_file_path, genetic_file_path = tcga_get_relevant_filepaths(os.path.join(tcga_root_dir, 'TCGA_Lung_Squamous_Cell_Carcinoma_(LUSC)'))\n",
195
+ "clinical_df = pd.read_csv(clinical_file_path, sep='\\t', index_col=0)\n",
196
+ "\n",
197
+ "# Extract and preview age-related columns\n",
198
+ "if candidate_age_cols:\n",
199
+ " age_data = clinical_df[candidate_age_cols]\n",
200
+ " print(\"Age columns preview:\")\n",
201
+ " print(preview_df(age_data, n=5))\n",
202
+ "\n",
203
+ "# Extract and preview gender-related columns\n",
204
+ "if candidate_gender_cols:\n",
205
+ " gender_data = clinical_df[candidate_gender_cols]\n",
206
+ " print(\"Gender columns preview:\")\n",
207
+ " print(preview_df(gender_data, n=5))\n"
208
+ ]
209
+ },
210
+ {
211
+ "cell_type": "markdown",
212
+ "id": "b6401480",
213
+ "metadata": {},
214
+ "source": [
215
+ "### Step 3: Select Demographic Features"
216
+ ]
217
+ },
218
+ {
219
+ "cell_type": "code",
220
+ "execution_count": 4,
221
+ "id": "a5c34fd4",
222
+ "metadata": {
223
+ "execution": {
224
+ "iopub.execute_input": "2025-03-25T08:26:16.988008Z",
225
+ "iopub.status.busy": "2025-03-25T08:26:16.987895Z",
226
+ "iopub.status.idle": "2025-03-25T08:26:16.990703Z",
227
+ "shell.execute_reply": "2025-03-25T08:26:16.990408Z"
228
+ }
229
+ },
230
+ "outputs": [
231
+ {
232
+ "name": "stdout",
233
+ "output_type": "stream",
234
+ "text": [
235
+ "Selected age column: age_at_initial_pathologic_diagnosis\n",
236
+ "Selected gender column: gender\n"
237
+ ]
238
+ }
239
+ ],
240
+ "source": [
241
+ "# Step 1: Select the most appropriate columns for age and gender\n",
242
+ "age_columns_preview = {'age_at_initial_pathologic_diagnosis': [67.0, 67.0, 72.0, 72.0, 77.0], \n",
243
+ " 'days_to_birth': [-24477.0, -24477.0, -26615.0, -26615.0, -28171.0]}\n",
244
+ "gender_columns_preview = {'gender': ['MALE', 'MALE', 'MALE', 'MALE', 'FEMALE']}\n",
245
+ "\n",
246
+ "# Select age column\n",
247
+ "if age_columns_preview:\n",
248
+ " # 'age_at_initial_pathologic_diagnosis' is a direct age value and is easier to interpret than days_to_birth\n",
249
+ " age_col = 'age_at_initial_pathologic_diagnosis'\n",
250
+ "else:\n",
251
+ " age_col = None\n",
252
+ "\n",
253
+ "# Select gender column\n",
254
+ "if gender_columns_preview:\n",
255
+ " # There's only one gender column and it has meaningful values\n",
256
+ " gender_col = 'gender'\n",
257
+ "else:\n",
258
+ " gender_col = None\n",
259
+ "\n",
260
+ "# Step 2: Print the selected columns\n",
261
+ "print(f\"Selected age column: {age_col}\")\n",
262
+ "print(f\"Selected gender column: {gender_col}\")\n"
263
+ ]
264
+ },
265
+ {
266
+ "cell_type": "markdown",
267
+ "id": "ebe659bc",
268
+ "metadata": {},
269
+ "source": [
270
+ "### Step 4: Feature Engineering and Validation"
271
+ ]
272
+ },
273
+ {
274
+ "cell_type": "code",
275
+ "execution_count": 5,
276
+ "id": "d95986fc",
277
+ "metadata": {
278
+ "execution": {
279
+ "iopub.execute_input": "2025-03-25T08:26:16.991848Z",
280
+ "iopub.status.busy": "2025-03-25T08:26:16.991747Z",
281
+ "iopub.status.idle": "2025-03-25T08:27:24.239907Z",
282
+ "shell.execute_reply": "2025-03-25T08:27:24.239515Z"
283
+ }
284
+ },
285
+ "outputs": [
286
+ {
287
+ "name": "stdout",
288
+ "output_type": "stream",
289
+ "text": [
290
+ "Clinical features (first 5 rows):\n",
291
+ " Congestive_heart_failure Age Gender\n",
292
+ "sampleID \n",
293
+ "TCGA-18-3406-01 1 67.0 1.0\n",
294
+ "TCGA-18-3406-11 0 67.0 1.0\n",
295
+ "TCGA-18-3407-01 1 72.0 1.0\n",
296
+ "TCGA-18-3407-11 0 72.0 1.0\n",
297
+ "TCGA-18-3408-01 1 77.0 0.0\n",
298
+ "\n",
299
+ "Processing gene expression data...\n"
300
+ ]
301
+ },
302
+ {
303
+ "name": "stdout",
304
+ "output_type": "stream",
305
+ "text": [
306
+ "Original gene data shape: (20530, 553)\n"
307
+ ]
308
+ },
309
+ {
310
+ "name": "stdout",
311
+ "output_type": "stream",
312
+ "text": [
313
+ "Attempting to normalize gene symbols...\n",
314
+ "Gene data shape after normalization: (0, 20530)\n",
315
+ "WARNING: Gene symbol normalization returned an empty DataFrame.\n",
316
+ "Using original gene data instead of normalized data.\n"
317
+ ]
318
+ },
319
+ {
320
+ "name": "stdout",
321
+ "output_type": "stream",
322
+ "text": [
323
+ "Gene data saved to: ../../output/preprocess/Congestive_heart_failure/gene_data/TCGA.csv\n",
324
+ "\n",
325
+ "Linking clinical and genetic data...\n",
326
+ "Clinical data shape: (626, 3)\n",
327
+ "Genetic data shape: (20530, 553)\n",
328
+ "Number of common samples: 553\n",
329
+ "\n",
330
+ "Linked data shape: (553, 20533)\n",
331
+ "Linked data preview (first 5 rows, first few columns):\n",
332
+ " Congestive_heart_failure Age Gender ARHGEF10L HIF3A\n",
333
+ "TCGA-94-7033-01 1 73.0 1.0 0.045008 -0.609826\n",
334
+ "TCGA-22-5471-01 1 75.0 1.0 -0.974692 -0.066026\n",
335
+ "TCGA-18-4086-01 1 64.0 1.0 -1.282192 -1.959226\n",
336
+ "TCGA-34-5928-01 1 83.0 0.0 -0.671492 4.506374\n",
337
+ "TCGA-43-A56U-01 1 76.0 0.0 0.136608 1.172974\n"
338
+ ]
339
+ },
340
+ {
341
+ "name": "stdout",
342
+ "output_type": "stream",
343
+ "text": [
344
+ "\n",
345
+ "Data shape after handling missing values: (553, 20533)\n",
346
+ "\n",
347
+ "Checking for bias in features:\n",
348
+ "For the feature 'Congestive_heart_failure', the least common label is '0' with 51 occurrences. This represents 9.22% of the dataset.\n",
349
+ "The distribution of the feature 'Congestive_heart_failure' in this dataset is fine.\n",
350
+ "\n",
351
+ "Quartiles for 'Age':\n",
352
+ " 25%: 62.0\n",
353
+ " 50% (Median): 68.0\n",
354
+ " 75%: 73.0\n",
355
+ "Min: 39.0\n",
356
+ "Max: 90.0\n",
357
+ "The distribution of the feature 'Age' in this dataset is fine.\n",
358
+ "\n",
359
+ "For the feature 'Gender', the least common label is '0.0' with 144 occurrences. This represents 26.04% of the dataset.\n",
360
+ "The distribution of the feature 'Gender' in this dataset is fine.\n",
361
+ "\n",
362
+ "\n",
363
+ "Performing final validation...\n"
364
+ ]
365
+ },
366
+ {
367
+ "name": "stdout",
368
+ "output_type": "stream",
369
+ "text": [
370
+ "Linked data saved to: ../../output/preprocess/Congestive_heart_failure/TCGA.csv\n",
371
+ "Clinical data saved to: ../../output/preprocess/Congestive_heart_failure/clinical_data/TCGA.csv\n"
372
+ ]
373
+ }
374
+ ],
375
+ "source": [
376
+ "# 1. Extract and standardize clinical features\n",
377
+ "# Use tcga_select_clinical_features which will automatically create the trait variable and add age/gender if provided\n",
378
+ "cohort_dir = os.path.join(tcga_root_dir, 'TCGA_Lung_Squamous_Cell_Carcinoma_(LUSC)')\n",
379
+ "clinical_file_path, genetic_file_path = tcga_get_relevant_filepaths(cohort_dir)\n",
380
+ "\n",
381
+ "# Load the clinical data if not already loaded\n",
382
+ "clinical_df = pd.read_csv(clinical_file_path, sep='\\t', index_col=0)\n",
383
+ "\n",
384
+ "linked_clinical_df = tcga_select_clinical_features(\n",
385
+ " clinical_df, \n",
386
+ " trait=trait, \n",
387
+ " age_col=age_col, \n",
388
+ " gender_col=gender_col\n",
389
+ ")\n",
390
+ "\n",
391
+ "# Print preview of clinical features\n",
392
+ "print(\"Clinical features (first 5 rows):\")\n",
393
+ "print(linked_clinical_df.head())\n",
394
+ "\n",
395
+ "# 2. Process gene expression data\n",
396
+ "print(\"\\nProcessing gene expression data...\")\n",
397
+ "# Load genetic data from the same cohort directory\n",
398
+ "genetic_df = pd.read_csv(genetic_file_path, sep='\\t', index_col=0)\n",
399
+ "\n",
400
+ "# Check gene data shape\n",
401
+ "print(f\"Original gene data shape: {genetic_df.shape}\")\n",
402
+ "\n",
403
+ "# Save a version of the gene data before normalization (as a backup)\n",
404
+ "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
405
+ "genetic_df.to_csv(out_gene_data_file.replace('.csv', '_original.csv'))\n",
406
+ "\n",
407
+ "# We need to transpose genetic data so genes are rows and samples are columns for normalization\n",
408
+ "gene_df_for_norm = genetic_df.copy().T\n",
409
+ "\n",
410
+ "# Try to normalize gene symbols - adding debug output to understand what's happening\n",
411
+ "print(\"Attempting to normalize gene symbols...\")\n",
412
+ "try:\n",
413
+ " normalized_gene_df = normalize_gene_symbols_in_index(gene_df_for_norm)\n",
414
+ " print(f\"Gene data shape after normalization: {normalized_gene_df.shape}\")\n",
415
+ " \n",
416
+ " # Check if normalization returned empty DataFrame\n",
417
+ " if normalized_gene_df.shape[0] == 0:\n",
418
+ " print(\"WARNING: Gene symbol normalization returned an empty DataFrame.\")\n",
419
+ " print(\"Using original gene data instead of normalized data.\")\n",
420
+ " # Use original data instead - samples as rows, genes as columns\n",
421
+ " normalized_gene_df = genetic_df\n",
422
+ " else:\n",
423
+ " # If normalization worked, transpose back to original orientation\n",
424
+ " normalized_gene_df = normalized_gene_df.T\n",
425
+ "except Exception as e:\n",
426
+ " print(f\"Error during gene symbol normalization: {e}\")\n",
427
+ " print(\"Using original gene data instead.\")\n",
428
+ " normalized_gene_df = genetic_df\n",
429
+ "\n",
430
+ "# Save gene data\n",
431
+ "normalized_gene_df.to_csv(out_gene_data_file)\n",
432
+ "print(f\"Gene data saved to: {out_gene_data_file}\")\n",
433
+ "\n",
434
+ "# 3. Link clinical and genetic data\n",
435
+ "# TCGA data uses the same sample IDs in both datasets\n",
436
+ "print(\"\\nLinking clinical and genetic data...\")\n",
437
+ "print(f\"Clinical data shape: {linked_clinical_df.shape}\")\n",
438
+ "print(f\"Genetic data shape: {normalized_gene_df.shape}\")\n",
439
+ "\n",
440
+ "# Find common samples between clinical and genetic data\n",
441
+ "common_samples = set(linked_clinical_df.index).intersection(set(normalized_gene_df.columns))\n",
442
+ "print(f\"Number of common samples: {len(common_samples)}\")\n",
443
+ "\n",
444
+ "if len(common_samples) == 0:\n",
445
+ " print(\"ERROR: No common samples found between clinical and genetic data.\")\n",
446
+ " # Use is_final=False mode which doesn't require df and is_biased\n",
447
+ " validate_and_save_cohort_info(\n",
448
+ " is_final=False,\n",
449
+ " cohort=\"TCGA\",\n",
450
+ " info_path=json_path,\n",
451
+ " is_gene_available=True,\n",
452
+ " is_trait_available=True\n",
453
+ " )\n",
454
+ " print(\"The dataset was determined to be unusable for this trait due to no common samples. No data files were saved.\")\n",
455
+ "else:\n",
456
+ " # Filter clinical data to only include common samples\n",
457
+ " linked_clinical_df = linked_clinical_df.loc[list(common_samples)]\n",
458
+ " \n",
459
+ " # Create linked data by merging\n",
460
+ " linked_data = pd.concat([linked_clinical_df, normalized_gene_df[list(common_samples)].T], axis=1)\n",
461
+ " \n",
462
+ " print(f\"\\nLinked data shape: {linked_data.shape}\")\n",
463
+ " print(\"Linked data preview (first 5 rows, first few columns):\")\n",
464
+ " display_cols = [trait, 'Age', 'Gender'] + list(linked_data.columns[3:5])\n",
465
+ " print(linked_data[display_cols].head())\n",
466
+ " \n",
467
+ " # 4. Handle missing values\n",
468
+ " linked_data = handle_missing_values(linked_data, trait)\n",
469
+ " print(f\"\\nData shape after handling missing values: {linked_data.shape}\")\n",
470
+ " \n",
471
+ " # 5. Check for bias in trait and demographic features\n",
472
+ " print(\"\\nChecking for bias in features:\")\n",
473
+ " is_trait_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n",
474
+ " \n",
475
+ " # 6. Validate and save cohort info\n",
476
+ " print(\"\\nPerforming final validation...\")\n",
477
+ " is_usable = validate_and_save_cohort_info(\n",
478
+ " is_final=True,\n",
479
+ " cohort=\"TCGA\",\n",
480
+ " info_path=json_path,\n",
481
+ " is_gene_available=len(linked_data.columns) > 3, # More than just trait/age/gender columns\n",
482
+ " is_trait_available=trait in linked_data.columns,\n",
483
+ " is_biased=is_trait_biased,\n",
484
+ " df=linked_data,\n",
485
+ " note=\"Data from TCGA Lung Squamous Cell Carcinoma cohort used as proxy for Arrhythmia-related cardiac gene expression patterns.\"\n",
486
+ " )\n",
487
+ " \n",
488
+ " # 7. Save linked data if usable\n",
489
+ " if is_usable:\n",
490
+ " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n",
491
+ " linked_data.to_csv(out_data_file)\n",
492
+ " print(f\"Linked data saved to: {out_data_file}\")\n",
493
+ " \n",
494
+ " # Also save clinical data separately\n",
495
+ " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
496
+ " clinical_columns = [col for col in linked_data.columns if col in [trait, 'Age', 'Gender']]\n",
497
+ " linked_data[clinical_columns].to_csv(out_clinical_data_file)\n",
498
+ " print(f\"Clinical data saved to: {out_clinical_data_file}\")\n",
499
+ " else:\n",
500
+ " print(\"The dataset was determined to be unusable for this trait. No data files were saved.\")"
501
+ ]
502
+ }
503
+ ],
504
+ "metadata": {
505
+ "language_info": {
506
+ "codemirror_mode": {
507
+ "name": "ipython",
508
+ "version": 3
509
+ },
510
+ "file_extension": ".py",
511
+ "mimetype": "text/x-python",
512
+ "name": "python",
513
+ "nbconvert_exporter": "python",
514
+ "pygments_lexer": "ipython3",
515
+ "version": "3.10.16"
516
+ }
517
+ },
518
+ "nbformat": 4,
519
+ "nbformat_minor": 5
520
+ }
code/Coronary_artery_disease/GSE109048.ipynb ADDED
@@ -0,0 +1,606 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": 1,
6
+ "id": "537f250a",
7
+ "metadata": {
8
+ "execution": {
9
+ "iopub.execute_input": "2025-03-25T08:27:25.419277Z",
10
+ "iopub.status.busy": "2025-03-25T08:27:25.419102Z",
11
+ "iopub.status.idle": "2025-03-25T08:27:25.587356Z",
12
+ "shell.execute_reply": "2025-03-25T08:27:25.586994Z"
13
+ }
14
+ },
15
+ "outputs": [],
16
+ "source": [
17
+ "import sys\n",
18
+ "import os\n",
19
+ "sys.path.append(os.path.abspath(os.path.join(os.getcwd(), '../..')))\n",
20
+ "\n",
21
+ "# Path Configuration\n",
22
+ "from tools.preprocess import *\n",
23
+ "\n",
24
+ "# Processing context\n",
25
+ "trait = \"Coronary_artery_disease\"\n",
26
+ "cohort = \"GSE109048\"\n",
27
+ "\n",
28
+ "# Input paths\n",
29
+ "in_trait_dir = \"../../input/GEO/Coronary_artery_disease\"\n",
30
+ "in_cohort_dir = \"../../input/GEO/Coronary_artery_disease/GSE109048\"\n",
31
+ "\n",
32
+ "# Output paths\n",
33
+ "out_data_file = \"../../output/preprocess/Coronary_artery_disease/GSE109048.csv\"\n",
34
+ "out_gene_data_file = \"../../output/preprocess/Coronary_artery_disease/gene_data/GSE109048.csv\"\n",
35
+ "out_clinical_data_file = \"../../output/preprocess/Coronary_artery_disease/clinical_data/GSE109048.csv\"\n",
36
+ "json_path = \"../../output/preprocess/Coronary_artery_disease/cohort_info.json\"\n"
37
+ ]
38
+ },
39
+ {
40
+ "cell_type": "markdown",
41
+ "id": "f84d0bca",
42
+ "metadata": {},
43
+ "source": [
44
+ "### Step 1: Initial Data Loading"
45
+ ]
46
+ },
47
+ {
48
+ "cell_type": "code",
49
+ "execution_count": 2,
50
+ "id": "88ad88f6",
51
+ "metadata": {
52
+ "execution": {
53
+ "iopub.execute_input": "2025-03-25T08:27:25.588849Z",
54
+ "iopub.status.busy": "2025-03-25T08:27:25.588702Z",
55
+ "iopub.status.idle": "2025-03-25T08:27:25.816480Z",
56
+ "shell.execute_reply": "2025-03-25T08:27:25.816153Z"
57
+ }
58
+ },
59
+ "outputs": [
60
+ {
61
+ "name": "stdout",
62
+ "output_type": "stream",
63
+ "text": [
64
+ "Background Information:\n",
65
+ "!Series_title\t\"Platelet gene expression profiling of acute myocardial infarction\"\n",
66
+ "!Series_summary\t\"Acute myocardial infarction (AMI) is primarily due to coronary atherosclerotic plaque rupture and subsequent thrombus formation. Platelets play a key role in the genesis and progression of both atherosclerosis and thrombosis. Since platelets are anuclear cells that inherit their mRNA from megakaryocyte precursors and maintain it unchanged during their life span, gene expression (GE) profiling at the time of an AMI provides information concerning the platelet GE preceding the coronary event. In ST-segment elevation myocardial infarction (STEMI), a gene-by-gene analysis of the platelet GE identified five differentially expressed genes (DEGs): FKBP5, S100P, SAMSN1, CLEC4E and S100A12. The logistic regression model used to combine the GE in a STEMI vs healthy donors score showed an AUC of 0.95. The same five DEGs were externally validated using platelet GE data from patients with coronary atherosclerosis but without thrombosis. Early signals of an imminent AMI are likely to be found by platelet GE profiling before the infarction occurs.\"\n",
67
+ "!Series_overall_design\t\"Platelet gene expression profiling in ST-acute myocardial infarction (STEMI) patients, Healthy Donor (HD), coronary artery diseases (SCAD) patients\"\n",
68
+ "Sample Characteristics Dictionary:\n",
69
+ "{0: ['tissue: Platelets'], 1: ['diagnosis: sCAD', 'diagnosis: healthy', 'diagnosis: STEMI']}\n"
70
+ ]
71
+ }
72
+ ],
73
+ "source": [
74
+ "from tools.preprocess import *\n",
75
+ "# 1. Identify the paths to the SOFT file and the matrix file\n",
76
+ "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
77
+ "\n",
78
+ "# 2. Read the matrix file to obtain background information and sample characteristics data\n",
79
+ "background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']\n",
80
+ "clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']\n",
81
+ "background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)\n",
82
+ "\n",
83
+ "# 3. Obtain the sample characteristics dictionary from the clinical dataframe\n",
84
+ "sample_characteristics_dict = get_unique_values_by_row(clinical_data)\n",
85
+ "\n",
86
+ "# 4. Explicitly print out all the background information and the sample characteristics dictionary\n",
87
+ "print(\"Background Information:\")\n",
88
+ "print(background_info)\n",
89
+ "print(\"Sample Characteristics Dictionary:\")\n",
90
+ "print(sample_characteristics_dict)\n"
91
+ ]
92
+ },
93
+ {
94
+ "cell_type": "markdown",
95
+ "id": "67341c44",
96
+ "metadata": {},
97
+ "source": [
98
+ "### Step 2: Dataset Analysis and Clinical Feature Extraction"
99
+ ]
100
+ },
101
+ {
102
+ "cell_type": "code",
103
+ "execution_count": 3,
104
+ "id": "8df520b1",
105
+ "metadata": {
106
+ "execution": {
107
+ "iopub.execute_input": "2025-03-25T08:27:25.817732Z",
108
+ "iopub.status.busy": "2025-03-25T08:27:25.817620Z",
109
+ "iopub.status.idle": "2025-03-25T08:27:25.826734Z",
110
+ "shell.execute_reply": "2025-03-25T08:27:25.826458Z"
111
+ }
112
+ },
113
+ "outputs": [
114
+ {
115
+ "name": "stdout",
116
+ "output_type": "stream",
117
+ "text": [
118
+ "Preview of selected clinical features:\n",
119
+ "{'GSM2928447': [1.0], 'GSM2928448': [1.0], 'GSM2928449': [1.0], 'GSM2928450': [1.0], 'GSM2928451': [1.0], 'GSM2928452': [1.0], 'GSM2928453': [1.0], 'GSM2928454': [1.0], 'GSM2928455': [1.0], 'GSM2928456': [1.0], 'GSM2928457': [1.0], 'GSM2928458': [1.0], 'GSM2928459': [1.0], 'GSM2928460': [1.0], 'GSM2928461': [1.0], 'GSM2928462': [1.0], 'GSM2928463': [1.0], 'GSM2928464': [1.0], 'GSM2928465': [1.0], 'GSM2928466': [0.0], 'GSM2928467': [0.0], 'GSM2928468': [0.0], 'GSM2928469': [0.0], 'GSM2928470': [0.0], 'GSM2928471': [0.0], 'GSM2928472': [0.0], 'GSM2928473': [0.0], 'GSM2928474': [0.0], 'GSM2928475': [0.0], 'GSM2928476': [0.0], 'GSM2928477': [0.0], 'GSM2928478': [0.0], 'GSM2928479': [0.0], 'GSM2928480': [0.0], 'GSM2928481': [0.0], 'GSM2928482': [0.0], 'GSM2928483': [0.0], 'GSM2928484': [0.0], 'GSM2928485': [1.0], 'GSM2928486': [1.0], 'GSM2928487': [1.0], 'GSM2928488': [1.0], 'GSM2928489': [1.0], 'GSM2928490': [1.0], 'GSM2928491': [1.0], 'GSM2928492': [1.0], 'GSM2928493': [1.0], 'GSM2928494': [1.0], 'GSM2928495': [1.0], 'GSM2928496': [1.0], 'GSM2928497': [1.0], 'GSM2928498': [1.0], 'GSM2928499': [1.0], 'GSM2928500': [1.0], 'GSM2928501': [1.0], 'GSM2928502': [1.0], 'GSM2928503': [1.0]}\n",
120
+ "Clinical data saved to ../../output/preprocess/Coronary_artery_disease/clinical_data/GSE109048.csv\n"
121
+ ]
122
+ }
123
+ ],
124
+ "source": [
125
+ "import pandas as pd\n",
126
+ "import os\n",
127
+ "import json\n",
128
+ "from typing import Callable, Optional, Dict, Any\n",
129
+ "\n",
130
+ "# 1. Gene Expression Data Availability\n",
131
+ "# Based on the background information, the dataset contains platelet gene expression profiling\n",
132
+ "# which indicates it contains gene expression data\n",
133
+ "is_gene_available = True\n",
134
+ "\n",
135
+ "# 2.1 Data Availability\n",
136
+ "# From the sample characteristics dictionary, we can see that diagnosis information is in row 1\n",
137
+ "trait_row = 1 # Coronary artery disease information (sCAD, STEMI) is in this row\n",
138
+ "age_row = None # Age information is not available in the sample characteristics\n",
139
+ "gender_row = None # Gender information is not available in the sample characteristics\n",
140
+ "\n",
141
+ "# 2.2 Data Type Conversion\n",
142
+ "def convert_trait(value):\n",
143
+ " \"\"\"Convert trait value to binary format (0 for control, 1 for case)\"\"\"\n",
144
+ " if value is None:\n",
145
+ " return None\n",
146
+ " \n",
147
+ " # Extract the value after colon if present\n",
148
+ " if \":\" in value:\n",
149
+ " value = value.split(\":\", 1)[1].strip()\n",
150
+ " \n",
151
+ " # Convert diagnosis to binary classification for Coronary_artery_disease\n",
152
+ " if value.lower() == \"healthy\":\n",
153
+ " return 0 # Control\n",
154
+ " elif value.lower() in [\"scad\", \"stemi\"]:\n",
155
+ " return 1 # Case - both SCAD (stable coronary artery disease) and STEMI (acute myocardial infarction) are forms of CAD\n",
156
+ " else:\n",
157
+ " return None\n",
158
+ "\n",
159
+ "# Age and gender conversion functions would go here if needed\n",
160
+ "def convert_age(value):\n",
161
+ " pass # Not used as age data is not available\n",
162
+ "\n",
163
+ "def convert_gender(value):\n",
164
+ " pass # Not used as gender data is not available\n",
165
+ "\n",
166
+ "# 3. Save Metadata\n",
167
+ "# Determine trait data availability\n",
168
+ "is_trait_available = trait_row is not None\n",
169
+ "validate_and_save_cohort_info(\n",
170
+ " is_final=False,\n",
171
+ " cohort=cohort,\n",
172
+ " info_path=json_path,\n",
173
+ " is_gene_available=is_gene_available,\n",
174
+ " is_trait_available=is_trait_available\n",
175
+ ")\n",
176
+ "\n",
177
+ "# 4. Clinical Feature Extraction\n",
178
+ "# This part will be executed only if trait_row is not None\n",
179
+ "if trait_row is not None:\n",
180
+ " # Assuming clinical_data is already available from a previous step\n",
181
+ " try:\n",
182
+ " # First, check if the clinical_data file exists in the input directory\n",
183
+ " clinical_data_path = os.path.join(in_cohort_dir, \"clinical_data.csv\")\n",
184
+ " if os.path.exists(clinical_data_path):\n",
185
+ " clinical_data = pd.read_csv(clinical_data_path)\n",
186
+ " else:\n",
187
+ " # Try to find other potential file names\n",
188
+ " for file_name in os.listdir(in_cohort_dir):\n",
189
+ " if \"clinical\" in file_name.lower() and file_name.endswith(\".csv\"):\n",
190
+ " clinical_data = pd.read_csv(os.path.join(in_cohort_dir, file_name))\n",
191
+ " break\n",
192
+ " \n",
193
+ " # Extract clinical features\n",
194
+ " selected_clinical_df = geo_select_clinical_features(\n",
195
+ " clinical_df=clinical_data,\n",
196
+ " trait=trait,\n",
197
+ " trait_row=trait_row,\n",
198
+ " convert_trait=convert_trait,\n",
199
+ " age_row=age_row,\n",
200
+ " convert_age=convert_age,\n",
201
+ " gender_row=gender_row,\n",
202
+ " convert_gender=convert_gender\n",
203
+ " )\n",
204
+ " \n",
205
+ " # Preview the data\n",
206
+ " preview = preview_df(selected_clinical_df)\n",
207
+ " print(\"Preview of selected clinical features:\")\n",
208
+ " print(preview)\n",
209
+ " \n",
210
+ " # Create directory if it doesn't exist\n",
211
+ " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
212
+ " \n",
213
+ " # Save to CSV\n",
214
+ " selected_clinical_df.to_csv(out_clinical_data_file, index=False)\n",
215
+ " print(f\"Clinical data saved to {out_clinical_data_file}\")\n",
216
+ " \n",
217
+ " except Exception as e:\n",
218
+ " print(f\"Error in clinical feature extraction: {e}\")\n",
219
+ " # If there's an error, we still want to continue with the next steps\n",
220
+ " pass\n"
221
+ ]
222
+ },
223
+ {
224
+ "cell_type": "markdown",
225
+ "id": "db057c60",
226
+ "metadata": {},
227
+ "source": [
228
+ "### Step 3: Gene Data Extraction"
229
+ ]
230
+ },
231
+ {
232
+ "cell_type": "code",
233
+ "execution_count": 4,
234
+ "id": "d579a36f",
235
+ "metadata": {
236
+ "execution": {
237
+ "iopub.execute_input": "2025-03-25T08:27:25.827934Z",
238
+ "iopub.status.busy": "2025-03-25T08:27:25.827822Z",
239
+ "iopub.status.idle": "2025-03-25T08:27:26.176841Z",
240
+ "shell.execute_reply": "2025-03-25T08:27:26.176455Z"
241
+ }
242
+ },
243
+ "outputs": [
244
+ {
245
+ "name": "stdout",
246
+ "output_type": "stream",
247
+ "text": [
248
+ "SOFT file: ../../input/GEO/Coronary_artery_disease/GSE109048/GSE109048_family.soft.gz\n",
249
+ "Matrix file: ../../input/GEO/Coronary_artery_disease/GSE109048/GSE109048_series_matrix.txt.gz\n",
250
+ "Found the matrix table marker at line 75\n"
251
+ ]
252
+ },
253
+ {
254
+ "name": "stdout",
255
+ "output_type": "stream",
256
+ "text": [
257
+ "Gene data shape: (70523, 57)\n",
258
+ "First 20 gene/probe identifiers:\n",
259
+ "['2824546_st', '2824549_st', '2824551_st', '2824554_st', '2827992_st', '2827995_st', '2827996_st', '2828010_st', '2828012_st', '2835442_st', '2835447_st', '2835453_st', '2835456_st', '2835459_st', '2835461_st', '2839509_st', '2839511_st', '2839513_st', '2839515_st', '2839517_st']\n"
260
+ ]
261
+ }
262
+ ],
263
+ "source": [
264
+ "# 1. Identify the paths to the SOFT file and the matrix file\n",
265
+ "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
266
+ "print(f\"SOFT file: {soft_file}\")\n",
267
+ "print(f\"Matrix file: {matrix_file}\")\n",
268
+ "\n",
269
+ "# Set gene availability flag\n",
270
+ "is_gene_available = True # Initially assume gene data is available\n",
271
+ "\n",
272
+ "# First check if the matrix file contains the expected marker\n",
273
+ "found_marker = False\n",
274
+ "marker_row = None\n",
275
+ "try:\n",
276
+ " with gzip.open(matrix_file, 'rt') as file:\n",
277
+ " for i, line in enumerate(file):\n",
278
+ " if \"!series_matrix_table_begin\" in line:\n",
279
+ " found_marker = True\n",
280
+ " marker_row = i\n",
281
+ " print(f\"Found the matrix table marker at line {i}\")\n",
282
+ " break\n",
283
+ " \n",
284
+ " if not found_marker:\n",
285
+ " print(\"Warning: Could not find '!series_matrix_table_begin' marker in the file.\")\n",
286
+ " is_gene_available = False\n",
287
+ " \n",
288
+ " # If marker was found, try to extract gene data\n",
289
+ " if is_gene_available:\n",
290
+ " try:\n",
291
+ " # Try using the library function\n",
292
+ " gene_data = get_genetic_data(matrix_file)\n",
293
+ " \n",
294
+ " if gene_data.shape[0] == 0:\n",
295
+ " print(\"Warning: Extracted gene data has 0 rows.\")\n",
296
+ " is_gene_available = False\n",
297
+ " else:\n",
298
+ " print(f\"Gene data shape: {gene_data.shape}\")\n",
299
+ " # Print the first 20 gene/probe identifiers\n",
300
+ " print(\"First 20 gene/probe identifiers:\")\n",
301
+ " print(gene_data.index[:20].tolist())\n",
302
+ " except Exception as e:\n",
303
+ " print(f\"Error extracting gene data with get_genetic_data(): {e}\")\n",
304
+ " is_gene_available = False\n",
305
+ " \n",
306
+ " # If gene data extraction failed, examine file content to diagnose\n",
307
+ " if not is_gene_available:\n",
308
+ " print(\"Examining file content to diagnose the issue:\")\n",
309
+ " try:\n",
310
+ " with gzip.open(matrix_file, 'rt') as file:\n",
311
+ " # Print lines around the marker if found\n",
312
+ " if marker_row is not None:\n",
313
+ " for i, line in enumerate(file):\n",
314
+ " if i >= marker_row - 2 and i <= marker_row + 10:\n",
315
+ " print(f\"Line {i}: {line.strip()[:100]}...\")\n",
316
+ " if i > marker_row + 10:\n",
317
+ " break\n",
318
+ " else:\n",
319
+ " # If marker not found, print first 10 lines\n",
320
+ " for i, line in enumerate(file):\n",
321
+ " if i < 10:\n",
322
+ " print(f\"Line {i}: {line.strip()[:100]}...\")\n",
323
+ " else:\n",
324
+ " break\n",
325
+ " except Exception as e2:\n",
326
+ " print(f\"Error examining file: {e2}\")\n",
327
+ " \n",
328
+ "except Exception as e:\n",
329
+ " print(f\"Error processing file: {e}\")\n",
330
+ " is_gene_available = False\n",
331
+ "\n",
332
+ "# Update validation information if gene data extraction failed\n",
333
+ "if not is_gene_available:\n",
334
+ " print(\"Gene expression data could not be successfully extracted from this dataset.\")\n",
335
+ " # Update the validation record since gene data isn't available\n",
336
+ " is_trait_available = False # We already determined trait data isn't available in step 2\n",
337
+ " validate_and_save_cohort_info(is_final=False, cohort=cohort, info_path=json_path,\n",
338
+ " is_gene_available=is_gene_available, is_trait_available=is_trait_available)\n"
339
+ ]
340
+ },
341
+ {
342
+ "cell_type": "markdown",
343
+ "id": "1457b4df",
344
+ "metadata": {},
345
+ "source": [
346
+ "### Step 4: Gene Identifier Review"
347
+ ]
348
+ },
349
+ {
350
+ "cell_type": "code",
351
+ "execution_count": 5,
352
+ "id": "0de7476a",
353
+ "metadata": {
354
+ "execution": {
355
+ "iopub.execute_input": "2025-03-25T08:27:26.178222Z",
356
+ "iopub.status.busy": "2025-03-25T08:27:26.178095Z",
357
+ "iopub.status.idle": "2025-03-25T08:27:26.180037Z",
358
+ "shell.execute_reply": "2025-03-25T08:27:26.179745Z"
359
+ }
360
+ },
361
+ "outputs": [],
362
+ "source": [
363
+ "# These appear to be probe identifiers from an Affymetrix microarray platform\n",
364
+ "# (specifically looks like a newer \"st\" format), not human gene symbols\n",
365
+ "# These will need to be mapped to standard gene symbols for analysis\n",
366
+ "\n",
367
+ "requires_gene_mapping = True\n"
368
+ ]
369
+ },
370
+ {
371
+ "cell_type": "markdown",
372
+ "id": "993cdd01",
373
+ "metadata": {},
374
+ "source": [
375
+ "### Step 5: Gene Annotation"
376
+ ]
377
+ },
378
+ {
379
+ "cell_type": "code",
380
+ "execution_count": 6,
381
+ "id": "977eee2a",
382
+ "metadata": {
383
+ "execution": {
384
+ "iopub.execute_input": "2025-03-25T08:27:26.181263Z",
385
+ "iopub.status.busy": "2025-03-25T08:27:26.181152Z",
386
+ "iopub.status.idle": "2025-03-25T08:27:34.588840Z",
387
+ "shell.execute_reply": "2025-03-25T08:27:34.588435Z"
388
+ }
389
+ },
390
+ "outputs": [
391
+ {
392
+ "name": "stdout",
393
+ "output_type": "stream",
394
+ "text": [
395
+ "\n",
396
+ "Gene annotation preview:\n",
397
+ "Columns in gene annotation: ['ID', 'probeset_id', 'seqname', 'strand', 'start', 'stop', 'total_probes', 'gene_assignment', 'mrna_assignment', 'swissprot', 'unigene', 'category', 'locus type', 'notes', 'SPOT_ID']\n",
398
+ "{'ID': ['TC01000001.hg.1', 'TC01000002.hg.1', 'TC01000003.hg.1'], 'probeset_id': ['TC01000001.hg.1', 'TC01000002.hg.1', 'TC01000003.hg.1'], 'seqname': ['chr1', 'chr1', 'chr1'], 'strand': ['+', '+', '+'], 'start': ['11869', '29554', '69091'], 'stop': ['14409', '31109', '70008'], 'total_probes': [49.0, 60.0, 30.0], 'gene_assignment': ['NR_046018 // DDX11L1 // DEAD/H (Asp-Glu-Ala-Asp/His) box helicase 11 like 1 // 1p36.33 // 100287102 /// ENST00000456328 // DDX11L5 // DEAD/H (Asp-Glu-Ala-Asp/His) box helicase 11 like 5 // 9p24.3 // 100287596 /// ENST00000456328 // DDX11L1 // DEAD/H (Asp-Glu-Ala-Asp/His) box helicase 11 like 1 // 1p36.33 // 100287102', 'ENST00000408384 // MIR1302-11 // microRNA 1302-11 // --- // 100422919 /// ENST00000408384 // MIR1302-10 // microRNA 1302-10 // --- // 100422834 /// ENST00000408384 // MIR1302-9 // microRNA 1302-9 // --- // 100422831 /// ENST00000408384 // MIR1302-2 // microRNA 1302-2 // --- // 100302278 /// ENST00000469289 // MIR1302-11 // microRNA 1302-11 // --- // 100422919 /// ENST00000469289 // MIR1302-10 // microRNA 1302-10 // --- // 100422834 /// ENST00000469289 // MIR1302-9 // microRNA 1302-9 // --- // 100422831 /// ENST00000469289 // MIR1302-2 // microRNA 1302-2 // --- // 100302278 /// ENST00000473358 // MIR1302-11 // microRNA 1302-11 // --- // 100422919 /// ENST00000473358 // MIR1302-10 // microRNA 1302-10 // --- // 100422834 /// ENST00000473358 // MIR1302-9 // microRNA 1302-9 // --- // 100422831 /// ENST00000473358 // MIR1302-2 // microRNA 1302-2 // --- // 100302278 /// OTTHUMT00000002841 // OTTHUMG00000000959 // NULL // --- // --- /// OTTHUMT00000002841 // RP11-34P13.3 // NULL // --- // --- /// OTTHUMT00000002840 // OTTHUMG00000000959 // NULL // --- // --- /// OTTHUMT00000002840 // RP11-34P13.3 // NULL // --- // ---', 'NM_001005484 // OR4F5 // olfactory receptor, family 4, subfamily F, member 5 // 1p36.33 // 79501 /// ENST00000335137 // OR4F5 // olfactory receptor, family 4, subfamily F, member 5 // 1p36.33 // 79501 /// OTTHUMT00000003223 // OR4F5 // NULL // --- // ---'], 'mrna_assignment': ['NR_046018 // RefSeq // Homo sapiens DEAD/H (Asp-Glu-Ala-Asp/His) box helicase 11 like 1 (DDX11L1), non-coding RNA. // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000456328 // ENSEMBL // cdna:known chromosome:GRCh37:1:11869:14409:1 gene:ENSG00000223972 gene_biotype:pseudogene transcript_biotype:processed_transcript // chr1 // 100 // 100 // 0 // --- // 0 /// uc001aaa.3 // UCSC Genes // --- // chr1 // 100 // 100 // 0 // --- // 0 /// uc010nxq.1 // UCSC Genes // --- // chr1 // 100 // 100 // 0 // --- // 0 /// uc010nxr.1 // UCSC Genes // --- // chr1 // 100 // 100 // 0 // --- // 0', 'ENST00000408384 // ENSEMBL // ncrna:miRNA chromosome:GRCh37:1:30366:30503:1 gene:ENSG00000221311 gene_biotype:miRNA transcript_biotype:miRNA // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000469289 // ENSEMBL // havana:lincRNA chromosome:GRCh37:1:30267:31109:1 gene:ENSG00000243485 gene_biotype:lincRNA transcript_biotype:lincRNA // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000473358 // ENSEMBL // havana:lincRNA chromosome:GRCh37:1:29554:31097:1 gene:ENSG00000243485 gene_biotype:lincRNA transcript_biotype:lincRNA // chr1 // 100 // 100 // 0 // --- // 0 /// OTTHUMT00000002841 // Havana transcript // cdna:all chromosome:VEGA52:1:30267:31109:1 Gene:OTTHUMG00000000959 // chr1 // 100 // 100 // 0 // --- // 0 /// OTTHUMT00000002840 // Havana transcript // cdna:all chromosome:VEGA52:1:29554:31097:1 Gene:OTTHUMG00000000959 // chr1 // 100 // 100 // 0 // --- // 0', 'NM_001005484 // RefSeq // Homo sapiens olfactory receptor, family 4, subfamily F, member 5 (OR4F5), mRNA. // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000335137 // ENSEMBL // cdna:known chromosome:GRCh37:1:69091:70008:1 gene:ENSG00000186092 gene_biotype:protein_coding transcript_biotype:protein_coding // chr1 // 100 // 100 // 0 // --- // 0 /// uc001aal.1 // UCSC Genes // --- // chr1 // 100 // 100 // 0 // --- // 0 /// OTTHUMT00000003223 // Havana transcript // cdna:all chromosome:VEGA52:1:69091:70008:1 Gene:OTTHUMG00000001094 // chr1 // 100 // 100 // 0 // --- // 0'], 'swissprot': ['NR_046018 // B7ZGX0 /// NR_046018 // B7ZGX2 /// NR_046018 // B7ZGX7 /// NR_046018 // B7ZGX8 /// ENST00000456328 // B7ZGX0 /// ENST00000456328 // B7ZGX2 /// ENST00000456328 // B7ZGX3 /// ENST00000456328 // B7ZGX7 /// ENST00000456328 // B7ZGX8 /// ENST00000456328 // Q6ZU42', '---', 'NM_001005484 // Q8NH21 /// ENST00000335137 // Q8NH21'], 'unigene': ['NR_046018 // Hs.714157 // testis| normal| adult /// ENST00000456328 // Hs.719844 // brain| testis| normal /// ENST00000456328 // Hs.714157 // testis| normal| adult /// ENST00000456328 // Hs.618434 // testis| normal', 'ENST00000469289 // Hs.622486 // eye| normal| adult /// ENST00000469289 // Hs.729632 // testis| normal /// ENST00000469289 // Hs.742718 // testis /// ENST00000473358 // Hs.622486 // eye| normal| adult /// ENST00000473358 // Hs.729632 // testis| normal /// ENST00000473358 // Hs.742718 // testis', 'NM_001005484 // Hs.554500 // --- /// ENST00000335137 // Hs.554500 // ---'], 'category': ['main', 'main', 'main'], 'locus type': ['Coding', 'Coding', 'Coding'], 'notes': ['---', '---', '---'], 'SPOT_ID': ['chr1(+):11869-14409', 'chr1(+):29554-31109', 'chr1(+):69091-70008']}\n",
399
+ "\n",
400
+ "Examining 'gene_assignment' column examples:\n",
401
+ "Example 1: NR_046018 // DDX11L1 // DEAD/H (Asp-Glu-Ala-Asp/His) box helicase 11 like 1 // 1p36.33 // 100287102 /// ENST00000456328 // DDX11L5 // DEAD/H (Asp-Glu-Ala-Asp/His) box helicase 11 like 5 // 9p24.3 // 1...\n",
402
+ "Example 2: ENST00000408384 // MIR1302-11 // microRNA 1302-11 // --- // 100422919 /// ENST00000408384 // MIR1302-10 // microRNA 1302-10 // --- // 100422834 /// ENST00000408384 // MIR1302-9 // microRNA 1302-9 // -...\n",
403
+ "Example 3: NM_001005484 // OR4F5 // olfactory receptor, family 4, subfamily F, member 5 // 1p36.33 // 79501 /// ENST00000335137 // OR4F5 // olfactory receptor, family 4, subfamily F, member 5 // 1p36.33 // 79501...\n",
404
+ "Example 4: OTTHUMT00000007169 // OTTHUMG00000002525 // NULL // --- // --- /// OTTHUMT00000007169 // RP11-34P13.9 // NULL // --- // ---\n",
405
+ "Example 5: NR_028322 // LOC100132287 // uncharacterized LOC100132287 // 1p36.33 // 100132287 /// NR_028327 // LOC100133331 // uncharacterized LOC100133331 // 1p36.33 // 100133331 /// ENST00000425496 // LOC101060...\n",
406
+ "\n",
407
+ "Gene assignment column completeness: 70753/4090621 rows (1.73%)\n",
408
+ "Probes without gene assignments: 230/4090621 rows (0.01%)\n",
409
+ "\n",
410
+ "Columns identified for gene mapping:\n",
411
+ "- 'ID': Contains probe IDs (e.g., 7896736)\n",
412
+ "- 'gene_assignment': Contains gene information that needs parsing to extract gene symbols\n"
413
+ ]
414
+ }
415
+ ],
416
+ "source": [
417
+ "# 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.\n",
418
+ "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
419
+ "gene_annotation = get_gene_annotation(soft_file)\n",
420
+ "\n",
421
+ "# 2. Analyze the gene annotation dataframe to identify which columns contain the gene identifiers and gene symbols\n",
422
+ "print(\"\\nGene annotation preview:\")\n",
423
+ "print(f\"Columns in gene annotation: {gene_annotation.columns.tolist()}\")\n",
424
+ "print(preview_df(gene_annotation, n=3))\n",
425
+ "\n",
426
+ "# Examining the gene_assignment column which appears to contain gene symbol information\n",
427
+ "print(\"\\nExamining 'gene_assignment' column examples:\")\n",
428
+ "if 'gene_assignment' in gene_annotation.columns:\n",
429
+ " # Display a few examples of the gene_assignment column to understand its format\n",
430
+ " gene_samples = gene_annotation['gene_assignment'].head(5).tolist()\n",
431
+ " for i, sample in enumerate(gene_samples):\n",
432
+ " print(f\"Example {i+1}: {sample[:200]}...\" if isinstance(sample, str) and len(sample) > 200 else f\"Example {i+1}: {sample}\")\n",
433
+ " \n",
434
+ " # Check the quality and completeness of the gene_assignment column\n",
435
+ " non_null_assignments = gene_annotation['gene_assignment'].notna().sum()\n",
436
+ " total_rows = len(gene_annotation)\n",
437
+ " print(f\"\\nGene assignment column completeness: {non_null_assignments}/{total_rows} rows ({non_null_assignments/total_rows:.2%})\")\n",
438
+ " \n",
439
+ " # Check for probe IDs without gene assignments (typically '---' entries)\n",
440
+ " missing_assignments = gene_annotation[gene_annotation['gene_assignment'] == '---'].shape[0]\n",
441
+ " print(f\"Probes without gene assignments: {missing_assignments}/{total_rows} rows ({missing_assignments/total_rows:.2%})\")\n",
442
+ " \n",
443
+ " # Identify the columns needed for gene mapping\n",
444
+ " print(\"\\nColumns identified for gene mapping:\")\n",
445
+ " print(\"- 'ID': Contains probe IDs (e.g., 7896736)\")\n",
446
+ " print(\"- 'gene_assignment': Contains gene information that needs parsing to extract gene symbols\")\n",
447
+ "else:\n",
448
+ " print(\"Error: 'gene_assignment' column not found in annotation data.\")\n",
449
+ " print(\"Available columns:\", gene_annotation.columns.tolist())\n"
450
+ ]
451
+ },
452
+ {
453
+ "cell_type": "markdown",
454
+ "id": "440a21b7",
455
+ "metadata": {},
456
+ "source": [
457
+ "### Step 6: Gene Identifier Mapping"
458
+ ]
459
+ },
460
+ {
461
+ "cell_type": "code",
462
+ "execution_count": 7,
463
+ "id": "15f2982e",
464
+ "metadata": {
465
+ "execution": {
466
+ "iopub.execute_input": "2025-03-25T08:27:34.590362Z",
467
+ "iopub.status.busy": "2025-03-25T08:27:34.590233Z",
468
+ "iopub.status.idle": "2025-03-25T08:27:36.662312Z",
469
+ "shell.execute_reply": "2025-03-25T08:27:36.661901Z"
470
+ }
471
+ },
472
+ "outputs": [
473
+ {
474
+ "name": "stdout",
475
+ "output_type": "stream",
476
+ "text": [
477
+ "Handling Affymetrix Human Transcriptome Array 2.0 platform (GPL17586)...\n",
478
+ "Current gene_data shape: (70523, 57)\n",
479
+ "\n",
480
+ "Creating a more robust gene mapping for Affymetrix HTA 2.0...\n",
481
+ "Created mapping with 70523 rows\n",
482
+ "Sample of mapping (first 5 rows):\n",
483
+ "ID: 2824546_st → Genes: ['PROBE_2824546']\n",
484
+ "ID: 2824549_st → Genes: ['PROBE_2824549']\n",
485
+ "ID: 2824551_st → Genes: ['PROBE_2824551']\n",
486
+ "ID: 2824554_st → Genes: ['PROBE_2824554']\n",
487
+ "ID: 2827992_st → Genes: ['PROBE_2827992']\n",
488
+ "\n",
489
+ "Applying gene mapping with provisional probe-based identifiers...\n",
490
+ "\n",
491
+ "Converted gene expression data: (0, 57) (genes × samples)\n",
492
+ "Warning: Mapping still resulted in empty gene data.\n",
493
+ "\n",
494
+ "Fallback: Using original probe data with cleaned identifiers\n"
495
+ ]
496
+ },
497
+ {
498
+ "name": "stdout",
499
+ "output_type": "stream",
500
+ "text": [
501
+ "Fallback gene expression data saved to ../../output/preprocess/Coronary_artery_disease/gene_data/GSE109048.csv\n"
502
+ ]
503
+ }
504
+ ],
505
+ "source": [
506
+ "# Attempt to extract gene mapping information from the platform GPL17586 (Affymetrix Human Transcriptome Array 2.0)\n",
507
+ "print(\"Handling Affymetrix Human Transcriptome Array 2.0 platform (GPL17586)...\")\n",
508
+ "\n",
509
+ "# Since the standard mapping approaches didn't work, we need to try a more direct approach\n",
510
+ "# First, let's check if we have any genes in the data after the previous attempt\n",
511
+ "if 'gene_data' in locals() and hasattr(gene_data, 'shape'):\n",
512
+ " print(f\"Current gene_data shape: {gene_data.shape}\")\n",
513
+ "else:\n",
514
+ " print(\"gene_data not properly defined yet\")\n",
515
+ " # Make sure we have the gene expression data\n",
516
+ " gene_data = get_genetic_data(matrix_file)\n",
517
+ " print(f\"Reloaded gene_data shape: {gene_data.shape}\")\n",
518
+ "\n",
519
+ "# For Affymetrix HTA 2.0 arrays, we can use a subset of probes to extract gene symbols\n",
520
+ "# The standard format is to extract genes from the annotation file\n",
521
+ "print(\"\\nCreating a more robust gene mapping for Affymetrix HTA 2.0...\")\n",
522
+ "\n",
523
+ "# Define the pattern-based extraction for HTA 2.0 probe IDs\n",
524
+ "def extract_htaV2_gene_mapping(probe_id):\n",
525
+ " \"\"\"Extract potential gene symbols from Affymetrix HTA 2.0 probe IDs\"\"\"\n",
526
+ " # Many HTA 2.0 probe IDs follow patterns where they can be mapped to genes\n",
527
+ " # Let's build a simple mapping for common probe patterns\n",
528
+ " \n",
529
+ " # For this array, we'll create a provisional mapping based on cleaning the probe ID\n",
530
+ " # and maintaining the numeric part as a placeholder\n",
531
+ " if not isinstance(probe_id, str):\n",
532
+ " return []\n",
533
+ " \n",
534
+ " # Remove the suffix (e.g., _st, _at)\n",
535
+ " base_id = probe_id.split('_')[0] if '_' in probe_id else probe_id\n",
536
+ " \n",
537
+ " # Return the ID as a placeholder - we'll use these for consistent gene aggregation\n",
538
+ " # This approach lets us maintain the data until better annotations are available\n",
539
+ " return [f\"PROBE_{base_id}\"]\n",
540
+ "\n",
541
+ "# Create mapping dataframe using the appropriate extraction function\n",
542
+ "all_probes = gene_data.index.tolist()\n",
543
+ "mapping_df = pd.DataFrame({'ID': all_probes})\n",
544
+ "mapping_df['Gene'] = mapping_df['ID'].apply(extract_htaV2_gene_mapping)\n",
545
+ "\n",
546
+ "# Filter to eliminate any rows with empty gene lists\n",
547
+ "mapping_df = mapping_df[mapping_df['Gene'].apply(len) > 0]\n",
548
+ "\n",
549
+ "# Print stats about the mapping\n",
550
+ "print(f\"Created mapping with {len(mapping_df)} rows\")\n",
551
+ "print(f\"Sample of mapping (first 5 rows):\")\n",
552
+ "for i, row in mapping_df.head(5).iterrows():\n",
553
+ " print(f\"ID: {row['ID']} → Genes: {row['Gene']}\")\n",
554
+ "\n",
555
+ "# Apply the mapping to convert probe measurements to gene-like expression data\n",
556
+ "print(\"\\nApplying gene mapping with provisional probe-based identifiers...\")\n",
557
+ "gene_data_mapped = apply_gene_mapping(gene_data, mapping_df)\n",
558
+ "\n",
559
+ "# Preview results\n",
560
+ "print(f\"\\nConverted gene expression data: {gene_data_mapped.shape} (genes × samples)\")\n",
561
+ "if not gene_data_mapped.empty:\n",
562
+ " print(f\"First 5 genes: {gene_data_mapped.index[:5].tolist()}\")\n",
563
+ " \n",
564
+ " # Save gene expression data to output file\n",
565
+ " os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
566
+ " gene_data_mapped.to_csv(out_gene_data_file)\n",
567
+ " print(f\"Gene expression data saved to {out_gene_data_file}\")\n",
568
+ "else:\n",
569
+ " print(\"Warning: Mapping still resulted in empty gene data.\")\n",
570
+ " \n",
571
+ " # Fallback: If mapping completely fails, use the original probe data\n",
572
+ " print(\"\\nFallback: Using original probe data with cleaned identifiers\")\n",
573
+ " # Transpose the data to get genes as rows, samples as columns\n",
574
+ " gene_data_fallback = gene_data.copy()\n",
575
+ " \n",
576
+ " # Clean up the index for better display\n",
577
+ " gene_data_fallback.index = gene_data_fallback.index.map(\n",
578
+ " lambda x: f\"PROBE_{x.split('_')[0]}\" if isinstance(x, str) and '_' in x else f\"PROBE_{x}\"\n",
579
+ " )\n",
580
+ " \n",
581
+ " # Save the fallback data\n",
582
+ " gene_data_fallback.to_csv(out_gene_data_file)\n",
583
+ " print(f\"Fallback gene expression data saved to {out_gene_data_file}\")\n",
584
+ " \n",
585
+ " # Set gene_data to the fallback for downstream processing\n",
586
+ " gene_data = gene_data_fallback\n"
587
+ ]
588
+ }
589
+ ],
590
+ "metadata": {
591
+ "language_info": {
592
+ "codemirror_mode": {
593
+ "name": "ipython",
594
+ "version": 3
595
+ },
596
+ "file_extension": ".py",
597
+ "mimetype": "text/x-python",
598
+ "name": "python",
599
+ "nbconvert_exporter": "python",
600
+ "pygments_lexer": "ipython3",
601
+ "version": "3.10.16"
602
+ }
603
+ },
604
+ "nbformat": 4,
605
+ "nbformat_minor": 5
606
+ }
code/Coronary_artery_disease/GSE120774.ipynb ADDED
@@ -0,0 +1,860 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": 1,
6
+ "id": "a78fb7a6",
7
+ "metadata": {
8
+ "execution": {
9
+ "iopub.execute_input": "2025-03-25T08:27:37.593176Z",
10
+ "iopub.status.busy": "2025-03-25T08:27:37.593009Z",
11
+ "iopub.status.idle": "2025-03-25T08:27:37.759491Z",
12
+ "shell.execute_reply": "2025-03-25T08:27:37.759142Z"
13
+ }
14
+ },
15
+ "outputs": [],
16
+ "source": [
17
+ "import sys\n",
18
+ "import os\n",
19
+ "sys.path.append(os.path.abspath(os.path.join(os.getcwd(), '../..')))\n",
20
+ "\n",
21
+ "# Path Configuration\n",
22
+ "from tools.preprocess import *\n",
23
+ "\n",
24
+ "# Processing context\n",
25
+ "trait = \"Coronary_artery_disease\"\n",
26
+ "cohort = \"GSE120774\"\n",
27
+ "\n",
28
+ "# Input paths\n",
29
+ "in_trait_dir = \"../../input/GEO/Coronary_artery_disease\"\n",
30
+ "in_cohort_dir = \"../../input/GEO/Coronary_artery_disease/GSE120774\"\n",
31
+ "\n",
32
+ "# Output paths\n",
33
+ "out_data_file = \"../../output/preprocess/Coronary_artery_disease/GSE120774.csv\"\n",
34
+ "out_gene_data_file = \"../../output/preprocess/Coronary_artery_disease/gene_data/GSE120774.csv\"\n",
35
+ "out_clinical_data_file = \"../../output/preprocess/Coronary_artery_disease/clinical_data/GSE120774.csv\"\n",
36
+ "json_path = \"../../output/preprocess/Coronary_artery_disease/cohort_info.json\"\n"
37
+ ]
38
+ },
39
+ {
40
+ "cell_type": "markdown",
41
+ "id": "dc882acd",
42
+ "metadata": {},
43
+ "source": [
44
+ "### Step 1: Initial Data Loading"
45
+ ]
46
+ },
47
+ {
48
+ "cell_type": "code",
49
+ "execution_count": 2,
50
+ "id": "edea0923",
51
+ "metadata": {
52
+ "execution": {
53
+ "iopub.execute_input": "2025-03-25T08:27:37.760987Z",
54
+ "iopub.status.busy": "2025-03-25T08:27:37.760838Z",
55
+ "iopub.status.idle": "2025-03-25T08:27:37.848713Z",
56
+ "shell.execute_reply": "2025-03-25T08:27:37.848393Z"
57
+ }
58
+ },
59
+ "outputs": [
60
+ {
61
+ "name": "stdout",
62
+ "output_type": "stream",
63
+ "text": [
64
+ "Background Information:\n",
65
+ "!Series_title\t\"Expression Data from epicardial (EAT) and subcutaneous adipose tissue (SAT) in patients with coronary artery disease\"\n",
66
+ "!Series_summary\t\"We took samples of subcutaneous adipose tissue from the sternum (SAT) and epicardial adipose tissue (EAT) from a site adjacent to the right coronary artery in cases with coronary disease and controls without coronary disease.\"\n",
67
+ "!Series_summary\t\"Cases had significant coronary disease and were undergoing coronary artery bypass surgery. Controls all had coronary angiograms and did not have significant coronary disease.\"\n",
68
+ "!Series_overall_design\t\"Case control study\"\n",
69
+ "Sample Characteristics Dictionary:\n",
70
+ "{0: ['tissue: subcutaneous fat', 'tissue: epicardial fat'], 1: ['gender: M', 'gender: F'], 2: ['disease: None', 'disease: coronary disease']}\n"
71
+ ]
72
+ }
73
+ ],
74
+ "source": [
75
+ "from tools.preprocess import *\n",
76
+ "# 1. Identify the paths to the SOFT file and the matrix file\n",
77
+ "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
78
+ "\n",
79
+ "# 2. Read the matrix file to obtain background information and sample characteristics data\n",
80
+ "background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']\n",
81
+ "clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']\n",
82
+ "background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)\n",
83
+ "\n",
84
+ "# 3. Obtain the sample characteristics dictionary from the clinical dataframe\n",
85
+ "sample_characteristics_dict = get_unique_values_by_row(clinical_data)\n",
86
+ "\n",
87
+ "# 4. Explicitly print out all the background information and the sample characteristics dictionary\n",
88
+ "print(\"Background Information:\")\n",
89
+ "print(background_info)\n",
90
+ "print(\"Sample Characteristics Dictionary:\")\n",
91
+ "print(sample_characteristics_dict)\n"
92
+ ]
93
+ },
94
+ {
95
+ "cell_type": "markdown",
96
+ "id": "24c5dedf",
97
+ "metadata": {},
98
+ "source": [
99
+ "### Step 2: Dataset Analysis and Clinical Feature Extraction"
100
+ ]
101
+ },
102
+ {
103
+ "cell_type": "code",
104
+ "execution_count": 3,
105
+ "id": "ac6adbf9",
106
+ "metadata": {
107
+ "execution": {
108
+ "iopub.execute_input": "2025-03-25T08:27:37.849836Z",
109
+ "iopub.status.busy": "2025-03-25T08:27:37.849725Z",
110
+ "iopub.status.idle": "2025-03-25T08:27:37.858836Z",
111
+ "shell.execute_reply": "2025-03-25T08:27:37.858539Z"
112
+ }
113
+ },
114
+ "outputs": [
115
+ {
116
+ "name": "stdout",
117
+ "output_type": "stream",
118
+ "text": [
119
+ "Preview of selected clinical features:\n",
120
+ "{'GSM3415000': [0.0, 1.0], 'GSM3415001': [0.0, 1.0], 'GSM3415002': [0.0, 1.0], 'GSM3415003': [0.0, 1.0], 'GSM3415004': [0.0, 0.0], 'GSM3415005': [0.0, 0.0], 'GSM3415006': [0.0, 1.0], 'GSM3415007': [0.0, 0.0], 'GSM3415008': [0.0, 0.0], 'GSM3415009': [1.0, 1.0], 'GSM3415010': [1.0, 1.0], 'GSM3415011': [1.0, 1.0], 'GSM3415012': [1.0, 0.0], 'GSM3415013': [1.0, 1.0], 'GSM3415014': [1.0, 0.0], 'GSM3415015': [1.0, 1.0], 'GSM3415016': [1.0, 0.0], 'GSM3415017': [0.0, 0.0], 'GSM3415018': [0.0, 1.0], 'GSM3415019': [0.0, 1.0], 'GSM3415020': [0.0, 0.0], 'GSM3415021': [0.0, 0.0], 'GSM3415022': [0.0, 0.0], 'GSM3415023': [0.0, 1.0], 'GSM3415024': [0.0, 1.0], 'GSM3415025': [0.0, 1.0], 'GSM3415026': [0.0, 0.0], 'GSM3415027': [1.0, 1.0], 'GSM3415028': [1.0, 1.0], 'GSM3415029': [1.0, 1.0], 'GSM3415030': [1.0, 1.0], 'GSM3415031': [1.0, 0.0], 'GSM3415032': [1.0, 0.0], 'GSM3415033': [1.0, 1.0], 'GSM3415034': [1.0, 1.0], 'GSM3415035': [1.0, 0.0]}\n",
121
+ "Saved clinical data to ../../output/preprocess/Coronary_artery_disease/clinical_data/GSE120774.csv\n"
122
+ ]
123
+ }
124
+ ],
125
+ "source": [
126
+ "# 1. Gene Expression Data Availability\n",
127
+ "# From the background information, this study collected tissue samples (EAT and SAT) from patients,\n",
128
+ "# which suggests gene expression data is likely available.\n",
129
+ "is_gene_available = True\n",
130
+ "\n",
131
+ "# 2. Variable Availability and Data Type Conversion\n",
132
+ "\n",
133
+ "# 2.1 Data Availability\n",
134
+ "# Trait (Coronary artery disease) - available in row 2 with unique values \"disease: None\" and \"disease: coronary disease\"\n",
135
+ "trait_row = 2\n",
136
+ "\n",
137
+ "# Gender - available in row 1 with unique values \"gender: M\" and \"gender: F\"\n",
138
+ "gender_row = 1 \n",
139
+ "\n",
140
+ "# Age - not provided in the sample characteristics\n",
141
+ "age_row = None\n",
142
+ "\n",
143
+ "# 2.2 Data Type Conversion\n",
144
+ "def convert_trait(value):\n",
145
+ " \"\"\"Convert trait value to binary (0 for controls, 1 for cases)\"\"\"\n",
146
+ " if not isinstance(value, str):\n",
147
+ " return None\n",
148
+ " value = value.lower()\n",
149
+ " if \":\" in value:\n",
150
+ " value = value.split(\":\", 1)[1].strip()\n",
151
+ " \n",
152
+ " if \"none\" in value or \"control\" in value or \"without\" in value:\n",
153
+ " return 0\n",
154
+ " elif \"coronary disease\" in value or \"cad\" in value:\n",
155
+ " return 1\n",
156
+ " return None\n",
157
+ "\n",
158
+ "def convert_gender(value):\n",
159
+ " \"\"\"Convert gender value to binary (0 for female, 1 for male)\"\"\"\n",
160
+ " if not isinstance(value, str):\n",
161
+ " return None\n",
162
+ " value = value.lower()\n",
163
+ " if \":\" in value:\n",
164
+ " value = value.split(\":\", 1)[1].strip()\n",
165
+ " \n",
166
+ " if value == \"f\" or \"female\" in value:\n",
167
+ " return 0\n",
168
+ " elif value == \"m\" or \"male\" in value:\n",
169
+ " return 1\n",
170
+ " return None\n",
171
+ "\n",
172
+ "# Age conversion not needed as age data is not available\n",
173
+ "convert_age = None\n",
174
+ "\n",
175
+ "# 3. Save Metadata\n",
176
+ "# Check if trait data is available (trait_row is not None)\n",
177
+ "is_trait_available = trait_row is not None\n",
178
+ "\n",
179
+ "# Initial filtering on usability and save information\n",
180
+ "validate_and_save_cohort_info(\n",
181
+ " is_final=False,\n",
182
+ " cohort=cohort,\n",
183
+ " info_path=json_path,\n",
184
+ " is_gene_available=is_gene_available,\n",
185
+ " is_trait_available=is_trait_available\n",
186
+ ")\n",
187
+ "\n",
188
+ "# 4. Clinical Feature Extraction\n",
189
+ "# Since trait_row is not None, we need to extract and save clinical features\n",
190
+ "if is_trait_available:\n",
191
+ " try:\n",
192
+ " # Extract clinical features - using the clinical_data variable that should be \n",
193
+ " # available from previous steps\n",
194
+ " selected_clinical_df = geo_select_clinical_features(\n",
195
+ " clinical_df=clinical_data, # Variable expected to be available from previous steps\n",
196
+ " trait=trait,\n",
197
+ " trait_row=trait_row,\n",
198
+ " convert_trait=convert_trait,\n",
199
+ " gender_row=gender_row,\n",
200
+ " convert_gender=convert_gender,\n",
201
+ " age_row=age_row,\n",
202
+ " convert_age=convert_age\n",
203
+ " )\n",
204
+ " \n",
205
+ " # Preview the dataframe\n",
206
+ " print(\"Preview of selected clinical features:\")\n",
207
+ " print(preview_df(selected_clinical_df))\n",
208
+ " \n",
209
+ " # Save the extracted clinical features\n",
210
+ " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
211
+ " selected_clinical_df.to_csv(out_clinical_data_file, index=False)\n",
212
+ " print(f\"Saved clinical data to {out_clinical_data_file}\")\n",
213
+ " except Exception as e:\n",
214
+ " print(f\"Error processing clinical data: {e}\")\n"
215
+ ]
216
+ },
217
+ {
218
+ "cell_type": "markdown",
219
+ "id": "07d93b24",
220
+ "metadata": {},
221
+ "source": [
222
+ "### Step 3: Gene Data Extraction"
223
+ ]
224
+ },
225
+ {
226
+ "cell_type": "code",
227
+ "execution_count": 4,
228
+ "id": "08fa721a",
229
+ "metadata": {
230
+ "execution": {
231
+ "iopub.execute_input": "2025-03-25T08:27:37.859759Z",
232
+ "iopub.status.busy": "2025-03-25T08:27:37.859651Z",
233
+ "iopub.status.idle": "2025-03-25T08:27:37.965689Z",
234
+ "shell.execute_reply": "2025-03-25T08:27:37.965280Z"
235
+ }
236
+ },
237
+ "outputs": [
238
+ {
239
+ "name": "stdout",
240
+ "output_type": "stream",
241
+ "text": [
242
+ "SOFT file: ../../input/GEO/Coronary_artery_disease/GSE120774/GSE120774_family.soft.gz\n",
243
+ "Matrix file: ../../input/GEO/Coronary_artery_disease/GSE120774/GSE120774_series_matrix.txt.gz\n",
244
+ "Found the matrix table marker at line 63\n",
245
+ "Gene data shape: (33297, 36)\n",
246
+ "First 20 gene/probe identifiers:\n",
247
+ "['7892501', '7892502', '7892503', '7892504', '7892505', '7892506', '7892507', '7892508', '7892509', '7892510', '7892511', '7892512', '7892513', '7892514', '7892515', '7892516', '7892517', '7892518', '7892519', '7892520']\n"
248
+ ]
249
+ }
250
+ ],
251
+ "source": [
252
+ "# 1. Identify the paths to the SOFT file and the matrix file\n",
253
+ "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
254
+ "print(f\"SOFT file: {soft_file}\")\n",
255
+ "print(f\"Matrix file: {matrix_file}\")\n",
256
+ "\n",
257
+ "# Set gene availability flag\n",
258
+ "is_gene_available = True # Initially assume gene data is available\n",
259
+ "\n",
260
+ "# First check if the matrix file contains the expected marker\n",
261
+ "found_marker = False\n",
262
+ "marker_row = None\n",
263
+ "try:\n",
264
+ " with gzip.open(matrix_file, 'rt') as file:\n",
265
+ " for i, line in enumerate(file):\n",
266
+ " if \"!series_matrix_table_begin\" in line:\n",
267
+ " found_marker = True\n",
268
+ " marker_row = i\n",
269
+ " print(f\"Found the matrix table marker at line {i}\")\n",
270
+ " break\n",
271
+ " \n",
272
+ " if not found_marker:\n",
273
+ " print(\"Warning: Could not find '!series_matrix_table_begin' marker in the file.\")\n",
274
+ " is_gene_available = False\n",
275
+ " \n",
276
+ " # If marker was found, try to extract gene data\n",
277
+ " if is_gene_available:\n",
278
+ " try:\n",
279
+ " # Try using the library function\n",
280
+ " gene_data = get_genetic_data(matrix_file)\n",
281
+ " \n",
282
+ " if gene_data.shape[0] == 0:\n",
283
+ " print(\"Warning: Extracted gene data has 0 rows.\")\n",
284
+ " is_gene_available = False\n",
285
+ " else:\n",
286
+ " print(f\"Gene data shape: {gene_data.shape}\")\n",
287
+ " # Print the first 20 gene/probe identifiers\n",
288
+ " print(\"First 20 gene/probe identifiers:\")\n",
289
+ " print(gene_data.index[:20].tolist())\n",
290
+ " except Exception as e:\n",
291
+ " print(f\"Error extracting gene data with get_genetic_data(): {e}\")\n",
292
+ " is_gene_available = False\n",
293
+ " \n",
294
+ " # If gene data extraction failed, examine file content to diagnose\n",
295
+ " if not is_gene_available:\n",
296
+ " print(\"Examining file content to diagnose the issue:\")\n",
297
+ " try:\n",
298
+ " with gzip.open(matrix_file, 'rt') as file:\n",
299
+ " # Print lines around the marker if found\n",
300
+ " if marker_row is not None:\n",
301
+ " for i, line in enumerate(file):\n",
302
+ " if i >= marker_row - 2 and i <= marker_row + 10:\n",
303
+ " print(f\"Line {i}: {line.strip()[:100]}...\")\n",
304
+ " if i > marker_row + 10:\n",
305
+ " break\n",
306
+ " else:\n",
307
+ " # If marker not found, print first 10 lines\n",
308
+ " for i, line in enumerate(file):\n",
309
+ " if i < 10:\n",
310
+ " print(f\"Line {i}: {line.strip()[:100]}...\")\n",
311
+ " else:\n",
312
+ " break\n",
313
+ " except Exception as e2:\n",
314
+ " print(f\"Error examining file: {e2}\")\n",
315
+ " \n",
316
+ "except Exception as e:\n",
317
+ " print(f\"Error processing file: {e}\")\n",
318
+ " is_gene_available = False\n",
319
+ "\n",
320
+ "# Update validation information if gene data extraction failed\n",
321
+ "if not is_gene_available:\n",
322
+ " print(\"Gene expression data could not be successfully extracted from this dataset.\")\n",
323
+ " # Update the validation record since gene data isn't available\n",
324
+ " is_trait_available = False # We already determined trait data isn't available in step 2\n",
325
+ " validate_and_save_cohort_info(is_final=False, cohort=cohort, info_path=json_path,\n",
326
+ " is_gene_available=is_gene_available, is_trait_available=is_trait_available)\n"
327
+ ]
328
+ },
329
+ {
330
+ "cell_type": "markdown",
331
+ "id": "cfc8664b",
332
+ "metadata": {},
333
+ "source": [
334
+ "### Step 4: Gene Identifier Review"
335
+ ]
336
+ },
337
+ {
338
+ "cell_type": "code",
339
+ "execution_count": 5,
340
+ "id": "d889df67",
341
+ "metadata": {
342
+ "execution": {
343
+ "iopub.execute_input": "2025-03-25T08:27:37.967026Z",
344
+ "iopub.status.busy": "2025-03-25T08:27:37.966905Z",
345
+ "iopub.status.idle": "2025-03-25T08:27:37.968856Z",
346
+ "shell.execute_reply": "2025-03-25T08:27:37.968564Z"
347
+ }
348
+ },
349
+ "outputs": [],
350
+ "source": [
351
+ "# The gene identifiers appear to be probe IDs (numeric identifiers) rather than human gene symbols\n",
352
+ "# These are likely microarray probe IDs which need to be mapped to gene symbols\n",
353
+ "\n",
354
+ "# Based on the format (7-digit numeric IDs), these appear to be Affymetrix or Illumina microarray probe IDs\n",
355
+ "# They need to be mapped to official gene symbols for meaningful biological interpretation\n",
356
+ "\n",
357
+ "requires_gene_mapping = True\n"
358
+ ]
359
+ },
360
+ {
361
+ "cell_type": "markdown",
362
+ "id": "dd8d7133",
363
+ "metadata": {},
364
+ "source": [
365
+ "### Step 5: Gene Annotation"
366
+ ]
367
+ },
368
+ {
369
+ "cell_type": "code",
370
+ "execution_count": 6,
371
+ "id": "afdc1303",
372
+ "metadata": {
373
+ "execution": {
374
+ "iopub.execute_input": "2025-03-25T08:27:37.970044Z",
375
+ "iopub.status.busy": "2025-03-25T08:27:37.969931Z",
376
+ "iopub.status.idle": "2025-03-25T08:27:40.649451Z",
377
+ "shell.execute_reply": "2025-03-25T08:27:40.649014Z"
378
+ }
379
+ },
380
+ "outputs": [
381
+ {
382
+ "name": "stdout",
383
+ "output_type": "stream",
384
+ "text": [
385
+ "\n",
386
+ "Gene annotation preview:\n",
387
+ "Columns in gene annotation: ['ID', 'GB_LIST', 'SPOT_ID', 'seqname', 'RANGE_GB', 'RANGE_STRAND', 'RANGE_START', 'RANGE_STOP', 'total_probes', 'gene_assignment', 'mrna_assignment', 'category']\n",
388
+ "{'ID': ['7896736', '7896738', '7896740'], 'GB_LIST': [nan, nan, 'NM_001004195,NM_001005240,NM_001005484,BC136848,BC136867,BC136907,BC136908'], 'SPOT_ID': ['chr1:53049-54936', 'chr1:63015-63887', 'chr1:69091-70008'], 'seqname': ['chr1', 'chr1', 'chr1'], 'RANGE_GB': ['NC_000001.10', 'NC_000001.10', 'NC_000001.10'], 'RANGE_STRAND': ['+', '+', '+'], 'RANGE_START': ['53049', '63015', '69091'], 'RANGE_STOP': ['54936', '63887', '70008'], 'total_probes': [7.0, 31.0, 24.0], 'gene_assignment': ['---', 'ENST00000328113 // OR4G2P // olfactory receptor, family 4, subfamily G, member 2 pseudogene // --- // --- /// ENST00000492842 // OR4G11P // olfactory receptor, family 4, subfamily G, member 11 pseudogene // --- // --- /// ENST00000588632 // OR4G1P // olfactory receptor, family 4, subfamily G, member 1 pseudogene // --- // ---', 'NM_001004195 // OR4F4 // olfactory receptor, family 4, subfamily F, member 4 // 15q26.3 // 26682 /// NM_001005240 // OR4F17 // olfactory receptor, family 4, subfamily F, member 17 // 19p13.3 // 81099 /// NM_001005484 // OR4F5 // olfactory receptor, family 4, subfamily F, member 5 // 1p36.33 // 79501 /// ENST00000318050 // OR4F17 // olfactory receptor, family 4, subfamily F, member 17 // 19p13.3 // 81099 /// ENST00000326183 // OR4F4 // olfactory receptor, family 4, subfamily F, member 4 // 15q26.3 // 26682 /// ENST00000335137 // OR4F5 // olfactory receptor, family 4, subfamily F, member 5 // 1p36.33 // 79501 /// ENST00000585993 // OR4F17 // olfactory receptor, family 4, subfamily F, member 17 // 19p13.3 // 81099 /// BC136848 // OR4F17 // olfactory receptor, family 4, subfamily F, member 17 // 19p13.3 // 81099 /// BC136867 // OR4F17 // olfactory receptor, family 4, subfamily F, member 17 // 19p13.3 // 81099 /// BC136907 // OR4F4 // olfactory receptor, family 4, subfamily F, member 4 // 15q26.3 // 26682 /// BC136908 // OR4F4 // olfactory receptor, family 4, subfamily F, member 4 // 15q26.3 // 26682'], 'mrna_assignment': ['NONHSAT060105 // NONCODE // Non-coding transcript identified by NONCODE // chr1 // 100 // 100 // 7 // 7 // 0', 'ENST00000328113 // ENSEMBL // havana:known chromosome:GRCh38:15:101926805:101927707:-1 gene:ENSG00000183909 gene_biotype:unprocessed_pseudogene transcript_biotype:unprocessed_pseudogene // chr1 // 100 // 100 // 31 // 31 // 0 /// ENST00000492842 // ENSEMBL // havana:known chromosome:GRCh38:1:62948:63887:1 gene:ENSG00000240361 gene_biotype:unprocessed_pseudogene transcript_biotype:unprocessed_pseudogene // chr1 // 100 // 100 // 31 // 31 // 0 /// ENST00000588632 // ENSEMBL // havana:known chromosome:GRCh38:19:104535:105471:1 gene:ENSG00000267310 gene_biotype:unprocessed_pseudogene transcript_biotype:unprocessed_pseudogene // chr1 // 100 // 100 // 31 // 31 // 0 /// NONHSAT000016 // NONCODE // Non-coding transcript identified by NONCODE: Linc // chr1 // 100 // 100 // 31 // 31 // 0 /// NONHSAT051704 // NONCODE // Non-coding transcript identified by NONCODE: Linc // chr1 // 100 // 100 // 31 // 31 // 0 /// NONHSAT060106 // NONCODE // Non-coding transcript identified by NONCODE: Linc // chr1 // 100 // 100 // 31 // 31 // 0', 'NM_001004195 // RefSeq // Homo sapiens olfactory receptor, family 4, subfamily F, member 4 (OR4F4), mRNA. // chr1 // 100 // 100 // 24 // 24 // 0 /// NM_001005240 // RefSeq // Homo sapiens olfactory receptor, family 4, subfamily F, member 17 (OR4F17), mRNA. // chr1 // 100 // 100 // 24 // 24 // 0 /// NM_001005484 // RefSeq // Homo sapiens olfactory receptor, family 4, subfamily F, member 5 (OR4F5), mRNA. // chr1 // 100 // 100 // 24 // 24 // 0 /// ENST00000318050 // ENSEMBL // ensembl:known chromosome:GRCh38:19:110643:111696:1 gene:ENSG00000176695 gene_biotype:protein_coding transcript_biotype:protein_coding // chr1 // 100 // 100 // 24 // 24 // 0 /// ENST00000326183 // ENSEMBL // ensembl_havana_transcript:known chromosome:GRCh38:15:101922042:101923095:-1 gene:ENSG00000177693 gene_biotype:protein_coding transcript_biotype:protein_coding // chr1 // 100 // 100 // 24 // 24 // 0 /// ENST00000335137 // ENSEMBL // ensembl_havana_transcript:known chromosome:GRCh38:1:69091:70008:1 gene:ENSG00000186092 gene_biotype:protein_coding transcript_biotype:protein_coding // chr1 // 100 // 100 // 24 // 24 // 0 /// ENST00000585993 // ENSEMBL // havana:known chromosome:GRCh38:19:107461:111696:1 gene:ENSG00000176695 gene_biotype:protein_coding transcript_biotype:protein_coding // chr1 // 100 // 100 // 24 // 24 // 0 /// BC136848 // GenBank // Homo sapiens olfactory receptor, family 4, subfamily F, member 17, mRNA (cDNA clone MGC:168462 IMAGE:9020839), complete cds. // chr1 // 100 // 100 // 24 // 24 // 0 /// BC136867 // GenBank // Homo sapiens olfactory receptor, family 4, subfamily F, member 17, mRNA (cDNA clone MGC:168481 IMAGE:9020858), complete cds. // chr1 // 100 // 100 // 24 // 24 // 0 /// BC136907 // GenBank // Homo sapiens olfactory receptor, family 4, subfamily F, member 4, mRNA (cDNA clone MGC:168521 IMAGE:9020898), complete cds. // chr1 // 100 // 100 // 24 // 24 // 0 /// BC136908 // GenBank // Homo sapiens olfactory receptor, family 4, subfamily F, member 4, mRNA (cDNA clone MGC:168522 IMAGE:9020899), complete cds. // chr1 // 100 // 100 // 24 // 24 // 0 /// ENST00000618231 // ENSEMBL // havana:known chromosome:GRCh38:19:110613:111417:1 gene:ENSG00000176695 gene_biotype:protein_coding transcript_biotype:retained_intron // chr1 // 100 // 88 // 21 // 21 // 0'], 'category': ['main', 'main', 'main']}\n",
389
+ "\n",
390
+ "Examining 'gene_assignment' column examples:\n",
391
+ "Example 1: ---\n",
392
+ "Example 2: ENST00000328113 // OR4G2P // olfactory receptor, family 4, subfamily G, member 2 pseudogene // --- // --- /// ENST00000492842 // OR4G11P // olfactory receptor, family 4, subfamily G, member 11 pseudog...\n",
393
+ "Example 3: NM_001004195 // OR4F4 // olfactory receptor, family 4, subfamily F, member 4 // 15q26.3 // 26682 /// NM_001005240 // OR4F17 // olfactory receptor, family 4, subfamily F, member 17 // 19p13.3 // 81099 ...\n",
394
+ "Example 4: NR_024437 // LOC728323 // uncharacterized LOC728323 // 2q37.3 // 728323 /// XM_006711854 // LOC101060626 // F-box only protein 25-like // --- // 101060626 /// XM_006726377 // LOC101060626 // F-box onl...\n",
395
+ "Example 5: NM_001005221 // OR4F29 // olfactory receptor, family 4, subfamily F, member 29 // 1p36.33 // 729759 /// NM_001005224 // OR4F3 // olfactory receptor, family 4, subfamily F, member 3 // 5q35.3 // 26683 ...\n",
396
+ "\n",
397
+ "Gene assignment column completeness: 33297/1232025 rows (2.70%)\n",
398
+ "Probes without gene assignments: 8004/1232025 rows (0.65%)\n",
399
+ "\n",
400
+ "Columns identified for gene mapping:\n",
401
+ "- 'ID': Contains probe IDs (e.g., 7896736)\n",
402
+ "- 'gene_assignment': Contains gene information that needs parsing to extract gene symbols\n"
403
+ ]
404
+ }
405
+ ],
406
+ "source": [
407
+ "# 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.\n",
408
+ "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
409
+ "gene_annotation = get_gene_annotation(soft_file)\n",
410
+ "\n",
411
+ "# 2. Analyze the gene annotation dataframe to identify which columns contain the gene identifiers and gene symbols\n",
412
+ "print(\"\\nGene annotation preview:\")\n",
413
+ "print(f\"Columns in gene annotation: {gene_annotation.columns.tolist()}\")\n",
414
+ "print(preview_df(gene_annotation, n=3))\n",
415
+ "\n",
416
+ "# Examining the gene_assignment column which appears to contain gene symbol information\n",
417
+ "print(\"\\nExamining 'gene_assignment' column examples:\")\n",
418
+ "if 'gene_assignment' in gene_annotation.columns:\n",
419
+ " # Display a few examples of the gene_assignment column to understand its format\n",
420
+ " gene_samples = gene_annotation['gene_assignment'].head(5).tolist()\n",
421
+ " for i, sample in enumerate(gene_samples):\n",
422
+ " print(f\"Example {i+1}: {sample[:200]}...\" if isinstance(sample, str) and len(sample) > 200 else f\"Example {i+1}: {sample}\")\n",
423
+ " \n",
424
+ " # Check the quality and completeness of the gene_assignment column\n",
425
+ " non_null_assignments = gene_annotation['gene_assignment'].notna().sum()\n",
426
+ " total_rows = len(gene_annotation)\n",
427
+ " print(f\"\\nGene assignment column completeness: {non_null_assignments}/{total_rows} rows ({non_null_assignments/total_rows:.2%})\")\n",
428
+ " \n",
429
+ " # Check for probe IDs without gene assignments (typically '---' entries)\n",
430
+ " missing_assignments = gene_annotation[gene_annotation['gene_assignment'] == '---'].shape[0]\n",
431
+ " print(f\"Probes without gene assignments: {missing_assignments}/{total_rows} rows ({missing_assignments/total_rows:.2%})\")\n",
432
+ " \n",
433
+ " # Identify the columns needed for gene mapping\n",
434
+ " print(\"\\nColumns identified for gene mapping:\")\n",
435
+ " print(\"- 'ID': Contains probe IDs (e.g., 7896736)\")\n",
436
+ " print(\"- 'gene_assignment': Contains gene information that needs parsing to extract gene symbols\")\n",
437
+ "else:\n",
438
+ " print(\"Error: 'gene_assignment' column not found in annotation data.\")\n",
439
+ " print(\"Available columns:\", gene_annotation.columns.tolist())\n"
440
+ ]
441
+ },
442
+ {
443
+ "cell_type": "markdown",
444
+ "id": "b468200e",
445
+ "metadata": {},
446
+ "source": [
447
+ "### Step 6: Gene Identifier Mapping"
448
+ ]
449
+ },
450
+ {
451
+ "cell_type": "code",
452
+ "execution_count": 7,
453
+ "id": "8bb23d73",
454
+ "metadata": {
455
+ "execution": {
456
+ "iopub.execute_input": "2025-03-25T08:27:40.651152Z",
457
+ "iopub.status.busy": "2025-03-25T08:27:40.650983Z",
458
+ "iopub.status.idle": "2025-03-25T08:27:46.284833Z",
459
+ "shell.execute_reply": "2025-03-25T08:27:46.284429Z"
460
+ }
461
+ },
462
+ "outputs": [
463
+ {
464
+ "name": "stdout",
465
+ "output_type": "stream",
466
+ "text": [
467
+ "Example gene symbol extractions:\n",
468
+ "Example 1:\n",
469
+ "Original: ---\n",
470
+ "Extracted symbols: []\n",
471
+ "Example 2:\n",
472
+ "Original: ENST00000328113 // OR4G2P // olfactory receptor, family 4, subfamily G, member 2 pseudogene // --- /...\n",
473
+ "Extracted symbols: ['OR4G1P', 'OR4G2P', 'OR4G11P']\n",
474
+ "Example 3:\n",
475
+ "Original: NM_001004195 // OR4F4 // olfactory receptor, family 4, subfamily F, member 4 // 15q26.3 // 26682 ///...\n",
476
+ "Extracted symbols: ['OR4F4', 'OR4F5', 'OR4F17']\n",
477
+ "Example 4:\n",
478
+ "Original: NR_024437 // LOC728323 // uncharacterized LOC728323 // 2q37.3 // 728323 /// XM_006711854 // LOC10106...\n",
479
+ "Extracted symbols: ['PCMTD2', 'SEPT14']\n",
480
+ "Example 5:\n",
481
+ "Original: NM_001005221 // OR4F29 // olfactory receptor, family 4, subfamily F, member 29 // 1p36.33 // 729759 ...\n",
482
+ "Extracted symbols: ['OR4F28P', 'OR4F16', 'OR4F29', 'OR4F8P', 'OR4F7P', 'OR4F3', 'OR4F2P', 'OR4F1P', 'OR4F21']\n"
483
+ ]
484
+ },
485
+ {
486
+ "name": "stdout",
487
+ "output_type": "stream",
488
+ "text": [
489
+ "\n",
490
+ "Total probes with valid gene symbols: 24707\n",
491
+ "\n",
492
+ "Gene mapping information:\n",
493
+ "Total probes in expression data: 33297\n",
494
+ "Probes with gene mappings: 24707\n",
495
+ "Unique genes after mapping: 0\n",
496
+ "\n",
497
+ "WARNING: Standard mapping produced 0 genes. Attempting alternate approach...\n"
498
+ ]
499
+ },
500
+ {
501
+ "name": "stdout",
502
+ "output_type": "stream",
503
+ "text": [
504
+ "Simplified mapping produced 25127 probe-to-gene mappings\n",
505
+ "Simplified mapping produced 23139 genes\n",
506
+ "After normalization: 22343 genes\n",
507
+ "\n",
508
+ "Preview of gene expression data:\n",
509
+ "{'GSM3415000': [6.95774, 5.6657, 12.0967, 5.64055, 5.23009], 'GSM3415001': [7.61407, 5.90698, 11.7109, 6.19953, 5.92731], 'GSM3415002': [7.21409, 5.6717, 11.87, 6.11775, 5.49881], 'GSM3415003': [7.19709, 5.75878, 11.8535, 5.93999, 5.77457], 'GSM3415004': [7.12083, 5.69981, 11.9852, 5.85591, 5.55674], 'GSM3415005': [7.30062, 5.77384, 11.8517, 5.67189, 5.69931], 'GSM3415006': [7.21898, 6.0316, 11.7973, 5.74427, 5.64976], 'GSM3415007': [6.90321, 5.56953, 11.4465, 5.69886, 5.55623], 'GSM3415008': [7.16062, 5.81981, 11.7353, 5.72275, 5.76073], 'GSM3415009': [7.15482, 5.74577, 11.8572, 5.71592, 5.62793], 'GSM3415010': [7.17004, 5.74897, 11.6864, 5.74791, 6.06825], 'GSM3415011': [7.26014, 5.73882, 11.7929, 5.69294, 5.59686], 'GSM3415012': [7.21029, 5.66763, 11.8685, 5.52236, 5.54461], 'GSM3415013': [7.03885, 5.43717, 11.9798, 5.58275, 5.81155], 'GSM3415014': [7.04218, 5.9481, 11.8107, 5.75532, 5.51786], 'GSM3415015': [6.91789, 5.54417, 11.8627, 5.47699, 5.70513], 'GSM3415016': [6.87814, 5.41642, 12.0208, 5.3062, 5.67245], 'GSM3415017': [7.2027, 5.82422, 11.9105, 6.02527, 5.75729], 'GSM3415018': [7.08367, 5.43742, 11.92, 5.47316, 5.70813], 'GSM3415019': [7.02314, 5.70738, 11.9368, 5.46817, 5.51984], 'GSM3415020': [7.31375, 5.83101, 11.8874, 5.95709, 5.77285], 'GSM3415021': [7.30992, 5.87096, 11.8168, 5.86899, 5.97262], 'GSM3415022': [7.48221, 6.31212, 11.2937, 6.05602, 5.72127], 'GSM3415023': [7.50397, 6.44974, 10.7588, 5.95392, 5.92881], 'GSM3415024': [7.19449, 5.89398, 11.6325, 5.78308, 5.57504], 'GSM3415025': [6.83583, 5.4434, 11.9428, 5.34154, 5.53078], 'GSM3415026': [6.98818, 5.71285, 11.8723, 5.73145, 5.69724], 'GSM3415027': [7.09204, 5.59079, 11.9521, 5.79614, 5.4907], 'GSM3415028': [7.38096, 5.61466, 11.8476, 5.60134, 5.58501], 'GSM3415029': [7.12859, 5.47982, 12.1107, 5.68366, 5.8375], 'GSM3415030': [7.13538, 5.59825, 11.912, 5.64041, 5.93221], 'GSM3415031': [7.06929, 5.63018, 11.8708, 5.67231, 5.64413], 'GSM3415032': [7.04818, 5.67969, 11.8481, 5.62486, 5.52272], 'GSM3415033': [7.12, 5.38563, 11.9914, 5.56929, 6.03025], 'GSM3415034': [6.93669, 5.28715, 11.7417, 5.52987, 5.66853], 'GSM3415035': [6.97924, 5.27288, 11.971, 5.30301, 5.81562]}\n"
510
+ ]
511
+ },
512
+ {
513
+ "name": "stdout",
514
+ "output_type": "stream",
515
+ "text": [
516
+ "\n",
517
+ "Saved gene expression data to ../../output/preprocess/Coronary_artery_disease/gene_data/GSE120774.csv\n"
518
+ ]
519
+ }
520
+ ],
521
+ "source": [
522
+ "# 1. From the output of previous steps, we need to map the numeric probe IDs to gene symbols\n",
523
+ "# The gene annotation contains 'ID' column with probe IDs and 'gene_assignment' column with gene symbols and other info\n",
524
+ "\n",
525
+ "# Load gene annotation and expression data\n",
526
+ "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
527
+ "gene_annotation = get_gene_annotation(soft_file)\n",
528
+ "gene_data_raw = get_genetic_data(matrix_file)\n",
529
+ "\n",
530
+ "# 2. Extract and process the mapping between probe IDs and gene symbols \n",
531
+ "# Create a custom function to extract gene symbols from the gene_assignment string\n",
532
+ "def extract_gene_symbols_from_assignment(assignment_str):\n",
533
+ " if not isinstance(assignment_str, str) or assignment_str == '---':\n",
534
+ " return []\n",
535
+ " \n",
536
+ " # The format appears to be: RefSeq_ID // GENE_SYMBOL // description // location // ID\n",
537
+ " # Multiple genes are separated by ///\n",
538
+ " gene_symbols = []\n",
539
+ " gene_entries = assignment_str.split('///')\n",
540
+ " \n",
541
+ " for entry in gene_entries:\n",
542
+ " parts = entry.strip().split('//')\n",
543
+ " if len(parts) >= 2:\n",
544
+ " gene_symbol = parts[1].strip()\n",
545
+ " # Some entries might have multiple symbols or additional info\n",
546
+ " if gene_symbol and gene_symbol != '---':\n",
547
+ " # Get the actual gene symbol without additional text\n",
548
+ " # The gene symbols appear to be standard symbols like OR4F4\n",
549
+ " symbols = extract_human_gene_symbols(gene_symbol)\n",
550
+ " gene_symbols.extend(symbols)\n",
551
+ " \n",
552
+ " return list(set(gene_symbols)) # Remove duplicates\n",
553
+ "\n",
554
+ "# Apply the function to create a mapping dataframe\n",
555
+ "gene_annotation['Gene'] = gene_annotation['gene_assignment'].apply(extract_gene_symbols_from_assignment)\n",
556
+ "\n",
557
+ "# Print some examples to verify extraction\n",
558
+ "print(\"Example gene symbol extractions:\")\n",
559
+ "for i, (assignment, symbols) in enumerate(zip(gene_annotation['gene_assignment'].head(5), gene_annotation['Gene'].head(5))):\n",
560
+ " print(f\"Example {i+1}:\")\n",
561
+ " print(f\"Original: {assignment[:100]}...\" if isinstance(assignment, str) and len(str(assignment)) > 100 else f\"Original: {assignment}\")\n",
562
+ " print(f\"Extracted symbols: {symbols}\")\n",
563
+ "\n",
564
+ "# Create mapping dataframe\n",
565
+ "mapping_df = gene_annotation[['ID', 'Gene']].copy()\n",
566
+ "\n",
567
+ "# Keep only entries with at least one gene symbol\n",
568
+ "mapping_df = mapping_df[mapping_df['Gene'].apply(len) > 0]\n",
569
+ "print(f\"\\nTotal probes with valid gene symbols: {len(mapping_df)}\")\n",
570
+ "\n",
571
+ "# 3. Convert probe-level measurements to gene expression using apply_gene_mapping\n",
572
+ "# Instead of directly calling the function, we'll manually do the steps to debug\n",
573
+ "try:\n",
574
+ " # Apply the mapping\n",
575
+ " gene_data = apply_gene_mapping(gene_data_raw, mapping_df)\n",
576
+ " \n",
577
+ " # Print mapping statistics\n",
578
+ " print(\"\\nGene mapping information:\")\n",
579
+ " print(f\"Total probes in expression data: {gene_data_raw.shape[0]}\")\n",
580
+ " print(f\"Probes with gene mappings: {len(mapping_df)}\")\n",
581
+ " print(f\"Unique genes after mapping: {gene_data.shape[0]}\")\n",
582
+ " \n",
583
+ " # If mapping still fails, try a direct approach for urgent debugging\n",
584
+ " if gene_data.shape[0] == 0:\n",
585
+ " print(\"\\nWARNING: Standard mapping produced 0 genes. Attempting alternate approach...\")\n",
586
+ " \n",
587
+ " # Fallback approach: Create a simpler mapping using only unique first symbols\n",
588
+ " simplified_mapping = gene_annotation[['ID']].copy()\n",
589
+ " simplified_mapping['Gene'] = gene_annotation['gene_assignment'].apply(\n",
590
+ " lambda x: extract_human_gene_symbols(str(x))[0] if isinstance(x, str) and len(extract_human_gene_symbols(str(x))) > 0 else None\n",
591
+ " )\n",
592
+ " simplified_mapping = simplified_mapping.dropna()\n",
593
+ " print(f\"Simplified mapping produced {len(simplified_mapping)} probe-to-gene mappings\")\n",
594
+ " \n",
595
+ " # Apply simplified mapping\n",
596
+ " gene_data = apply_gene_mapping(gene_data_raw, simplified_mapping)\n",
597
+ " print(f\"Simplified mapping produced {gene_data.shape[0]} genes\")\n",
598
+ " \n",
599
+ " # Normalize gene symbols to ensure consistency\n",
600
+ " gene_data = normalize_gene_symbols_in_index(gene_data)\n",
601
+ " print(f\"After normalization: {gene_data.shape[0]} genes\")\n",
602
+ " \n",
603
+ " # Preview the final gene expression data\n",
604
+ " print(\"\\nPreview of gene expression data:\")\n",
605
+ " print(preview_df(gene_data, n=5))\n",
606
+ " \n",
607
+ " # Save the processed gene expression data\n",
608
+ " os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
609
+ " gene_data.to_csv(out_gene_data_file)\n",
610
+ " print(f\"\\nSaved gene expression data to {out_gene_data_file}\")\n",
611
+ " \n",
612
+ "except Exception as e:\n",
613
+ " print(f\"Error during gene mapping: {e}\")\n",
614
+ " \n",
615
+ " # If an error occurs, try a minimal approach to extract at least some data\n",
616
+ " print(\"\\nAttempting minimal approach to extract gene data...\")\n",
617
+ " \n",
618
+ " # Create a direct mapping using a more lenient approach\n",
619
+ " direct_mapping = []\n",
620
+ " for idx, row in gene_annotation.iterrows():\n",
621
+ " gene_id = row['ID']\n",
622
+ " if isinstance(row['gene_assignment'], str):\n",
623
+ " # Extract gene symbols using regex\n",
624
+ " genes = re.findall(r'//\\s+([A-Z0-9]+)\\s+//', row['gene_assignment'])\n",
625
+ " if genes:\n",
626
+ " for gene in genes:\n",
627
+ " direct_mapping.append({'ID': gene_id, 'Gene': gene})\n",
628
+ " \n",
629
+ " if direct_mapping:\n",
630
+ " direct_mapping_df = pd.DataFrame(direct_mapping)\n",
631
+ " \n",
632
+ " # Apply direct mapping\n",
633
+ " gene_data = apply_gene_mapping(gene_data_raw, direct_mapping_df)\n",
634
+ " \n",
635
+ " # Normalize and save\n",
636
+ " gene_data = normalize_gene_symbols_in_index(gene_data)\n",
637
+ " gene_data.to_csv(out_gene_data_file)\n",
638
+ " print(f\"Minimal approach produced {gene_data.shape[0]} genes\")\n",
639
+ " print(f\"Saved gene expression data to {out_gene_data_file}\")\n",
640
+ " else:\n",
641
+ " print(\"Failed to extract gene data with all approaches. Cannot proceed with gene mapping.\")\n"
642
+ ]
643
+ },
644
+ {
645
+ "cell_type": "markdown",
646
+ "id": "885f3f41",
647
+ "metadata": {},
648
+ "source": [
649
+ "### Step 7: Data Normalization and Linking"
650
+ ]
651
+ },
652
+ {
653
+ "cell_type": "code",
654
+ "execution_count": 8,
655
+ "id": "f014c57c",
656
+ "metadata": {
657
+ "execution": {
658
+ "iopub.execute_input": "2025-03-25T08:27:46.286277Z",
659
+ "iopub.status.busy": "2025-03-25T08:27:46.286146Z",
660
+ "iopub.status.idle": "2025-03-25T08:27:56.452190Z",
661
+ "shell.execute_reply": "2025-03-25T08:27:56.451783Z"
662
+ }
663
+ },
664
+ "outputs": [
665
+ {
666
+ "name": "stdout",
667
+ "output_type": "stream",
668
+ "text": [
669
+ "Debug - trait variable: Coronary_artery_disease (type: <class 'str'>)\n",
670
+ "Gene data shape before normalization: (22343, 36)\n"
671
+ ]
672
+ },
673
+ {
674
+ "name": "stdout",
675
+ "output_type": "stream",
676
+ "text": [
677
+ "Gene data saved to ../../output/preprocess/Coronary_artery_disease/gene_data/GSE120774.csv\n",
678
+ "Loaded clinical data shape: (2, 36)\n",
679
+ "Clinical data columns: ['GSM3415000', 'GSM3415001', 'GSM3415002', 'GSM3415003', 'GSM3415004', 'GSM3415005', 'GSM3415006', 'GSM3415007', 'GSM3415008', 'GSM3415009', 'GSM3415010', 'GSM3415011', 'GSM3415012', 'GSM3415013', 'GSM3415014', 'GSM3415015', 'GSM3415016', 'GSM3415017', 'GSM3415018', 'GSM3415019', 'GSM3415020', 'GSM3415021', 'GSM3415022', 'GSM3415023', 'GSM3415024', 'GSM3415025', 'GSM3415026', 'GSM3415027', 'GSM3415028', 'GSM3415029', 'GSM3415030', 'GSM3415031', 'GSM3415032', 'GSM3415033', 'GSM3415034', 'GSM3415035']\n",
680
+ "Initial linked data shape: (36, 22345)\n",
681
+ "Linked data columns: [0, 1, 'A1BG', 'A1CF', 'A2M', 'A2ML1', 'A3GALT2', 'A4GALT', 'A4GNT', 'AAAS']...\n",
682
+ "Using trait column name: 0\n"
683
+ ]
684
+ },
685
+ {
686
+ "name": "stdout",
687
+ "output_type": "stream",
688
+ "text": [
689
+ "Linked data shape after handling missing values: (36, 22345)\n",
690
+ "For the feature '0', the least common label is '1.0' with 17 occurrences. This represents 47.22% of the dataset.\n",
691
+ "The distribution of the feature '0' in this dataset is fine.\n",
692
+ "\n",
693
+ "A new JSON file was created at: ../../output/preprocess/Coronary_artery_disease/cohort_info.json\n"
694
+ ]
695
+ },
696
+ {
697
+ "name": "stdout",
698
+ "output_type": "stream",
699
+ "text": [
700
+ "Linked data saved to ../../output/preprocess/Coronary_artery_disease/GSE120774.csv\n"
701
+ ]
702
+ }
703
+ ],
704
+ "source": [
705
+ "# 1. Attempt to load gene data and handle possible issues with normalization\n",
706
+ "try:\n",
707
+ " # Create output directory if it doesn't exist\n",
708
+ " os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
709
+ " \n",
710
+ " # Debug the trait variable and data structure\n",
711
+ " print(f\"Debug - trait variable: {trait} (type: {type(trait)})\")\n",
712
+ " \n",
713
+ " # Check if gene_data (from previous step) has any content\n",
714
+ " if 'gene_data' not in locals() or gene_data.shape[0] == 0:\n",
715
+ " print(\"WARNING: Gene data is empty after normalization in previous step.\")\n",
716
+ " print(\"This appears to be miRNA data rather than gene expression data.\")\n",
717
+ " \n",
718
+ " # Since gene_data is empty, set gene_available to False\n",
719
+ " is_gene_available = False\n",
720
+ " \n",
721
+ " # Create an empty dataframe for metadata purposes\n",
722
+ " empty_df = pd.DataFrame()\n",
723
+ " \n",
724
+ " # Log information about this dataset for future reference\n",
725
+ " validate_and_save_cohort_info(\n",
726
+ " is_final=True,\n",
727
+ " cohort=cohort,\n",
728
+ " info_path=json_path,\n",
729
+ " is_gene_available=is_gene_available,\n",
730
+ " is_trait_available=True, # Based on previous steps\n",
731
+ " is_biased=True, # Consider it biased as we can't use it\n",
732
+ " df=empty_df,\n",
733
+ " note=\"Dataset appears to contain miRNA data rather than gene expression data. Gene symbols could not be normalized.\"\n",
734
+ " )\n",
735
+ " \n",
736
+ " print(\"Dataset marked as unusable due to lack of valid gene expression data.\")\n",
737
+ " else:\n",
738
+ " # If gene_data is not empty, proceed with normalization and linking\n",
739
+ " print(f\"Gene data shape before normalization: {gene_data.shape}\")\n",
740
+ " \n",
741
+ " # Save the gene data we have, even if it's already normalized\n",
742
+ " gene_data.to_csv(out_gene_data_file)\n",
743
+ " print(f\"Gene data saved to {out_gene_data_file}\")\n",
744
+ " \n",
745
+ " # Attempt to link clinical and gene data\n",
746
+ " try:\n",
747
+ " # Load clinical data\n",
748
+ " clinical_features = pd.read_csv(out_clinical_data_file)\n",
749
+ " print(f\"Loaded clinical data shape: {clinical_features.shape}\")\n",
750
+ " print(f\"Clinical data columns: {clinical_features.columns.tolist()}\")\n",
751
+ " \n",
752
+ " # Set the index for clinical features if needed\n",
753
+ " if 'Unnamed: 0' in clinical_features.columns:\n",
754
+ " clinical_features = clinical_features.set_index('Unnamed: 0')\n",
755
+ " \n",
756
+ " # Link the clinical and genetic data\n",
757
+ " linked_data = geo_link_clinical_genetic_data(clinical_features, gene_data)\n",
758
+ " print(f\"Initial linked data shape: {linked_data.shape}\")\n",
759
+ " print(f\"Linked data columns: {linked_data.columns[:10].tolist()}...\") # Show first 10 columns\n",
760
+ " \n",
761
+ " # Check which columns are available for trait\n",
762
+ " if trait in linked_data.columns:\n",
763
+ " trait_column = trait\n",
764
+ " else:\n",
765
+ " # Since clinical data only has 2 rows, and one is likely Gender, the other is the trait\n",
766
+ " # Find column that's not Gender\n",
767
+ " possible_trait_columns = [col for col in linked_data.columns if col != 'Gender']\n",
768
+ " trait_column = possible_trait_columns[0] if possible_trait_columns else linked_data.columns[0]\n",
769
+ " \n",
770
+ " print(f\"Using trait column name: {trait_column}\")\n",
771
+ " \n",
772
+ " # Handle missing values\n",
773
+ " linked_data = handle_missing_values(linked_data, trait_column)\n",
774
+ " print(f\"Linked data shape after handling missing values: {linked_data.shape}\")\n",
775
+ " \n",
776
+ " if linked_data.shape[0] > 0:\n",
777
+ " # Check for bias in trait and demographic features\n",
778
+ " is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait_column)\n",
779
+ " \n",
780
+ " # Validate data quality and save cohort info\n",
781
+ " is_usable = validate_and_save_cohort_info(\n",
782
+ " is_final=True,\n",
783
+ " cohort=cohort,\n",
784
+ " info_path=json_path,\n",
785
+ " is_gene_available=is_gene_available,\n",
786
+ " is_trait_available=True,\n",
787
+ " is_biased=is_biased,\n",
788
+ " df=linked_data,\n",
789
+ " note=\"Successfully processed gene expression data for coronary artery disease.\"\n",
790
+ " )\n",
791
+ " \n",
792
+ " # Save the linked data if it's usable\n",
793
+ " if is_usable:\n",
794
+ " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n",
795
+ " linked_data.to_csv(out_data_file)\n",
796
+ " print(f\"Linked data saved to {out_data_file}\")\n",
797
+ " else:\n",
798
+ " print(\"Data not usable for trait study - not saving final linked data.\")\n",
799
+ " else:\n",
800
+ " print(\"After handling missing values, no samples remain.\")\n",
801
+ " validate_and_save_cohort_info(\n",
802
+ " is_final=True,\n",
803
+ " cohort=cohort,\n",
804
+ " info_path=json_path,\n",
805
+ " is_gene_available=is_gene_available,\n",
806
+ " is_trait_available=True,\n",
807
+ " is_biased=True,\n",
808
+ " df=pd.DataFrame(),\n",
809
+ " note=\"No valid samples after handling missing values.\"\n",
810
+ " )\n",
811
+ " except Exception as inner_e:\n",
812
+ " print(f\"Error in linking or processing data: {inner_e}\")\n",
813
+ " import traceback\n",
814
+ " traceback.print_exc()\n",
815
+ " validate_and_save_cohort_info(\n",
816
+ " is_final=True,\n",
817
+ " cohort=cohort,\n",
818
+ " info_path=json_path,\n",
819
+ " is_gene_available=is_gene_available,\n",
820
+ " is_trait_available=True,\n",
821
+ " is_biased=True,\n",
822
+ " df=pd.DataFrame(),\n",
823
+ " note=f\"Error during linking or processing: {str(inner_e)}\"\n",
824
+ " )\n",
825
+ "except Exception as e:\n",
826
+ " print(f\"Error in data processing: {e}\")\n",
827
+ " import traceback\n",
828
+ " traceback.print_exc()\n",
829
+ " \n",
830
+ " # Log the error and mark the dataset as unusable\n",
831
+ " validate_and_save_cohort_info(\n",
832
+ " is_final=True,\n",
833
+ " cohort=cohort,\n",
834
+ " info_path=json_path,\n",
835
+ " is_gene_available=False, # Consider gene data unavailable if we had an error\n",
836
+ " is_trait_available=True, # Based on previous steps\n",
837
+ " is_biased=True, # Consider it biased as we can't use it\n",
838
+ " df=pd.DataFrame(), # Empty dataframe for metadata\n",
839
+ " note=f\"Error during normalization or linking: {str(e)}\"\n",
840
+ " )"
841
+ ]
842
+ }
843
+ ],
844
+ "metadata": {
845
+ "language_info": {
846
+ "codemirror_mode": {
847
+ "name": "ipython",
848
+ "version": 3
849
+ },
850
+ "file_extension": ".py",
851
+ "mimetype": "text/x-python",
852
+ "name": "python",
853
+ "nbconvert_exporter": "python",
854
+ "pygments_lexer": "ipython3",
855
+ "version": "3.10.16"
856
+ }
857
+ },
858
+ "nbformat": 4,
859
+ "nbformat_minor": 5
860
+ }
code/Coronary_artery_disease/GSE156357.ipynb ADDED
@@ -0,0 +1,793 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": 1,
6
+ "id": "ed408600",
7
+ "metadata": {
8
+ "execution": {
9
+ "iopub.execute_input": "2025-03-25T08:27:57.481393Z",
10
+ "iopub.status.busy": "2025-03-25T08:27:57.481151Z",
11
+ "iopub.status.idle": "2025-03-25T08:27:57.652385Z",
12
+ "shell.execute_reply": "2025-03-25T08:27:57.652032Z"
13
+ }
14
+ },
15
+ "outputs": [],
16
+ "source": [
17
+ "import sys\n",
18
+ "import os\n",
19
+ "sys.path.append(os.path.abspath(os.path.join(os.getcwd(), '../..')))\n",
20
+ "\n",
21
+ "# Path Configuration\n",
22
+ "from tools.preprocess import *\n",
23
+ "\n",
24
+ "# Processing context\n",
25
+ "trait = \"Coronary_artery_disease\"\n",
26
+ "cohort = \"GSE156357\"\n",
27
+ "\n",
28
+ "# Input paths\n",
29
+ "in_trait_dir = \"../../input/GEO/Coronary_artery_disease\"\n",
30
+ "in_cohort_dir = \"../../input/GEO/Coronary_artery_disease/GSE156357\"\n",
31
+ "\n",
32
+ "# Output paths\n",
33
+ "out_data_file = \"../../output/preprocess/Coronary_artery_disease/GSE156357.csv\"\n",
34
+ "out_gene_data_file = \"../../output/preprocess/Coronary_artery_disease/gene_data/GSE156357.csv\"\n",
35
+ "out_clinical_data_file = \"../../output/preprocess/Coronary_artery_disease/clinical_data/GSE156357.csv\"\n",
36
+ "json_path = \"../../output/preprocess/Coronary_artery_disease/cohort_info.json\"\n"
37
+ ]
38
+ },
39
+ {
40
+ "cell_type": "markdown",
41
+ "id": "a5b59818",
42
+ "metadata": {},
43
+ "source": [
44
+ "### Step 1: Initial Data Loading"
45
+ ]
46
+ },
47
+ {
48
+ "cell_type": "code",
49
+ "execution_count": 2,
50
+ "id": "ad7f516f",
51
+ "metadata": {
52
+ "execution": {
53
+ "iopub.execute_input": "2025-03-25T08:27:57.653845Z",
54
+ "iopub.status.busy": "2025-03-25T08:27:57.653703Z",
55
+ "iopub.status.idle": "2025-03-25T08:27:57.784715Z",
56
+ "shell.execute_reply": "2025-03-25T08:27:57.784360Z"
57
+ }
58
+ },
59
+ "outputs": [
60
+ {
61
+ "name": "stdout",
62
+ "output_type": "stream",
63
+ "text": [
64
+ "Background Information:\n",
65
+ "!Series_title\t\"Supplementation with Probiotic Lactobacillus plantarum 299v in Men With Stable Coronary Artery Disease Suppresses Systemic Inflammation\"\n",
66
+ "!Series_summary\t\"Recent clinical trials demonstrate the efficacy of treatment strategies to reduce cardiovascular events in patients with coronary artery disease (CAD) that focus in reducing inflammatory signaling. Emerging data implicate the gut microbiota as a critical regulator of systemic inflammation. We recently demonstrated that supplementation with Lactobacillus plantarum 299v (Lp299v) improved vascular endothelial function in men with stable CAD. In this study we investigated whether the favorable effects of Lp299v on vascular health are due in part to coordinated suppression of systemic inflammation. We applied pre- and post-Lp299v supplementation plasma from these patients to peripheral blood mononuclear cells of a healthy donor to determine the transcriptional response to this intervention.\"\n",
67
+ "!Series_overall_design\t\"UPN119 cells were stimulated with plasma samples obtained prior to and immediately following 6 weeks of Lp299v supplementation from 19 men with stable CAD (n=19 PRE, n=19 POST). Gene expression analysis was perfromed in order to evaluate induced overal transcriptome changes as well as inflammatory signature changes associated with post-Lp299v supplementation plasma.\"\n",
68
+ "Sample Characteristics Dictionary:\n",
69
+ "{0: ['responder cells: UPN119 cells'], 1: ['treatment: stimulated with PRE Sub001 plasma', 'treatment: stimulated with POST Sub001 plasma', 'treatment: stimulated with PRE Sub003 plasma', 'treatment: stimulated with POST Sub003 plasma', 'treatment: stimulated with PRE Sub004 plasma', 'treatment: stimulated with POST Sub004 plasma', 'treatment: stimulated with PRE Sub005 plasma', 'treatment: stimulated with POST Sub005 plasma', 'treatment: stimulated with PRE Sub006 plasma', 'treatment: stimulated with POST Sub006 plasma', 'treatment: stimulated with PRE Sub007 plasma', 'treatment: stimulated with POST Sub007 plasma', 'treatment: stimulated with PRE Sub008 plasma', 'treatment: stimulated with POST Sub008 plasma', 'treatment: stimulated with PRE Sub009 plasma', 'treatment: stimulated with POST Sub009 plasma', 'treatment: stimulated with PRE Sub0010 plasma', 'treatment: stimulated with POST Sub0010 plasma', 'treatment: stimulated with PRE Sub0011plasma', 'treatment: stimulated with POST Sub0011 plasma', 'treatment: stimulated with PRE Sub0013 plasma', 'treatment: stimulated with POST Sub0013 plasma', 'treatment: stimulated with PRE Sub0014 plasma', 'treatment: stimulated with POST Sub0014 plasma', 'treatment: stimulated with PRE Sub0016 plasma', 'treatment: stimulated with POST Sub0016 plasma', 'treatment: stimulated with PRE Sub0017 plasma', 'treatment: stimulated with POST Sub0017 plasma', 'treatment: stimulated with PRE Sub0018 plasma', 'treatment: stimulated with POST Sub0018 plasma']}\n"
70
+ ]
71
+ }
72
+ ],
73
+ "source": [
74
+ "from tools.preprocess import *\n",
75
+ "# 1. Identify the paths to the SOFT file and the matrix file\n",
76
+ "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
77
+ "\n",
78
+ "# 2. Read the matrix file to obtain background information and sample characteristics data\n",
79
+ "background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']\n",
80
+ "clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']\n",
81
+ "background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)\n",
82
+ "\n",
83
+ "# 3. Obtain the sample characteristics dictionary from the clinical dataframe\n",
84
+ "sample_characteristics_dict = get_unique_values_by_row(clinical_data)\n",
85
+ "\n",
86
+ "# 4. Explicitly print out all the background information and the sample characteristics dictionary\n",
87
+ "print(\"Background Information:\")\n",
88
+ "print(background_info)\n",
89
+ "print(\"Sample Characteristics Dictionary:\")\n",
90
+ "print(sample_characteristics_dict)\n"
91
+ ]
92
+ },
93
+ {
94
+ "cell_type": "markdown",
95
+ "id": "e6163e0d",
96
+ "metadata": {},
97
+ "source": [
98
+ "### Step 2: Dataset Analysis and Clinical Feature Extraction"
99
+ ]
100
+ },
101
+ {
102
+ "cell_type": "code",
103
+ "execution_count": 3,
104
+ "id": "f8b43482",
105
+ "metadata": {
106
+ "execution": {
107
+ "iopub.execute_input": "2025-03-25T08:27:57.785956Z",
108
+ "iopub.status.busy": "2025-03-25T08:27:57.785844Z",
109
+ "iopub.status.idle": "2025-03-25T08:27:57.793422Z",
110
+ "shell.execute_reply": "2025-03-25T08:27:57.793108Z"
111
+ }
112
+ },
113
+ "outputs": [
114
+ {
115
+ "name": "stdout",
116
+ "output_type": "stream",
117
+ "text": [
118
+ "Preview of selected clinical features:\n",
119
+ "{'GSM4729476': [1.0], 'GSM4729477': [0.0], 'GSM4729478': [1.0], 'GSM4729479': [0.0], 'GSM4729480': [1.0], 'GSM4729481': [0.0], 'GSM4729482': [1.0], 'GSM4729483': [0.0], 'GSM4729484': [1.0], 'GSM4729485': [0.0], 'GSM4729486': [1.0], 'GSM4729487': [0.0], 'GSM4729488': [1.0], 'GSM4729489': [0.0], 'GSM4729490': [1.0], 'GSM4729491': [0.0], 'GSM4729492': [1.0], 'GSM4729493': [0.0], 'GSM4729494': [1.0], 'GSM4729495': [0.0], 'GSM4729496': [1.0], 'GSM4729497': [0.0], 'GSM4729498': [1.0], 'GSM4729499': [0.0], 'GSM4729500': [1.0], 'GSM4729501': [0.0], 'GSM4729502': [1.0], 'GSM4729503': [0.0], 'GSM4729504': [1.0], 'GSM4729505': [0.0], 'GSM4729506': [1.0], 'GSM4729507': [0.0], 'GSM4729508': [1.0], 'GSM4729509': [0.0], 'GSM4729510': [1.0], 'GSM4729511': [0.0], 'GSM4729512': [1.0], 'GSM4729513': [0.0]}\n",
120
+ "Clinical data saved to ../../output/preprocess/Coronary_artery_disease/clinical_data/GSE156357.csv\n"
121
+ ]
122
+ }
123
+ ],
124
+ "source": [
125
+ "# 1. Gene Expression Data Availability\n",
126
+ "# The dataset seems to be gene expression data as the series title and design\n",
127
+ "# indicate transcriptome analysis was performed. It's not purely miRNA or methylation data.\n",
128
+ "is_gene_available = True\n",
129
+ "\n",
130
+ "# 2. Variable Availability and Data Type Conversion\n",
131
+ "# 2.1 Data Availability\n",
132
+ "# For trait (CAD), there's no explicit row but we know all subjects have CAD based on background\n",
133
+ "trait_row = 1 # We'll use the treatment row to extract patient identifiers and assign CAD status\n",
134
+ "\n",
135
+ "# No explicit age information is provided\n",
136
+ "age_row = None\n",
137
+ "\n",
138
+ "# No explicit gender information is provided, though the background indicates all subjects are men\n",
139
+ "gender_row = None\n",
140
+ "\n",
141
+ "# 2.2 Data Type Conversion\n",
142
+ "def convert_trait(value):\n",
143
+ " \"\"\"Convert treatment text to CAD status (binary)\"\"\"\n",
144
+ " if value is None:\n",
145
+ " return None\n",
146
+ " # All participants have CAD according to background info\n",
147
+ " # We'll extract if this is PRE or POST treatment\n",
148
+ " if isinstance(value, str) and \":\" in value:\n",
149
+ " value = value.split(\":\", 1)[1].strip()\n",
150
+ " if \"PRE\" in value:\n",
151
+ " return 1 # CAD patients before treatment\n",
152
+ " elif \"POST\" in value:\n",
153
+ " return 0 # CAD patients after treatment\n",
154
+ " return None\n",
155
+ "\n",
156
+ "def convert_age(value):\n",
157
+ " \"\"\"Convert age value to numeric format\"\"\"\n",
158
+ " # Age data not available\n",
159
+ " return None\n",
160
+ "\n",
161
+ "def convert_gender(value):\n",
162
+ " \"\"\"Convert gender value to binary format (0 for female, 1 for male)\"\"\"\n",
163
+ " # Gender data not available directly, but background says all are men\n",
164
+ " return None\n",
165
+ "\n",
166
+ "# 3. Save Metadata\n",
167
+ "# Initial validation and filtering\n",
168
+ "is_trait_available = trait_row is not None\n",
169
+ "validate_and_save_cohort_info(\n",
170
+ " is_final=False,\n",
171
+ " cohort=cohort,\n",
172
+ " info_path=json_path,\n",
173
+ " is_gene_available=is_gene_available,\n",
174
+ " is_trait_available=is_trait_available\n",
175
+ ")\n",
176
+ "\n",
177
+ "# 4. Clinical Feature Extraction\n",
178
+ "if trait_row is not None:\n",
179
+ " # Extract clinical features\n",
180
+ " selected_clinical_df = geo_select_clinical_features(\n",
181
+ " clinical_df=clinical_data,\n",
182
+ " trait=trait,\n",
183
+ " trait_row=trait_row,\n",
184
+ " convert_trait=convert_trait,\n",
185
+ " age_row=age_row,\n",
186
+ " convert_age=convert_age,\n",
187
+ " gender_row=gender_row,\n",
188
+ " convert_gender=convert_gender\n",
189
+ " )\n",
190
+ " \n",
191
+ " # Preview the extracted clinical data\n",
192
+ " print(\"Preview of selected clinical features:\")\n",
193
+ " preview = preview_df(selected_clinical_df)\n",
194
+ " print(preview)\n",
195
+ " \n",
196
+ " # Save the clinical data\n",
197
+ " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
198
+ " selected_clinical_df.to_csv(out_clinical_data_file, index=False)\n",
199
+ " print(f\"Clinical data saved to {out_clinical_data_file}\")\n"
200
+ ]
201
+ },
202
+ {
203
+ "cell_type": "markdown",
204
+ "id": "216b6437",
205
+ "metadata": {},
206
+ "source": [
207
+ "### Step 3: Gene Data Extraction"
208
+ ]
209
+ },
210
+ {
211
+ "cell_type": "code",
212
+ "execution_count": 4,
213
+ "id": "50ea1731",
214
+ "metadata": {
215
+ "execution": {
216
+ "iopub.execute_input": "2025-03-25T08:27:57.794591Z",
217
+ "iopub.status.busy": "2025-03-25T08:27:57.794480Z",
218
+ "iopub.status.idle": "2025-03-25T08:27:57.975408Z",
219
+ "shell.execute_reply": "2025-03-25T08:27:57.975015Z"
220
+ }
221
+ },
222
+ "outputs": [
223
+ {
224
+ "name": "stdout",
225
+ "output_type": "stream",
226
+ "text": [
227
+ "SOFT file: ../../input/GEO/Coronary_artery_disease/GSE156357/GSE156357_family.soft.gz\n",
228
+ "Matrix file: ../../input/GEO/Coronary_artery_disease/GSE156357/GSE156357_series_matrix.txt.gz\n",
229
+ "Found the matrix table marker at line 71\n",
230
+ "Gene data shape: (54675, 38)\n",
231
+ "First 20 gene/probe identifiers:\n",
232
+ "['1007_s_at', '1053_at', '117_at', '121_at', '1255_g_at', '1294_at', '1316_at', '1320_at', '1405_i_at', '1431_at', '1438_at', '1487_at', '1494_f_at', '1552256_a_at', '1552257_a_at', '1552258_at', '1552261_at', '1552263_at', '1552264_a_at', '1552266_at']\n"
233
+ ]
234
+ }
235
+ ],
236
+ "source": [
237
+ "# 1. Identify the paths to the SOFT file and the matrix file\n",
238
+ "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
239
+ "print(f\"SOFT file: {soft_file}\")\n",
240
+ "print(f\"Matrix file: {matrix_file}\")\n",
241
+ "\n",
242
+ "# Set gene availability flag\n",
243
+ "is_gene_available = True # Initially assume gene data is available\n",
244
+ "\n",
245
+ "# First check if the matrix file contains the expected marker\n",
246
+ "found_marker = False\n",
247
+ "marker_row = None\n",
248
+ "try:\n",
249
+ " with gzip.open(matrix_file, 'rt') as file:\n",
250
+ " for i, line in enumerate(file):\n",
251
+ " if \"!series_matrix_table_begin\" in line:\n",
252
+ " found_marker = True\n",
253
+ " marker_row = i\n",
254
+ " print(f\"Found the matrix table marker at line {i}\")\n",
255
+ " break\n",
256
+ " \n",
257
+ " if not found_marker:\n",
258
+ " print(\"Warning: Could not find '!series_matrix_table_begin' marker in the file.\")\n",
259
+ " is_gene_available = False\n",
260
+ " \n",
261
+ " # If marker was found, try to extract gene data\n",
262
+ " if is_gene_available:\n",
263
+ " try:\n",
264
+ " # Try using the library function\n",
265
+ " gene_data = get_genetic_data(matrix_file)\n",
266
+ " \n",
267
+ " if gene_data.shape[0] == 0:\n",
268
+ " print(\"Warning: Extracted gene data has 0 rows.\")\n",
269
+ " is_gene_available = False\n",
270
+ " else:\n",
271
+ " print(f\"Gene data shape: {gene_data.shape}\")\n",
272
+ " # Print the first 20 gene/probe identifiers\n",
273
+ " print(\"First 20 gene/probe identifiers:\")\n",
274
+ " print(gene_data.index[:20].tolist())\n",
275
+ " except Exception as e:\n",
276
+ " print(f\"Error extracting gene data with get_genetic_data(): {e}\")\n",
277
+ " is_gene_available = False\n",
278
+ " \n",
279
+ " # If gene data extraction failed, examine file content to diagnose\n",
280
+ " if not is_gene_available:\n",
281
+ " print(\"Examining file content to diagnose the issue:\")\n",
282
+ " try:\n",
283
+ " with gzip.open(matrix_file, 'rt') as file:\n",
284
+ " # Print lines around the marker if found\n",
285
+ " if marker_row is not None:\n",
286
+ " for i, line in enumerate(file):\n",
287
+ " if i >= marker_row - 2 and i <= marker_row + 10:\n",
288
+ " print(f\"Line {i}: {line.strip()[:100]}...\")\n",
289
+ " if i > marker_row + 10:\n",
290
+ " break\n",
291
+ " else:\n",
292
+ " # If marker not found, print first 10 lines\n",
293
+ " for i, line in enumerate(file):\n",
294
+ " if i < 10:\n",
295
+ " print(f\"Line {i}: {line.strip()[:100]}...\")\n",
296
+ " else:\n",
297
+ " break\n",
298
+ " except Exception as e2:\n",
299
+ " print(f\"Error examining file: {e2}\")\n",
300
+ " \n",
301
+ "except Exception as e:\n",
302
+ " print(f\"Error processing file: {e}\")\n",
303
+ " is_gene_available = False\n",
304
+ "\n",
305
+ "# Update validation information if gene data extraction failed\n",
306
+ "if not is_gene_available:\n",
307
+ " print(\"Gene expression data could not be successfully extracted from this dataset.\")\n",
308
+ " # Update the validation record since gene data isn't available\n",
309
+ " is_trait_available = False # We already determined trait data isn't available in step 2\n",
310
+ " validate_and_save_cohort_info(is_final=False, cohort=cohort, info_path=json_path,\n",
311
+ " is_gene_available=is_gene_available, is_trait_available=is_trait_available)\n"
312
+ ]
313
+ },
314
+ {
315
+ "cell_type": "markdown",
316
+ "id": "f8de9bdb",
317
+ "metadata": {},
318
+ "source": [
319
+ "### Step 4: Gene Identifier Review"
320
+ ]
321
+ },
322
+ {
323
+ "cell_type": "code",
324
+ "execution_count": 5,
325
+ "id": "97bc1ad0",
326
+ "metadata": {
327
+ "execution": {
328
+ "iopub.execute_input": "2025-03-25T08:27:57.976755Z",
329
+ "iopub.status.busy": "2025-03-25T08:27:57.976630Z",
330
+ "iopub.status.idle": "2025-03-25T08:27:57.978600Z",
331
+ "shell.execute_reply": "2025-03-25T08:27:57.978312Z"
332
+ }
333
+ },
334
+ "outputs": [],
335
+ "source": [
336
+ "# The gene identifiers shown in the previous output appear to be Affymetrix probe IDs\n",
337
+ "# (like \"1007_s_at\", \"1053_at\", etc.), not standard human gene symbols.\n",
338
+ "# These are microarray probe identifiers that need to be mapped to actual gene symbols\n",
339
+ "# for biological interpretation.\n",
340
+ "\n",
341
+ "requires_gene_mapping = True\n"
342
+ ]
343
+ },
344
+ {
345
+ "cell_type": "markdown",
346
+ "id": "ea3ae436",
347
+ "metadata": {},
348
+ "source": [
349
+ "### Step 5: Gene Annotation"
350
+ ]
351
+ },
352
+ {
353
+ "cell_type": "code",
354
+ "execution_count": 6,
355
+ "id": "323746ef",
356
+ "metadata": {
357
+ "execution": {
358
+ "iopub.execute_input": "2025-03-25T08:27:57.979741Z",
359
+ "iopub.status.busy": "2025-03-25T08:27:57.979634Z",
360
+ "iopub.status.idle": "2025-03-25T08:28:01.454775Z",
361
+ "shell.execute_reply": "2025-03-25T08:28:01.454372Z"
362
+ }
363
+ },
364
+ "outputs": [
365
+ {
366
+ "name": "stdout",
367
+ "output_type": "stream",
368
+ "text": [
369
+ "\n",
370
+ "Gene annotation preview:\n",
371
+ "Columns in gene annotation: ['ID', 'GB_ACC', 'SPOT_ID', 'Species Scientific Name', 'Annotation Date', 'Sequence Type', 'Sequence Source', 'Target Description', 'Representative Public ID', 'Gene Title', 'Gene Symbol', 'ENTREZ_GENE_ID', 'RefSeq Transcript ID', 'Gene Ontology Biological Process', 'Gene Ontology Cellular Component', 'Gene Ontology Molecular Function']\n",
372
+ "{'ID': ['1007_s_at', '1053_at', '117_at'], 'GB_ACC': ['U48705', 'M87338', 'X51757'], 'SPOT_ID': [nan, nan, nan], 'Species Scientific Name': ['Homo sapiens', 'Homo sapiens', 'Homo sapiens'], 'Annotation Date': ['Oct 6, 2014', 'Oct 6, 2014', 'Oct 6, 2014'], 'Sequence Type': ['Exemplar sequence', 'Exemplar sequence', 'Exemplar sequence'], 'Sequence Source': ['Affymetrix Proprietary Database', 'GenBank', 'Affymetrix Proprietary Database'], 'Target Description': ['U48705 /FEATURE=mRNA /DEFINITION=HSU48705 Human receptor tyrosine kinase DDR gene, complete cds', 'M87338 /FEATURE= /DEFINITION=HUMA1SBU Human replication factor C, 40-kDa subunit (A1) mRNA, complete cds', \"X51757 /FEATURE=cds /DEFINITION=HSP70B Human heat-shock protein HSP70B' gene\"], 'Representative Public ID': ['U48705', 'M87338', 'X51757'], 'Gene Title': ['discoidin domain receptor tyrosine kinase 1 /// microRNA 4640', 'replication factor C (activator 1) 2, 40kDa', \"heat shock 70kDa protein 6 (HSP70B')\"], 'Gene Symbol': ['DDR1 /// MIR4640', 'RFC2', 'HSPA6'], 'ENTREZ_GENE_ID': ['780 /// 100616237', '5982', '3310'], 'RefSeq Transcript ID': ['NM_001202521 /// NM_001202522 /// NM_001202523 /// NM_001954 /// NM_013993 /// NM_013994 /// NR_039783 /// XM_005249385 /// XM_005249386 /// XM_005249387 /// XM_005249389 /// XM_005272873 /// XM_005272874 /// XM_005272875 /// XM_005272877 /// XM_005275027 /// XM_005275028 /// XM_005275030 /// XM_005275031 /// XM_005275162 /// XM_005275163 /// XM_005275164 /// XM_005275166 /// XM_005275457 /// XM_005275458 /// XM_005275459 /// XM_005275461 /// XM_006715185 /// XM_006715186 /// XM_006715187 /// XM_006715188 /// XM_006715189 /// XM_006715190 /// XM_006725501 /// XM_006725502 /// XM_006725503 /// XM_006725504 /// XM_006725505 /// XM_006725506 /// XM_006725714 /// XM_006725715 /// XM_006725716 /// XM_006725717 /// XM_006725718 /// XM_006725719 /// XM_006725720 /// XM_006725721 /// XM_006725722 /// XM_006725827 /// XM_006725828 /// XM_006725829 /// XM_006725830 /// XM_006725831 /// XM_006725832 /// XM_006726017 /// XM_006726018 /// XM_006726019 /// XM_006726020 /// XM_006726021 /// XM_006726022 /// XR_427836 /// XR_430858 /// XR_430938 /// XR_430974 /// XR_431015', 'NM_001278791 /// NM_001278792 /// NM_001278793 /// NM_002914 /// NM_181471 /// XM_006716080', 'NM_002155'], 'Gene Ontology Biological Process': ['0001558 // regulation of cell growth // inferred from electronic annotation /// 0001952 // regulation of cell-matrix adhesion // inferred from electronic annotation /// 0006468 // protein phosphorylation // inferred from electronic annotation /// 0007155 // cell adhesion // traceable author statement /// 0007169 // transmembrane receptor protein tyrosine kinase signaling pathway // inferred from electronic annotation /// 0007565 // female pregnancy // inferred from electronic annotation /// 0007566 // embryo implantation // inferred from electronic annotation /// 0007595 // lactation // inferred from electronic annotation /// 0008285 // negative regulation of cell proliferation // inferred from electronic annotation /// 0010715 // regulation of extracellular matrix disassembly // inferred from mutant phenotype /// 0014909 // smooth muscle cell migration // inferred from mutant phenotype /// 0016310 // phosphorylation // inferred from electronic annotation /// 0018108 // peptidyl-tyrosine phosphorylation // inferred from electronic annotation /// 0030198 // extracellular matrix organization // traceable author statement /// 0038063 // collagen-activated tyrosine kinase receptor signaling pathway // inferred from direct assay /// 0038063 // collagen-activated tyrosine kinase receptor signaling pathway // inferred from mutant phenotype /// 0038083 // peptidyl-tyrosine autophosphorylation // inferred from direct assay /// 0043583 // ear development // inferred from electronic annotation /// 0044319 // wound healing, spreading of cells // inferred from mutant phenotype /// 0046777 // protein autophosphorylation // inferred from direct assay /// 0060444 // branching involved in mammary gland duct morphogenesis // inferred from electronic annotation /// 0060749 // mammary gland alveolus development // inferred from electronic annotation /// 0061302 // smooth muscle cell-matrix adhesion // inferred from mutant phenotype', '0000278 // mitotic cell cycle // traceable author statement /// 0000722 // telomere maintenance via recombination // traceable author statement /// 0000723 // telomere maintenance // traceable author statement /// 0006260 // DNA replication // traceable author statement /// 0006271 // DNA strand elongation involved in DNA replication // traceable author statement /// 0006281 // DNA repair // traceable author statement /// 0006283 // transcription-coupled nucleotide-excision repair // traceable author statement /// 0006289 // nucleotide-excision repair // traceable author statement /// 0006297 // nucleotide-excision repair, DNA gap filling // traceable author statement /// 0015979 // photosynthesis // inferred from electronic annotation /// 0015995 // chlorophyll biosynthetic process // inferred from electronic annotation /// 0032201 // telomere maintenance via semi-conservative replication // traceable author statement', '0000902 // cell morphogenesis // inferred from electronic annotation /// 0006200 // ATP catabolic process // inferred from direct assay /// 0006950 // response to stress // inferred from electronic annotation /// 0006986 // response to unfolded protein // traceable author statement /// 0034605 // cellular response to heat // inferred from direct assay /// 0042026 // protein refolding // inferred from direct assay /// 0070370 // cellular heat acclimation // inferred from mutant phenotype'], 'Gene Ontology Cellular Component': ['0005576 // extracellular region // inferred from electronic annotation /// 0005615 // extracellular space // inferred from direct assay /// 0005886 // plasma membrane // traceable author statement /// 0005887 // integral component of plasma membrane // traceable author statement /// 0016020 // membrane // inferred from electronic annotation /// 0016021 // integral component of membrane // inferred from electronic annotation /// 0043235 // receptor complex // inferred from direct assay /// 0070062 // extracellular vesicular exosome // inferred from direct assay', '0005634 // nucleus // inferred from electronic annotation /// 0005654 // nucleoplasm // traceable author statement /// 0005663 // DNA replication factor C complex // inferred from direct assay', '0005737 // cytoplasm // inferred from direct assay /// 0005814 // centriole // inferred from direct assay /// 0005829 // cytosol // inferred from direct assay /// 0008180 // COP9 signalosome // inferred from direct assay /// 0070062 // extracellular vesicular exosome // inferred from direct assay /// 0072562 // blood microparticle // inferred from direct assay'], 'Gene Ontology Molecular Function': ['0000166 // nucleotide binding // inferred from electronic annotation /// 0004672 // protein kinase activity // inferred from electronic annotation /// 0004713 // protein tyrosine kinase activity // inferred from electronic annotation /// 0004714 // transmembrane receptor protein tyrosine kinase activity // traceable author statement /// 0005515 // protein binding // inferred from physical interaction /// 0005518 // collagen binding // inferred from direct assay /// 0005518 // collagen binding // inferred from mutant phenotype /// 0005524 // ATP binding // inferred from electronic annotation /// 0016301 // kinase activity // inferred from electronic annotation /// 0016740 // transferase activity // inferred from electronic annotation /// 0016772 // transferase activity, transferring phosphorus-containing groups // inferred from electronic annotation /// 0038062 // protein tyrosine kinase collagen receptor activity // inferred from direct assay /// 0046872 // metal ion binding // inferred from electronic annotation', '0000166 // nucleotide binding // inferred from electronic annotation /// 0003677 // DNA binding // inferred from electronic annotation /// 0005515 // protein binding // inferred from physical interaction /// 0005524 // ATP binding // inferred from electronic annotation /// 0016851 // magnesium chelatase activity // inferred from electronic annotation /// 0017111 // nucleoside-triphosphatase activity // inferred from electronic annotation', '0000166 // nucleotide binding // inferred from electronic annotation /// 0005524 // ATP binding // inferred from electronic annotation /// 0019899 // enzyme binding // inferred from physical interaction /// 0031072 // heat shock protein binding // inferred from physical interaction /// 0042623 // ATPase activity, coupled // inferred from direct assay /// 0051082 // unfolded protein binding // inferred from direct assay']}\n",
373
+ "\n",
374
+ "Examining mapping information (first 5 rows):\n",
375
+ "Row 0: ID=1007_s_at, Gene Symbol=DDR1 /// MIR4640\n",
376
+ "Row 1: ID=1053_at, Gene Symbol=RFC2\n",
377
+ "Row 2: ID=117_at, Gene Symbol=HSPA6\n",
378
+ "Row 3: ID=121_at, Gene Symbol=PAX8\n",
379
+ "Row 4: ID=1255_g_at, Gene Symbol=GUCA1A\n",
380
+ "\n",
381
+ "Gene Symbol column completeness: 45782/2132363 rows (2.15%)\n",
382
+ "\n",
383
+ "Columns identified for gene mapping:\n",
384
+ "- 'ID': Contains probe IDs (e.g., 1007_s_at)\n",
385
+ "- 'Gene Symbol': Contains gene symbols (e.g., DDR1 /// MIR4640)\n"
386
+ ]
387
+ }
388
+ ],
389
+ "source": [
390
+ "# 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.\n",
391
+ "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
392
+ "gene_annotation = get_gene_annotation(soft_file)\n",
393
+ "\n",
394
+ "# 2. Analyze the gene annotation dataframe to identify which columns contain the gene identifiers and gene symbols\n",
395
+ "print(\"\\nGene annotation preview:\")\n",
396
+ "print(f\"Columns in gene annotation: {gene_annotation.columns.tolist()}\")\n",
397
+ "print(preview_df(gene_annotation, n=3))\n",
398
+ "\n",
399
+ "# Examine the ID and Gene Symbol columns that appear to contain the mapping information\n",
400
+ "print(\"\\nExamining mapping information (first 5 rows):\")\n",
401
+ "if 'ID' in gene_annotation.columns and 'Gene Symbol' in gene_annotation.columns:\n",
402
+ " for i in range(min(5, len(gene_annotation))):\n",
403
+ " print(f\"Row {i}: ID={gene_annotation['ID'].iloc[i]}, Gene Symbol={gene_annotation['Gene Symbol'].iloc[i]}\")\n",
404
+ " \n",
405
+ " # Check the quality and completeness of the mapping\n",
406
+ " non_null_symbols = gene_annotation['Gene Symbol'].notna().sum()\n",
407
+ " total_rows = len(gene_annotation)\n",
408
+ " print(f\"\\nGene Symbol column completeness: {non_null_symbols}/{total_rows} rows ({non_null_symbols/total_rows:.2%})\")\n",
409
+ " \n",
410
+ " # Identify the columns needed for gene mapping\n",
411
+ " print(\"\\nColumns identified for gene mapping:\")\n",
412
+ " print(\"- 'ID': Contains probe IDs (e.g., 1007_s_at)\")\n",
413
+ " print(\"- 'Gene Symbol': Contains gene symbols (e.g., DDR1 /// MIR4640)\")\n",
414
+ "else:\n",
415
+ " print(\"Error: Required mapping columns ('ID' and/or 'Gene Symbol') not found in annotation data.\")\n",
416
+ " print(\"Available columns:\", gene_annotation.columns.tolist())\n"
417
+ ]
418
+ },
419
+ {
420
+ "cell_type": "markdown",
421
+ "id": "ae4f00a5",
422
+ "metadata": {},
423
+ "source": [
424
+ "### Step 6: Gene Identifier Mapping"
425
+ ]
426
+ },
427
+ {
428
+ "cell_type": "code",
429
+ "execution_count": 7,
430
+ "id": "4c8a712c",
431
+ "metadata": {
432
+ "execution": {
433
+ "iopub.execute_input": "2025-03-25T08:28:01.456195Z",
434
+ "iopub.status.busy": "2025-03-25T08:28:01.456063Z",
435
+ "iopub.status.idle": "2025-03-25T08:28:01.839142Z",
436
+ "shell.execute_reply": "2025-03-25T08:28:01.838789Z"
437
+ }
438
+ },
439
+ "outputs": [
440
+ {
441
+ "name": "stdout",
442
+ "output_type": "stream",
443
+ "text": [
444
+ "Gene mapping dataframe created with shape: (45782, 2)\n",
445
+ "First 5 rows of gene mapping:\n",
446
+ " ID Gene\n",
447
+ "0 1007_s_at DDR1 /// MIR4640\n",
448
+ "1 1053_at RFC2\n",
449
+ "2 117_at HSPA6\n",
450
+ "3 121_at PAX8\n",
451
+ "4 1255_g_at GUCA1A\n"
452
+ ]
453
+ },
454
+ {
455
+ "name": "stdout",
456
+ "output_type": "stream",
457
+ "text": [
458
+ "Original gene expression data shape: (54675, 38)\n"
459
+ ]
460
+ },
461
+ {
462
+ "name": "stdout",
463
+ "output_type": "stream",
464
+ "text": [
465
+ "Gene expression data after mapping: (21278, 38)\n",
466
+ "First 10 genes and their expression values:\n",
467
+ " GSM4729476 GSM4729477 GSM4729478 GSM4729479 GSM4729480 \\\n",
468
+ "Gene \n",
469
+ "A1BG 4.64853 5.00640 5.12824 4.74476 4.74095 \n",
470
+ "A1BG-AS1 3.57276 3.59143 3.71808 3.17932 2.85107 \n",
471
+ "A1CF 6.65677 6.98451 7.18984 6.96510 7.10847 \n",
472
+ "A2M 7.03923 6.91868 6.84097 6.69868 8.12533 \n",
473
+ "A2M-AS1 7.49411 6.40790 6.19496 7.09980 5.83301 \n",
474
+ "A2ML1 5.09101 5.89952 6.04903 5.14808 5.42730 \n",
475
+ "A2MP1 3.50384 3.96831 4.30658 3.37655 3.83151 \n",
476
+ "A4GALT 3.61928 3.91700 4.24931 4.51080 4.28586 \n",
477
+ "A4GNT 3.59239 3.70216 3.78352 3.44427 3.99832 \n",
478
+ "AA06 2.67766 2.93053 3.37049 3.06110 3.04772 \n",
479
+ "\n",
480
+ " GSM4729481 GSM4729482 GSM4729483 GSM4729484 GSM4729485 ... \\\n",
481
+ "Gene ... \n",
482
+ "A1BG 4.93362 4.82868 4.42357 4.78422 5.07834 ... \n",
483
+ "A1BG-AS1 3.49136 3.54330 3.59890 3.46317 3.70472 ... \n",
484
+ "A1CF 6.72796 6.51640 7.46115 6.63590 6.68935 ... \n",
485
+ "A2M 7.34528 7.85745 8.35682 8.00629 7.50767 ... \n",
486
+ "A2M-AS1 6.42521 6.15316 5.49621 6.30978 6.22456 ... \n",
487
+ "A2ML1 5.31184 5.30924 5.67836 5.49467 5.17507 ... \n",
488
+ "A2MP1 3.93461 3.74364 3.91249 3.74330 3.77380 ... \n",
489
+ "A4GALT 3.95639 3.75574 3.84924 3.89135 4.07532 ... \n",
490
+ "A4GNT 3.43500 3.42852 4.01156 3.58249 3.81886 ... \n",
491
+ "AA06 2.82879 2.71176 3.20588 3.05561 2.85062 ... \n",
492
+ "\n",
493
+ " GSM4729504 GSM4729505 GSM4729506 GSM4729507 GSM4729508 \\\n",
494
+ "Gene \n",
495
+ "A1BG 4.93685 4.77093 4.76665 4.64291 4.51300 \n",
496
+ "A1BG-AS1 3.45748 3.29467 3.49795 3.48070 3.59143 \n",
497
+ "A1CF 6.37768 6.47071 6.44465 6.25206 6.10176 \n",
498
+ "A2M 7.29573 6.17568 7.35081 7.06128 6.87083 \n",
499
+ "A2M-AS1 6.99585 7.02066 6.54858 6.75832 7.52206 \n",
500
+ "A2ML1 4.90858 4.97065 5.77661 5.18340 5.42575 \n",
501
+ "A2MP1 3.42852 2.97025 3.27521 3.18905 3.29670 \n",
502
+ "A4GALT 3.75110 3.41150 4.20059 3.87713 3.34746 \n",
503
+ "A4GNT 3.31763 3.37850 3.64093 3.43836 3.26837 \n",
504
+ "AA06 2.65670 2.53124 2.80016 2.68908 2.91728 \n",
505
+ "\n",
506
+ " GSM4729509 GSM4729510 GSM4729511 GSM4729512 GSM4729513 \n",
507
+ "Gene \n",
508
+ "A1BG 4.45508 4.78711 4.56902 4.99555 4.78431 \n",
509
+ "A1BG-AS1 3.42089 3.35914 3.40349 3.33315 3.70338 \n",
510
+ "A1CF 6.09612 6.80185 6.60032 6.84296 6.10580 \n",
511
+ "A2M 6.99747 7.94587 7.55155 7.40392 7.43523 \n",
512
+ "A2M-AS1 7.26412 6.51689 6.27537 5.93217 6.51181 \n",
513
+ "A2ML1 5.42112 5.30776 5.71922 5.28647 5.62669 \n",
514
+ "A2MP1 3.68265 4.47624 3.46862 3.79801 3.59475 \n",
515
+ "A4GALT 3.71044 3.59015 3.68427 3.91845 3.85687 \n",
516
+ "A4GNT 3.31837 3.81603 3.82565 3.64933 3.87848 \n",
517
+ "AA06 3.18539 2.90285 3.31876 2.93411 2.97204 \n",
518
+ "\n",
519
+ "[10 rows x 38 columns]\n",
520
+ "Total number of genes after mapping: 21278\n"
521
+ ]
522
+ }
523
+ ],
524
+ "source": [
525
+ "# 1. Identify which columns contain probe IDs and gene symbols\n",
526
+ "probe_id_col = 'ID'\n",
527
+ "gene_symbol_col = 'Gene Symbol'\n",
528
+ "\n",
529
+ "# 2. Create the gene mapping dataframe using the get_gene_mapping function\n",
530
+ "gene_mapping = get_gene_mapping(gene_annotation, probe_id_col, gene_symbol_col)\n",
531
+ "\n",
532
+ "print(f\"Gene mapping dataframe created with shape: {gene_mapping.shape}\")\n",
533
+ "print(\"First 5 rows of gene mapping:\")\n",
534
+ "print(gene_mapping.head())\n",
535
+ "\n",
536
+ "# 3. Apply the gene mapping to convert probe-level measurements to gene expression\n",
537
+ "# First get the gene expression data from the matrix file\n",
538
+ "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
539
+ "gene_expression = get_genetic_data(matrix_file)\n",
540
+ "\n",
541
+ "print(f\"Original gene expression data shape: {gene_expression.shape}\")\n",
542
+ "\n",
543
+ "# Apply the gene mapping to convert probe-level data to gene-level data\n",
544
+ "gene_data = apply_gene_mapping(gene_expression, gene_mapping)\n",
545
+ "\n",
546
+ "print(f\"Gene expression data after mapping: {gene_data.shape}\")\n",
547
+ "print(\"First 10 genes and their expression values:\")\n",
548
+ "print(gene_data.head(10))\n",
549
+ "\n",
550
+ "# Check how many genes we have after mapping\n",
551
+ "print(f\"Total number of genes after mapping: {len(gene_data)}\")\n"
552
+ ]
553
+ },
554
+ {
555
+ "cell_type": "markdown",
556
+ "id": "499267df",
557
+ "metadata": {},
558
+ "source": [
559
+ "### Step 7: Data Normalization and Linking"
560
+ ]
561
+ },
562
+ {
563
+ "cell_type": "code",
564
+ "execution_count": 8,
565
+ "id": "fdde45c5",
566
+ "metadata": {
567
+ "execution": {
568
+ "iopub.execute_input": "2025-03-25T08:28:01.841145Z",
569
+ "iopub.status.busy": "2025-03-25T08:28:01.840994Z",
570
+ "iopub.status.idle": "2025-03-25T08:28:11.082777Z",
571
+ "shell.execute_reply": "2025-03-25T08:28:11.082441Z"
572
+ }
573
+ },
574
+ "outputs": [
575
+ {
576
+ "name": "stdout",
577
+ "output_type": "stream",
578
+ "text": [
579
+ "Gene data shape before normalization: (21278, 38)\n"
580
+ ]
581
+ },
582
+ {
583
+ "name": "stdout",
584
+ "output_type": "stream",
585
+ "text": [
586
+ "Gene data shape after normalization: (19845, 38)\n"
587
+ ]
588
+ },
589
+ {
590
+ "name": "stdout",
591
+ "output_type": "stream",
592
+ "text": [
593
+ "Normalized gene data saved to ../../output/preprocess/Coronary_artery_disease/gene_data/GSE156357.csv\n",
594
+ "Loaded clinical data shape: (1, 38)\n",
595
+ "Clinical data columns: ['GSM4729476', 'GSM4729477', 'GSM4729478', 'GSM4729479', 'GSM4729480', 'GSM4729481', 'GSM4729482', 'GSM4729483', 'GSM4729484', 'GSM4729485', 'GSM4729486', 'GSM4729487', 'GSM4729488', 'GSM4729489', 'GSM4729490', 'GSM4729491', 'GSM4729492', 'GSM4729493', 'GSM4729494', 'GSM4729495', 'GSM4729496', 'GSM4729497', 'GSM4729498', 'GSM4729499', 'GSM4729500', 'GSM4729501', 'GSM4729502', 'GSM4729503', 'GSM4729504', 'GSM4729505', 'GSM4729506', 'GSM4729507', 'GSM4729508', 'GSM4729509', 'GSM4729510', 'GSM4729511', 'GSM4729512', 'GSM4729513']\n",
596
+ "Initial linked data shape: (38, 19846)\n",
597
+ "Linked data columns (first 5): [0, 'A1BG', 'A1BG-AS1', 'A1CF', 'A2M']\n",
598
+ "Using first column as trait: 0\n"
599
+ ]
600
+ },
601
+ {
602
+ "name": "stdout",
603
+ "output_type": "stream",
604
+ "text": [
605
+ "Linked data shape after handling missing values: (38, 19846)\n",
606
+ "For the feature '0', the least common label is '1.0' with 19 occurrences. This represents 50.00% of the dataset.\n",
607
+ "The distribution of the feature '0' in this dataset is fine.\n",
608
+ "\n"
609
+ ]
610
+ },
611
+ {
612
+ "name": "stdout",
613
+ "output_type": "stream",
614
+ "text": [
615
+ "Linked data saved to ../../output/preprocess/Coronary_artery_disease/GSE156357.csv\n"
616
+ ]
617
+ }
618
+ ],
619
+ "source": [
620
+ "# 1. Normalize gene symbols in the gene expression data\n",
621
+ "try:\n",
622
+ " # Create output directory if it doesn't exist\n",
623
+ " os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
624
+ " \n",
625
+ " # Check if gene_data (from previous step) has any content\n",
626
+ " if gene_data.shape[0] == 0:\n",
627
+ " print(\"WARNING: Gene data is empty after mapping in previous step.\")\n",
628
+ " \n",
629
+ " # Since gene_data is empty, set gene_available to False\n",
630
+ " is_gene_available = False\n",
631
+ " \n",
632
+ " # Create an empty dataframe for metadata purposes\n",
633
+ " empty_df = pd.DataFrame()\n",
634
+ " \n",
635
+ " # Log information about this dataset for future reference\n",
636
+ " validate_and_save_cohort_info(\n",
637
+ " is_final=True,\n",
638
+ " cohort=cohort,\n",
639
+ " info_path=json_path,\n",
640
+ " is_gene_available=is_gene_available,\n",
641
+ " is_trait_available=True, # We determined trait data is available in step 2\n",
642
+ " is_biased=True, # Consider it biased as we can't use it\n",
643
+ " df=empty_df,\n",
644
+ " note=\"Gene symbols could not be mapped properly. No valid gene expression data available.\"\n",
645
+ " )\n",
646
+ " \n",
647
+ " print(\"Dataset marked as unusable due to lack of valid gene expression data.\")\n",
648
+ " else:\n",
649
+ " # If gene_data is not empty, proceed with normalization and linking\n",
650
+ " print(f\"Gene data shape before normalization: {gene_data.shape}\")\n",
651
+ " \n",
652
+ " # Normalize gene symbols using NCBI Gene database\n",
653
+ " normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n",
654
+ " print(f\"Gene data shape after normalization: {normalized_gene_data.shape}\")\n",
655
+ " \n",
656
+ " # Save the normalized gene data\n",
657
+ " normalized_gene_data.to_csv(out_gene_data_file)\n",
658
+ " print(f\"Normalized gene data saved to {out_gene_data_file}\")\n",
659
+ " \n",
660
+ " # Attempt to link clinical and gene data\n",
661
+ " # Load clinical data\n",
662
+ " clinical_features = pd.read_csv(out_clinical_data_file)\n",
663
+ " print(f\"Loaded clinical data shape: {clinical_features.shape}\")\n",
664
+ " print(f\"Clinical data columns: {clinical_features.columns.tolist()}\")\n",
665
+ " \n",
666
+ " # Convert the index column to actual index if needed\n",
667
+ " if 'Unnamed: 0' in clinical_features.columns:\n",
668
+ " clinical_features.set_index('Unnamed: 0', inplace=True)\n",
669
+ " \n",
670
+ " # Link the clinical and genetic data\n",
671
+ " linked_data = geo_link_clinical_genetic_data(clinical_features, normalized_gene_data)\n",
672
+ " print(f\"Initial linked data shape: {linked_data.shape}\")\n",
673
+ " print(f\"Linked data columns (first 5): {linked_data.columns[:5].tolist()}\")\n",
674
+ " \n",
675
+ " # Check which columns are available for the trait\n",
676
+ " if trait in linked_data.columns:\n",
677
+ " trait_column = trait\n",
678
+ " else:\n",
679
+ " # If trait name isn't a column, check if the first column is the trait\n",
680
+ " # (based on how geo_select_clinical_features returns data)\n",
681
+ " first_col = linked_data.columns[0]\n",
682
+ " print(f\"Using first column as trait: {first_col}\")\n",
683
+ " trait_column = first_col\n",
684
+ " \n",
685
+ " # Handle missing values with the correct trait column\n",
686
+ " linked_data = handle_missing_values(linked_data, trait_column)\n",
687
+ " print(f\"Linked data shape after handling missing values: {linked_data.shape}\")\n",
688
+ " \n",
689
+ " if linked_data.shape[0] > 0:\n",
690
+ " # Check for bias in trait and demographic features\n",
691
+ " # Implement judge_and_remove_biased_features function\n",
692
+ " def judge_and_remove_biased_features(df, trait_col):\n",
693
+ " \"\"\"Evaluate and remove biased features from the dataset.\"\"\"\n",
694
+ " trait_type = 'binary' if len(df[trait_col].unique()) <= 2 else 'continuous'\n",
695
+ " if trait_type == \"binary\":\n",
696
+ " trait_biased = judge_binary_variable_biased(df, trait_col)\n",
697
+ " else:\n",
698
+ " trait_biased = judge_continuous_variable_biased(df, trait_col)\n",
699
+ " \n",
700
+ " if trait_biased:\n",
701
+ " print(f\"The distribution of the feature \\'{trait_col}\\' in this dataset is severely biased.\\n\")\n",
702
+ " else:\n",
703
+ " print(f\"The distribution of the feature \\'{trait_col}\\' in this dataset is fine.\\n\")\n",
704
+ " \n",
705
+ " # Check age if present\n",
706
+ " if \"Age\" in df.columns:\n",
707
+ " age_biased = judge_continuous_variable_biased(df, 'Age')\n",
708
+ " if age_biased:\n",
709
+ " print(f\"The distribution of the feature \\'Age\\' in this dataset is severely biased.\\n\")\n",
710
+ " df = df.drop(columns='Age')\n",
711
+ " else:\n",
712
+ " print(f\"The distribution of the feature \\'Age\\' in this dataset is fine.\\n\")\n",
713
+ " \n",
714
+ " # Check gender if present\n",
715
+ " if \"Gender\" in df.columns:\n",
716
+ " gender_biased = judge_binary_variable_biased(df, 'Gender')\n",
717
+ " if gender_biased:\n",
718
+ " print(f\"The distribution of the feature \\'Gender\\' in this dataset is severely biased.\\n\")\n",
719
+ " df = df.drop(columns='Gender')\n",
720
+ " else:\n",
721
+ " print(f\"The distribution of the feature \\'Gender\\' in this dataset is fine.\\n\")\n",
722
+ " \n",
723
+ " return trait_biased, df\n",
724
+ " \n",
725
+ " is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait_column)\n",
726
+ " \n",
727
+ " # Validate data quality and save cohort info\n",
728
+ " is_usable = validate_and_save_cohort_info(\n",
729
+ " is_final=True,\n",
730
+ " cohort=cohort,\n",
731
+ " info_path=json_path,\n",
732
+ " is_gene_available=True,\n",
733
+ " is_trait_available=True,\n",
734
+ " is_biased=is_biased,\n",
735
+ " df=linked_data,\n",
736
+ " note=\"Successfully processed gene expression data for coronary artery disease.\"\n",
737
+ " )\n",
738
+ " \n",
739
+ " # Save the linked data if it's usable\n",
740
+ " if is_usable:\n",
741
+ " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n",
742
+ " linked_data.to_csv(out_data_file)\n",
743
+ " print(f\"Linked data saved to {out_data_file}\")\n",
744
+ " else:\n",
745
+ " print(\"Data not usable for trait study - not saving final linked data.\")\n",
746
+ " else:\n",
747
+ " print(\"After handling missing values, no samples remain.\")\n",
748
+ " validate_and_save_cohort_info(\n",
749
+ " is_final=True,\n",
750
+ " cohort=cohort,\n",
751
+ " info_path=json_path,\n",
752
+ " is_gene_available=True,\n",
753
+ " is_trait_available=True,\n",
754
+ " is_biased=True,\n",
755
+ " df=pd.DataFrame(),\n",
756
+ " note=\"No valid samples after handling missing values.\"\n",
757
+ " )\n",
758
+ "except Exception as e:\n",
759
+ " import traceback\n",
760
+ " print(f\"Error in data processing: {e}\")\n",
761
+ " print(traceback.format_exc())\n",
762
+ " \n",
763
+ " # Log the error and mark the dataset as unusable\n",
764
+ " validate_and_save_cohort_info(\n",
765
+ " is_final=True,\n",
766
+ " cohort=cohort,\n",
767
+ " info_path=json_path,\n",
768
+ " is_gene_available=False, # Consider gene data unavailable if we had an error\n",
769
+ " is_trait_available=True,\n",
770
+ " is_biased=True, # Consider it biased as we can't use it\n",
771
+ " df=pd.DataFrame(), # Empty dataframe for metadata\n",
772
+ " note=f\"Error during normalization or linking: {str(e)}\"\n",
773
+ " )"
774
+ ]
775
+ }
776
+ ],
777
+ "metadata": {
778
+ "language_info": {
779
+ "codemirror_mode": {
780
+ "name": "ipython",
781
+ "version": 3
782
+ },
783
+ "file_extension": ".py",
784
+ "mimetype": "text/x-python",
785
+ "name": "python",
786
+ "nbconvert_exporter": "python",
787
+ "pygments_lexer": "ipython3",
788
+ "version": "3.10.16"
789
+ }
790
+ },
791
+ "nbformat": 4,
792
+ "nbformat_minor": 5
793
+ }
code/Coronary_artery_disease/GSE234398.ipynb ADDED
@@ -0,0 +1,704 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": 1,
6
+ "id": "0230e186",
7
+ "metadata": {
8
+ "execution": {
9
+ "iopub.execute_input": "2025-03-25T08:28:11.946552Z",
10
+ "iopub.status.busy": "2025-03-25T08:28:11.946340Z",
11
+ "iopub.status.idle": "2025-03-25T08:28:12.105585Z",
12
+ "shell.execute_reply": "2025-03-25T08:28:12.105277Z"
13
+ }
14
+ },
15
+ "outputs": [],
16
+ "source": [
17
+ "import sys\n",
18
+ "import os\n",
19
+ "sys.path.append(os.path.abspath(os.path.join(os.getcwd(), '../..')))\n",
20
+ "\n",
21
+ "# Path Configuration\n",
22
+ "from tools.preprocess import *\n",
23
+ "\n",
24
+ "# Processing context\n",
25
+ "trait = \"Coronary_artery_disease\"\n",
26
+ "cohort = \"GSE234398\"\n",
27
+ "\n",
28
+ "# Input paths\n",
29
+ "in_trait_dir = \"../../input/GEO/Coronary_artery_disease\"\n",
30
+ "in_cohort_dir = \"../../input/GEO/Coronary_artery_disease/GSE234398\"\n",
31
+ "\n",
32
+ "# Output paths\n",
33
+ "out_data_file = \"../../output/preprocess/Coronary_artery_disease/GSE234398.csv\"\n",
34
+ "out_gene_data_file = \"../../output/preprocess/Coronary_artery_disease/gene_data/GSE234398.csv\"\n",
35
+ "out_clinical_data_file = \"../../output/preprocess/Coronary_artery_disease/clinical_data/GSE234398.csv\"\n",
36
+ "json_path = \"../../output/preprocess/Coronary_artery_disease/cohort_info.json\"\n"
37
+ ]
38
+ },
39
+ {
40
+ "cell_type": "markdown",
41
+ "id": "1c82b7fc",
42
+ "metadata": {},
43
+ "source": [
44
+ "### Step 1: Initial Data Loading"
45
+ ]
46
+ },
47
+ {
48
+ "cell_type": "code",
49
+ "execution_count": 2,
50
+ "id": "2c0f82b2",
51
+ "metadata": {
52
+ "execution": {
53
+ "iopub.execute_input": "2025-03-25T08:28:12.106992Z",
54
+ "iopub.status.busy": "2025-03-25T08:28:12.106851Z",
55
+ "iopub.status.idle": "2025-03-25T08:28:12.282411Z",
56
+ "shell.execute_reply": "2025-03-25T08:28:12.282074Z"
57
+ }
58
+ },
59
+ "outputs": [
60
+ {
61
+ "name": "stdout",
62
+ "output_type": "stream",
63
+ "text": [
64
+ "Background Information:\n",
65
+ "!Series_title\t\"Analysis of gene expression of LPS-stimulated monocyte from CAD patients\"\n",
66
+ "!Series_summary\t\"Data for the publication 'Identification of a Gene Network Driving the Attenuated Monocyte Response to Lipopolysaccharide of Hypertensive Coronary Artery Disease Patients'.\"\n",
67
+ "!Series_summary\t\"Dissection of the impact of CVD risk factors on monocyte phenotype at the gene expression level, and in particular on their response to trauma and infection response.\"\n",
68
+ "!Series_summary\t\"For any questions about the dataset, please contact Erik Biessen‘s Lab, Department of Pathology, Cardiovascular Research Institute Maastricht (CARIM), Maastricht University Medical Center, Maastricht, Netherlands\"\n",
69
+ "!Series_overall_design\t\"Total RNA obtained from LPS stimulated monocytes of CAD patients.\"\n",
70
+ "Sample Characteristics Dictionary:\n",
71
+ "{0: ['cell type: monocytes'], 1: ['Sex: male', 'Sex: female'], 2: ['age: 78', 'age: 50', 'age: 67', 'age: 74', 'age: 60', 'age: 72', 'age: 73', 'age: 77', 'age: 56', 'age: 51', 'age: 66', 'age: 65', 'age: 63', 'age: 71', 'age: 57', 'age: 75', 'age: 64', 'age: 39', 'age: 40']}\n"
72
+ ]
73
+ }
74
+ ],
75
+ "source": [
76
+ "from tools.preprocess import *\n",
77
+ "# 1. Identify the paths to the SOFT file and the matrix file\n",
78
+ "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
79
+ "\n",
80
+ "# 2. Read the matrix file to obtain background information and sample characteristics data\n",
81
+ "background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']\n",
82
+ "clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']\n",
83
+ "background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)\n",
84
+ "\n",
85
+ "# 3. Obtain the sample characteristics dictionary from the clinical dataframe\n",
86
+ "sample_characteristics_dict = get_unique_values_by_row(clinical_data)\n",
87
+ "\n",
88
+ "# 4. Explicitly print out all the background information and the sample characteristics dictionary\n",
89
+ "print(\"Background Information:\")\n",
90
+ "print(background_info)\n",
91
+ "print(\"Sample Characteristics Dictionary:\")\n",
92
+ "print(sample_characteristics_dict)\n"
93
+ ]
94
+ },
95
+ {
96
+ "cell_type": "markdown",
97
+ "id": "f5184adf",
98
+ "metadata": {},
99
+ "source": [
100
+ "### Step 2: Dataset Analysis and Clinical Feature Extraction"
101
+ ]
102
+ },
103
+ {
104
+ "cell_type": "code",
105
+ "execution_count": 3,
106
+ "id": "b8fcadee",
107
+ "metadata": {
108
+ "execution": {
109
+ "iopub.execute_input": "2025-03-25T08:28:12.283688Z",
110
+ "iopub.status.busy": "2025-03-25T08:28:12.283582Z",
111
+ "iopub.status.idle": "2025-03-25T08:28:12.293360Z",
112
+ "shell.execute_reply": "2025-03-25T08:28:12.293081Z"
113
+ }
114
+ },
115
+ "outputs": [
116
+ {
117
+ "name": "stdout",
118
+ "output_type": "stream",
119
+ "text": [
120
+ "Clinical Data Preview:\n",
121
+ "{'GSM7466724': [1.0, 78.0, 1.0], 'GSM7466725': [1.0, 78.0, 1.0], 'GSM7466726': [1.0, 50.0, 0.0], 'GSM7466727': [1.0, 67.0, 0.0], 'GSM7466728': [1.0, 74.0, 0.0], 'GSM7466729': [1.0, 60.0, 1.0], 'GSM7466730': [1.0, 72.0, 1.0], 'GSM7466731': [1.0, 67.0, 1.0], 'GSM7466732': [1.0, 67.0, 1.0], 'GSM7466733': [1.0, 73.0, 1.0], 'GSM7466734': [1.0, 77.0, 0.0], 'GSM7466735': [1.0, 78.0, 0.0], 'GSM7466736': [1.0, 56.0, 1.0], 'GSM7466737': [1.0, 51.0, 1.0], 'GSM7466738': [1.0, 78.0, 1.0], 'GSM7466739': [1.0, 66.0, 1.0], 'GSM7466740': [1.0, 65.0, 1.0], 'GSM7466741': [1.0, 51.0, 1.0], 'GSM7466742': [1.0, 63.0, 0.0], 'GSM7466743': [1.0, 60.0, 0.0], 'GSM7466744': [1.0, 71.0, 1.0], 'GSM7466745': [1.0, 57.0, 0.0], 'GSM7466746': [1.0, 73.0, 1.0], 'GSM7466747': [1.0, 75.0, 0.0], 'GSM7466748': [1.0, 72.0, 0.0], 'GSM7466749': [1.0, 74.0, 0.0], 'GSM7466750': [1.0, 64.0, 0.0], 'GSM7466751': [1.0, 39.0, 1.0], 'GSM7466752': [1.0, 78.0, 0.0], 'GSM7466753': [1.0, 57.0, 1.0], 'GSM7466754': [1.0, 74.0, 0.0], 'GSM7466755': [1.0, 75.0, 0.0], 'GSM7466756': [1.0, 67.0, 0.0], 'GSM7466757': [1.0, 63.0, 0.0], 'GSM7466758': [1.0, 71.0, 1.0], 'GSM7466759': [1.0, 72.0, 1.0], 'GSM7466760': [1.0, 40.0, 1.0], 'GSM7466761': [1.0, 63.0, 1.0], 'GSM7466762': [1.0, 73.0, 0.0], 'GSM7466763': [1.0, 77.0, 1.0], 'GSM7466764': [1.0, 50.0, 0.0], 'GSM7466765': [1.0, 73.0, 0.0], 'GSM7466766': [1.0, 72.0, 1.0], 'GSM7466767': [1.0, 56.0, 1.0], 'GSM7466768': [1.0, 56.0, 0.0], 'GSM7466769': [1.0, 64.0, 0.0], 'GSM7466770': [1.0, 66.0, 1.0], 'GSM7466771': [1.0, 65.0, 1.0], 'GSM7466772': [1.0, 63.0, 1.0], 'GSM7466773': [1.0, 56.0, 1.0]}\n",
122
+ "Clinical data saved to ../../output/preprocess/Coronary_artery_disease/clinical_data/GSE234398.csv\n"
123
+ ]
124
+ }
125
+ ],
126
+ "source": [
127
+ "# 1. Gene Expression Data Availability\n",
128
+ "# Based on the background information, this dataset contains gene expression data from LPS-stimulated monocytes\n",
129
+ "is_gene_available = True\n",
130
+ "\n",
131
+ "# 2. Variable Availability and Data Type Conversion\n",
132
+ "# 2.1 Data Availability\n",
133
+ "# Trait: From the background info, this dataset is specifically about CAD patients\n",
134
+ "# We can use row 0 to represent all samples as having CAD (even though it doesn't explicitly state CAD)\n",
135
+ "trait_row = 0 # All samples are CAD patients as per the background information\n",
136
+ "\n",
137
+ "# Age: This is available in row 2\n",
138
+ "age_row = 2\n",
139
+ "\n",
140
+ "# Gender: This is available in row 1\n",
141
+ "gender_row = 1\n",
142
+ "\n",
143
+ "# 2.2 Data Type Conversion\n",
144
+ "def convert_trait(value):\n",
145
+ " # All samples are CAD patients according to the background info\n",
146
+ " return 1 # Binary: 1 = has CAD\n",
147
+ "\n",
148
+ "def convert_age(value):\n",
149
+ " if \":\" in value:\n",
150
+ " value = value.split(\":\", 1)[1].strip()\n",
151
+ " try:\n",
152
+ " return float(value) # Convert to continuous numeric value\n",
153
+ " except (ValueError, TypeError):\n",
154
+ " return None\n",
155
+ "\n",
156
+ "def convert_gender(value):\n",
157
+ " if \":\" in value:\n",
158
+ " value = value.split(\":\", 1)[1].strip().lower()\n",
159
+ " if value == \"male\":\n",
160
+ " return 1\n",
161
+ " elif value == \"female\":\n",
162
+ " return 0\n",
163
+ " else:\n",
164
+ " return None\n",
165
+ "\n",
166
+ "# 3. Save Metadata - initial filtering\n",
167
+ "is_trait_available = trait_row is not None\n",
168
+ "validate_and_save_cohort_info(\n",
169
+ " is_final=False,\n",
170
+ " cohort=cohort,\n",
171
+ " info_path=json_path,\n",
172
+ " is_gene_available=is_gene_available,\n",
173
+ " is_trait_available=is_trait_available\n",
174
+ ")\n",
175
+ "\n",
176
+ "# 4. Clinical Feature Extraction\n",
177
+ "if trait_row is not None:\n",
178
+ " # Extract clinical features\n",
179
+ " clinical_selected = geo_select_clinical_features(\n",
180
+ " clinical_df=clinical_data,\n",
181
+ " trait=trait,\n",
182
+ " trait_row=trait_row,\n",
183
+ " convert_trait=convert_trait,\n",
184
+ " age_row=age_row,\n",
185
+ " convert_age=convert_age,\n",
186
+ " gender_row=gender_row,\n",
187
+ " convert_gender=convert_gender\n",
188
+ " )\n",
189
+ " \n",
190
+ " # Preview the data\n",
191
+ " preview = preview_df(clinical_selected)\n",
192
+ " print(\"Clinical Data Preview:\")\n",
193
+ " print(preview)\n",
194
+ " \n",
195
+ " # Save to file\n",
196
+ " clinical_selected.to_csv(out_clinical_data_file)\n",
197
+ " print(f\"Clinical data saved to {out_clinical_data_file}\")\n"
198
+ ]
199
+ },
200
+ {
201
+ "cell_type": "markdown",
202
+ "id": "af810ea2",
203
+ "metadata": {},
204
+ "source": [
205
+ "### Step 3: Gene Data Extraction"
206
+ ]
207
+ },
208
+ {
209
+ "cell_type": "code",
210
+ "execution_count": 4,
211
+ "id": "9ab59c05",
212
+ "metadata": {
213
+ "execution": {
214
+ "iopub.execute_input": "2025-03-25T08:28:12.294447Z",
215
+ "iopub.status.busy": "2025-03-25T08:28:12.294346Z",
216
+ "iopub.status.idle": "2025-03-25T08:28:12.540618Z",
217
+ "shell.execute_reply": "2025-03-25T08:28:12.540240Z"
218
+ }
219
+ },
220
+ "outputs": [
221
+ {
222
+ "name": "stdout",
223
+ "output_type": "stream",
224
+ "text": [
225
+ "SOFT file: ../../input/GEO/Coronary_artery_disease/GSE234398/GSE234398_family.soft.gz\n",
226
+ "Matrix file: ../../input/GEO/Coronary_artery_disease/GSE234398/GSE234398_series_matrix.txt.gz\n",
227
+ "Found the matrix table marker at line 63\n"
228
+ ]
229
+ },
230
+ {
231
+ "name": "stdout",
232
+ "output_type": "stream",
233
+ "text": [
234
+ "Gene data shape: (47231, 50)\n",
235
+ "First 20 gene/probe identifiers:\n",
236
+ "['ILMN_1343291', 'ILMN_1343295', 'ILMN_1651199', 'ILMN_1651209', 'ILMN_1651210', 'ILMN_1651221', 'ILMN_1651228', 'ILMN_1651229', 'ILMN_1651230', 'ILMN_1651232', 'ILMN_1651235', 'ILMN_1651236', 'ILMN_1651237', 'ILMN_1651238', 'ILMN_1651249', 'ILMN_1651253', 'ILMN_1651254', 'ILMN_1651259', 'ILMN_1651260', 'ILMN_1651262']\n"
237
+ ]
238
+ }
239
+ ],
240
+ "source": [
241
+ "# 1. Identify the paths to the SOFT file and the matrix file\n",
242
+ "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
243
+ "print(f\"SOFT file: {soft_file}\")\n",
244
+ "print(f\"Matrix file: {matrix_file}\")\n",
245
+ "\n",
246
+ "# Set gene availability flag\n",
247
+ "is_gene_available = True # Initially assume gene data is available\n",
248
+ "\n",
249
+ "# First check if the matrix file contains the expected marker\n",
250
+ "found_marker = False\n",
251
+ "marker_row = None\n",
252
+ "try:\n",
253
+ " with gzip.open(matrix_file, 'rt') as file:\n",
254
+ " for i, line in enumerate(file):\n",
255
+ " if \"!series_matrix_table_begin\" in line:\n",
256
+ " found_marker = True\n",
257
+ " marker_row = i\n",
258
+ " print(f\"Found the matrix table marker at line {i}\")\n",
259
+ " break\n",
260
+ " \n",
261
+ " if not found_marker:\n",
262
+ " print(\"Warning: Could not find '!series_matrix_table_begin' marker in the file.\")\n",
263
+ " is_gene_available = False\n",
264
+ " \n",
265
+ " # If marker was found, try to extract gene data\n",
266
+ " if is_gene_available:\n",
267
+ " try:\n",
268
+ " # Try using the library function\n",
269
+ " gene_data = get_genetic_data(matrix_file)\n",
270
+ " \n",
271
+ " if gene_data.shape[0] == 0:\n",
272
+ " print(\"Warning: Extracted gene data has 0 rows.\")\n",
273
+ " is_gene_available = False\n",
274
+ " else:\n",
275
+ " print(f\"Gene data shape: {gene_data.shape}\")\n",
276
+ " # Print the first 20 gene/probe identifiers\n",
277
+ " print(\"First 20 gene/probe identifiers:\")\n",
278
+ " print(gene_data.index[:20].tolist())\n",
279
+ " except Exception as e:\n",
280
+ " print(f\"Error extracting gene data with get_genetic_data(): {e}\")\n",
281
+ " is_gene_available = False\n",
282
+ " \n",
283
+ " # If gene data extraction failed, examine file content to diagnose\n",
284
+ " if not is_gene_available:\n",
285
+ " print(\"Examining file content to diagnose the issue:\")\n",
286
+ " try:\n",
287
+ " with gzip.open(matrix_file, 'rt') as file:\n",
288
+ " # Print lines around the marker if found\n",
289
+ " if marker_row is not None:\n",
290
+ " for i, line in enumerate(file):\n",
291
+ " if i >= marker_row - 2 and i <= marker_row + 10:\n",
292
+ " print(f\"Line {i}: {line.strip()[:100]}...\")\n",
293
+ " if i > marker_row + 10:\n",
294
+ " break\n",
295
+ " else:\n",
296
+ " # If marker not found, print first 10 lines\n",
297
+ " for i, line in enumerate(file):\n",
298
+ " if i < 10:\n",
299
+ " print(f\"Line {i}: {line.strip()[:100]}...\")\n",
300
+ " else:\n",
301
+ " break\n",
302
+ " except Exception as e2:\n",
303
+ " print(f\"Error examining file: {e2}\")\n",
304
+ " \n",
305
+ "except Exception as e:\n",
306
+ " print(f\"Error processing file: {e}\")\n",
307
+ " is_gene_available = False\n",
308
+ "\n",
309
+ "# Update validation information if gene data extraction failed\n",
310
+ "if not is_gene_available:\n",
311
+ " print(\"Gene expression data could not be successfully extracted from this dataset.\")\n",
312
+ " # Update the validation record since gene data isn't available\n",
313
+ " is_trait_available = False # We already determined trait data isn't available in step 2\n",
314
+ " validate_and_save_cohort_info(is_final=False, cohort=cohort, info_path=json_path,\n",
315
+ " is_gene_available=is_gene_available, is_trait_available=is_trait_available)\n"
316
+ ]
317
+ },
318
+ {
319
+ "cell_type": "markdown",
320
+ "id": "25e3e77f",
321
+ "metadata": {},
322
+ "source": [
323
+ "### Step 4: Gene Identifier Review"
324
+ ]
325
+ },
326
+ {
327
+ "cell_type": "code",
328
+ "execution_count": 5,
329
+ "id": "9effad6c",
330
+ "metadata": {
331
+ "execution": {
332
+ "iopub.execute_input": "2025-03-25T08:28:12.541949Z",
333
+ "iopub.status.busy": "2025-03-25T08:28:12.541830Z",
334
+ "iopub.status.idle": "2025-03-25T08:28:12.543688Z",
335
+ "shell.execute_reply": "2025-03-25T08:28:12.543421Z"
336
+ }
337
+ },
338
+ "outputs": [],
339
+ "source": [
340
+ "# Examining the gene identifiers\n",
341
+ "# The identifiers with prefix 'ILMN_' are Illumina probe IDs, not human gene symbols\n",
342
+ "# These are probe IDs from Illumina microarray platforms and need to be mapped to gene symbols\n",
343
+ "\n",
344
+ "requires_gene_mapping = True\n"
345
+ ]
346
+ },
347
+ {
348
+ "cell_type": "markdown",
349
+ "id": "2df6206b",
350
+ "metadata": {},
351
+ "source": [
352
+ "### Step 5: Gene Annotation"
353
+ ]
354
+ },
355
+ {
356
+ "cell_type": "code",
357
+ "execution_count": 6,
358
+ "id": "00c3c38a",
359
+ "metadata": {
360
+ "execution": {
361
+ "iopub.execute_input": "2025-03-25T08:28:12.544775Z",
362
+ "iopub.status.busy": "2025-03-25T08:28:12.544677Z",
363
+ "iopub.status.idle": "2025-03-25T08:28:17.704922Z",
364
+ "shell.execute_reply": "2025-03-25T08:28:17.704544Z"
365
+ }
366
+ },
367
+ "outputs": [
368
+ {
369
+ "name": "stdout",
370
+ "output_type": "stream",
371
+ "text": [
372
+ "\n",
373
+ "Gene annotation preview:\n",
374
+ "Columns in gene annotation: ['ID', 'Species', 'Source', 'Search_Key', 'Transcript', 'ILMN_Gene', 'Source_Reference_ID', 'RefSeq_ID', 'Unigene_ID', 'Entrez_Gene_ID', 'GI', 'Accession', 'Symbol', 'Protein_Product', 'Probe_Id', 'Array_Address_Id', 'Probe_Type', 'Probe_Start', 'SEQUENCE', 'Chromosome', 'Probe_Chr_Orientation', 'Probe_Coordinates', 'Cytoband', 'Definition', 'Ontology_Component', 'Ontology_Process', 'Ontology_Function', 'Synonyms', 'Obsolete_Probe_Id', 'GB_ACC']\n",
375
+ "{'ID': ['ILMN_1343048', 'ILMN_1343049', 'ILMN_1343050'], 'Species': [nan, nan, nan], 'Source': [nan, nan, nan], 'Search_Key': [nan, nan, nan], 'Transcript': [nan, nan, nan], 'ILMN_Gene': [nan, nan, nan], 'Source_Reference_ID': [nan, nan, nan], 'RefSeq_ID': [nan, nan, nan], 'Unigene_ID': [nan, nan, nan], 'Entrez_Gene_ID': [nan, nan, nan], 'GI': [nan, nan, nan], 'Accession': [nan, nan, nan], 'Symbol': ['phage_lambda_genome', 'phage_lambda_genome', 'phage_lambda_genome:low'], 'Protein_Product': [nan, nan, nan], 'Probe_Id': [nan, nan, nan], 'Array_Address_Id': [5090180.0, 6510136.0, 7560739.0], 'Probe_Type': [nan, nan, nan], 'Probe_Start': [nan, nan, nan], 'SEQUENCE': ['GAATAAAGAACAATCTGCTGATGATCCCTCCGTGGATCTGATTCGTGTAA', 'CCATGTGATACGAGGGCGCGTAGTTTGCATTATCGTTTTTATCGTTTCAA', 'CCGACAGATGTATGTAAGGCCAACGTGCTCAAATCTTCATACAGAAAGAT'], 'Chromosome': [nan, nan, nan], 'Probe_Chr_Orientation': [nan, nan, nan], 'Probe_Coordinates': [nan, nan, nan], 'Cytoband': [nan, nan, nan], 'Definition': [nan, nan, nan], 'Ontology_Component': [nan, nan, nan], 'Ontology_Process': [nan, nan, nan], 'Ontology_Function': [nan, nan, nan], 'Synonyms': [nan, nan, nan], 'Obsolete_Probe_Id': [nan, nan, nan], 'GB_ACC': [nan, nan, nan]}\n",
376
+ "\n",
377
+ "Examining mapping information (first 5 rows):\n",
378
+ "Row 0: ID=ILMN_1343048, Symbol=phage_lambda_genome\n",
379
+ "Row 1: ID=ILMN_1343049, Symbol=phage_lambda_genome\n",
380
+ "Row 2: ID=ILMN_1343050, Symbol=phage_lambda_genome:low\n",
381
+ "Row 3: ID=ILMN_1343052, Symbol=phage_lambda_genome:low\n",
382
+ "Row 4: ID=ILMN_1343059, Symbol=thrB\n",
383
+ "\n",
384
+ "Symbol column completeness: 44837/2409707 rows (1.86%)\n",
385
+ "\n",
386
+ "Columns identified for gene mapping:\n",
387
+ "- 'ID': Contains Illumina probe IDs (e.g., ILMN_*)\n",
388
+ "- 'Symbol': Contains gene symbols\n"
389
+ ]
390
+ }
391
+ ],
392
+ "source": [
393
+ "# 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.\n",
394
+ "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
395
+ "gene_annotation = get_gene_annotation(soft_file)\n",
396
+ "\n",
397
+ "# 2. Analyze the gene annotation dataframe to identify which columns contain the gene identifiers and gene symbols\n",
398
+ "print(\"\\nGene annotation preview:\")\n",
399
+ "print(f\"Columns in gene annotation: {gene_annotation.columns.tolist()}\")\n",
400
+ "print(preview_df(gene_annotation, n=3))\n",
401
+ "\n",
402
+ "# Examine the ID and Symbol columns that appear to contain the mapping information\n",
403
+ "print(\"\\nExamining mapping information (first 5 rows):\")\n",
404
+ "if 'ID' in gene_annotation.columns and 'Symbol' in gene_annotation.columns:\n",
405
+ " for i in range(min(5, len(gene_annotation))):\n",
406
+ " print(f\"Row {i}: ID={gene_annotation['ID'].iloc[i]}, Symbol={gene_annotation['Symbol'].iloc[i]}\")\n",
407
+ " \n",
408
+ " # Check the quality and completeness of the mapping\n",
409
+ " non_null_symbols = gene_annotation['Symbol'].notna().sum()\n",
410
+ " total_rows = len(gene_annotation)\n",
411
+ " print(f\"\\nSymbol column completeness: {non_null_symbols}/{total_rows} rows ({non_null_symbols/total_rows:.2%})\")\n",
412
+ " \n",
413
+ " # Identify the columns needed for gene mapping\n",
414
+ " print(\"\\nColumns identified for gene mapping:\")\n",
415
+ " print(\"- 'ID': Contains Illumina probe IDs (e.g., ILMN_*)\")\n",
416
+ " print(\"- 'Symbol': Contains gene symbols\")\n",
417
+ "else:\n",
418
+ " print(\"Error: Required mapping columns ('ID' and/or 'Symbol') not found in annotation data.\")\n",
419
+ " print(\"Available columns:\", gene_annotation.columns.tolist())\n"
420
+ ]
421
+ },
422
+ {
423
+ "cell_type": "markdown",
424
+ "id": "f60fdb5b",
425
+ "metadata": {},
426
+ "source": [
427
+ "### Step 6: Gene Identifier Mapping"
428
+ ]
429
+ },
430
+ {
431
+ "cell_type": "code",
432
+ "execution_count": 7,
433
+ "id": "0abd3b48",
434
+ "metadata": {
435
+ "execution": {
436
+ "iopub.execute_input": "2025-03-25T08:28:17.706270Z",
437
+ "iopub.status.busy": "2025-03-25T08:28:17.706149Z",
438
+ "iopub.status.idle": "2025-03-25T08:28:18.789831Z",
439
+ "shell.execute_reply": "2025-03-25T08:28:18.789454Z"
440
+ }
441
+ },
442
+ "outputs": [
443
+ {
444
+ "name": "stdout",
445
+ "output_type": "stream",
446
+ "text": [
447
+ "Gene mapping dataframe shape: (44837, 2)\n",
448
+ "First 5 rows of gene mapping:\n",
449
+ " ID Gene\n",
450
+ "0 ILMN_1343048 phage_lambda_genome\n",
451
+ "1 ILMN_1343049 phage_lambda_genome\n",
452
+ "2 ILMN_1343050 phage_lambda_genome:low\n",
453
+ "3 ILMN_1343052 phage_lambda_genome:low\n",
454
+ "4 ILMN_1343059 thrB\n"
455
+ ]
456
+ },
457
+ {
458
+ "name": "stdout",
459
+ "output_type": "stream",
460
+ "text": [
461
+ "Gene expression data shape: (47231, 50)\n",
462
+ "Gene data after mapping shape: (21372, 50)\n",
463
+ "First 10 gene symbols after mapping:\n",
464
+ "['A1BG', 'A1CF', 'A26C3', 'A2BP1', 'A2LD1', 'A2M', 'A2ML1', 'A3GALT2', 'A4GALT', 'A4GNT']\n"
465
+ ]
466
+ },
467
+ {
468
+ "name": "stdout",
469
+ "output_type": "stream",
470
+ "text": [
471
+ "Gene expression data saved to ../../output/preprocess/Coronary_artery_disease/gene_data/GSE234398.csv\n"
472
+ ]
473
+ }
474
+ ],
475
+ "source": [
476
+ "# 1. Based on the gene annotation data, I see that 'ID' contains Illumina probe IDs (like ILMN_*) which match \n",
477
+ "# the gene identifiers in the gene expression data, and 'Symbol' contains the gene symbols we need to map to.\n",
478
+ "\n",
479
+ "# 2. Extract the two columns from gene annotation for mapping\n",
480
+ "# Get the SOFT and matrix files again (for consistency with previous steps)\n",
481
+ "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
482
+ "\n",
483
+ "# Extract the gene annotation data - already done in previous step\n",
484
+ "# gene_annotation = get_gene_annotation(soft_file)\n",
485
+ "\n",
486
+ "# Get the gene mapping dataframe using the library function\n",
487
+ "gene_mapping = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='Symbol')\n",
488
+ "print(f\"Gene mapping dataframe shape: {gene_mapping.shape}\")\n",
489
+ "print(\"First 5 rows of gene mapping:\")\n",
490
+ "print(gene_mapping.head())\n",
491
+ "\n",
492
+ "# Extract gene expression data - already done in previous step\n",
493
+ "gene_expression = get_genetic_data(matrix_file)\n",
494
+ "print(f\"Gene expression data shape: {gene_expression.shape}\")\n",
495
+ "\n",
496
+ "# 3. Apply gene mapping to convert probe-level measurements to gene expression data\n",
497
+ "gene_data = apply_gene_mapping(gene_expression, gene_mapping)\n",
498
+ "print(f\"Gene data after mapping shape: {gene_data.shape}\")\n",
499
+ "print(\"First 10 gene symbols after mapping:\")\n",
500
+ "print(gene_data.index[:10].tolist())\n",
501
+ "\n",
502
+ "# Save the processed gene data\n",
503
+ "gene_data.to_csv(out_gene_data_file)\n",
504
+ "print(f\"Gene expression data saved to {out_gene_data_file}\")\n"
505
+ ]
506
+ },
507
+ {
508
+ "cell_type": "markdown",
509
+ "id": "deb34098",
510
+ "metadata": {},
511
+ "source": [
512
+ "### Step 7: Data Normalization and Linking"
513
+ ]
514
+ },
515
+ {
516
+ "cell_type": "code",
517
+ "execution_count": 8,
518
+ "id": "d8b04473",
519
+ "metadata": {
520
+ "execution": {
521
+ "iopub.execute_input": "2025-03-25T08:28:18.791224Z",
522
+ "iopub.status.busy": "2025-03-25T08:28:18.791103Z",
523
+ "iopub.status.idle": "2025-03-25T08:28:25.771337Z",
524
+ "shell.execute_reply": "2025-03-25T08:28:25.771017Z"
525
+ }
526
+ },
527
+ "outputs": [
528
+ {
529
+ "name": "stdout",
530
+ "output_type": "stream",
531
+ "text": [
532
+ "Gene data shape before normalization: (21372, 50)\n"
533
+ ]
534
+ },
535
+ {
536
+ "name": "stdout",
537
+ "output_type": "stream",
538
+ "text": [
539
+ "Gene data saved to ../../output/preprocess/Coronary_artery_disease/gene_data/GSE234398.csv\n",
540
+ "Loaded clinical data shape: (3, 50)\n",
541
+ "Initial linked data shape: (50, 21375)\n"
542
+ ]
543
+ },
544
+ {
545
+ "name": "stdout",
546
+ "output_type": "stream",
547
+ "text": [
548
+ "Linked data shape after handling missing values: (50, 21375)\n",
549
+ "Quartiles for 'Coronary_artery_disease':\n",
550
+ " 25%: 1.0\n",
551
+ " 50% (Median): 1.0\n",
552
+ " 75%: 1.0\n",
553
+ "Min: 1.0\n",
554
+ "Max: 1.0\n",
555
+ "The distribution of the feature 'Coronary_artery_disease' in this dataset is severely biased.\n",
556
+ "\n",
557
+ "Quartiles for 'Age':\n",
558
+ " 25%: 60.0\n",
559
+ " 50% (Median): 67.0\n",
560
+ " 75%: 73.0\n",
561
+ "Min: 39.0\n",
562
+ "Max: 78.0\n",
563
+ "The distribution of the feature 'Age' in this dataset is fine.\n",
564
+ "\n",
565
+ "For the feature 'Gender', the least common label is '0.0' with 22 occurrences. This represents 44.00% of the dataset.\n",
566
+ "The distribution of the feature 'Gender' in this dataset is fine.\n",
567
+ "\n",
568
+ "Data not usable for trait study - not saving final linked data.\n"
569
+ ]
570
+ }
571
+ ],
572
+ "source": [
573
+ "# 1. Attempt to load gene data and handle possible issues with normalization\n",
574
+ "try:\n",
575
+ " # Create output directory if it doesn't exist\n",
576
+ " os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
577
+ " \n",
578
+ " # Check if gene_data (from previous step) has any content\n",
579
+ " if gene_data.shape[0] == 0:\n",
580
+ " print(\"WARNING: Gene data is empty after normalization in previous step.\")\n",
581
+ " print(\"This appears to be miRNA data rather than gene expression data.\")\n",
582
+ " \n",
583
+ " # Since gene_data is empty, set gene_available to False\n",
584
+ " is_gene_available = False\n",
585
+ " \n",
586
+ " # Create an empty dataframe for metadata purposes\n",
587
+ " empty_df = pd.DataFrame()\n",
588
+ " \n",
589
+ " # Log information about this dataset for future reference\n",
590
+ " validate_and_save_cohort_info(\n",
591
+ " is_final=True,\n",
592
+ " cohort=cohort,\n",
593
+ " info_path=json_path,\n",
594
+ " is_gene_available=is_gene_available,\n",
595
+ " is_trait_available=is_trait_available,\n",
596
+ " is_biased=True, # Consider it biased as we can't use it\n",
597
+ " df=empty_df,\n",
598
+ " note=\"Dataset appears to contain miRNA data rather than gene expression data. Gene symbols could not be normalized.\"\n",
599
+ " )\n",
600
+ " \n",
601
+ " print(\"Dataset marked as unusable due to lack of valid gene expression data.\")\n",
602
+ " else:\n",
603
+ " # If gene_data is not empty, proceed with normalization and linking\n",
604
+ " print(f\"Gene data shape before normalization: {gene_data.shape}\")\n",
605
+ " \n",
606
+ " # Save the gene data we have, even if it's already normalized\n",
607
+ " gene_data.to_csv(out_gene_data_file)\n",
608
+ " print(f\"Gene data saved to {out_gene_data_file}\")\n",
609
+ " \n",
610
+ " # Attempt to link clinical and gene data\n",
611
+ " if is_trait_available:\n",
612
+ " # Load clinical data\n",
613
+ " clinical_features = pd.read_csv(out_clinical_data_file, index_col=0)\n",
614
+ " print(f\"Loaded clinical data shape: {clinical_features.shape}\")\n",
615
+ " \n",
616
+ " # Link the clinical and genetic data\n",
617
+ " linked_data = geo_link_clinical_genetic_data(clinical_features, gene_data)\n",
618
+ " print(f\"Initial linked data shape: {linked_data.shape}\")\n",
619
+ " \n",
620
+ " # Handle missing values\n",
621
+ " linked_data = handle_missing_values(linked_data, trait)\n",
622
+ " print(f\"Linked data shape after handling missing values: {linked_data.shape}\")\n",
623
+ " \n",
624
+ " if linked_data.shape[0] > 0:\n",
625
+ " # Check for bias in trait and demographic features\n",
626
+ " is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n",
627
+ " \n",
628
+ " # Validate data quality and save cohort info\n",
629
+ " is_usable = validate_and_save_cohort_info(\n",
630
+ " is_final=True,\n",
631
+ " cohort=cohort,\n",
632
+ " info_path=json_path,\n",
633
+ " is_gene_available=is_gene_available,\n",
634
+ " is_trait_available=is_trait_available,\n",
635
+ " is_biased=is_biased,\n",
636
+ " df=linked_data,\n",
637
+ " note=\"Successfully processed gene expression data for coronary artery disease.\"\n",
638
+ " )\n",
639
+ " \n",
640
+ " # Save the linked data if it's usable\n",
641
+ " if is_usable:\n",
642
+ " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n",
643
+ " linked_data.to_csv(out_data_file)\n",
644
+ " print(f\"Linked data saved to {out_data_file}\")\n",
645
+ " else:\n",
646
+ " print(\"Data not usable for trait study - not saving final linked data.\")\n",
647
+ " else:\n",
648
+ " print(\"After handling missing values, no samples remain.\")\n",
649
+ " validate_and_save_cohort_info(\n",
650
+ " is_final=True,\n",
651
+ " cohort=cohort,\n",
652
+ " info_path=json_path,\n",
653
+ " is_gene_available=is_gene_available,\n",
654
+ " is_trait_available=is_trait_available,\n",
655
+ " is_biased=True,\n",
656
+ " df=pd.DataFrame(),\n",
657
+ " note=\"No valid samples after handling missing values.\"\n",
658
+ " )\n",
659
+ " else:\n",
660
+ " # Cannot proceed with linking if trait data is missing\n",
661
+ " validate_and_save_cohort_info(\n",
662
+ " is_final=True,\n",
663
+ " cohort=cohort,\n",
664
+ " info_path=json_path,\n",
665
+ " is_gene_available=is_gene_available,\n",
666
+ " is_trait_available=is_trait_available,\n",
667
+ " is_biased=True,\n",
668
+ " df=pd.DataFrame(),\n",
669
+ " note=\"Cannot link data because trait information is not available.\"\n",
670
+ " )\n",
671
+ "except Exception as e:\n",
672
+ " print(f\"Error in data processing: {e}\")\n",
673
+ " \n",
674
+ " # Log the error and mark the dataset as unusable\n",
675
+ " validate_and_save_cohort_info(\n",
676
+ " is_final=True,\n",
677
+ " cohort=cohort,\n",
678
+ " info_path=json_path,\n",
679
+ " is_gene_available=False, # Consider gene data unavailable if we had an error\n",
680
+ " is_trait_available=is_trait_available,\n",
681
+ " is_biased=True, # Consider it biased as we can't use it\n",
682
+ " df=pd.DataFrame(), # Empty dataframe for metadata\n",
683
+ " note=f\"Error during normalization or linking: {str(e)}\"\n",
684
+ " )"
685
+ ]
686
+ }
687
+ ],
688
+ "metadata": {
689
+ "language_info": {
690
+ "codemirror_mode": {
691
+ "name": "ipython",
692
+ "version": 3
693
+ },
694
+ "file_extension": ".py",
695
+ "mimetype": "text/x-python",
696
+ "name": "python",
697
+ "nbconvert_exporter": "python",
698
+ "pygments_lexer": "ipython3",
699
+ "version": "3.10.16"
700
+ }
701
+ },
702
+ "nbformat": 4,
703
+ "nbformat_minor": 5
704
+ }
code/Coronary_artery_disease/GSE250283.ipynb ADDED
@@ -0,0 +1,737 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": 1,
6
+ "id": "8d031a69",
7
+ "metadata": {
8
+ "execution": {
9
+ "iopub.execute_input": "2025-03-25T08:28:26.576109Z",
10
+ "iopub.status.busy": "2025-03-25T08:28:26.575996Z",
11
+ "iopub.status.idle": "2025-03-25T08:28:26.737662Z",
12
+ "shell.execute_reply": "2025-03-25T08:28:26.737321Z"
13
+ }
14
+ },
15
+ "outputs": [],
16
+ "source": [
17
+ "import sys\n",
18
+ "import os\n",
19
+ "sys.path.append(os.path.abspath(os.path.join(os.getcwd(), '../..')))\n",
20
+ "\n",
21
+ "# Path Configuration\n",
22
+ "from tools.preprocess import *\n",
23
+ "\n",
24
+ "# Processing context\n",
25
+ "trait = \"Coronary_artery_disease\"\n",
26
+ "cohort = \"GSE250283\"\n",
27
+ "\n",
28
+ "# Input paths\n",
29
+ "in_trait_dir = \"../../input/GEO/Coronary_artery_disease\"\n",
30
+ "in_cohort_dir = \"../../input/GEO/Coronary_artery_disease/GSE250283\"\n",
31
+ "\n",
32
+ "# Output paths\n",
33
+ "out_data_file = \"../../output/preprocess/Coronary_artery_disease/GSE250283.csv\"\n",
34
+ "out_gene_data_file = \"../../output/preprocess/Coronary_artery_disease/gene_data/GSE250283.csv\"\n",
35
+ "out_clinical_data_file = \"../../output/preprocess/Coronary_artery_disease/clinical_data/GSE250283.csv\"\n",
36
+ "json_path = \"../../output/preprocess/Coronary_artery_disease/cohort_info.json\"\n"
37
+ ]
38
+ },
39
+ {
40
+ "cell_type": "markdown",
41
+ "id": "69e44225",
42
+ "metadata": {},
43
+ "source": [
44
+ "### Step 1: Initial Data Loading"
45
+ ]
46
+ },
47
+ {
48
+ "cell_type": "code",
49
+ "execution_count": 2,
50
+ "id": "6128ca21",
51
+ "metadata": {
52
+ "execution": {
53
+ "iopub.execute_input": "2025-03-25T08:28:26.738913Z",
54
+ "iopub.status.busy": "2025-03-25T08:28:26.738774Z",
55
+ "iopub.status.idle": "2025-03-25T08:28:26.883406Z",
56
+ "shell.execute_reply": "2025-03-25T08:28:26.883101Z"
57
+ }
58
+ },
59
+ "outputs": [
60
+ {
61
+ "name": "stdout",
62
+ "output_type": "stream",
63
+ "text": [
64
+ "Background Information:\n",
65
+ "!Series_title\t\"Transcriptional profiles associated with coronary artery disease in Type 2 diabetes mellitus\"\n",
66
+ "!Series_summary\t\"Coronary artery disease (CAD) is a common complication of Type 2 diabetes mellitus (T2DM). Understanding the pathogenesis of this complication is essential in both diagnosis and management. Thus, this study aimed to characterize the presence of CAD in T2DM using molecular markers and pathway analyses.\"\n",
67
+ "!Series_summary\t\"Total RNA from peripheral blood mononuclear cells (PBMCs) underwent whole transcriptomic profiling using the Illumina HumanHT-12 v4.0 expression beadchip. Differential gene expression with gene ontogeny analyses was performed, with supporting correlational analyses using weighted correlation network analysis (WGCNA)\"\n",
68
+ "!Series_overall_design\t\"The study is a sex- and age-frequency matched case-control design comparing 23 unrelated adult Filipinos with T2DM-CAD to 23 controls (DM with CAD).\"\n",
69
+ "Sample Characteristics Dictionary:\n",
70
+ "{0: ['tissue: blood'], 1: ['gender: Female', 'gender: Male'], 2: ['sample group (dm or no dm): DM', 'sample group (dm or no dm): Healthy'], 3: ['comorbidity: with no Retinopathy', 'comorbidity: with Retinopathy', 'comorbidity: Healthy']}\n"
71
+ ]
72
+ }
73
+ ],
74
+ "source": [
75
+ "from tools.preprocess import *\n",
76
+ "# 1. Identify the paths to the SOFT file and the matrix file\n",
77
+ "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
78
+ "\n",
79
+ "# 2. Read the matrix file to obtain background information and sample characteristics data\n",
80
+ "background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']\n",
81
+ "clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']\n",
82
+ "background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)\n",
83
+ "\n",
84
+ "# 3. Obtain the sample characteristics dictionary from the clinical dataframe\n",
85
+ "sample_characteristics_dict = get_unique_values_by_row(clinical_data)\n",
86
+ "\n",
87
+ "# 4. Explicitly print out all the background information and the sample characteristics dictionary\n",
88
+ "print(\"Background Information:\")\n",
89
+ "print(background_info)\n",
90
+ "print(\"Sample Characteristics Dictionary:\")\n",
91
+ "print(sample_characteristics_dict)\n"
92
+ ]
93
+ },
94
+ {
95
+ "cell_type": "markdown",
96
+ "id": "6ed35ca9",
97
+ "metadata": {},
98
+ "source": [
99
+ "### Step 2: Dataset Analysis and Clinical Feature Extraction"
100
+ ]
101
+ },
102
+ {
103
+ "cell_type": "code",
104
+ "execution_count": 3,
105
+ "id": "65862a18",
106
+ "metadata": {
107
+ "execution": {
108
+ "iopub.execute_input": "2025-03-25T08:28:26.884830Z",
109
+ "iopub.status.busy": "2025-03-25T08:28:26.884720Z",
110
+ "iopub.status.idle": "2025-03-25T08:28:26.894693Z",
111
+ "shell.execute_reply": "2025-03-25T08:28:26.894399Z"
112
+ }
113
+ },
114
+ "outputs": [
115
+ {
116
+ "name": "stdout",
117
+ "output_type": "stream",
118
+ "text": [
119
+ "Clinical Features Preview:\n",
120
+ "{'GSM7976778': [0.0, 0.0], 'GSM7976779': [0.0, 0.0], 'GSM7976780': [0.0, 1.0], 'GSM7976781': [0.0, 1.0], 'GSM7976782': [1.0, 0.0], 'GSM7976783': [1.0, 0.0], 'GSM7976784': [1.0, 0.0], 'GSM7976785': [1.0, 0.0], 'GSM7976786': [0.0, 0.0], 'GSM7976787': [0.0, 0.0], 'GSM7976788': [0.0, 0.0], 'GSM7976789': [0.0, 0.0], 'GSM7976790': [0.0, 0.0], 'GSM7976791': [1.0, 0.0], 'GSM7976792': [0.0, 0.0], 'GSM7976793': [1.0, 1.0], 'GSM7976794': [0.0, 1.0], 'GSM7976795': [0.0, 0.0], 'GSM7976796': [0.0, 1.0], 'GSM7976797': [0.0, 1.0], 'GSM7976798': [0.0, 0.0], 'GSM7976799': [0.0, 1.0], 'GSM7976800': [0.0, 1.0], 'GSM7976801': [0.0, 0.0], 'GSM7976802': [1.0, 0.0], 'GSM7976803': [0.0, 0.0], 'GSM7976804': [0.0, 0.0], 'GSM7976805': [0.0, 0.0], 'GSM7976806': [1.0, 1.0], 'GSM7976807': [1.0, 1.0], 'GSM7976808': [0.0, 1.0], 'GSM7976809': [0.0, 0.0], 'GSM7976810': [0.0, 0.0], 'GSM7976811': [0.0, 0.0], 'GSM7976812': [0.0, 0.0], 'GSM7976813': [0.0, 0.0], 'GSM7976814': [1.0, 1.0], 'GSM7976815': [0.0, 0.0], 'GSM7976816': [0.0, 0.0], 'GSM7976817': [1.0, 1.0], 'GSM7976818': [0.0, 1.0], 'GSM7976819': [1.0, 1.0], 'GSM7976820': [0.0, 0.0], 'GSM7976821': [1.0, 1.0], 'GSM7976822': [0.0, 1.0], 'GSM7976823': [0.0, 0.0], 'GSM7976824': [1.0, 0.0], 'GSM7976825': [1.0, 1.0], 'GSM7976826': [1.0, 0.0], 'GSM7976827': [1.0, 0.0], 'GSM7976828': [0.0, 1.0], 'GSM7976829': [0.0, 0.0], 'GSM7976830': [0.0, 1.0], 'GSM7976831': [1.0, 0.0], 'GSM7976832': [1.0, 0.0], 'GSM7976833': [1.0, 0.0]}\n",
121
+ "Clinical data saved to ../../output/preprocess/Coronary_artery_disease/clinical_data/GSE250283.csv\n"
122
+ ]
123
+ }
124
+ ],
125
+ "source": [
126
+ "# 1. Determine gene expression data availability\n",
127
+ "# The series description mentions \"whole transcriptomic profiling using the Illumina HumanHT-12 v4.0 expression beadchip\"\n",
128
+ "# which indicates gene expression data is available\n",
129
+ "is_gene_available = True\n",
130
+ "\n",
131
+ "# 2. Variable Availability and Data Type Conversion\n",
132
+ "# 2.1 Determine the keys for trait, age, and gender in the sample characteristics\n",
133
+ "\n",
134
+ "# For trait (coronary artery disease):\n",
135
+ "# Looking at the background info, this is a study comparing T2DM-CAD to controls\n",
136
+ "# Based on the study design, CAD status is likely contained in key 3 (comorbidity)\n",
137
+ "# Even though CAD isn't explicitly mentioned in the preview, the study's primary focus \n",
138
+ "# is on coronary artery disease in T2DM patients\n",
139
+ "trait_row = 3\n",
140
+ "\n",
141
+ "# For gender:\n",
142
+ "# Key 1 has 'gender: Female', 'gender: Male'\n",
143
+ "gender_row = 1\n",
144
+ "\n",
145
+ "# For age:\n",
146
+ "# There's no age information in the sample characteristics\n",
147
+ "age_row = None\n",
148
+ "\n",
149
+ "# 2.2 Define conversion functions for each variable\n",
150
+ "\n",
151
+ "# Trait conversion function for CAD\n",
152
+ "def convert_trait(value):\n",
153
+ " if not value or ':' not in value:\n",
154
+ " return None\n",
155
+ " \n",
156
+ " comorbidity = value.split(':', 1)[1].strip().lower()\n",
157
+ " \n",
158
+ " # Based on the study design (T2DM-CAD vs controls with DM without CAD)\n",
159
+ " # The exact encoding isn't clear from the limited preview, but we can make an educated guess\n",
160
+ " # Based on biomedical knowledge, assume:\n",
161
+ " # - Patients with retinopathy are more likely to have CAD (common diabetes complication)\n",
162
+ " # - \"Healthy\" in this context likely means without CAD\n",
163
+ " if 'with retinopathy' in comorbidity:\n",
164
+ " return 1 # More likely to have CAD\n",
165
+ " elif 'healthy' in comorbidity or 'with no' in comorbidity:\n",
166
+ " return 0 # Less likely to have CAD\n",
167
+ " \n",
168
+ " return None\n",
169
+ "\n",
170
+ "# Gender conversion function\n",
171
+ "def convert_gender(value):\n",
172
+ " if not value or ':' not in value:\n",
173
+ " return None\n",
174
+ " gender = value.split(':', 1)[1].strip().lower()\n",
175
+ " if 'female' in gender:\n",
176
+ " return 0\n",
177
+ " elif 'male' in gender:\n",
178
+ " return 1\n",
179
+ " return None\n",
180
+ "\n",
181
+ "# Age conversion function (not used since age_row is None)\n",
182
+ "def convert_age(value):\n",
183
+ " return None\n",
184
+ "\n",
185
+ "# 3. Save metadata\n",
186
+ "is_trait_available = trait_row is not None\n",
187
+ "validate_and_save_cohort_info(is_final=False, cohort=cohort, info_path=json_path, \n",
188
+ " is_gene_available=is_gene_available, \n",
189
+ " is_trait_available=is_trait_available)\n",
190
+ "\n",
191
+ "# 4. Clinical Feature Extraction\n",
192
+ "# Proceed with extraction since trait_row is not None\n",
193
+ "if is_trait_available:\n",
194
+ " clinical_features = geo_select_clinical_features(\n",
195
+ " clinical_df=clinical_data,\n",
196
+ " trait=trait,\n",
197
+ " trait_row=trait_row,\n",
198
+ " convert_trait=convert_trait,\n",
199
+ " gender_row=gender_row,\n",
200
+ " convert_gender=convert_gender,\n",
201
+ " age_row=age_row,\n",
202
+ " convert_age=convert_age\n",
203
+ " )\n",
204
+ " \n",
205
+ " # Preview the extracted clinical features\n",
206
+ " preview = preview_df(clinical_features)\n",
207
+ " print(\"Clinical Features Preview:\")\n",
208
+ " print(preview)\n",
209
+ " \n",
210
+ " # Save the clinical features to a CSV file\n",
211
+ " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
212
+ " clinical_features.to_csv(out_clinical_data_file, index=False)\n",
213
+ " print(f\"Clinical data saved to {out_clinical_data_file}\")\n"
214
+ ]
215
+ },
216
+ {
217
+ "cell_type": "markdown",
218
+ "id": "bbd67968",
219
+ "metadata": {},
220
+ "source": [
221
+ "### Step 3: Gene Data Extraction"
222
+ ]
223
+ },
224
+ {
225
+ "cell_type": "code",
226
+ "execution_count": 4,
227
+ "id": "1cdd8784",
228
+ "metadata": {
229
+ "execution": {
230
+ "iopub.execute_input": "2025-03-25T08:28:26.896018Z",
231
+ "iopub.status.busy": "2025-03-25T08:28:26.895906Z",
232
+ "iopub.status.idle": "2025-03-25T08:28:27.109235Z",
233
+ "shell.execute_reply": "2025-03-25T08:28:27.108880Z"
234
+ }
235
+ },
236
+ "outputs": [
237
+ {
238
+ "name": "stdout",
239
+ "output_type": "stream",
240
+ "text": [
241
+ "SOFT file: ../../input/GEO/Coronary_artery_disease/GSE250283/GSE250283_family.soft.gz\n",
242
+ "Matrix file: ../../input/GEO/Coronary_artery_disease/GSE250283/GSE250283_series_matrix.txt.gz\n",
243
+ "Found the matrix table marker at line 71\n"
244
+ ]
245
+ },
246
+ {
247
+ "name": "stdout",
248
+ "output_type": "stream",
249
+ "text": [
250
+ "Gene data shape: (33427, 56)\n",
251
+ "First 20 gene/probe identifiers:\n",
252
+ "['ILMN_1343295', 'ILMN_1651199', 'ILMN_1651209', 'ILMN_1651221', 'ILMN_1651228', 'ILMN_1651229', 'ILMN_1651230', 'ILMN_1651232', 'ILMN_1651237', 'ILMN_1651238', 'ILMN_1651249', 'ILMN_1651253', 'ILMN_1651254', 'ILMN_1651259', 'ILMN_1651268', 'ILMN_1651278', 'ILMN_1651279', 'ILMN_1651281', 'ILMN_1651282', 'ILMN_1651285']\n"
253
+ ]
254
+ }
255
+ ],
256
+ "source": [
257
+ "# 1. Identify the paths to the SOFT file and the matrix file\n",
258
+ "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
259
+ "print(f\"SOFT file: {soft_file}\")\n",
260
+ "print(f\"Matrix file: {matrix_file}\")\n",
261
+ "\n",
262
+ "# Set gene availability flag\n",
263
+ "is_gene_available = True # Initially assume gene data is available\n",
264
+ "\n",
265
+ "# First check if the matrix file contains the expected marker\n",
266
+ "found_marker = False\n",
267
+ "marker_row = None\n",
268
+ "try:\n",
269
+ " with gzip.open(matrix_file, 'rt') as file:\n",
270
+ " for i, line in enumerate(file):\n",
271
+ " if \"!series_matrix_table_begin\" in line:\n",
272
+ " found_marker = True\n",
273
+ " marker_row = i\n",
274
+ " print(f\"Found the matrix table marker at line {i}\")\n",
275
+ " break\n",
276
+ " \n",
277
+ " if not found_marker:\n",
278
+ " print(\"Warning: Could not find '!series_matrix_table_begin' marker in the file.\")\n",
279
+ " is_gene_available = False\n",
280
+ " \n",
281
+ " # If marker was found, try to extract gene data\n",
282
+ " if is_gene_available:\n",
283
+ " try:\n",
284
+ " # Try using the library function\n",
285
+ " gene_data = get_genetic_data(matrix_file)\n",
286
+ " \n",
287
+ " if gene_data.shape[0] == 0:\n",
288
+ " print(\"Warning: Extracted gene data has 0 rows.\")\n",
289
+ " is_gene_available = False\n",
290
+ " else:\n",
291
+ " print(f\"Gene data shape: {gene_data.shape}\")\n",
292
+ " # Print the first 20 gene/probe identifiers\n",
293
+ " print(\"First 20 gene/probe identifiers:\")\n",
294
+ " print(gene_data.index[:20].tolist())\n",
295
+ " except Exception as e:\n",
296
+ " print(f\"Error extracting gene data with get_genetic_data(): {e}\")\n",
297
+ " is_gene_available = False\n",
298
+ " \n",
299
+ " # If gene data extraction failed, examine file content to diagnose\n",
300
+ " if not is_gene_available:\n",
301
+ " print(\"Examining file content to diagnose the issue:\")\n",
302
+ " try:\n",
303
+ " with gzip.open(matrix_file, 'rt') as file:\n",
304
+ " # Print lines around the marker if found\n",
305
+ " if marker_row is not None:\n",
306
+ " for i, line in enumerate(file):\n",
307
+ " if i >= marker_row - 2 and i <= marker_row + 10:\n",
308
+ " print(f\"Line {i}: {line.strip()[:100]}...\")\n",
309
+ " if i > marker_row + 10:\n",
310
+ " break\n",
311
+ " else:\n",
312
+ " # If marker not found, print first 10 lines\n",
313
+ " for i, line in enumerate(file):\n",
314
+ " if i < 10:\n",
315
+ " print(f\"Line {i}: {line.strip()[:100]}...\")\n",
316
+ " else:\n",
317
+ " break\n",
318
+ " except Exception as e2:\n",
319
+ " print(f\"Error examining file: {e2}\")\n",
320
+ " \n",
321
+ "except Exception as e:\n",
322
+ " print(f\"Error processing file: {e}\")\n",
323
+ " is_gene_available = False\n",
324
+ "\n",
325
+ "# Update validation information if gene data extraction failed\n",
326
+ "if not is_gene_available:\n",
327
+ " print(\"Gene expression data could not be successfully extracted from this dataset.\")\n",
328
+ " # Update the validation record since gene data isn't available\n",
329
+ " is_trait_available = False # We already determined trait data isn't available in step 2\n",
330
+ " validate_and_save_cohort_info(is_final=False, cohort=cohort, info_path=json_path,\n",
331
+ " is_gene_available=is_gene_available, is_trait_available=is_trait_available)\n"
332
+ ]
333
+ },
334
+ {
335
+ "cell_type": "markdown",
336
+ "id": "7d8b9889",
337
+ "metadata": {},
338
+ "source": [
339
+ "### Step 4: Gene Identifier Review"
340
+ ]
341
+ },
342
+ {
343
+ "cell_type": "code",
344
+ "execution_count": 5,
345
+ "id": "057267b5",
346
+ "metadata": {
347
+ "execution": {
348
+ "iopub.execute_input": "2025-03-25T08:28:27.110469Z",
349
+ "iopub.status.busy": "2025-03-25T08:28:27.110353Z",
350
+ "iopub.status.idle": "2025-03-25T08:28:27.112240Z",
351
+ "shell.execute_reply": "2025-03-25T08:28:27.111958Z"
352
+ }
353
+ },
354
+ "outputs": [],
355
+ "source": [
356
+ "# Looking at the gene identifiers, I can see they start with \"ILMN_\" which indicates they are Illumina probe IDs.\n",
357
+ "# These are not standard human gene symbols and will need to be mapped to gene symbols for proper analysis.\n",
358
+ "# Illumina IDs typically need to be converted to Entrez gene IDs or gene symbols.\n",
359
+ "\n",
360
+ "requires_gene_mapping = True\n"
361
+ ]
362
+ },
363
+ {
364
+ "cell_type": "markdown",
365
+ "id": "f8c24fd0",
366
+ "metadata": {},
367
+ "source": [
368
+ "### Step 5: Gene Annotation"
369
+ ]
370
+ },
371
+ {
372
+ "cell_type": "code",
373
+ "execution_count": 6,
374
+ "id": "5826de83",
375
+ "metadata": {
376
+ "execution": {
377
+ "iopub.execute_input": "2025-03-25T08:28:27.113402Z",
378
+ "iopub.status.busy": "2025-03-25T08:28:27.113295Z",
379
+ "iopub.status.idle": "2025-03-25T08:28:31.729495Z",
380
+ "shell.execute_reply": "2025-03-25T08:28:31.729138Z"
381
+ }
382
+ },
383
+ "outputs": [
384
+ {
385
+ "name": "stdout",
386
+ "output_type": "stream",
387
+ "text": [
388
+ "\n",
389
+ "Gene annotation preview:\n",
390
+ "Columns in gene annotation: ['ID', 'ARRAY_ADDRESS_ID', 'TRANSCRIPT', 'ILMN_GENE', 'PA_Call', 'TARGETID', 'SPECIES', 'SOURCE', 'SEARCH_KEY', 'SOURCE_REFERENCE_ID', 'REFSEQ_ID', 'UNIGENE_ID', 'ENTREZ_GENE_ID', 'GI', 'ACCESSION', 'SYMBOL', 'PROTEIN_PRODUCT', 'PROBE_TYPE', 'PROBE_START', 'SEQUENCE', 'CHROMOSOME', 'PROBE_CHR_ORIENTATION', 'PROBE_COORDINATES', 'CYTOBAND', 'DEFINITION', 'ONTOLOGY_COMPONENT', 'ONTOLOGY_PROCESS', 'ONTOLOGY_FUNCTION', 'SYNONYMS', 'OBSOLETE_PROBE_ID', 'GB_ACC']\n",
391
+ "{'ID': ['ILMN_1343061', 'ILMN_1343291', 'ILMN_1343295'], 'ARRAY_ADDRESS_ID': ['2900397', '3450719', '4490161'], 'TRANSCRIPT': ['ILMN_160461', 'ILMN_137991', 'ILMN_137405'], 'ILMN_GENE': ['CY3_HYB:HIGH_1_MM2', 'EEF1A1', 'GAPDH'], 'PA_Call': [1.0, 1.0, 1.0], 'TARGETID': ['CY3_HYB:HIGH_1_MM2', 'EEF1A1', 'GAPDH'], 'SPECIES': ['ILMN Controls', 'Homo sapiens', 'Homo sapiens'], 'SOURCE': ['ILMN_Controls', 'RefSeq', 'RefSeq'], 'SEARCH_KEY': ['cy3_hyb:high_1_mm2', 'NM_001402.4', nan], 'SOURCE_REFERENCE_ID': ['cy3_hyb:high_1_mm2', 'NM_001402.4', 'NM_002046.2'], 'REFSEQ_ID': [nan, 'NM_001402.4', 'NM_002046.2'], 'UNIGENE_ID': [nan, nan, nan], 'ENTREZ_GENE_ID': [nan, 1915.0, 2597.0], 'GI': [nan, 25453469.0, 7669491.0], 'ACCESSION': ['cy3_hyb:high_1_mm2', 'NM_001402.4', 'NM_002046.2'], 'SYMBOL': ['cy3_hyb:high_1_mm2', 'EEF1A1', 'GAPDH'], 'PROTEIN_PRODUCT': [nan, 'NP_001393.1', 'NP_002037.2'], 'PROBE_TYPE': ['S', 'S', 'S'], 'PROBE_START': [1.0, 1293.0, 930.0], 'SEQUENCE': ['AATTAAAACGATGCACTCAGGGTTTAGCGCGTAGACGTATTGCATTATGC', 'TGTGTTGAGAGCTTCTCAGACTATCCACCTTTGGGTCGCTTTGCTGTTCG', 'CTTCAACAGCGACACCCACTCCTCCACCTTTGACGCTGGGGCTGGCATTG'], 'CHROMOSOME': [nan, '6', '12'], 'PROBE_CHR_ORIENTATION': [nan, '-', '+'], 'PROBE_COORDINATES': [nan, '74284362-74284378:74284474-74284506', '6517340-6517389'], 'CYTOBAND': [nan, '6q13c', '12p13.31d'], 'DEFINITION': [nan, 'Homo sapiens eukaryotic translation elongation factor 1 alpha 1 (EEF1A1)', 'Homo sapiens glyceraldehyde-3-phosphate dehydrogenase (GAPDH)'], 'ONTOLOGY_COMPONENT': [nan, 'mRNA.', 'mRNA.'], 'ONTOLOGY_PROCESS': [nan, 'All of the contents of a cell excluding the plasma membrane and nucleus', 'All of the contents of a cell excluding the plasma membrane and nucleus'], 'ONTOLOGY_FUNCTION': [nan, 'but including other subcellular structures [goid 5737] [evidence NAS]', 'but including other subcellular structures [goid 5737] [evidence NAS]'], 'SYNONYMS': [nan, 'The chemical reactions and pathways resulting in the formation of a protein. This is a ribosome-mediated process in which the information in messenger RNA (mRNA) is used to specify the sequence of amino acids in the protein [goid 6412] [evidence IEA]; The successive addition of amino acid residues to a nascent polypeptide chain during protein biosynthesis [goid 6414] [pmid 3570288] [evidence NAS]', 'The chemical reactions and pathways involving glucose'], 'OBSOLETE_PROBE_ID': [nan, 'Interacting selectively with a nucleotide', 'the aldohexose gluco-hexose. D-glucose is dextrorotatory and is sometimes known as dextrose; it is an important source of energy for living organisms and is found free as well as combined in homo- and hetero-oligosaccharides and polysaccharides [goid 6006] [evidence IEA]; The chemical reactions and pathways resulting in the breakdown of a monosaccharide (generally glucose) into pyruvate'], 'GB_ACC': [nan, 'NM_001402.4', 'NM_002046.2']}\n",
392
+ "\n",
393
+ "Examining mapping information (first 5 rows):\n",
394
+ "Row 0: ID=ILMN_1343061, SYMBOL=cy3_hyb:high_1_mm2\n",
395
+ "Row 1: ID=ILMN_1343291, SYMBOL=EEF1A1\n",
396
+ "Row 2: ID=ILMN_1343295, SYMBOL=GAPDH\n",
397
+ "Row 3: ID=ILMN_1343321, SYMBOL=negative_0971\n",
398
+ "Row 4: ID=ILMN_1343339, SYMBOL=negative_0953\n",
399
+ "\n",
400
+ "SYMBOL column completeness: 44044/1919524 rows (2.29%)\n",
401
+ "\n",
402
+ "Columns identified for gene mapping:\n",
403
+ "- 'ID': Contains Illumina probe IDs (e.g., ILMN_*)\n",
404
+ "- 'SYMBOL': Contains gene symbols\n"
405
+ ]
406
+ }
407
+ ],
408
+ "source": [
409
+ "# 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.\n",
410
+ "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
411
+ "gene_annotation = get_gene_annotation(soft_file)\n",
412
+ "\n",
413
+ "# 2. Analyze the gene annotation dataframe to identify which columns contain the gene identifiers and gene symbols\n",
414
+ "print(\"\\nGene annotation preview:\")\n",
415
+ "print(f\"Columns in gene annotation: {gene_annotation.columns.tolist()}\")\n",
416
+ "print(preview_df(gene_annotation, n=3))\n",
417
+ "\n",
418
+ "# Examine the ID and SYMBOL columns that appear to contain the mapping information\n",
419
+ "print(\"\\nExamining mapping information (first 5 rows):\")\n",
420
+ "if 'ID' in gene_annotation.columns and 'SYMBOL' in gene_annotation.columns:\n",
421
+ " for i in range(min(5, len(gene_annotation))):\n",
422
+ " print(f\"Row {i}: ID={gene_annotation['ID'].iloc[i]}, SYMBOL={gene_annotation['SYMBOL'].iloc[i]}\")\n",
423
+ " \n",
424
+ " # Check the quality and completeness of the mapping\n",
425
+ " non_null_symbols = gene_annotation['SYMBOL'].notna().sum()\n",
426
+ " total_rows = len(gene_annotation)\n",
427
+ " print(f\"\\nSYMBOL column completeness: {non_null_symbols}/{total_rows} rows ({non_null_symbols/total_rows:.2%})\")\n",
428
+ " \n",
429
+ " # Identify the columns needed for gene mapping\n",
430
+ " print(\"\\nColumns identified for gene mapping:\")\n",
431
+ " print(\"- 'ID': Contains Illumina probe IDs (e.g., ILMN_*)\")\n",
432
+ " print(\"- 'SYMBOL': Contains gene symbols\")\n",
433
+ "else:\n",
434
+ " print(\"Error: Required mapping columns ('ID' and/or 'SYMBOL') not found in annotation data.\")\n",
435
+ " print(\"Available columns:\", gene_annotation.columns.tolist())\n"
436
+ ]
437
+ },
438
+ {
439
+ "cell_type": "markdown",
440
+ "id": "46b42c71",
441
+ "metadata": {},
442
+ "source": [
443
+ "### Step 6: Gene Identifier Mapping"
444
+ ]
445
+ },
446
+ {
447
+ "cell_type": "code",
448
+ "execution_count": 7,
449
+ "id": "61c3e1a8",
450
+ "metadata": {
451
+ "execution": {
452
+ "iopub.execute_input": "2025-03-25T08:28:31.731226Z",
453
+ "iopub.status.busy": "2025-03-25T08:28:31.731106Z",
454
+ "iopub.status.idle": "2025-03-25T08:28:32.727796Z",
455
+ "shell.execute_reply": "2025-03-25T08:28:32.727447Z"
456
+ }
457
+ },
458
+ "outputs": [
459
+ {
460
+ "name": "stdout",
461
+ "output_type": "stream",
462
+ "text": [
463
+ "\n",
464
+ "Extracting gene mapping from annotation data...\n",
465
+ "Gene mapping dataframe shape: (44044, 2)\n",
466
+ "First 5 rows of mapping data:\n",
467
+ " ID Gene\n",
468
+ "0 ILMN_1343061 cy3_hyb:high_1_mm2\n",
469
+ "1 ILMN_1343291 EEF1A1\n",
470
+ "2 ILMN_1343295 GAPDH\n",
471
+ "3 ILMN_1343321 negative_0971\n",
472
+ "4 ILMN_1343339 negative_0953\n"
473
+ ]
474
+ },
475
+ {
476
+ "name": "stdout",
477
+ "output_type": "stream",
478
+ "text": [
479
+ "\n",
480
+ "Gene expression data shape: (33427, 56)\n",
481
+ "First 5 probe IDs: ['ILMN_1343295', 'ILMN_1651199', 'ILMN_1651209', 'ILMN_1651221', 'ILMN_1651228']\n",
482
+ "\n",
483
+ "Converting probe-level measurements to gene-level expression data...\n",
484
+ "Gene expression data shape after mapping: (19609, 56)\n",
485
+ "Sample of mapped gene data:\n",
486
+ " GSM7976778 GSM7976779 GSM7976780 GSM7976781 GSM7976782\n",
487
+ "Gene \n",
488
+ "A1BG 3.953042 3.794302 3.997124 3.624063 4.117292\n",
489
+ "A2BP1 3.868455 4.073620 4.183542 4.359270 4.165845\n",
490
+ "A2LD1 5.721705 4.069221 5.230038 4.941044 5.949655\n",
491
+ "A2M 4.313322 3.782428 3.857348 3.448928 3.690780\n",
492
+ "A2ML1 4.145858 3.383440 2.982239 4.012935 3.861670\n"
493
+ ]
494
+ },
495
+ {
496
+ "name": "stdout",
497
+ "output_type": "stream",
498
+ "text": [
499
+ "\n",
500
+ "Gene expression data saved to ../../output/preprocess/Coronary_artery_disease/gene_data/GSE250283.csv\n"
501
+ ]
502
+ }
503
+ ],
504
+ "source": [
505
+ "# 1. First, identify the relevant columns for mapping\n",
506
+ "# From the gene annotation preview, we see that:\n",
507
+ "# - 'ID' contains the Illumina probe IDs (e.g., ILMN_*)\n",
508
+ "# - 'SYMBOL' contains the gene symbols\n",
509
+ "prob_col = 'ID'\n",
510
+ "gene_col = 'SYMBOL'\n",
511
+ "\n",
512
+ "# 2. Get a gene mapping dataframe by extracting the two columns\n",
513
+ "print(\"\\nExtracting gene mapping from annotation data...\")\n",
514
+ "mapping_df = get_gene_mapping(gene_annotation, prob_col, gene_col)\n",
515
+ "print(f\"Gene mapping dataframe shape: {mapping_df.shape}\")\n",
516
+ "print(f\"First 5 rows of mapping data:\")\n",
517
+ "print(mapping_df.head())\n",
518
+ "\n",
519
+ "# 3. Extract the genetic data (probe expression values)\n",
520
+ "gene_expr_data = get_genetic_data(matrix_file)\n",
521
+ "print(f\"\\nGene expression data shape: {gene_expr_data.shape}\")\n",
522
+ "print(f\"First 5 probe IDs: {gene_expr_data.index[:5].tolist()}\")\n",
523
+ "\n",
524
+ "# 4. Convert probe-level measurements to gene-level expression data\n",
525
+ "print(\"\\nConverting probe-level measurements to gene-level expression data...\")\n",
526
+ "gene_data = apply_gene_mapping(gene_expr_data, mapping_df)\n",
527
+ "print(f\"Gene expression data shape after mapping: {gene_data.shape}\")\n",
528
+ "print(\"Sample of mapped gene data:\")\n",
529
+ "print(gene_data.iloc[:5, :5])\n",
530
+ "\n",
531
+ "# 5. Save the processed gene expression data\n",
532
+ "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
533
+ "gene_data.to_csv(out_gene_data_file)\n",
534
+ "print(f\"\\nGene expression data saved to {out_gene_data_file}\")\n"
535
+ ]
536
+ },
537
+ {
538
+ "cell_type": "markdown",
539
+ "id": "14c7c859",
540
+ "metadata": {},
541
+ "source": [
542
+ "### Step 7: Data Normalization and Linking"
543
+ ]
544
+ },
545
+ {
546
+ "cell_type": "code",
547
+ "execution_count": 8,
548
+ "id": "e611f6b3",
549
+ "metadata": {
550
+ "execution": {
551
+ "iopub.execute_input": "2025-03-25T08:28:32.729614Z",
552
+ "iopub.status.busy": "2025-03-25T08:28:32.729451Z",
553
+ "iopub.status.idle": "2025-03-25T08:28:33.445034Z",
554
+ "shell.execute_reply": "2025-03-25T08:28:33.444694Z"
555
+ }
556
+ },
557
+ "outputs": [
558
+ {
559
+ "name": "stdout",
560
+ "output_type": "stream",
561
+ "text": [
562
+ "Normalizing gene symbols...\n",
563
+ "Gene data shape after normalization: (18433, 56)\n"
564
+ ]
565
+ },
566
+ {
567
+ "name": "stdout",
568
+ "output_type": "stream",
569
+ "text": [
570
+ "Normalized gene data saved to ../../output/preprocess/Coronary_artery_disease/gene_data/GSE250283.csv\n",
571
+ "Loaded clinical data shape: (2, 55)\n",
572
+ "Clinical features columns: ['GSM7976779', 'GSM7976780', 'GSM7976781', 'GSM7976782', 'GSM7976783', 'GSM7976784', 'GSM7976785', 'GSM7976786', 'GSM7976787', 'GSM7976788', 'GSM7976789', 'GSM7976790', 'GSM7976791', 'GSM7976792', 'GSM7976793', 'GSM7976794', 'GSM7976795', 'GSM7976796', 'GSM7976797', 'GSM7976798', 'GSM7976799', 'GSM7976800', 'GSM7976801', 'GSM7976802', 'GSM7976803', 'GSM7976804', 'GSM7976805', 'GSM7976806', 'GSM7976807', 'GSM7976808', 'GSM7976809', 'GSM7976810', 'GSM7976811', 'GSM7976812', 'GSM7976813', 'GSM7976814', 'GSM7976815', 'GSM7976816', 'GSM7976817', 'GSM7976818', 'GSM7976819', 'GSM7976820', 'GSM7976821', 'GSM7976822', 'GSM7976823', 'GSM7976824', 'GSM7976825', 'GSM7976826', 'GSM7976827', 'GSM7976828', 'GSM7976829', 'GSM7976830', 'GSM7976831', 'GSM7976832', 'GSM7976833']\n",
573
+ "Initial linked data shape: (56, 18435)\n",
574
+ "Linked data columns: [0.0, 0.0, 'A1BG', 'A2M', 'A2ML1', 'A3GALT2', 'A4GALT', 'A4GNT', 'AAA1', 'AAAS']\n",
575
+ "Handling missing values...\n",
576
+ "Error linking clinical and genetic data: ['Coronary_artery_disease']\n",
577
+ "Abnormality detected in the cohort: GSE250283. Preprocessing failed.\n"
578
+ ]
579
+ },
580
+ {
581
+ "name": "stderr",
582
+ "output_type": "stream",
583
+ "text": [
584
+ "Traceback (most recent call last):\n",
585
+ " File \"/tmp/ipykernel_74302/3819971687.py\", line 54, in <module>\n",
586
+ " linked_data = handle_missing_values(linked_data, trait)\n",
587
+ " File \"/media/techt/DATA/GenoAgent/tools/preprocess.py\", line 430, in handle_missing_values\n",
588
+ " df = df.dropna(subset=[trait_col])\n",
589
+ " File \"/home/techt/anaconda3/envs/agent/lib/python3.10/site-packages/pandas/core/frame.py\", line 6670, in dropna\n",
590
+ " raise KeyError(np.array(subset)[check].tolist())\n",
591
+ "KeyError: ['Coronary_artery_disease']\n"
592
+ ]
593
+ }
594
+ ],
595
+ "source": [
596
+ "# 1. Normalize gene symbols in the obtained gene expression data\n",
597
+ "try:\n",
598
+ " print(\"Normalizing gene symbols...\")\n",
599
+ " normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n",
600
+ " print(f\"Gene data shape after normalization: {normalized_gene_data.shape}\")\n",
601
+ " \n",
602
+ " # Save the normalized gene data\n",
603
+ " os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
604
+ " normalized_gene_data.to_csv(out_gene_data_file)\n",
605
+ " print(f\"Normalized gene data saved to {out_gene_data_file}\")\n",
606
+ " \n",
607
+ " # Check if we have valid gene data to proceed\n",
608
+ " if normalized_gene_data.shape[0] == 0:\n",
609
+ " print(\"WARNING: Gene data is empty after normalization.\")\n",
610
+ " is_gene_available = False\n",
611
+ " \n",
612
+ " # Create an empty dataframe for metadata purposes\n",
613
+ " empty_df = pd.DataFrame()\n",
614
+ " \n",
615
+ " # Log information about this dataset for future reference\n",
616
+ " validate_and_save_cohort_info(\n",
617
+ " is_final=True,\n",
618
+ " cohort=cohort,\n",
619
+ " info_path=json_path,\n",
620
+ " is_gene_available=is_gene_available,\n",
621
+ " is_trait_available=True, # We determined trait data is available in step 2\n",
622
+ " is_biased=True, # Consider it biased as we can't use it\n",
623
+ " df=empty_df,\n",
624
+ " note=\"Gene symbols could not be normalized properly.\"\n",
625
+ " )\n",
626
+ " print(\"Dataset marked as unusable due to lack of valid gene expression data.\")\n",
627
+ " else:\n",
628
+ " # 2. Link the clinical and genetic data if both are available\n",
629
+ " is_trait_available = True # We determined this in step 2\n",
630
+ " \n",
631
+ " # Load clinical data\n",
632
+ " try:\n",
633
+ " clinical_features = pd.read_csv(out_clinical_data_file, index_col=0) # Set index_col=0 to properly load the data\n",
634
+ " print(f\"Loaded clinical data shape: {clinical_features.shape}\")\n",
635
+ " \n",
636
+ " # Debug - inspect column names of clinical_features\n",
637
+ " print(f\"Clinical features columns: {clinical_features.columns.tolist()}\")\n",
638
+ " \n",
639
+ " # Link the clinical and genetic data\n",
640
+ " linked_data = geo_link_clinical_genetic_data(clinical_features, normalized_gene_data)\n",
641
+ " print(f\"Initial linked data shape: {linked_data.shape}\")\n",
642
+ " \n",
643
+ " # Debug - inspect column names of linked_data\n",
644
+ " print(f\"Linked data columns: {linked_data.columns[:10].tolist()}\") # Show first 10 columns\n",
645
+ " \n",
646
+ " # 3. Handle missing values\n",
647
+ " print(\"Handling missing values...\")\n",
648
+ " # Use the trait variable directly, which should contain the correct trait name\n",
649
+ " linked_data = handle_missing_values(linked_data, trait)\n",
650
+ " print(f\"Linked data shape after handling missing values: {linked_data.shape}\")\n",
651
+ " \n",
652
+ " if linked_data.shape[0] > 0:\n",
653
+ " # 4. Check for bias in trait and demographic features\n",
654
+ " print(\"Checking for bias in features...\")\n",
655
+ " is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n",
656
+ " \n",
657
+ " # 5. Validate data quality and save cohort info\n",
658
+ " is_usable = validate_and_save_cohort_info(\n",
659
+ " is_final=True,\n",
660
+ " cohort=cohort,\n",
661
+ " info_path=json_path,\n",
662
+ " is_gene_available=is_gene_available,\n",
663
+ " is_trait_available=is_trait_available,\n",
664
+ " is_biased=is_biased,\n",
665
+ " df=linked_data,\n",
666
+ " note=\"Successfully processed gene expression data for coronary artery disease.\"\n",
667
+ " )\n",
668
+ " \n",
669
+ " # 6. Save the linked data if it's usable\n",
670
+ " if is_usable:\n",
671
+ " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n",
672
+ " linked_data.to_csv(out_data_file)\n",
673
+ " print(f\"Linked data saved to {out_data_file}\")\n",
674
+ " else:\n",
675
+ " print(\"Data not usable for trait study - not saving final linked data.\")\n",
676
+ " else:\n",
677
+ " print(\"After handling missing values, no samples remain.\")\n",
678
+ " validate_and_save_cohort_info(\n",
679
+ " is_final=True,\n",
680
+ " cohort=cohort,\n",
681
+ " info_path=json_path,\n",
682
+ " is_gene_available=is_gene_available,\n",
683
+ " is_trait_available=is_trait_available,\n",
684
+ " is_biased=True,\n",
685
+ " df=pd.DataFrame(),\n",
686
+ " note=\"No valid samples after handling missing values.\"\n",
687
+ " )\n",
688
+ " except Exception as e:\n",
689
+ " print(f\"Error linking clinical and genetic data: {e}\")\n",
690
+ " import traceback\n",
691
+ " traceback.print_exc() # Print full traceback for better debugging\n",
692
+ " validate_and_save_cohort_info(\n",
693
+ " is_final=True,\n",
694
+ " cohort=cohort,\n",
695
+ " info_path=json_path,\n",
696
+ " is_gene_available=is_gene_available,\n",
697
+ " is_trait_available=is_trait_available,\n",
698
+ " is_biased=True,\n",
699
+ " df=pd.DataFrame(),\n",
700
+ " note=f\"Error during data linking: {str(e)}\"\n",
701
+ " )\n",
702
+ "except Exception as e:\n",
703
+ " print(f\"Error in gene symbol normalization: {e}\")\n",
704
+ " import traceback\n",
705
+ " traceback.print_exc() # Print full traceback for better debugging\n",
706
+ " \n",
707
+ " # Log the error and mark the dataset as unusable\n",
708
+ " validate_and_save_cohort_info(\n",
709
+ " is_final=True,\n",
710
+ " cohort=cohort,\n",
711
+ " info_path=json_path,\n",
712
+ " is_gene_available=False, # Consider gene data unavailable if we had an error\n",
713
+ " is_trait_available=True, # We determined trait data is available in step 2\n",
714
+ " is_biased=True, # Consider it biased as we can't use it\n",
715
+ " df=pd.DataFrame(), # Empty dataframe for metadata\n",
716
+ " note=f\"Error during gene symbol normalization: {str(e)}\"\n",
717
+ " )"
718
+ ]
719
+ }
720
+ ],
721
+ "metadata": {
722
+ "language_info": {
723
+ "codemirror_mode": {
724
+ "name": "ipython",
725
+ "version": 3
726
+ },
727
+ "file_extension": ".py",
728
+ "mimetype": "text/x-python",
729
+ "name": "python",
730
+ "nbconvert_exporter": "python",
731
+ "pygments_lexer": "ipython3",
732
+ "version": "3.10.16"
733
+ }
734
+ },
735
+ "nbformat": 4,
736
+ "nbformat_minor": 5
737
+ }
code/Coronary_artery_disease/GSE54975.ipynb ADDED
@@ -0,0 +1,676 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": 1,
6
+ "id": "183719bd",
7
+ "metadata": {
8
+ "execution": {
9
+ "iopub.execute_input": "2025-03-25T08:28:34.347067Z",
10
+ "iopub.status.busy": "2025-03-25T08:28:34.346763Z",
11
+ "iopub.status.idle": "2025-03-25T08:28:34.510336Z",
12
+ "shell.execute_reply": "2025-03-25T08:28:34.510002Z"
13
+ }
14
+ },
15
+ "outputs": [],
16
+ "source": [
17
+ "import sys\n",
18
+ "import os\n",
19
+ "sys.path.append(os.path.abspath(os.path.join(os.getcwd(), '../..')))\n",
20
+ "\n",
21
+ "# Path Configuration\n",
22
+ "from tools.preprocess import *\n",
23
+ "\n",
24
+ "# Processing context\n",
25
+ "trait = \"Coronary_artery_disease\"\n",
26
+ "cohort = \"GSE54975\"\n",
27
+ "\n",
28
+ "# Input paths\n",
29
+ "in_trait_dir = \"../../input/GEO/Coronary_artery_disease\"\n",
30
+ "in_cohort_dir = \"../../input/GEO/Coronary_artery_disease/GSE54975\"\n",
31
+ "\n",
32
+ "# Output paths\n",
33
+ "out_data_file = \"../../output/preprocess/Coronary_artery_disease/GSE54975.csv\"\n",
34
+ "out_gene_data_file = \"../../output/preprocess/Coronary_artery_disease/gene_data/GSE54975.csv\"\n",
35
+ "out_clinical_data_file = \"../../output/preprocess/Coronary_artery_disease/clinical_data/GSE54975.csv\"\n",
36
+ "json_path = \"../../output/preprocess/Coronary_artery_disease/cohort_info.json\"\n"
37
+ ]
38
+ },
39
+ {
40
+ "cell_type": "markdown",
41
+ "id": "b000b636",
42
+ "metadata": {},
43
+ "source": [
44
+ "### Step 1: Initial Data Loading"
45
+ ]
46
+ },
47
+ {
48
+ "cell_type": "code",
49
+ "execution_count": 2,
50
+ "id": "4fc3b3e1",
51
+ "metadata": {
52
+ "execution": {
53
+ "iopub.execute_input": "2025-03-25T08:28:34.511532Z",
54
+ "iopub.status.busy": "2025-03-25T08:28:34.511385Z",
55
+ "iopub.status.idle": "2025-03-25T08:28:34.589910Z",
56
+ "shell.execute_reply": "2025-03-25T08:28:34.589619Z"
57
+ }
58
+ },
59
+ "outputs": [
60
+ {
61
+ "name": "stdout",
62
+ "output_type": "stream",
63
+ "text": [
64
+ "Background Information:\n",
65
+ "!Series_title\t\"Lipid-induced epigenomic changes in human macrophages identify a coronary artery disease associated variant that regulates PPAP2B expression through altered C/EBP-beta binding\"\n",
66
+ "!Series_summary\t\"This SuperSeries is composed of the SubSeries listed below.\"\n",
67
+ "!Series_overall_design\t\"Refer to individual Series\"\n",
68
+ "Sample Characteristics Dictionary:\n",
69
+ "{0: ['background: European', 'background: Nepalese'], 1: ['cell type: Macrophage'], 2: ['agent: oxLDL', 'agent: control buffer']}\n"
70
+ ]
71
+ }
72
+ ],
73
+ "source": [
74
+ "from tools.preprocess import *\n",
75
+ "# 1. Identify the paths to the SOFT file and the matrix file\n",
76
+ "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
77
+ "\n",
78
+ "# 2. Read the matrix file to obtain background information and sample characteristics data\n",
79
+ "background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']\n",
80
+ "clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']\n",
81
+ "background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)\n",
82
+ "\n",
83
+ "# 3. Obtain the sample characteristics dictionary from the clinical dataframe\n",
84
+ "sample_characteristics_dict = get_unique_values_by_row(clinical_data)\n",
85
+ "\n",
86
+ "# 4. Explicitly print out all the background information and the sample characteristics dictionary\n",
87
+ "print(\"Background Information:\")\n",
88
+ "print(background_info)\n",
89
+ "print(\"Sample Characteristics Dictionary:\")\n",
90
+ "print(sample_characteristics_dict)\n"
91
+ ]
92
+ },
93
+ {
94
+ "cell_type": "markdown",
95
+ "id": "59cc5744",
96
+ "metadata": {},
97
+ "source": [
98
+ "### Step 2: Dataset Analysis and Clinical Feature Extraction"
99
+ ]
100
+ },
101
+ {
102
+ "cell_type": "code",
103
+ "execution_count": 3,
104
+ "id": "b4803a43",
105
+ "metadata": {
106
+ "execution": {
107
+ "iopub.execute_input": "2025-03-25T08:28:34.590921Z",
108
+ "iopub.status.busy": "2025-03-25T08:28:34.590810Z",
109
+ "iopub.status.idle": "2025-03-25T08:28:34.597114Z",
110
+ "shell.execute_reply": "2025-03-25T08:28:34.596816Z"
111
+ }
112
+ },
113
+ "outputs": [
114
+ {
115
+ "name": "stdout",
116
+ "output_type": "stream",
117
+ "text": [
118
+ "Clinical Features Preview:\n",
119
+ "{'GSM1321503': [1.0], 'GSM1321504': [0.0], 'GSM1321505': [1.0], 'GSM1321506': [0.0], 'GSM1321507': [1.0], 'GSM1321508': [0.0], 'GSM1321509': [1.0], 'GSM1321510': [0.0], 'GSM1321511': [1.0], 'GSM1321512': [1.0], 'GSM1321513': [0.0], 'GSM1321514': [0.0]}\n",
120
+ "Clinical data saved to ../../output/preprocess/Coronary_artery_disease/clinical_data/GSE54975.csv\n"
121
+ ]
122
+ }
123
+ ],
124
+ "source": [
125
+ "# 1. Gene Expression Data Availability\n",
126
+ "# Based on the title and characteristics, this dataset appears to focus on epigenomic changes and gene expression\n",
127
+ "# related to coronary artery disease, which suggests gene expression data is available\n",
128
+ "is_gene_available = True\n",
129
+ "\n",
130
+ "# 2. Variable Availability and Data Type Conversion\n",
131
+ "# 2.1 Data Availability\n",
132
+ "# Looking at the sample characteristics dictionary:\n",
133
+ "# - trait (disease status): Not explicitly available in the characteristics\n",
134
+ "# - age: Not available in the characteristics\n",
135
+ "# - gender: Not available in the characteristics\n",
136
+ "\n",
137
+ "# For trait, we can infer from agent field (key 2): oxLDL vs control buffer\n",
138
+ "trait_row = 2 \n",
139
+ "age_row = None # Age data not available\n",
140
+ "gender_row = None # Gender data not available\n",
141
+ "\n",
142
+ "# 2.2 Data Type Conversion\n",
143
+ "\n",
144
+ "# For trait (CAD status), we'll convert from the agent field:\n",
145
+ "# \"agent: oxLDL\" indicates treated/case sample (1)\n",
146
+ "# \"agent: control buffer\" indicates control (0)\n",
147
+ "def convert_trait(value):\n",
148
+ " if not isinstance(value, str):\n",
149
+ " return None\n",
150
+ " value = value.lower().strip()\n",
151
+ " if 'agent:' in value:\n",
152
+ " value = value.split('agent:')[1].strip()\n",
153
+ " if 'oxldl' in value:\n",
154
+ " return 1 # Treated with oxidized LDL (case)\n",
155
+ " elif 'control' in value:\n",
156
+ " return 0 # Control\n",
157
+ " return None\n",
158
+ "\n",
159
+ "# Age conversion function (not used but defined for completeness)\n",
160
+ "def convert_age(value):\n",
161
+ " return None\n",
162
+ "\n",
163
+ "# Gender conversion function (not used but defined for completeness)\n",
164
+ "def convert_gender(value):\n",
165
+ " return None\n",
166
+ "\n",
167
+ "# 3. Save Metadata\n",
168
+ "# Determine if trait data is available\n",
169
+ "is_trait_available = trait_row is not None\n",
170
+ "\n",
171
+ "# Initial filtering on usability\n",
172
+ "validate_and_save_cohort_info(\n",
173
+ " is_final=False,\n",
174
+ " cohort=cohort,\n",
175
+ " info_path=json_path,\n",
176
+ " is_gene_available=is_gene_available,\n",
177
+ " is_trait_available=is_trait_available\n",
178
+ ")\n",
179
+ "\n",
180
+ "# 4. Clinical Feature Extraction\n",
181
+ "# Since trait_row is not None, we need to extract clinical features\n",
182
+ "if trait_row is not None:\n",
183
+ " try:\n",
184
+ " # Use the clinical_data variable that should be available from previous steps\n",
185
+ " selected_clinical_df = geo_select_clinical_features(\n",
186
+ " clinical_df=clinical_data,\n",
187
+ " trait=trait,\n",
188
+ " trait_row=trait_row,\n",
189
+ " convert_trait=convert_trait,\n",
190
+ " age_row=age_row,\n",
191
+ " convert_age=convert_age,\n",
192
+ " gender_row=gender_row,\n",
193
+ " convert_gender=convert_gender\n",
194
+ " )\n",
195
+ " \n",
196
+ " # Preview the extracted clinical features\n",
197
+ " print(\"Clinical Features Preview:\")\n",
198
+ " preview = preview_df(selected_clinical_df)\n",
199
+ " print(preview)\n",
200
+ " \n",
201
+ " # Save the clinical features to a CSV file\n",
202
+ " selected_clinical_df.to_csv(out_clinical_data_file)\n",
203
+ " print(f\"Clinical data saved to {out_clinical_data_file}\")\n",
204
+ " \n",
205
+ " except Exception as e:\n",
206
+ " print(f\"Error in clinical feature extraction: {e}\")\n",
207
+ " is_trait_available = False\n"
208
+ ]
209
+ },
210
+ {
211
+ "cell_type": "markdown",
212
+ "id": "b1ab8829",
213
+ "metadata": {},
214
+ "source": [
215
+ "### Step 3: Gene Data Extraction"
216
+ ]
217
+ },
218
+ {
219
+ "cell_type": "code",
220
+ "execution_count": 4,
221
+ "id": "f1f40dbe",
222
+ "metadata": {
223
+ "execution": {
224
+ "iopub.execute_input": "2025-03-25T08:28:34.598026Z",
225
+ "iopub.status.busy": "2025-03-25T08:28:34.597914Z",
226
+ "iopub.status.idle": "2025-03-25T08:28:34.674435Z",
227
+ "shell.execute_reply": "2025-03-25T08:28:34.674082Z"
228
+ }
229
+ },
230
+ "outputs": [
231
+ {
232
+ "name": "stdout",
233
+ "output_type": "stream",
234
+ "text": [
235
+ "SOFT file: ../../input/GEO/Coronary_artery_disease/GSE54975/GSE54975_family.soft.gz\n",
236
+ "Matrix file: ../../input/GEO/Coronary_artery_disease/GSE54975/GSE54975-GPL10558_series_matrix.txt.gz\n",
237
+ "Found the matrix table marker at line 71\n",
238
+ "Gene data shape: (47231, 12)\n",
239
+ "First 20 gene/probe identifiers:\n",
240
+ "['ILMN_1343291', 'ILMN_1343295', 'ILMN_1651199', 'ILMN_1651209', 'ILMN_1651210', 'ILMN_1651221', 'ILMN_1651228', 'ILMN_1651229', 'ILMN_1651230', 'ILMN_1651232', 'ILMN_1651235', 'ILMN_1651236', 'ILMN_1651237', 'ILMN_1651238', 'ILMN_1651249', 'ILMN_1651253', 'ILMN_1651254', 'ILMN_1651259', 'ILMN_1651260', 'ILMN_1651262']\n"
241
+ ]
242
+ }
243
+ ],
244
+ "source": [
245
+ "# 1. Identify the paths to the SOFT file and the matrix file\n",
246
+ "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
247
+ "print(f\"SOFT file: {soft_file}\")\n",
248
+ "print(f\"Matrix file: {matrix_file}\")\n",
249
+ "\n",
250
+ "# Set gene availability flag\n",
251
+ "is_gene_available = True # Initially assume gene data is available\n",
252
+ "\n",
253
+ "# First check if the matrix file contains the expected marker\n",
254
+ "found_marker = False\n",
255
+ "marker_row = None\n",
256
+ "try:\n",
257
+ " with gzip.open(matrix_file, 'rt') as file:\n",
258
+ " for i, line in enumerate(file):\n",
259
+ " if \"!series_matrix_table_begin\" in line:\n",
260
+ " found_marker = True\n",
261
+ " marker_row = i\n",
262
+ " print(f\"Found the matrix table marker at line {i}\")\n",
263
+ " break\n",
264
+ " \n",
265
+ " if not found_marker:\n",
266
+ " print(\"Warning: Could not find '!series_matrix_table_begin' marker in the file.\")\n",
267
+ " is_gene_available = False\n",
268
+ " \n",
269
+ " # If marker was found, try to extract gene data\n",
270
+ " if is_gene_available:\n",
271
+ " try:\n",
272
+ " # Try using the library function\n",
273
+ " gene_data = get_genetic_data(matrix_file)\n",
274
+ " \n",
275
+ " if gene_data.shape[0] == 0:\n",
276
+ " print(\"Warning: Extracted gene data has 0 rows.\")\n",
277
+ " is_gene_available = False\n",
278
+ " else:\n",
279
+ " print(f\"Gene data shape: {gene_data.shape}\")\n",
280
+ " # Print the first 20 gene/probe identifiers\n",
281
+ " print(\"First 20 gene/probe identifiers:\")\n",
282
+ " print(gene_data.index[:20].tolist())\n",
283
+ " except Exception as e:\n",
284
+ " print(f\"Error extracting gene data with get_genetic_data(): {e}\")\n",
285
+ " is_gene_available = False\n",
286
+ " \n",
287
+ " # If gene data extraction failed, examine file content to diagnose\n",
288
+ " if not is_gene_available:\n",
289
+ " print(\"Examining file content to diagnose the issue:\")\n",
290
+ " try:\n",
291
+ " with gzip.open(matrix_file, 'rt') as file:\n",
292
+ " # Print lines around the marker if found\n",
293
+ " if marker_row is not None:\n",
294
+ " for i, line in enumerate(file):\n",
295
+ " if i >= marker_row - 2 and i <= marker_row + 10:\n",
296
+ " print(f\"Line {i}: {line.strip()[:100]}...\")\n",
297
+ " if i > marker_row + 10:\n",
298
+ " break\n",
299
+ " else:\n",
300
+ " # If marker not found, print first 10 lines\n",
301
+ " for i, line in enumerate(file):\n",
302
+ " if i < 10:\n",
303
+ " print(f\"Line {i}: {line.strip()[:100]}...\")\n",
304
+ " else:\n",
305
+ " break\n",
306
+ " except Exception as e2:\n",
307
+ " print(f\"Error examining file: {e2}\")\n",
308
+ " \n",
309
+ "except Exception as e:\n",
310
+ " print(f\"Error processing file: {e}\")\n",
311
+ " is_gene_available = False\n",
312
+ "\n",
313
+ "# Update validation information if gene data extraction failed\n",
314
+ "if not is_gene_available:\n",
315
+ " print(\"Gene expression data could not be successfully extracted from this dataset.\")\n",
316
+ " # Update the validation record since gene data isn't available\n",
317
+ " is_trait_available = False # We already determined trait data isn't available in step 2\n",
318
+ " validate_and_save_cohort_info(is_final=False, cohort=cohort, info_path=json_path,\n",
319
+ " is_gene_available=is_gene_available, is_trait_available=is_trait_available)\n"
320
+ ]
321
+ },
322
+ {
323
+ "cell_type": "markdown",
324
+ "id": "b57b756a",
325
+ "metadata": {},
326
+ "source": [
327
+ "### Step 4: Gene Identifier Review"
328
+ ]
329
+ },
330
+ {
331
+ "cell_type": "code",
332
+ "execution_count": 5,
333
+ "id": "a6c323b3",
334
+ "metadata": {
335
+ "execution": {
336
+ "iopub.execute_input": "2025-03-25T08:28:34.675548Z",
337
+ "iopub.status.busy": "2025-03-25T08:28:34.675435Z",
338
+ "iopub.status.idle": "2025-03-25T08:28:34.677305Z",
339
+ "shell.execute_reply": "2025-03-25T08:28:34.677013Z"
340
+ }
341
+ },
342
+ "outputs": [],
343
+ "source": [
344
+ "# The identifiers shown (ILMN_xxxxxxx) are Illumina probe IDs from the Illumina BeadChip platform (GPL10558)\n",
345
+ "# These are not human gene symbols and will need to be mapped to gene symbols\n",
346
+ "\n",
347
+ "requires_gene_mapping = True\n"
348
+ ]
349
+ },
350
+ {
351
+ "cell_type": "markdown",
352
+ "id": "0894210b",
353
+ "metadata": {},
354
+ "source": [
355
+ "### Step 5: Gene Annotation"
356
+ ]
357
+ },
358
+ {
359
+ "cell_type": "code",
360
+ "execution_count": 6,
361
+ "id": "d8a95a20",
362
+ "metadata": {
363
+ "execution": {
364
+ "iopub.execute_input": "2025-03-25T08:28:34.678368Z",
365
+ "iopub.status.busy": "2025-03-25T08:28:34.678243Z",
366
+ "iopub.status.idle": "2025-03-25T08:28:36.607778Z",
367
+ "shell.execute_reply": "2025-03-25T08:28:36.607404Z"
368
+ }
369
+ },
370
+ "outputs": [
371
+ {
372
+ "name": "stdout",
373
+ "output_type": "stream",
374
+ "text": [
375
+ "\n",
376
+ "Gene annotation preview:\n",
377
+ "Columns in gene annotation: ['ID', 'Species', 'Source', 'Search_Key', 'Transcript', 'ILMN_Gene', 'Source_Reference_ID', 'RefSeq_ID', 'Unigene_ID', 'Entrez_Gene_ID', 'GI', 'Accession', 'Symbol', 'Protein_Product', 'Probe_Id', 'Array_Address_Id', 'Probe_Type', 'Probe_Start', 'SEQUENCE', 'Chromosome', 'Probe_Chr_Orientation', 'Probe_Coordinates', 'Cytoband', 'Definition', 'Ontology_Component', 'Ontology_Process', 'Ontology_Function', 'Synonyms', 'Obsolete_Probe_Id', 'GB_ACC']\n",
378
+ "{'ID': ['ILMN_1343048', 'ILMN_1343049', 'ILMN_1343050'], 'Species': [nan, nan, nan], 'Source': [nan, nan, nan], 'Search_Key': [nan, nan, nan], 'Transcript': [nan, nan, nan], 'ILMN_Gene': [nan, nan, nan], 'Source_Reference_ID': [nan, nan, nan], 'RefSeq_ID': [nan, nan, nan], 'Unigene_ID': [nan, nan, nan], 'Entrez_Gene_ID': [nan, nan, nan], 'GI': [nan, nan, nan], 'Accession': [nan, nan, nan], 'Symbol': ['phage_lambda_genome', 'phage_lambda_genome', 'phage_lambda_genome:low'], 'Protein_Product': [nan, nan, nan], 'Probe_Id': [nan, nan, nan], 'Array_Address_Id': [5090180.0, 6510136.0, 7560739.0], 'Probe_Type': [nan, nan, nan], 'Probe_Start': [nan, nan, nan], 'SEQUENCE': ['GAATAAAGAACAATCTGCTGATGATCCCTCCGTGGATCTGATTCGTGTAA', 'CCATGTGATACGAGGGCGCGTAGTTTGCATTATCGTTTTTATCGTTTCAA', 'CCGACAGATGTATGTAAGGCCAACGTGCTCAAATCTTCATACAGAAAGAT'], 'Chromosome': [nan, nan, nan], 'Probe_Chr_Orientation': [nan, nan, nan], 'Probe_Coordinates': [nan, nan, nan], 'Cytoband': [nan, nan, nan], 'Definition': [nan, nan, nan], 'Ontology_Component': [nan, nan, nan], 'Ontology_Process': [nan, nan, nan], 'Ontology_Function': [nan, nan, nan], 'Synonyms': [nan, nan, nan], 'Obsolete_Probe_Id': [nan, nan, nan], 'GB_ACC': [nan, nan, nan]}\n",
379
+ "\n",
380
+ "Examining mapping information (first 5 rows):\n",
381
+ "Row 0: ID=ILMN_1343048, Symbol=phage_lambda_genome\n",
382
+ "Row 1: ID=ILMN_1343049, Symbol=phage_lambda_genome\n",
383
+ "Row 2: ID=ILMN_1343050, Symbol=phage_lambda_genome:low\n",
384
+ "Row 3: ID=ILMN_1343052, Symbol=phage_lambda_genome:low\n",
385
+ "Row 4: ID=ILMN_1343059, Symbol=thrB\n",
386
+ "\n",
387
+ "Symbol column completeness: 44837/614891 rows (7.29%)\n",
388
+ "\n",
389
+ "Columns identified for gene mapping:\n",
390
+ "- 'ID': Contains Illumina probe IDs (e.g., ILMN_*)\n",
391
+ "- 'Symbol': Contains gene symbols\n"
392
+ ]
393
+ }
394
+ ],
395
+ "source": [
396
+ "# 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.\n",
397
+ "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
398
+ "gene_annotation = get_gene_annotation(soft_file)\n",
399
+ "\n",
400
+ "# 2. Analyze the gene annotation dataframe to identify which columns contain the gene identifiers and gene symbols\n",
401
+ "print(\"\\nGene annotation preview:\")\n",
402
+ "print(f\"Columns in gene annotation: {gene_annotation.columns.tolist()}\")\n",
403
+ "print(preview_df(gene_annotation, n=3))\n",
404
+ "\n",
405
+ "# Examine the ID and Symbol columns that appear to contain the mapping information\n",
406
+ "print(\"\\nExamining mapping information (first 5 rows):\")\n",
407
+ "if 'ID' in gene_annotation.columns and 'Symbol' in gene_annotation.columns:\n",
408
+ " for i in range(min(5, len(gene_annotation))):\n",
409
+ " print(f\"Row {i}: ID={gene_annotation['ID'].iloc[i]}, Symbol={gene_annotation['Symbol'].iloc[i]}\")\n",
410
+ " \n",
411
+ " # Check the quality and completeness of the mapping\n",
412
+ " non_null_symbols = gene_annotation['Symbol'].notna().sum()\n",
413
+ " total_rows = len(gene_annotation)\n",
414
+ " print(f\"\\nSymbol column completeness: {non_null_symbols}/{total_rows} rows ({non_null_symbols/total_rows:.2%})\")\n",
415
+ " \n",
416
+ " # Identify the columns needed for gene mapping\n",
417
+ " print(\"\\nColumns identified for gene mapping:\")\n",
418
+ " print(\"- 'ID': Contains Illumina probe IDs (e.g., ILMN_*)\")\n",
419
+ " print(\"- 'Symbol': Contains gene symbols\")\n"
420
+ ]
421
+ },
422
+ {
423
+ "cell_type": "markdown",
424
+ "id": "aae4a242",
425
+ "metadata": {},
426
+ "source": [
427
+ "### Step 6: Gene Identifier Mapping"
428
+ ]
429
+ },
430
+ {
431
+ "cell_type": "code",
432
+ "execution_count": 7,
433
+ "id": "c6ad8e2b",
434
+ "metadata": {
435
+ "execution": {
436
+ "iopub.execute_input": "2025-03-25T08:28:36.609006Z",
437
+ "iopub.status.busy": "2025-03-25T08:28:36.608882Z",
438
+ "iopub.status.idle": "2025-03-25T08:28:36.944557Z",
439
+ "shell.execute_reply": "2025-03-25T08:28:36.944183Z"
440
+ }
441
+ },
442
+ "outputs": [
443
+ {
444
+ "name": "stdout",
445
+ "output_type": "stream",
446
+ "text": [
447
+ "Gene mapping dataframe shape: (44837, 2)\n",
448
+ "Gene mapping preview:\n",
449
+ "{'ID': ['ILMN_1343048', 'ILMN_1343049', 'ILMN_1343050', 'ILMN_1343052', 'ILMN_1343059'], 'Gene': ['phage_lambda_genome', 'phage_lambda_genome', 'phage_lambda_genome:low', 'phage_lambda_genome:low', 'thrB']}\n",
450
+ "Gene expression data shape (before mapping): (47231, 12)\n",
451
+ "Gene expression data shape (after mapping): (21372, 12)\n",
452
+ "Gene data preview (first 5 genes):\n",
453
+ "{'GSM1321503': [14.725556807, 21.877370881, 22.014179287, 28.66824101, 8.37253827], 'GSM1321504': [14.699442151, 21.844561159, 22.021686406, 28.699002439, 8.579392591], 'GSM1321505': [14.689998565, 22.035022234, 22.092588802999998, 28.604531031, 8.075103553], 'GSM1321506': [14.768962991999999, 21.647306364000002, 21.625944806, 28.692870384, 8.293847264], 'GSM1321507': [14.825603059999999, 21.810194296, 21.507765248, 28.665816932, 7.943434895], 'GSM1321508': [14.879285424999999, 21.974036685, 21.563995386000002, 28.804042170000002, 8.219964587], 'GSM1321509': [14.620800768, 21.742304923, 21.616011012, 28.653105011, 8.341763357], 'GSM1321510': [15.020158855, 21.685478628, 21.635962415999998, 28.737932848, 8.380644481], 'GSM1321511': [14.681011672, 21.931430797, 21.589841269, 28.798567665, 8.314139397], 'GSM1321512': [14.781740257, 21.738303121, 21.663216964, 28.885017461, 7.893778796], 'GSM1321513': [14.829924474999999, 21.657077327, 21.536321309, 28.524867212, 8.132349026], 'GSM1321514': [14.746322423, 22.048818431999997, 21.511160908999997, 28.671119793, 8.312752247]}\n"
454
+ ]
455
+ },
456
+ {
457
+ "name": "stdout",
458
+ "output_type": "stream",
459
+ "text": [
460
+ "Gene expression data saved to ../../output/preprocess/Coronary_artery_disease/gene_data/GSE54975.csv\n"
461
+ ]
462
+ }
463
+ ],
464
+ "source": [
465
+ "# 1. Create a mapping dataframe from the gene annotation\n",
466
+ "# Based on previous outputs, we identified:\n",
467
+ "# - 'ID' column contains Illumina probe IDs that match the gene expression data index\n",
468
+ "# - 'Symbol' column contains gene symbols we need to map to\n",
469
+ "\n",
470
+ "# Get the mapping dataframe with 'ID' and 'Symbol' columns\n",
471
+ "gene_mapping = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='Symbol')\n",
472
+ "\n",
473
+ "# Check the mapping dataframe \n",
474
+ "print(f\"Gene mapping dataframe shape: {gene_mapping.shape}\")\n",
475
+ "print(\"Gene mapping preview:\")\n",
476
+ "print(preview_df(gene_mapping, n=5))\n",
477
+ "\n",
478
+ "# 2. Read genetic data again to ensure we're working with the correct data\n",
479
+ "gene_data_raw = get_genetic_data(matrix_file)\n",
480
+ "print(f\"Gene expression data shape (before mapping): {gene_data_raw.shape}\")\n",
481
+ "\n",
482
+ "# 3. Apply the gene mapping to convert probe-level measurements to gene-level data\n",
483
+ "gene_data = apply_gene_mapping(gene_data_raw, gene_mapping)\n",
484
+ "\n",
485
+ "# Check the processed gene data\n",
486
+ "print(f\"Gene expression data shape (after mapping): {gene_data.shape}\")\n",
487
+ "print(\"Gene data preview (first 5 genes):\")\n",
488
+ "print(preview_df(gene_data, n=5))\n",
489
+ "\n",
490
+ "# Save the gene expression data to a CSV file\n",
491
+ "gene_data.to_csv(out_gene_data_file)\n",
492
+ "print(f\"Gene expression data saved to {out_gene_data_file}\")\n"
493
+ ]
494
+ },
495
+ {
496
+ "cell_type": "markdown",
497
+ "id": "51234f92",
498
+ "metadata": {},
499
+ "source": [
500
+ "### Step 7: Data Normalization and Linking"
501
+ ]
502
+ },
503
+ {
504
+ "cell_type": "code",
505
+ "execution_count": 8,
506
+ "id": "466c5fc8",
507
+ "metadata": {
508
+ "execution": {
509
+ "iopub.execute_input": "2025-03-25T08:28:36.946303Z",
510
+ "iopub.status.busy": "2025-03-25T08:28:36.946189Z",
511
+ "iopub.status.idle": "2025-03-25T08:28:44.438632Z",
512
+ "shell.execute_reply": "2025-03-25T08:28:44.438262Z"
513
+ }
514
+ },
515
+ "outputs": [
516
+ {
517
+ "name": "stdout",
518
+ "output_type": "stream",
519
+ "text": [
520
+ "Gene data shape before normalization: (21372, 12)\n",
521
+ "Gene data saved to ../../output/preprocess/Coronary_artery_disease/gene_data/GSE54975.csv\n",
522
+ "Loaded clinical data shape: (1, 12)\n",
523
+ "Initial linked data shape: (12, 21373)\n"
524
+ ]
525
+ },
526
+ {
527
+ "name": "stdout",
528
+ "output_type": "stream",
529
+ "text": [
530
+ "Linked data shape after handling missing values: (12, 21373)\n",
531
+ "For the feature 'Coronary_artery_disease', the least common label is '1.0' with 6 occurrences. This represents 50.00% of the dataset.\n",
532
+ "The distribution of the feature 'Coronary_artery_disease' in this dataset is fine.\n",
533
+ "\n"
534
+ ]
535
+ },
536
+ {
537
+ "name": "stdout",
538
+ "output_type": "stream",
539
+ "text": [
540
+ "Linked data saved to ../../output/preprocess/Coronary_artery_disease/GSE54975.csv\n"
541
+ ]
542
+ }
543
+ ],
544
+ "source": [
545
+ "# 1. Attempt to load gene data and handle possible issues with normalization\n",
546
+ "try:\n",
547
+ " # Create output directory if it doesn't exist\n",
548
+ " os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
549
+ " \n",
550
+ " # Check if gene_data (from previous step) has any content\n",
551
+ " if gene_data.shape[0] == 0:\n",
552
+ " print(\"WARNING: Gene data is empty after normalization in previous step.\")\n",
553
+ " print(\"This appears to be miRNA data rather than gene expression data.\")\n",
554
+ " \n",
555
+ " # Since gene_data is empty, set gene_available to False\n",
556
+ " is_gene_available = False\n",
557
+ " \n",
558
+ " # Create an empty dataframe for metadata purposes\n",
559
+ " empty_df = pd.DataFrame()\n",
560
+ " \n",
561
+ " # Log information about this dataset for future reference\n",
562
+ " validate_and_save_cohort_info(\n",
563
+ " is_final=True,\n",
564
+ " cohort=cohort,\n",
565
+ " info_path=json_path,\n",
566
+ " is_gene_available=is_gene_available,\n",
567
+ " is_trait_available=is_trait_available,\n",
568
+ " is_biased=True, # Consider it biased as we can't use it\n",
569
+ " df=empty_df,\n",
570
+ " note=\"Dataset appears to contain miRNA data rather than gene expression data. Gene symbols could not be normalized.\"\n",
571
+ " )\n",
572
+ " \n",
573
+ " print(\"Dataset marked as unusable due to lack of valid gene expression data.\")\n",
574
+ " else:\n",
575
+ " # If gene_data is not empty, proceed with normalization and linking\n",
576
+ " print(f\"Gene data shape before normalization: {gene_data.shape}\")\n",
577
+ " \n",
578
+ " # Save the gene data we have, even if it's already normalized\n",
579
+ " gene_data.to_csv(out_gene_data_file)\n",
580
+ " print(f\"Gene data saved to {out_gene_data_file}\")\n",
581
+ " \n",
582
+ " # Attempt to link clinical and gene data\n",
583
+ " if is_trait_available:\n",
584
+ " # Load clinical data\n",
585
+ " clinical_features = pd.read_csv(out_clinical_data_file, index_col=0)\n",
586
+ " print(f\"Loaded clinical data shape: {clinical_features.shape}\")\n",
587
+ " \n",
588
+ " # Link the clinical and genetic data\n",
589
+ " linked_data = geo_link_clinical_genetic_data(clinical_features, gene_data)\n",
590
+ " print(f\"Initial linked data shape: {linked_data.shape}\")\n",
591
+ " \n",
592
+ " # Handle missing values\n",
593
+ " linked_data = handle_missing_values(linked_data, trait)\n",
594
+ " print(f\"Linked data shape after handling missing values: {linked_data.shape}\")\n",
595
+ " \n",
596
+ " if linked_data.shape[0] > 0:\n",
597
+ " # Check for bias in trait and demographic features\n",
598
+ " is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n",
599
+ " \n",
600
+ " # Validate data quality and save cohort info\n",
601
+ " is_usable = validate_and_save_cohort_info(\n",
602
+ " is_final=True,\n",
603
+ " cohort=cohort,\n",
604
+ " info_path=json_path,\n",
605
+ " is_gene_available=is_gene_available,\n",
606
+ " is_trait_available=is_trait_available,\n",
607
+ " is_biased=is_biased,\n",
608
+ " df=linked_data,\n",
609
+ " note=\"Successfully processed gene expression data for coronary artery disease.\"\n",
610
+ " )\n",
611
+ " \n",
612
+ " # Save the linked data if it's usable\n",
613
+ " if is_usable:\n",
614
+ " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n",
615
+ " linked_data.to_csv(out_data_file)\n",
616
+ " print(f\"Linked data saved to {out_data_file}\")\n",
617
+ " else:\n",
618
+ " print(\"Data not usable for trait study - not saving final linked data.\")\n",
619
+ " else:\n",
620
+ " print(\"After handling missing values, no samples remain.\")\n",
621
+ " validate_and_save_cohort_info(\n",
622
+ " is_final=True,\n",
623
+ " cohort=cohort,\n",
624
+ " info_path=json_path,\n",
625
+ " is_gene_available=is_gene_available,\n",
626
+ " is_trait_available=is_trait_available,\n",
627
+ " is_biased=True,\n",
628
+ " df=pd.DataFrame(),\n",
629
+ " note=\"No valid samples after handling missing values.\"\n",
630
+ " )\n",
631
+ " else:\n",
632
+ " # Cannot proceed with linking if trait data is missing\n",
633
+ " validate_and_save_cohort_info(\n",
634
+ " is_final=True,\n",
635
+ " cohort=cohort,\n",
636
+ " info_path=json_path,\n",
637
+ " is_gene_available=is_gene_available,\n",
638
+ " is_trait_available=is_trait_available,\n",
639
+ " is_biased=True,\n",
640
+ " df=pd.DataFrame(),\n",
641
+ " note=\"Cannot link data because trait information is not available.\"\n",
642
+ " )\n",
643
+ "except Exception as e:\n",
644
+ " print(f\"Error in data processing: {e}\")\n",
645
+ " \n",
646
+ " # Log the error and mark the dataset as unusable\n",
647
+ " validate_and_save_cohort_info(\n",
648
+ " is_final=True,\n",
649
+ " cohort=cohort,\n",
650
+ " info_path=json_path,\n",
651
+ " is_gene_available=False, # Consider gene data unavailable if we had an error\n",
652
+ " is_trait_available=is_trait_available,\n",
653
+ " is_biased=True, # Consider it biased as we can't use it\n",
654
+ " df=pd.DataFrame(), # Empty dataframe for metadata\n",
655
+ " note=f\"Error during normalization or linking: {str(e)}\"\n",
656
+ " )"
657
+ ]
658
+ }
659
+ ],
660
+ "metadata": {
661
+ "language_info": {
662
+ "codemirror_mode": {
663
+ "name": "ipython",
664
+ "version": 3
665
+ },
666
+ "file_extension": ".py",
667
+ "mimetype": "text/x-python",
668
+ "name": "python",
669
+ "nbconvert_exporter": "python",
670
+ "pygments_lexer": "ipython3",
671
+ "version": "3.10.16"
672
+ }
673
+ },
674
+ "nbformat": 4,
675
+ "nbformat_minor": 5
676
+ }
code/Coronary_artery_disease/GSE59867.ipynb ADDED
@@ -0,0 +1,1156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": 1,
6
+ "id": "59f5434a",
7
+ "metadata": {
8
+ "execution": {
9
+ "iopub.execute_input": "2025-03-25T08:28:45.214697Z",
10
+ "iopub.status.busy": "2025-03-25T08:28:45.214587Z",
11
+ "iopub.status.idle": "2025-03-25T08:28:45.375790Z",
12
+ "shell.execute_reply": "2025-03-25T08:28:45.375460Z"
13
+ }
14
+ },
15
+ "outputs": [],
16
+ "source": [
17
+ "import sys\n",
18
+ "import os\n",
19
+ "sys.path.append(os.path.abspath(os.path.join(os.getcwd(), '../..')))\n",
20
+ "\n",
21
+ "# Path Configuration\n",
22
+ "from tools.preprocess import *\n",
23
+ "\n",
24
+ "# Processing context\n",
25
+ "trait = \"Coronary_artery_disease\"\n",
26
+ "cohort = \"GSE59867\"\n",
27
+ "\n",
28
+ "# Input paths\n",
29
+ "in_trait_dir = \"../../input/GEO/Coronary_artery_disease\"\n",
30
+ "in_cohort_dir = \"../../input/GEO/Coronary_artery_disease/GSE59867\"\n",
31
+ "\n",
32
+ "# Output paths\n",
33
+ "out_data_file = \"../../output/preprocess/Coronary_artery_disease/GSE59867.csv\"\n",
34
+ "out_gene_data_file = \"../../output/preprocess/Coronary_artery_disease/gene_data/GSE59867.csv\"\n",
35
+ "out_clinical_data_file = \"../../output/preprocess/Coronary_artery_disease/clinical_data/GSE59867.csv\"\n",
36
+ "json_path = \"../../output/preprocess/Coronary_artery_disease/cohort_info.json\"\n"
37
+ ]
38
+ },
39
+ {
40
+ "cell_type": "markdown",
41
+ "id": "60c8bfe3",
42
+ "metadata": {},
43
+ "source": [
44
+ "### Step 1: Initial Data Loading"
45
+ ]
46
+ },
47
+ {
48
+ "cell_type": "code",
49
+ "execution_count": 2,
50
+ "id": "d86a0dc5",
51
+ "metadata": {
52
+ "execution": {
53
+ "iopub.execute_input": "2025-03-25T08:28:45.377246Z",
54
+ "iopub.status.busy": "2025-03-25T08:28:45.377105Z",
55
+ "iopub.status.idle": "2025-03-25T08:28:45.908877Z",
56
+ "shell.execute_reply": "2025-03-25T08:28:45.908517Z"
57
+ }
58
+ },
59
+ "outputs": [
60
+ {
61
+ "name": "stdout",
62
+ "output_type": "stream",
63
+ "text": [
64
+ "Background Information:\n",
65
+ "!Series_title\t\"Gene expression profiling reveals potential prognostic biomarkers associated with the progression of heart failure\"\n",
66
+ "!Series_summary\t\"Heart failure (HF) is the most common cause of morbidity and mortality in the developed countries, especially considering the present demographic tendencies in those populations.\"\n",
67
+ "!Series_summary\t\"We identified biologically relevant transcripts that are significantly altered in the early phase of myocardial infarction (MI) and are associated with the development of post-myocardial infarction HF.\"\n",
68
+ "!Series_overall_design\t\"We collected peripheral blood samples from patients (n=111) with ST-segment elevation myocardial infarction (STEMI) at four time points (admission, discharge, 1 month after MI, and 6 months after MI). Control group comprised patients (n=46) with a stable coronary artery disease and without a history of myocardial infarction. Affymetrix HuGene 1.0 ST arrays were used to analyze mRNA levels in periperal blood mononuclear cells (PBMCs) isolated from the study and control groups. Samples from the first three time points were compared with the samples from the same patients collected 6 months after MI (stable phase) and with the control group. Additionaly, based on plasma NT-proBNP level and left ventricular ejection fraction parameters the STEMI patients were divided into HF and non-HF groups.We attempted to identify transcripts whose differential expression on the 1st day of myocardial infarction predicted which patients would develop symptoms of HF during the 6 months of follow-up. For this purpose, we compared the microarray results for samples collected on admission for the HF group versus the non-HF group.\"\n",
69
+ "Sample Characteristics Dictionary:\n",
70
+ "{0: ['cell type: PBMC'], 1: ['samples collection: on the 1st day of MI (admission)', 'samples collection: after 4-6 days of MI (discharge)', 'samples collection: 1 month after MI', 'samples collection: 6 months after MI', 'samples collection: N/A'], 2: ['hf progression: N/A', 'hf progression: HF', 'hf progression: non-HF', 'hf progression: stable CAD']}\n"
71
+ ]
72
+ }
73
+ ],
74
+ "source": [
75
+ "from tools.preprocess import *\n",
76
+ "# 1. Identify the paths to the SOFT file and the matrix file\n",
77
+ "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
78
+ "\n",
79
+ "# 2. Read the matrix file to obtain background information and sample characteristics data\n",
80
+ "background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']\n",
81
+ "clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']\n",
82
+ "background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)\n",
83
+ "\n",
84
+ "# 3. Obtain the sample characteristics dictionary from the clinical dataframe\n",
85
+ "sample_characteristics_dict = get_unique_values_by_row(clinical_data)\n",
86
+ "\n",
87
+ "# 4. Explicitly print out all the background information and the sample characteristics dictionary\n",
88
+ "print(\"Background Information:\")\n",
89
+ "print(background_info)\n",
90
+ "print(\"Sample Characteristics Dictionary:\")\n",
91
+ "print(sample_characteristics_dict)\n"
92
+ ]
93
+ },
94
+ {
95
+ "cell_type": "markdown",
96
+ "id": "3b46ba6d",
97
+ "metadata": {},
98
+ "source": [
99
+ "### Step 2: Dataset Analysis and Clinical Feature Extraction"
100
+ ]
101
+ },
102
+ {
103
+ "cell_type": "code",
104
+ "execution_count": 3,
105
+ "id": "2b386545",
106
+ "metadata": {
107
+ "execution": {
108
+ "iopub.execute_input": "2025-03-25T08:28:45.910299Z",
109
+ "iopub.status.busy": "2025-03-25T08:28:45.910185Z",
110
+ "iopub.status.idle": "2025-03-25T08:28:45.935897Z",
111
+ "shell.execute_reply": "2025-03-25T08:28:45.935588Z"
112
+ }
113
+ },
114
+ "outputs": [
115
+ {
116
+ "name": "stdout",
117
+ "output_type": "stream",
118
+ "text": [
119
+ "Unique values in trait_row:\n",
120
+ " !Sample_characteristics_ch1\n",
121
+ " hf progression: N/A\n",
122
+ " hf progression: HF\n",
123
+ " hf progression: non-HF\n",
124
+ " hf progression: stable CAD\n",
125
+ "Processing trait value: 'N/A'\n",
126
+ "Processing trait value: 'N/A'\n",
127
+ "Processing trait value: 'N/A'\n",
128
+ "Processing trait value: 'N/A'\n",
129
+ "Processing trait value: 'N/A'\n",
130
+ "Processing trait value: 'N/A'\n",
131
+ "Processing trait value: 'N/A'\n",
132
+ "Processing trait value: 'N/A'\n",
133
+ "Processing trait value: 'N/A'\n",
134
+ "Processing trait value: 'N/A'\n",
135
+ "Processing trait value: 'N/A'\n",
136
+ "Processing trait value: 'HF'\n",
137
+ "Processing trait value: 'HF'\n",
138
+ "Processing trait value: 'HF'\n",
139
+ "Processing trait value: 'HF'\n",
140
+ "Processing trait value: 'N/A'\n",
141
+ "Processing trait value: 'N/A'\n",
142
+ "Processing trait value: 'N/A'\n",
143
+ "Processing trait value: 'N/A'\n",
144
+ "Processing trait value: 'N/A'\n",
145
+ "Processing trait value: 'N/A'\n",
146
+ "Processing trait value: 'N/A'\n",
147
+ "Processing trait value: 'N/A'\n",
148
+ "Processing trait value: 'N/A'\n",
149
+ "Processing trait value: 'N/A'\n",
150
+ "Processing trait value: 'N/A'\n",
151
+ "Processing trait value: 'N/A'\n",
152
+ "Processing trait value: 'N/A'\n",
153
+ "Processing trait value: 'N/A'\n",
154
+ "Processing trait value: 'N/A'\n",
155
+ "Processing trait value: 'N/A'\n",
156
+ "Processing trait value: 'N/A'\n",
157
+ "Processing trait value: 'N/A'\n",
158
+ "Processing trait value: 'N/A'\n",
159
+ "Processing trait value: 'N/A'\n",
160
+ "Processing trait value: 'N/A'\n",
161
+ "Processing trait value: 'N/A'\n",
162
+ "Processing trait value: 'N/A'\n",
163
+ "Processing trait value: 'N/A'\n",
164
+ "Processing trait value: 'N/A'\n",
165
+ "Processing trait value: 'N/A'\n",
166
+ "Processing trait value: 'N/A'\n",
167
+ "Processing trait value: 'N/A'\n",
168
+ "Processing trait value: 'N/A'\n",
169
+ "Processing trait value: 'N/A'\n",
170
+ "Processing trait value: 'N/A'\n",
171
+ "Processing trait value: 'N/A'\n",
172
+ "Processing trait value: 'N/A'\n",
173
+ "Processing trait value: 'N/A'\n",
174
+ "Processing trait value: 'N/A'\n",
175
+ "Processing trait value: 'N/A'\n",
176
+ "Processing trait value: 'N/A'\n",
177
+ "Processing trait value: 'N/A'\n",
178
+ "Processing trait value: 'N/A'\n",
179
+ "Processing trait value: 'N/A'\n",
180
+ "Processing trait value: 'N/A'\n",
181
+ "Processing trait value: 'N/A'\n",
182
+ "Processing trait value: 'N/A'\n",
183
+ "Processing trait value: 'N/A'\n",
184
+ "Processing trait value: 'N/A'\n",
185
+ "Processing trait value: 'N/A'\n",
186
+ "Processing trait value: 'N/A'\n",
187
+ "Processing trait value: 'N/A'\n",
188
+ "Processing trait value: 'N/A'\n",
189
+ "Processing trait value: 'N/A'\n",
190
+ "Processing trait value: 'N/A'\n",
191
+ "Processing trait value: 'N/A'\n",
192
+ "Processing trait value: 'N/A'\n",
193
+ "Processing trait value: 'N/A'\n",
194
+ "Processing trait value: 'N/A'\n",
195
+ "Processing trait value: 'N/A'\n",
196
+ "Processing trait value: 'N/A'\n",
197
+ "Processing trait value: 'N/A'\n",
198
+ "Processing trait value: 'N/A'\n",
199
+ "Processing trait value: 'N/A'\n",
200
+ "Processing trait value: 'N/A'\n",
201
+ "Processing trait value: 'N/A'\n",
202
+ "Processing trait value: 'N/A'\n",
203
+ "Processing trait value: 'N/A'\n",
204
+ "Processing trait value: 'N/A'\n",
205
+ "Processing trait value: 'N/A'\n",
206
+ "Processing trait value: 'N/A'\n",
207
+ "Processing trait value: 'N/A'\n",
208
+ "Processing trait value: 'N/A'\n",
209
+ "Processing trait value: 'N/A'\n",
210
+ "Processing trait value: 'N/A'\n",
211
+ "Processing trait value: 'N/A'\n",
212
+ "Processing trait value: 'N/A'\n",
213
+ "Processing trait value: 'N/A'\n",
214
+ "Processing trait value: 'N/A'\n",
215
+ "Processing trait value: 'HF'\n",
216
+ "Processing trait value: 'HF'\n",
217
+ "Processing trait value: 'HF'\n",
218
+ "Processing trait value: 'HF'\n",
219
+ "Processing trait value: 'N/A'\n",
220
+ "Processing trait value: 'N/A'\n",
221
+ "Processing trait value: 'N/A'\n",
222
+ "Processing trait value: 'N/A'\n",
223
+ "Processing trait value: 'N/A'\n",
224
+ "Processing trait value: 'N/A'\n",
225
+ "Processing trait value: 'N/A'\n",
226
+ "Processing trait value: 'N/A'\n",
227
+ "Processing trait value: 'N/A'\n",
228
+ "Processing trait value: 'N/A'\n",
229
+ "Processing trait value: 'N/A'\n",
230
+ "Processing trait value: 'N/A'\n",
231
+ "Processing trait value: 'N/A'\n",
232
+ "Processing trait value: 'HF'\n",
233
+ "Processing trait value: 'HF'\n",
234
+ "Processing trait value: 'HF'\n",
235
+ "Processing trait value: 'N/A'\n",
236
+ "Processing trait value: 'non-HF'\n",
237
+ "Processing trait value: 'non-HF'\n",
238
+ "Processing trait value: 'non-HF'\n",
239
+ "Processing trait value: 'non-HF'\n",
240
+ "Processing trait value: 'N/A'\n",
241
+ "Processing trait value: 'N/A'\n",
242
+ "Processing trait value: 'N/A'\n",
243
+ "Processing trait value: 'N/A'\n",
244
+ "Processing trait value: 'N/A'\n",
245
+ "Processing trait value: 'HF'\n",
246
+ "Processing trait value: 'HF'\n",
247
+ "Processing trait value: 'HF'\n",
248
+ "Processing trait value: 'HF'\n",
249
+ "Processing trait value: 'N/A'\n",
250
+ "Processing trait value: 'N/A'\n",
251
+ "Processing trait value: 'N/A'\n",
252
+ "Processing trait value: 'N/A'\n",
253
+ "Processing trait value: 'non-HF'\n",
254
+ "Processing trait value: 'non-HF'\n",
255
+ "Processing trait value: 'non-HF'\n",
256
+ "Processing trait value: 'non-HF'\n",
257
+ "Processing trait value: 'N/A'\n",
258
+ "Processing trait value: 'N/A'\n",
259
+ "Processing trait value: 'N/A'\n",
260
+ "Processing trait value: 'N/A'\n",
261
+ "Processing trait value: 'N/A'\n",
262
+ "Processing trait value: 'N/A'\n",
263
+ "Processing trait value: 'N/A'\n",
264
+ "Processing trait value: 'N/A'\n",
265
+ "Processing trait value: 'N/A'\n",
266
+ "Processing trait value: 'N/A'\n",
267
+ "Processing trait value: 'N/A'\n",
268
+ "Processing trait value: 'N/A'\n",
269
+ "Processing trait value: 'N/A'\n",
270
+ "Processing trait value: 'N/A'\n",
271
+ "Processing trait value: 'N/A'\n",
272
+ "Processing trait value: 'N/A'\n",
273
+ "Processing trait value: 'N/A'\n",
274
+ "Processing trait value: 'N/A'\n",
275
+ "Processing trait value: 'N/A'\n",
276
+ "Processing trait value: 'N/A'\n",
277
+ "Processing trait value: 'N/A'\n",
278
+ "Processing trait value: 'N/A'\n",
279
+ "Processing trait value: 'N/A'\n",
280
+ "Processing trait value: 'N/A'\n",
281
+ "Processing trait value: 'N/A'\n",
282
+ "Processing trait value: 'N/A'\n",
283
+ "Processing trait value: 'N/A'\n",
284
+ "Processing trait value: 'N/A'\n",
285
+ "Processing trait value: 'N/A'\n",
286
+ "Processing trait value: 'N/A'\n",
287
+ "Processing trait value: 'N/A'\n",
288
+ "Processing trait value: 'N/A'\n",
289
+ "Processing trait value: 'N/A'\n",
290
+ "Processing trait value: 'N/A'\n",
291
+ "Processing trait value: 'N/A'\n",
292
+ "Processing trait value: 'N/A'\n",
293
+ "Processing trait value: 'N/A'\n",
294
+ "Processing trait value: 'N/A'\n",
295
+ "Processing trait value: 'N/A'\n",
296
+ "Processing trait value: 'N/A'\n",
297
+ "Processing trait value: 'N/A'\n",
298
+ "Processing trait value: 'N/A'\n",
299
+ "Processing trait value: 'N/A'\n",
300
+ "Processing trait value: 'N/A'\n",
301
+ "Processing trait value: 'N/A'\n",
302
+ "Processing trait value: 'non-HF'\n",
303
+ "Processing trait value: 'non-HF'\n",
304
+ "Processing trait value: 'non-HF'\n",
305
+ "Processing trait value: 'non-HF'\n",
306
+ "Processing trait value: 'N/A'\n",
307
+ "Processing trait value: 'N/A'\n",
308
+ "Processing trait value: 'N/A'\n",
309
+ "Processing trait value: 'N/A'\n",
310
+ "Processing trait value: 'N/A'\n",
311
+ "Processing trait value: 'N/A'\n",
312
+ "Processing trait value: 'N/A'\n",
313
+ "Processing trait value: 'N/A'\n",
314
+ "Processing trait value: 'N/A'\n",
315
+ "Processing trait value: 'N/A'\n",
316
+ "Processing trait value: 'N/A'\n",
317
+ "Processing trait value: 'N/A'\n",
318
+ "Processing trait value: 'N/A'\n",
319
+ "Processing trait value: 'N/A'\n",
320
+ "Processing trait value: 'N/A'\n",
321
+ "Processing trait value: 'N/A'\n",
322
+ "Processing trait value: 'N/A'\n",
323
+ "Processing trait value: 'N/A'\n",
324
+ "Processing trait value: 'N/A'\n",
325
+ "Processing trait value: 'N/A'\n",
326
+ "Processing trait value: 'N/A'\n",
327
+ "Processing trait value: 'N/A'\n",
328
+ "Processing trait value: 'N/A'\n",
329
+ "Processing trait value: 'N/A'\n",
330
+ "Processing trait value: 'N/A'\n",
331
+ "Processing trait value: 'N/A'\n",
332
+ "Processing trait value: 'N/A'\n",
333
+ "Processing trait value: 'N/A'\n",
334
+ "Processing trait value: 'N/A'\n",
335
+ "Processing trait value: 'non-HF'\n",
336
+ "Processing trait value: 'non-HF'\n",
337
+ "Processing trait value: 'non-HF'\n",
338
+ "Processing trait value: 'N/A'\n",
339
+ "Processing trait value: 'N/A'\n",
340
+ "Processing trait value: 'N/A'\n",
341
+ "Processing trait value: 'N/A'\n",
342
+ "Processing trait value: 'N/A'\n",
343
+ "Processing trait value: 'N/A'\n",
344
+ "Processing trait value: 'non-HF'\n",
345
+ "Processing trait value: 'non-HF'\n",
346
+ "Processing trait value: 'non-HF'\n",
347
+ "Processing trait value: 'non-HF'\n",
348
+ "Processing trait value: 'non-HF'\n",
349
+ "Processing trait value: 'non-HF'\n",
350
+ "Processing trait value: 'non-HF'\n",
351
+ "Processing trait value: 'N/A'\n",
352
+ "Processing trait value: 'N/A'\n",
353
+ "Processing trait value: 'N/A'\n",
354
+ "Processing trait value: 'N/A'\n",
355
+ "Processing trait value: 'N/A'\n",
356
+ "Processing trait value: 'N/A'\n",
357
+ "Processing trait value: 'N/A'\n",
358
+ "Processing trait value: 'N/A'\n",
359
+ "Processing trait value: 'N/A'\n",
360
+ "Processing trait value: 'N/A'\n",
361
+ "Processing trait value: 'N/A'\n",
362
+ "Processing trait value: 'N/A'\n",
363
+ "Processing trait value: 'N/A'\n",
364
+ "Processing trait value: 'N/A'\n",
365
+ "Processing trait value: 'N/A'\n",
366
+ "Processing trait value: 'N/A'\n",
367
+ "Processing trait value: 'N/A'\n",
368
+ "Processing trait value: 'N/A'\n",
369
+ "Processing trait value: 'N/A'\n",
370
+ "Processing trait value: 'N/A'\n",
371
+ "Processing trait value: 'N/A'\n",
372
+ "Processing trait value: 'N/A'\n",
373
+ "Processing trait value: 'N/A'\n",
374
+ "Processing trait value: 'N/A'\n",
375
+ "Processing trait value: 'N/A'\n",
376
+ "Processing trait value: 'N/A'\n",
377
+ "Processing trait value: 'N/A'\n",
378
+ "Processing trait value: 'N/A'\n",
379
+ "Processing trait value: 'N/A'\n",
380
+ "Processing trait value: 'N/A'\n",
381
+ "Processing trait value: 'N/A'\n",
382
+ "Processing trait value: 'N/A'\n",
383
+ "Processing trait value: 'N/A'\n",
384
+ "Processing trait value: 'N/A'\n",
385
+ "Processing trait value: 'N/A'\n",
386
+ "Processing trait value: 'N/A'\n",
387
+ "Processing trait value: 'N/A'\n",
388
+ "Processing trait value: 'N/A'\n",
389
+ "Processing trait value: 'N/A'\n",
390
+ "Processing trait value: 'N/A'\n",
391
+ "Processing trait value: 'N/A'\n",
392
+ "Processing trait value: 'N/A'\n",
393
+ "Processing trait value: 'N/A'\n",
394
+ "Processing trait value: 'N/A'\n",
395
+ "Processing trait value: 'N/A'\n",
396
+ "Processing trait value: 'N/A'\n",
397
+ "Processing trait value: 'N/A'\n",
398
+ "Processing trait value: 'N/A'\n",
399
+ "Processing trait value: 'N/A'\n",
400
+ "Processing trait value: 'N/A'\n",
401
+ "Processing trait value: 'N/A'\n",
402
+ "Processing trait value: 'N/A'\n",
403
+ "Processing trait value: 'N/A'\n",
404
+ "Processing trait value: 'N/A'\n",
405
+ "Processing trait value: 'N/A'\n",
406
+ "Processing trait value: 'N/A'\n",
407
+ "Processing trait value: 'N/A'\n",
408
+ "Processing trait value: 'N/A'\n",
409
+ "Processing trait value: 'N/A'\n",
410
+ "Processing trait value: 'N/A'\n",
411
+ "Processing trait value: 'N/A'\n",
412
+ "Processing trait value: 'N/A'\n",
413
+ "Processing trait value: 'N/A'\n",
414
+ "Processing trait value: 'N/A'\n",
415
+ "Processing trait value: 'N/A'\n",
416
+ "Processing trait value: 'N/A'\n",
417
+ "Processing trait value: 'N/A'\n",
418
+ "Processing trait value: 'N/A'\n",
419
+ "Processing trait value: 'N/A'\n",
420
+ "Processing trait value: 'N/A'\n",
421
+ "Processing trait value: 'N/A'\n",
422
+ "Processing trait value: 'N/A'\n",
423
+ "Processing trait value: 'N/A'\n",
424
+ "Processing trait value: 'N/A'\n",
425
+ "Processing trait value: 'N/A'\n",
426
+ "Processing trait value: 'N/A'\n",
427
+ "Processing trait value: 'N/A'\n",
428
+ "Processing trait value: 'N/A'\n",
429
+ "Processing trait value: 'N/A'\n",
430
+ "Processing trait value: 'N/A'\n",
431
+ "Processing trait value: 'N/A'\n",
432
+ "Processing trait value: 'N/A'\n",
433
+ "Processing trait value: 'N/A'\n",
434
+ "Processing trait value: 'N/A'\n",
435
+ "Processing trait value: 'N/A'\n",
436
+ "Processing trait value: 'N/A'\n",
437
+ "Processing trait value: 'N/A'\n",
438
+ "Processing trait value: 'N/A'\n",
439
+ "Processing trait value: 'N/A'\n",
440
+ "Processing trait value: 'N/A'\n",
441
+ "Processing trait value: 'N/A'\n",
442
+ "Processing trait value: 'N/A'\n",
443
+ "Processing trait value: 'N/A'\n",
444
+ "Processing trait value: 'N/A'\n",
445
+ "Processing trait value: 'N/A'\n",
446
+ "Processing trait value: 'N/A'\n",
447
+ "Processing trait value: 'N/A'\n",
448
+ "Processing trait value: 'N/A'\n",
449
+ "Processing trait value: 'N/A'\n",
450
+ "Processing trait value: 'N/A'\n",
451
+ "Processing trait value: 'N/A'\n",
452
+ "Processing trait value: 'HF'\n",
453
+ "Processing trait value: 'HF'\n",
454
+ "Processing trait value: 'HF'\n",
455
+ "Processing trait value: 'HF'\n",
456
+ "Processing trait value: 'HF'\n",
457
+ "Processing trait value: 'HF'\n",
458
+ "Processing trait value: 'HF'\n",
459
+ "Processing trait value: 'HF'\n",
460
+ "Processing trait value: 'N/A'\n",
461
+ "Processing trait value: 'N/A'\n",
462
+ "Processing trait value: 'non-HF'\n",
463
+ "Processing trait value: 'non-HF'\n",
464
+ "Processing trait value: 'non-HF'\n",
465
+ "Processing trait value: 'non-HF'\n",
466
+ "Processing trait value: 'non-HF'\n",
467
+ "Processing trait value: 'non-HF'\n",
468
+ "Processing trait value: 'non-HF'\n",
469
+ "Processing trait value: 'non-HF'\n",
470
+ "Processing trait value: 'N/A'\n",
471
+ "Processing trait value: 'N/A'\n",
472
+ "Processing trait value: 'N/A'\n",
473
+ "Processing trait value: 'N/A'\n",
474
+ "Processing trait value: 'HF'\n",
475
+ "Processing trait value: 'HF'\n",
476
+ "Processing trait value: 'HF'\n",
477
+ "Processing trait value: 'HF'\n",
478
+ "Processing trait value: 'N/A'\n",
479
+ "Processing trait value: 'N/A'\n",
480
+ "Processing trait value: 'N/A'\n",
481
+ "Processing trait value: 'N/A'\n",
482
+ "Processing trait value: 'HF'\n",
483
+ "Processing trait value: 'HF'\n",
484
+ "Processing trait value: 'HF'\n",
485
+ "Processing trait value: 'N/A'\n",
486
+ "Processing trait value: 'N/A'\n",
487
+ "Processing trait value: 'N/A'\n",
488
+ "Processing trait value: 'N/A'\n",
489
+ "Processing trait value: 'N/A'\n",
490
+ "Processing trait value: 'N/A'\n",
491
+ "Processing trait value: 'N/A'\n",
492
+ "Processing trait value: 'N/A'\n",
493
+ "Processing trait value: 'N/A'\n",
494
+ "Processing trait value: 'N/A'\n",
495
+ "Processing trait value: 'N/A'\n",
496
+ "Processing trait value: 'N/A'\n",
497
+ "Processing trait value: 'N/A'\n",
498
+ "Processing trait value: 'N/A'\n",
499
+ "Processing trait value: 'N/A'\n",
500
+ "Processing trait value: 'N/A'\n",
501
+ "Processing trait value: 'N/A'\n",
502
+ "Processing trait value: 'N/A'\n",
503
+ "Processing trait value: 'N/A'\n",
504
+ "Processing trait value: 'HF'\n",
505
+ "Processing trait value: 'HF'\n",
506
+ "Processing trait value: 'HF'\n",
507
+ "Processing trait value: 'HF'\n",
508
+ "Processing trait value: 'N/A'\n",
509
+ "Processing trait value: 'N/A'\n",
510
+ "Processing trait value: 'N/A'\n",
511
+ "Processing trait value: 'N/A'\n",
512
+ "Processing trait value: 'N/A'\n",
513
+ "Processing trait value: 'N/A'\n",
514
+ "Processing trait value: 'N/A'\n",
515
+ "Processing trait value: 'stable CAD'\n",
516
+ "Processing trait value: 'stable CAD'\n",
517
+ "Processing trait value: 'stable CAD'\n",
518
+ "Processing trait value: 'stable CAD'\n",
519
+ "Processing trait value: 'stable CAD'\n",
520
+ "Processing trait value: 'stable CAD'\n",
521
+ "Processing trait value: 'stable CAD'\n",
522
+ "Processing trait value: 'stable CAD'\n",
523
+ "Processing trait value: 'stable CAD'\n",
524
+ "Processing trait value: 'stable CAD'\n",
525
+ "Processing trait value: 'stable CAD'\n",
526
+ "Processing trait value: 'stable CAD'\n",
527
+ "Processing trait value: 'stable CAD'\n",
528
+ "Processing trait value: 'stable CAD'\n",
529
+ "Processing trait value: 'stable CAD'\n",
530
+ "Processing trait value: 'stable CAD'\n",
531
+ "Processing trait value: 'stable CAD'\n",
532
+ "Processing trait value: 'stable CAD'\n",
533
+ "Processing trait value: 'stable CAD'\n",
534
+ "Processing trait value: 'stable CAD'\n",
535
+ "Processing trait value: 'stable CAD'\n",
536
+ "Processing trait value: 'stable CAD'\n",
537
+ "Processing trait value: 'stable CAD'\n",
538
+ "Processing trait value: 'stable CAD'\n",
539
+ "Processing trait value: 'stable CAD'\n",
540
+ "Processing trait value: 'stable CAD'\n",
541
+ "Processing trait value: 'stable CAD'\n",
542
+ "Processing trait value: 'stable CAD'\n",
543
+ "Processing trait value: 'stable CAD'\n",
544
+ "Processing trait value: 'stable CAD'\n",
545
+ "Processing trait value: 'stable CAD'\n",
546
+ "Processing trait value: 'stable CAD'\n",
547
+ "Processing trait value: 'stable CAD'\n",
548
+ "Processing trait value: 'stable CAD'\n",
549
+ "Processing trait value: 'stable CAD'\n",
550
+ "Processing trait value: 'stable CAD'\n",
551
+ "Processing trait value: 'stable CAD'\n",
552
+ "Processing trait value: 'stable CAD'\n",
553
+ "Processing trait value: 'stable CAD'\n",
554
+ "Processing trait value: 'stable CAD'\n",
555
+ "Processing trait value: 'stable CAD'\n",
556
+ "Processing trait value: 'stable CAD'\n",
557
+ "Processing trait value: 'stable CAD'\n",
558
+ "Processing trait value: 'stable CAD'\n",
559
+ "Processing trait value: 'stable CAD'\n",
560
+ "Processing trait value: 'stable CAD'\n",
561
+ "Preview of clinical data:\n",
562
+ "{'GSM1448335': [nan], 'GSM1448336': [nan], 'GSM1448337': [nan], 'GSM1448338': [nan], 'GSM1448339': [nan], 'GSM1448340': [nan], 'GSM1448341': [nan], 'GSM1448342': [nan], 'GSM1448343': [nan], 'GSM1448344': [nan], 'GSM1448345': [nan], 'GSM1448346': [1.0], 'GSM1448347': [1.0], 'GSM1448348': [1.0], 'GSM1448349': [1.0], 'GSM1448350': [nan], 'GSM1448351': [nan], 'GSM1448352': [nan], 'GSM1448353': [nan], 'GSM1448354': [nan], 'GSM1448355': [nan], 'GSM1448356': [nan], 'GSM1448357': [nan], 'GSM1448358': [nan], 'GSM1448359': [nan], 'GSM1448360': [nan], 'GSM1448361': [nan], 'GSM1448362': [nan], 'GSM1448363': [nan], 'GSM1448364': [nan], 'GSM1448365': [nan], 'GSM1448366': [nan], 'GSM1448367': [nan], 'GSM1448368': [nan], 'GSM1448369': [nan], 'GSM1448370': [nan], 'GSM1448371': [nan], 'GSM1448372': [nan], 'GSM1448373': [nan], 'GSM1448374': [nan], 'GSM1448375': [nan], 'GSM1448376': [nan], 'GSM1448377': [nan], 'GSM1448378': [nan], 'GSM1448379': [nan], 'GSM1448380': [nan], 'GSM1448381': [nan], 'GSM1448382': [nan], 'GSM1448383': [nan], 'GSM1448384': [nan], 'GSM1448385': [nan], 'GSM1448386': [nan], 'GSM1448387': [nan], 'GSM1448388': [nan], 'GSM1448389': [nan], 'GSM1448390': [nan], 'GSM1448391': [nan], 'GSM1448392': [nan], 'GSM1448393': [nan], 'GSM1448394': [nan], 'GSM1448395': [nan], 'GSM1448396': [nan], 'GSM1448397': [nan], 'GSM1448398': [nan], 'GSM1448399': [nan], 'GSM1448400': [nan], 'GSM1448401': [nan], 'GSM1448402': [nan], 'GSM1448403': [nan], 'GSM1448404': [nan], 'GSM1448405': [nan], 'GSM1448406': [nan], 'GSM1448407': [nan], 'GSM1448408': [nan], 'GSM1448409': [nan], 'GSM1448410': [nan], 'GSM1448411': [nan], 'GSM1448412': [nan], 'GSM1448413': [nan], 'GSM1448414': [nan], 'GSM1448415': [nan], 'GSM1448416': [nan], 'GSM1448417': [nan], 'GSM1448418': [nan], 'GSM1448419': [nan], 'GSM1448420': [nan], 'GSM1448421': [nan], 'GSM1448422': [nan], 'GSM1448423': [nan], 'GSM1448424': [nan], 'GSM1448425': [1.0], 'GSM1448426': [1.0], 'GSM1448427': [1.0], 'GSM1448428': [1.0], 'GSM1448429': [nan], 'GSM1448430': [nan], 'GSM1448431': [nan], 'GSM1448432': [nan], 'GSM1448433': [nan], 'GSM1448434': [nan], 'GSM1448435': [nan], 'GSM1448436': [nan], 'GSM1448437': [nan], 'GSM1448438': [nan], 'GSM1448439': [nan], 'GSM1448440': [nan], 'GSM1448441': [nan], 'GSM1448442': [1.0], 'GSM1448443': [1.0], 'GSM1448444': [1.0], 'GSM1448445': [nan], 'GSM1448446': [1.0], 'GSM1448447': [1.0], 'GSM1448448': [1.0], 'GSM1448449': [1.0], 'GSM1448450': [nan], 'GSM1448451': [nan], 'GSM1448452': [nan], 'GSM1448453': [nan], 'GSM1448454': [nan], 'GSM1448455': [1.0], 'GSM1448456': [1.0], 'GSM1448457': [1.0], 'GSM1448458': [1.0], 'GSM1448459': [nan], 'GSM1448460': [nan], 'GSM1448461': [nan], 'GSM1448462': [nan], 'GSM1448463': [1.0], 'GSM1448464': [1.0], 'GSM1448465': [1.0], 'GSM1448466': [1.0], 'GSM1448467': [nan], 'GSM1448468': [nan], 'GSM1448469': [nan], 'GSM1448470': [nan], 'GSM1448471': [nan], 'GSM1448472': [nan], 'GSM1448473': [nan], 'GSM1448474': [nan], 'GSM1448475': [nan], 'GSM1448476': [nan], 'GSM1448477': [nan], 'GSM1448478': [nan], 'GSM1448479': [nan], 'GSM1448480': [nan], 'GSM1448481': [nan], 'GSM1448482': [nan], 'GSM1448483': [nan], 'GSM1448484': [nan], 'GSM1448485': [nan], 'GSM1448486': [nan], 'GSM1448487': [nan], 'GSM1448488': [nan], 'GSM1448489': [nan], 'GSM1448490': [nan], 'GSM1448491': [nan], 'GSM1448492': [nan], 'GSM1448493': [nan], 'GSM1448494': [nan], 'GSM1448495': [nan], 'GSM1448496': [nan], 'GSM1448497': [nan], 'GSM1448498': [nan], 'GSM1448499': [nan], 'GSM1448500': [nan], 'GSM1448501': [nan], 'GSM1448502': [nan], 'GSM1448503': [nan], 'GSM1448504': [nan], 'GSM1448505': [nan], 'GSM1448506': [nan], 'GSM1448507': [nan], 'GSM1448508': [nan], 'GSM1448509': [nan], 'GSM1448510': [nan], 'GSM1448511': [nan], 'GSM1448512': [1.0], 'GSM1448513': [1.0], 'GSM1448514': [1.0], 'GSM1448515': [1.0], 'GSM1448516': [nan], 'GSM1448517': [nan], 'GSM1448518': [nan], 'GSM1448519': [nan], 'GSM1448520': [nan], 'GSM1448521': [nan], 'GSM1448522': [nan], 'GSM1448523': [nan], 'GSM1448524': [nan], 'GSM1448525': [nan], 'GSM1448526': [nan], 'GSM1448527': [nan], 'GSM1448528': [nan], 'GSM1448529': [nan], 'GSM1448530': [nan], 'GSM1448531': [nan], 'GSM1448532': [nan], 'GSM1448533': [nan], 'GSM1448534': [nan]}\n",
563
+ "Clinical data saved to ../../output/preprocess/Coronary_artery_disease/clinical_data/GSE59867.csv\n"
564
+ ]
565
+ }
566
+ ],
567
+ "source": [
568
+ "# 1. Gene Expression Data Availability\n",
569
+ "# Based on the background information, this dataset contains gene expression data from PBMCs\n",
570
+ "# using Affymetrix HuGene 1.0 ST arrays, so it's suitable for our analysis.\n",
571
+ "is_gene_available = True\n",
572
+ "\n",
573
+ "# 2. Variable Availability and Data Type Conversion\n",
574
+ "# 2.1 Data Availability\n",
575
+ "# From the Sample Characteristics Dictionary, we can identify the following:\n",
576
+ "\n",
577
+ "# For trait (Coronary_artery_disease):\n",
578
+ "# Row 2 contains 'hf progression', which has information about heart failure (HF) and stable CAD\n",
579
+ "trait_row = 2\n",
580
+ "\n",
581
+ "# Age is not explicitly mentioned in the characteristics\n",
582
+ "age_row = None\n",
583
+ "\n",
584
+ "# Gender is not explicitly mentioned in the characteristics\n",
585
+ "gender_row = None\n",
586
+ "\n",
587
+ "# 2.2 Data Type Conversion Functions\n",
588
+ "def convert_trait(value):\n",
589
+ " \"\"\"\n",
590
+ " Convert trait value to binary:\n",
591
+ " 1 for MI patients (HF, non-HF) - these are the cases with CAD that had myocardial infarction\n",
592
+ " 0 for controls (stable CAD without MI history)\n",
593
+ " None for unclear cases\n",
594
+ " \"\"\"\n",
595
+ " if value is None:\n",
596
+ " return None\n",
597
+ " \n",
598
+ " # Extract the value after the colon if present\n",
599
+ " if isinstance(value, str) and ':' in value:\n",
600
+ " value = value.split(':', 1)[1].strip()\n",
601
+ " \n",
602
+ " # Print for debugging\n",
603
+ " print(f\"Processing trait value: '{value}'\")\n",
604
+ " \n",
605
+ " if value == 'stable CAD':\n",
606
+ " return 0 # Control group (CAD without MI)\n",
607
+ " elif value in ['HF', 'non-HF']:\n",
608
+ " return 1 # CAD/MI patients (cases)\n",
609
+ " elif value == 'N/A':\n",
610
+ " return None\n",
611
+ " else:\n",
612
+ " return None\n",
613
+ "\n",
614
+ "def convert_age(value):\n",
615
+ " \"\"\"Placeholder function for age conversion since age data is not available\"\"\"\n",
616
+ " return None\n",
617
+ "\n",
618
+ "def convert_gender(value):\n",
619
+ " \"\"\"Placeholder function for gender conversion since gender data is not available\"\"\"\n",
620
+ " return None\n",
621
+ "\n",
622
+ "# 3. Save Metadata\n",
623
+ "# Determine trait data availability\n",
624
+ "is_trait_available = trait_row is not None\n",
625
+ "\n",
626
+ "# Validate and save cohort info\n",
627
+ "validate_and_save_cohort_info(\n",
628
+ " is_final=False,\n",
629
+ " cohort=cohort,\n",
630
+ " info_path=json_path,\n",
631
+ " is_gene_available=is_gene_available,\n",
632
+ " is_trait_available=is_trait_available\n",
633
+ ")\n",
634
+ "\n",
635
+ "# 4. Clinical Feature Extraction\n",
636
+ "if trait_row is not None:\n",
637
+ " # Print the unique values in the trait row for debugging\n",
638
+ " print(\"Unique values in trait_row:\")\n",
639
+ " unique_vals = clinical_data.iloc[trait_row].unique()\n",
640
+ " for val in unique_vals:\n",
641
+ " print(f\" {val}\")\n",
642
+ " \n",
643
+ " # Extract clinical features\n",
644
+ " clinical_df = geo_select_clinical_features(\n",
645
+ " clinical_df=clinical_data,\n",
646
+ " trait=trait,\n",
647
+ " trait_row=trait_row,\n",
648
+ " convert_trait=convert_trait,\n",
649
+ " age_row=age_row,\n",
650
+ " convert_age=convert_age,\n",
651
+ " gender_row=gender_row,\n",
652
+ " convert_gender=convert_gender\n",
653
+ " )\n",
654
+ " \n",
655
+ " # Preview the extracted clinical data\n",
656
+ " print(\"Preview of clinical data:\")\n",
657
+ " print(preview_df(clinical_df))\n",
658
+ " \n",
659
+ " # Save the clinical data to CSV\n",
660
+ " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
661
+ " clinical_df.to_csv(out_clinical_data_file)\n",
662
+ " print(f\"Clinical data saved to {out_clinical_data_file}\")\n"
663
+ ]
664
+ },
665
+ {
666
+ "cell_type": "markdown",
667
+ "id": "7d417fdf",
668
+ "metadata": {},
669
+ "source": [
670
+ "### Step 3: Gene Data Extraction"
671
+ ]
672
+ },
673
+ {
674
+ "cell_type": "code",
675
+ "execution_count": 4,
676
+ "id": "6630c059",
677
+ "metadata": {
678
+ "execution": {
679
+ "iopub.execute_input": "2025-03-25T08:28:45.937218Z",
680
+ "iopub.status.busy": "2025-03-25T08:28:45.937096Z",
681
+ "iopub.status.idle": "2025-03-25T08:28:47.035904Z",
682
+ "shell.execute_reply": "2025-03-25T08:28:47.035546Z"
683
+ }
684
+ },
685
+ "outputs": [
686
+ {
687
+ "name": "stdout",
688
+ "output_type": "stream",
689
+ "text": [
690
+ "SOFT file: ../../input/GEO/Coronary_artery_disease/GSE59867/GSE59867_family.soft.gz\n",
691
+ "Matrix file: ../../input/GEO/Coronary_artery_disease/GSE59867/GSE59867_series_matrix.txt.gz\n",
692
+ "Found the matrix table marker at line 66\n"
693
+ ]
694
+ },
695
+ {
696
+ "name": "stdout",
697
+ "output_type": "stream",
698
+ "text": [
699
+ "Gene data shape: (33297, 436)\n",
700
+ "First 20 gene/probe identifiers:\n",
701
+ "['7892501', '7892502', '7892503', '7892504', '7892505', '7892506', '7892507', '7892508', '7892509', '7892510', '7892511', '7892512', '7892513', '7892514', '7892515', '7892516', '7892517', '7892518', '7892519', '7892520']\n"
702
+ ]
703
+ }
704
+ ],
705
+ "source": [
706
+ "# 1. Identify the paths to the SOFT file and the matrix file\n",
707
+ "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
708
+ "print(f\"SOFT file: {soft_file}\")\n",
709
+ "print(f\"Matrix file: {matrix_file}\")\n",
710
+ "\n",
711
+ "# Set gene availability flag\n",
712
+ "is_gene_available = True # Initially assume gene data is available\n",
713
+ "\n",
714
+ "# First check if the matrix file contains the expected marker\n",
715
+ "found_marker = False\n",
716
+ "marker_row = None\n",
717
+ "try:\n",
718
+ " with gzip.open(matrix_file, 'rt') as file:\n",
719
+ " for i, line in enumerate(file):\n",
720
+ " if \"!series_matrix_table_begin\" in line:\n",
721
+ " found_marker = True\n",
722
+ " marker_row = i\n",
723
+ " print(f\"Found the matrix table marker at line {i}\")\n",
724
+ " break\n",
725
+ " \n",
726
+ " if not found_marker:\n",
727
+ " print(\"Warning: Could not find '!series_matrix_table_begin' marker in the file.\")\n",
728
+ " is_gene_available = False\n",
729
+ " \n",
730
+ " # If marker was found, try to extract gene data\n",
731
+ " if is_gene_available:\n",
732
+ " try:\n",
733
+ " # Try using the library function\n",
734
+ " gene_data = get_genetic_data(matrix_file)\n",
735
+ " \n",
736
+ " if gene_data.shape[0] == 0:\n",
737
+ " print(\"Warning: Extracted gene data has 0 rows.\")\n",
738
+ " is_gene_available = False\n",
739
+ " else:\n",
740
+ " print(f\"Gene data shape: {gene_data.shape}\")\n",
741
+ " # Print the first 20 gene/probe identifiers\n",
742
+ " print(\"First 20 gene/probe identifiers:\")\n",
743
+ " print(gene_data.index[:20].tolist())\n",
744
+ " except Exception as e:\n",
745
+ " print(f\"Error extracting gene data with get_genetic_data(): {e}\")\n",
746
+ " is_gene_available = False\n",
747
+ " \n",
748
+ " # If gene data extraction failed, examine file content to diagnose\n",
749
+ " if not is_gene_available:\n",
750
+ " print(\"Examining file content to diagnose the issue:\")\n",
751
+ " try:\n",
752
+ " with gzip.open(matrix_file, 'rt') as file:\n",
753
+ " # Print lines around the marker if found\n",
754
+ " if marker_row is not None:\n",
755
+ " for i, line in enumerate(file):\n",
756
+ " if i >= marker_row - 2 and i <= marker_row + 10:\n",
757
+ " print(f\"Line {i}: {line.strip()[:100]}...\")\n",
758
+ " if i > marker_row + 10:\n",
759
+ " break\n",
760
+ " else:\n",
761
+ " # If marker not found, print first 10 lines\n",
762
+ " for i, line in enumerate(file):\n",
763
+ " if i < 10:\n",
764
+ " print(f\"Line {i}: {line.strip()[:100]}...\")\n",
765
+ " else:\n",
766
+ " break\n",
767
+ " except Exception as e2:\n",
768
+ " print(f\"Error examining file: {e2}\")\n",
769
+ " \n",
770
+ "except Exception as e:\n",
771
+ " print(f\"Error processing file: {e}\")\n",
772
+ " is_gene_available = False\n",
773
+ "\n",
774
+ "# Update validation information if gene data extraction failed\n",
775
+ "if not is_gene_available:\n",
776
+ " print(\"Gene expression data could not be successfully extracted from this dataset.\")\n",
777
+ " # Update the validation record since gene data isn't available\n",
778
+ " is_trait_available = False # We already determined trait data isn't available in step 2\n",
779
+ " validate_and_save_cohort_info(is_final=False, cohort=cohort, info_path=json_path,\n",
780
+ " is_gene_available=is_gene_available, is_trait_available=is_trait_available)\n"
781
+ ]
782
+ },
783
+ {
784
+ "cell_type": "markdown",
785
+ "id": "545e46bb",
786
+ "metadata": {},
787
+ "source": [
788
+ "### Step 4: Gene Identifier Review"
789
+ ]
790
+ },
791
+ {
792
+ "cell_type": "code",
793
+ "execution_count": 5,
794
+ "id": "94e50ed3",
795
+ "metadata": {
796
+ "execution": {
797
+ "iopub.execute_input": "2025-03-25T08:28:47.037317Z",
798
+ "iopub.status.busy": "2025-03-25T08:28:47.037188Z",
799
+ "iopub.status.idle": "2025-03-25T08:28:47.039157Z",
800
+ "shell.execute_reply": "2025-03-25T08:28:47.038881Z"
801
+ }
802
+ },
803
+ "outputs": [],
804
+ "source": [
805
+ "# The gene identifiers in the expression data appear to be numerical probe IDs (7892501, 7892502, etc.)\n",
806
+ "# These are not standard human gene symbols (which would be like BRCA1, TP53, etc.)\n",
807
+ "# Most likely these are Illumina or Affymetrix probe IDs that need to be mapped to gene symbols\n",
808
+ "\n",
809
+ "requires_gene_mapping = True\n"
810
+ ]
811
+ },
812
+ {
813
+ "cell_type": "markdown",
814
+ "id": "17257032",
815
+ "metadata": {},
816
+ "source": [
817
+ "### Step 5: Gene Annotation"
818
+ ]
819
+ },
820
+ {
821
+ "cell_type": "code",
822
+ "execution_count": 6,
823
+ "id": "8eb08ea2",
824
+ "metadata": {
825
+ "execution": {
826
+ "iopub.execute_input": "2025-03-25T08:28:47.040409Z",
827
+ "iopub.status.busy": "2025-03-25T08:28:47.040304Z",
828
+ "iopub.status.idle": "2025-03-25T08:29:06.806860Z",
829
+ "shell.execute_reply": "2025-03-25T08:29:06.806177Z"
830
+ }
831
+ },
832
+ "outputs": [
833
+ {
834
+ "name": "stdout",
835
+ "output_type": "stream",
836
+ "text": [
837
+ "\n",
838
+ "Gene annotation preview:\n",
839
+ "Columns in gene annotation: ['ID', 'GB_LIST', 'SPOT_ID', 'seqname', 'RANGE_GB', 'RANGE_STRAND', 'RANGE_START', 'RANGE_STOP', 'total_probes', 'gene_assignment', 'mrna_assignment', 'category']\n",
840
+ "{'ID': ['7896736', '7896738', '7896740'], 'GB_LIST': [nan, nan, 'NM_001004195,NM_001005240,NM_001005484,BC136848,BC136867,BC136907,BC136908'], 'SPOT_ID': ['chr1:53049-54936', 'chr1:63015-63887', 'chr1:69091-70008'], 'seqname': ['chr1', 'chr1', 'chr1'], 'RANGE_GB': ['NC_000001.10', 'NC_000001.10', 'NC_000001.10'], 'RANGE_STRAND': ['+', '+', '+'], 'RANGE_START': ['53049', '63015', '69091'], 'RANGE_STOP': ['54936', '63887', '70008'], 'total_probes': [7.0, 31.0, 24.0], 'gene_assignment': ['---', 'ENST00000328113 // OR4G2P // olfactory receptor, family 4, subfamily G, member 2 pseudogene // --- // --- /// ENST00000492842 // OR4G11P // olfactory receptor, family 4, subfamily G, member 11 pseudogene // --- // --- /// ENST00000588632 // OR4G1P // olfactory receptor, family 4, subfamily G, member 1 pseudogene // --- // ---', 'NM_001004195 // OR4F4 // olfactory receptor, family 4, subfamily F, member 4 // 15q26.3 // 26682 /// NM_001005240 // OR4F17 // olfactory receptor, family 4, subfamily F, member 17 // 19p13.3 // 81099 /// NM_001005484 // OR4F5 // olfactory receptor, family 4, subfamily F, member 5 // 1p36.33 // 79501 /// ENST00000318050 // OR4F17 // olfactory receptor, family 4, subfamily F, member 17 // 19p13.3 // 81099 /// ENST00000326183 // OR4F4 // olfactory receptor, family 4, subfamily F, member 4 // 15q26.3 // 26682 /// ENST00000335137 // OR4F5 // olfactory receptor, family 4, subfamily F, member 5 // 1p36.33 // 79501 /// ENST00000585993 // OR4F17 // olfactory receptor, family 4, subfamily F, member 17 // 19p13.3 // 81099 /// BC136848 // OR4F17 // olfactory receptor, family 4, subfamily F, member 17 // 19p13.3 // 81099 /// BC136867 // OR4F17 // olfactory receptor, family 4, subfamily F, member 17 // 19p13.3 // 81099 /// BC136907 // OR4F4 // olfactory receptor, family 4, subfamily F, member 4 // 15q26.3 // 26682 /// BC136908 // OR4F4 // olfactory receptor, family 4, subfamily F, member 4 // 15q26.3 // 26682'], 'mrna_assignment': ['NONHSAT060105 // NONCODE // Non-coding transcript identified by NONCODE // chr1 // 100 // 100 // 7 // 7 // 0', 'ENST00000328113 // ENSEMBL // havana:known chromosome:GRCh38:15:101926805:101927707:-1 gene:ENSG00000183909 gene_biotype:unprocessed_pseudogene transcript_biotype:unprocessed_pseudogene // chr1 // 100 // 100 // 31 // 31 // 0 /// ENST00000492842 // ENSEMBL // havana:known chromosome:GRCh38:1:62948:63887:1 gene:ENSG00000240361 gene_biotype:unprocessed_pseudogene transcript_biotype:unprocessed_pseudogene // chr1 // 100 // 100 // 31 // 31 // 0 /// ENST00000588632 // ENSEMBL // havana:known chromosome:GRCh38:19:104535:105471:1 gene:ENSG00000267310 gene_biotype:unprocessed_pseudogene transcript_biotype:unprocessed_pseudogene // chr1 // 100 // 100 // 31 // 31 // 0 /// NONHSAT000016 // NONCODE // Non-coding transcript identified by NONCODE: Linc // chr1 // 100 // 100 // 31 // 31 // 0 /// NONHSAT051704 // NONCODE // Non-coding transcript identified by NONCODE: Linc // chr1 // 100 // 100 // 31 // 31 // 0 /// NONHSAT060106 // NONCODE // Non-coding transcript identified by NONCODE: Linc // chr1 // 100 // 100 // 31 // 31 // 0', 'NM_001004195 // RefSeq // Homo sapiens olfactory receptor, family 4, subfamily F, member 4 (OR4F4), mRNA. // chr1 // 100 // 100 // 24 // 24 // 0 /// NM_001005240 // RefSeq // Homo sapiens olfactory receptor, family 4, subfamily F, member 17 (OR4F17), mRNA. // chr1 // 100 // 100 // 24 // 24 // 0 /// NM_001005484 // RefSeq // Homo sapiens olfactory receptor, family 4, subfamily F, member 5 (OR4F5), mRNA. // chr1 // 100 // 100 // 24 // 24 // 0 /// ENST00000318050 // ENSEMBL // ensembl:known chromosome:GRCh38:19:110643:111696:1 gene:ENSG00000176695 gene_biotype:protein_coding transcript_biotype:protein_coding // chr1 // 100 // 100 // 24 // 24 // 0 /// ENST00000326183 // ENSEMBL // ensembl_havana_transcript:known chromosome:GRCh38:15:101922042:101923095:-1 gene:ENSG00000177693 gene_biotype:protein_coding transcript_biotype:protein_coding // chr1 // 100 // 100 // 24 // 24 // 0 /// ENST00000335137 // ENSEMBL // ensembl_havana_transcript:known chromosome:GRCh38:1:69091:70008:1 gene:ENSG00000186092 gene_biotype:protein_coding transcript_biotype:protein_coding // chr1 // 100 // 100 // 24 // 24 // 0 /// ENST00000585993 // ENSEMBL // havana:known chromosome:GRCh38:19:107461:111696:1 gene:ENSG00000176695 gene_biotype:protein_coding transcript_biotype:protein_coding // chr1 // 100 // 100 // 24 // 24 // 0 /// BC136848 // GenBank // Homo sapiens olfactory receptor, family 4, subfamily F, member 17, mRNA (cDNA clone MGC:168462 IMAGE:9020839), complete cds. // chr1 // 100 // 100 // 24 // 24 // 0 /// BC136867 // GenBank // Homo sapiens olfactory receptor, family 4, subfamily F, member 17, mRNA (cDNA clone MGC:168481 IMAGE:9020858), complete cds. // chr1 // 100 // 100 // 24 // 24 // 0 /// BC136907 // GenBank // Homo sapiens olfactory receptor, family 4, subfamily F, member 4, mRNA (cDNA clone MGC:168521 IMAGE:9020898), complete cds. // chr1 // 100 // 100 // 24 // 24 // 0 /// BC136908 // GenBank // Homo sapiens olfactory receptor, family 4, subfamily F, member 4, mRNA (cDNA clone MGC:168522 IMAGE:9020899), complete cds. // chr1 // 100 // 100 // 24 // 24 // 0 /// ENST00000618231 // ENSEMBL // havana:known chromosome:GRCh38:19:110613:111417:1 gene:ENSG00000176695 gene_biotype:protein_coding transcript_biotype:retained_intron // chr1 // 100 // 88 // 21 // 21 // 0'], 'category': ['main', 'main', 'main']}\n",
841
+ "\n",
842
+ "Examining gene_assignment column format (first 3 rows):\n",
843
+ "Row 0: ID=7896736\n",
844
+ "Gene assignment: ---...\n",
845
+ "Row 1: ID=7896738\n",
846
+ "Gene assignment: ENST00000328113 // OR4G2P // olfactory receptor, family 4, subfamily G, member 2 pseudogene // --- // --- /// ENST00000492842 // OR4G11P // olfactory receptor, family 4, subfamily G, member 11 pseudog...\n",
847
+ "Row 2: ID=7896740\n",
848
+ "Gene assignment: NM_001004195 // OR4F4 // olfactory receptor, family 4, subfamily F, member 4 // 15q26.3 // 26682 /// NM_001005240 // OR4F17 // olfactory receptor, family 4, subfamily F, member 17 // 19p13.3 // 81099 ...\n",
849
+ "\n",
850
+ "Gene assignment column completeness: 33297/14551225 rows (0.23%)\n",
851
+ "\n",
852
+ "Attempting to extract gene symbols from the first few gene_assignment entries:\n",
853
+ "Row 0 extracted symbols: []\n",
854
+ "Row 1 extracted symbols: ['OR4G2P', 'OR4G11P', 'OR4G1P']\n",
855
+ "Row 2 extracted symbols: ['OR4F4', 'OR4F17', 'OR4F5', 'BC136848', 'BC136867', 'BC136907', 'BC136908']\n"
856
+ ]
857
+ }
858
+ ],
859
+ "source": [
860
+ "# 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.\n",
861
+ "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
862
+ "gene_annotation = get_gene_annotation(soft_file)\n",
863
+ "\n",
864
+ "# 2. Analyze the gene annotation dataframe to identify which columns contain the gene identifiers and gene symbols\n",
865
+ "print(\"\\nGene annotation preview:\")\n",
866
+ "print(f\"Columns in gene annotation: {gene_annotation.columns.tolist()}\")\n",
867
+ "print(preview_df(gene_annotation, n=3))\n",
868
+ "\n",
869
+ "# Examine the gene_assignment column that contains gene symbol information\n",
870
+ "print(\"\\nExamining gene_assignment column format (first 3 rows):\")\n",
871
+ "if 'ID' in gene_annotation.columns and 'gene_assignment' in gene_annotation.columns:\n",
872
+ " for i in range(min(3, len(gene_annotation))):\n",
873
+ " print(f\"Row {i}: ID={gene_annotation['ID'].iloc[i]}\")\n",
874
+ " print(f\"Gene assignment: {gene_annotation['gene_assignment'].iloc[i][:200]}...\") # Show first 200 chars\n",
875
+ "\n",
876
+ " # Check the quality and completeness of the mapping\n",
877
+ " non_null_assignments = gene_annotation['gene_assignment'].notna().sum()\n",
878
+ " total_rows = len(gene_annotation)\n",
879
+ " print(f\"\\nGene assignment column completeness: {non_null_assignments}/{total_rows} rows ({non_null_assignments/total_rows:.2%})\")\n",
880
+ " \n",
881
+ " # Check if some extracted gene symbols can be found in the gene_assignment column\n",
882
+ " print(\"\\nAttempting to extract gene symbols from the first few gene_assignment entries:\")\n",
883
+ " for i in range(min(3, len(gene_annotation))):\n",
884
+ " if pd.notna(gene_annotation['gene_assignment'].iloc[i]):\n",
885
+ " symbols = extract_human_gene_symbols(str(gene_annotation['gene_assignment'].iloc[i]))\n",
886
+ " print(f\"Row {i} extracted symbols: {symbols}\")\n"
887
+ ]
888
+ },
889
+ {
890
+ "cell_type": "markdown",
891
+ "id": "dce65401",
892
+ "metadata": {},
893
+ "source": [
894
+ "### Step 6: Gene Identifier Mapping"
895
+ ]
896
+ },
897
+ {
898
+ "cell_type": "code",
899
+ "execution_count": 7,
900
+ "id": "59113efd",
901
+ "metadata": {
902
+ "execution": {
903
+ "iopub.execute_input": "2025-03-25T08:29:06.808763Z",
904
+ "iopub.status.busy": "2025-03-25T08:29:06.808638Z",
905
+ "iopub.status.idle": "2025-03-25T08:29:16.657122Z",
906
+ "shell.execute_reply": "2025-03-25T08:29:16.656458Z"
907
+ }
908
+ },
909
+ "outputs": [
910
+ {
911
+ "name": "stdout",
912
+ "output_type": "stream",
913
+ "text": [
914
+ "Gene mapping dataframe shape: (33297, 2)\n",
915
+ "Sample of mapping data:\n",
916
+ " ID Gene\n",
917
+ "0 7896736 ---\n",
918
+ "1 7896738 ENST00000328113 // OR4G2P // olfactory recepto...\n",
919
+ "2 7896740 NM_001004195 // OR4F4 // olfactory receptor, f...\n"
920
+ ]
921
+ },
922
+ {
923
+ "name": "stdout",
924
+ "output_type": "stream",
925
+ "text": [
926
+ "Gene expression data after mapping - shape: (24229, 436)\n",
927
+ "First 10 gene symbols after mapping:\n",
928
+ "['A1BG', 'A1CF', 'A2M', 'A2ML1', 'A3GALT2', 'A4GALT', 'A4GNT', 'AAA1', 'AAAS', 'AACS']\n"
929
+ ]
930
+ },
931
+ {
932
+ "name": "stdout",
933
+ "output_type": "stream",
934
+ "text": [
935
+ "Gene expression data saved to ../../output/preprocess/Coronary_artery_disease/gene_data/GSE59867.csv\n"
936
+ ]
937
+ }
938
+ ],
939
+ "source": [
940
+ "# 1. Identify the columns in the gene annotation that contain probe IDs and gene symbols\n",
941
+ "# Based on examining the data, 'ID' appears to contain the probe IDs matching those in gene_data\n",
942
+ "# 'gene_assignment' contains the gene symbol information that needs extraction\n",
943
+ "\n",
944
+ "# 2. Extract gene mapping dataframe from annotation\n",
945
+ "mapping_data = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='gene_assignment')\n",
946
+ "\n",
947
+ "# Print mapping info to verify\n",
948
+ "print(f\"Gene mapping dataframe shape: {mapping_data.shape}\")\n",
949
+ "print(\"Sample of mapping data:\")\n",
950
+ "print(mapping_data.head(3))\n",
951
+ "\n",
952
+ "# 3. Apply gene mapping to convert probe-level measurements to gene expression\n",
953
+ "# The apply_gene_mapping function will handle many-to-many mappings as specified\n",
954
+ "gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_data)\n",
955
+ "\n",
956
+ "# Normalize gene symbols to standard format\n",
957
+ "gene_data = normalize_gene_symbols_in_index(gene_data)\n",
958
+ "\n",
959
+ "print(f\"Gene expression data after mapping - shape: {gene_data.shape}\")\n",
960
+ "print(\"First 10 gene symbols after mapping:\")\n",
961
+ "print(gene_data.index[:10].tolist())\n",
962
+ "\n",
963
+ "# Save gene data to CSV for future use\n",
964
+ "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
965
+ "gene_data.to_csv(out_gene_data_file)\n",
966
+ "print(f\"Gene expression data saved to {out_gene_data_file}\")\n"
967
+ ]
968
+ },
969
+ {
970
+ "cell_type": "markdown",
971
+ "id": "67264aea",
972
+ "metadata": {},
973
+ "source": [
974
+ "### Step 7: Data Normalization and Linking"
975
+ ]
976
+ },
977
+ {
978
+ "cell_type": "code",
979
+ "execution_count": 8,
980
+ "id": "8f802e35",
981
+ "metadata": {
982
+ "execution": {
983
+ "iopub.execute_input": "2025-03-25T08:29:16.658928Z",
984
+ "iopub.status.busy": "2025-03-25T08:29:16.658814Z",
985
+ "iopub.status.idle": "2025-03-25T08:29:41.899002Z",
986
+ "shell.execute_reply": "2025-03-25T08:29:41.898239Z"
987
+ }
988
+ },
989
+ "outputs": [
990
+ {
991
+ "name": "stdout",
992
+ "output_type": "stream",
993
+ "text": [
994
+ "Gene data shape before normalization: (24229, 436)\n"
995
+ ]
996
+ },
997
+ {
998
+ "name": "stdout",
999
+ "output_type": "stream",
1000
+ "text": [
1001
+ "Gene data saved to ../../output/preprocess/Coronary_artery_disease/gene_data/GSE59867.csv\n",
1002
+ "Loaded clinical data shape: (1, 436)\n",
1003
+ "Initial linked data shape: (436, 24230)\n"
1004
+ ]
1005
+ },
1006
+ {
1007
+ "name": "stdout",
1008
+ "output_type": "stream",
1009
+ "text": [
1010
+ "Linked data shape after handling missing values: (110, 24230)\n",
1011
+ "For the feature 'Coronary_artery_disease', the least common label is '0.0' with 46 occurrences. This represents 41.82% of the dataset.\n",
1012
+ "The distribution of the feature 'Coronary_artery_disease' in this dataset is fine.\n",
1013
+ "\n"
1014
+ ]
1015
+ },
1016
+ {
1017
+ "name": "stdout",
1018
+ "output_type": "stream",
1019
+ "text": [
1020
+ "Linked data saved to ../../output/preprocess/Coronary_artery_disease/GSE59867.csv\n"
1021
+ ]
1022
+ }
1023
+ ],
1024
+ "source": [
1025
+ "# 1. Attempt to load gene data and handle possible issues with normalization\n",
1026
+ "try:\n",
1027
+ " # Create output directory if it doesn't exist\n",
1028
+ " os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
1029
+ " \n",
1030
+ " # Check if gene_data (from previous step) has any content\n",
1031
+ " if gene_data.shape[0] == 0:\n",
1032
+ " print(\"WARNING: Gene data is empty after normalization in previous step.\")\n",
1033
+ " print(\"This appears to be miRNA data rather than gene expression data.\")\n",
1034
+ " \n",
1035
+ " # Since gene_data is empty, set gene_available to False\n",
1036
+ " is_gene_available = False\n",
1037
+ " \n",
1038
+ " # Create an empty dataframe for metadata purposes\n",
1039
+ " empty_df = pd.DataFrame()\n",
1040
+ " \n",
1041
+ " # Log information about this dataset for future reference\n",
1042
+ " validate_and_save_cohort_info(\n",
1043
+ " is_final=True,\n",
1044
+ " cohort=cohort,\n",
1045
+ " info_path=json_path,\n",
1046
+ " is_gene_available=is_gene_available,\n",
1047
+ " is_trait_available=is_trait_available,\n",
1048
+ " is_biased=True, # Consider it biased as we can't use it\n",
1049
+ " df=empty_df,\n",
1050
+ " note=\"Dataset appears to contain miRNA data rather than gene expression data. Gene symbols could not be normalized.\"\n",
1051
+ " )\n",
1052
+ " \n",
1053
+ " print(\"Dataset marked as unusable due to lack of valid gene expression data.\")\n",
1054
+ " else:\n",
1055
+ " # If gene_data is not empty, proceed with normalization and linking\n",
1056
+ " print(f\"Gene data shape before normalization: {gene_data.shape}\")\n",
1057
+ " \n",
1058
+ " # Save the gene data we have, even if it's already normalized\n",
1059
+ " gene_data.to_csv(out_gene_data_file)\n",
1060
+ " print(f\"Gene data saved to {out_gene_data_file}\")\n",
1061
+ " \n",
1062
+ " # Attempt to link clinical and gene data\n",
1063
+ " if is_trait_available:\n",
1064
+ " # Load clinical data\n",
1065
+ " clinical_features = pd.read_csv(out_clinical_data_file, index_col=0)\n",
1066
+ " print(f\"Loaded clinical data shape: {clinical_features.shape}\")\n",
1067
+ " \n",
1068
+ " # Link the clinical and genetic data\n",
1069
+ " linked_data = geo_link_clinical_genetic_data(clinical_features, gene_data)\n",
1070
+ " print(f\"Initial linked data shape: {linked_data.shape}\")\n",
1071
+ " \n",
1072
+ " # Handle missing values\n",
1073
+ " linked_data = handle_missing_values(linked_data, trait)\n",
1074
+ " print(f\"Linked data shape after handling missing values: {linked_data.shape}\")\n",
1075
+ " \n",
1076
+ " if linked_data.shape[0] > 0:\n",
1077
+ " # Check for bias in trait and demographic features\n",
1078
+ " is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n",
1079
+ " \n",
1080
+ " # Validate data quality and save cohort info\n",
1081
+ " is_usable = validate_and_save_cohort_info(\n",
1082
+ " is_final=True,\n",
1083
+ " cohort=cohort,\n",
1084
+ " info_path=json_path,\n",
1085
+ " is_gene_available=is_gene_available,\n",
1086
+ " is_trait_available=is_trait_available,\n",
1087
+ " is_biased=is_biased,\n",
1088
+ " df=linked_data,\n",
1089
+ " note=\"Successfully processed gene expression data for coronary artery disease.\"\n",
1090
+ " )\n",
1091
+ " \n",
1092
+ " # Save the linked data if it's usable\n",
1093
+ " if is_usable:\n",
1094
+ " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n",
1095
+ " linked_data.to_csv(out_data_file)\n",
1096
+ " print(f\"Linked data saved to {out_data_file}\")\n",
1097
+ " else:\n",
1098
+ " print(\"Data not usable for trait study - not saving final linked data.\")\n",
1099
+ " else:\n",
1100
+ " print(\"After handling missing values, no samples remain.\")\n",
1101
+ " validate_and_save_cohort_info(\n",
1102
+ " is_final=True,\n",
1103
+ " cohort=cohort,\n",
1104
+ " info_path=json_path,\n",
1105
+ " is_gene_available=is_gene_available,\n",
1106
+ " is_trait_available=is_trait_available,\n",
1107
+ " is_biased=True,\n",
1108
+ " df=pd.DataFrame(),\n",
1109
+ " note=\"No valid samples after handling missing values.\"\n",
1110
+ " )\n",
1111
+ " else:\n",
1112
+ " # Cannot proceed with linking if trait data is missing\n",
1113
+ " validate_and_save_cohort_info(\n",
1114
+ " is_final=True,\n",
1115
+ " cohort=cohort,\n",
1116
+ " info_path=json_path,\n",
1117
+ " is_gene_available=is_gene_available,\n",
1118
+ " is_trait_available=is_trait_available,\n",
1119
+ " is_biased=True,\n",
1120
+ " df=pd.DataFrame(),\n",
1121
+ " note=\"Cannot link data because trait information is not available.\"\n",
1122
+ " )\n",
1123
+ "except Exception as e:\n",
1124
+ " print(f\"Error in data processing: {e}\")\n",
1125
+ " \n",
1126
+ " # Log the error and mark the dataset as unusable\n",
1127
+ " validate_and_save_cohort_info(\n",
1128
+ " is_final=True,\n",
1129
+ " cohort=cohort,\n",
1130
+ " info_path=json_path,\n",
1131
+ " is_gene_available=False, # Consider gene data unavailable if we had an error\n",
1132
+ " is_trait_available=is_trait_available,\n",
1133
+ " is_biased=True, # Consider it biased as we can't use it\n",
1134
+ " df=pd.DataFrame(), # Empty dataframe for metadata\n",
1135
+ " note=f\"Error during normalization or linking: {str(e)}\"\n",
1136
+ " )"
1137
+ ]
1138
+ }
1139
+ ],
1140
+ "metadata": {
1141
+ "language_info": {
1142
+ "codemirror_mode": {
1143
+ "name": "ipython",
1144
+ "version": 3
1145
+ },
1146
+ "file_extension": ".py",
1147
+ "mimetype": "text/x-python",
1148
+ "name": "python",
1149
+ "nbconvert_exporter": "python",
1150
+ "pygments_lexer": "ipython3",
1151
+ "version": "3.10.16"
1152
+ }
1153
+ },
1154
+ "nbformat": 4,
1155
+ "nbformat_minor": 5
1156
+ }
code/Coronary_artery_disease/GSE64554.ipynb ADDED
@@ -0,0 +1,721 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": 1,
6
+ "id": "ae0392e9",
7
+ "metadata": {
8
+ "execution": {
9
+ "iopub.execute_input": "2025-03-25T08:29:43.226721Z",
10
+ "iopub.status.busy": "2025-03-25T08:29:43.226589Z",
11
+ "iopub.status.idle": "2025-03-25T08:29:43.395364Z",
12
+ "shell.execute_reply": "2025-03-25T08:29:43.395008Z"
13
+ }
14
+ },
15
+ "outputs": [],
16
+ "source": [
17
+ "import sys\n",
18
+ "import os\n",
19
+ "sys.path.append(os.path.abspath(os.path.join(os.getcwd(), '../..')))\n",
20
+ "\n",
21
+ "# Path Configuration\n",
22
+ "from tools.preprocess import *\n",
23
+ "\n",
24
+ "# Processing context\n",
25
+ "trait = \"Coronary_artery_disease\"\n",
26
+ "cohort = \"GSE64554\"\n",
27
+ "\n",
28
+ "# Input paths\n",
29
+ "in_trait_dir = \"../../input/GEO/Coronary_artery_disease\"\n",
30
+ "in_cohort_dir = \"../../input/GEO/Coronary_artery_disease/GSE64554\"\n",
31
+ "\n",
32
+ "# Output paths\n",
33
+ "out_data_file = \"../../output/preprocess/Coronary_artery_disease/GSE64554.csv\"\n",
34
+ "out_gene_data_file = \"../../output/preprocess/Coronary_artery_disease/gene_data/GSE64554.csv\"\n",
35
+ "out_clinical_data_file = \"../../output/preprocess/Coronary_artery_disease/clinical_data/GSE64554.csv\"\n",
36
+ "json_path = \"../../output/preprocess/Coronary_artery_disease/cohort_info.json\"\n"
37
+ ]
38
+ },
39
+ {
40
+ "cell_type": "markdown",
41
+ "id": "f02e2f52",
42
+ "metadata": {},
43
+ "source": [
44
+ "### Step 1: Initial Data Loading"
45
+ ]
46
+ },
47
+ {
48
+ "cell_type": "code",
49
+ "execution_count": 2,
50
+ "id": "71f53b76",
51
+ "metadata": {
52
+ "execution": {
53
+ "iopub.execute_input": "2025-03-25T08:29:43.396825Z",
54
+ "iopub.status.busy": "2025-03-25T08:29:43.396683Z",
55
+ "iopub.status.idle": "2025-03-25T08:29:43.532804Z",
56
+ "shell.execute_reply": "2025-03-25T08:29:43.532406Z"
57
+ }
58
+ },
59
+ "outputs": [
60
+ {
61
+ "name": "stdout",
62
+ "output_type": "stream",
63
+ "text": [
64
+ "Background Information:\n",
65
+ "!Series_title\t\"GE/miRNA expression profile of Human Epicardial Adipose Tissue (EAT) and Subcutaneous Adipose Tissue (SAT) in Patients with Coronary Artery Disease (CAD) vs. Controls (CTRL) - PART 1 - Genes\"\n",
66
+ "!Series_summary\t\"Gene expression profiles of Human EAT vs. SAT (CTRL & CAD). The aim of the present study was to assess a gene expression chart characterizing EAT vs. SAT, and CAD vs. CTRL. Results provide the information that EAT is characterized by a differential expression of different genes when compared to its reference tissue (SAT), and that EAT is characterized by specific gene expression changes in patients with CAD.\"\n",
67
+ "!Series_overall_design\t\"RNA obtained from EAT & SAT of the same patients (paired samples). Comparisons: EAT vs. SAT (paired samples) & CAD vs. CTRL\"\n",
68
+ "Sample Characteristics Dictionary:\n",
69
+ "{0: ['age: 76', 'age: 71', 'age: 57', 'age: 30', 'age: 81', 'age: 51', 'age: 36', 'age: 44', 'age: 52', 'age: 73', 'age: 69', 'age: 56', 'age: 70', 'age: 67', 'age: 60', 'age: 61', 'age: 86', 'age: 82'], 1: ['tissue: Subcutaneous Adipose', 'tissue: Epicardial Adipose'], 2: ['disease state: control', 'disease state: coronary artery disease']}\n"
70
+ ]
71
+ }
72
+ ],
73
+ "source": [
74
+ "from tools.preprocess import *\n",
75
+ "# 1. Identify the paths to the SOFT file and the matrix file\n",
76
+ "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
77
+ "\n",
78
+ "# 2. Read the matrix file to obtain background information and sample characteristics data\n",
79
+ "background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']\n",
80
+ "clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']\n",
81
+ "background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)\n",
82
+ "\n",
83
+ "# 3. Obtain the sample characteristics dictionary from the clinical dataframe\n",
84
+ "sample_characteristics_dict = get_unique_values_by_row(clinical_data)\n",
85
+ "\n",
86
+ "# 4. Explicitly print out all the background information and the sample characteristics dictionary\n",
87
+ "print(\"Background Information:\")\n",
88
+ "print(background_info)\n",
89
+ "print(\"Sample Characteristics Dictionary:\")\n",
90
+ "print(sample_characteristics_dict)\n"
91
+ ]
92
+ },
93
+ {
94
+ "cell_type": "markdown",
95
+ "id": "b360499b",
96
+ "metadata": {},
97
+ "source": [
98
+ "### Step 2: Dataset Analysis and Clinical Feature Extraction"
99
+ ]
100
+ },
101
+ {
102
+ "cell_type": "code",
103
+ "execution_count": 3,
104
+ "id": "6e16f435",
105
+ "metadata": {
106
+ "execution": {
107
+ "iopub.execute_input": "2025-03-25T08:29:43.534143Z",
108
+ "iopub.status.busy": "2025-03-25T08:29:43.534031Z",
109
+ "iopub.status.idle": "2025-03-25T08:29:43.543696Z",
110
+ "shell.execute_reply": "2025-03-25T08:29:43.543394Z"
111
+ }
112
+ },
113
+ "outputs": [
114
+ {
115
+ "name": "stdout",
116
+ "output_type": "stream",
117
+ "text": [
118
+ "Preview of processed clinical data:\n",
119
+ "{'GSM1574149': [0.0, 76.0], 'GSM1574150': [0.0, 76.0], 'GSM1574151': [0.0, 71.0], 'GSM1574152': [0.0, 71.0], 'GSM1574153': [0.0, 57.0], 'GSM1574154': [0.0, 57.0], 'GSM1574155': [0.0, 30.0], 'GSM1574156': [0.0, 30.0], 'GSM1574157': [0.0, 81.0], 'GSM1574158': [0.0, 81.0], 'GSM1574159': [0.0, 51.0], 'GSM1574160': [0.0, 51.0], 'GSM1574161': [0.0, 36.0], 'GSM1574162': [0.0, 36.0], 'GSM1574163': [0.0, 44.0], 'GSM1574164': [0.0, 44.0], 'GSM1574165': [0.0, 36.0], 'GSM1574166': [0.0, 36.0], 'GSM1574167': [0.0, 52.0], 'GSM1574168': [0.0, 52.0], 'GSM1574169': [1.0, 73.0], 'GSM1574170': [1.0, 73.0], 'GSM1574171': [1.0, 69.0], 'GSM1574172': [1.0, 69.0], 'GSM1574173': [1.0, 56.0], 'GSM1574174': [1.0, 56.0], 'GSM1574175': [1.0, 69.0], 'GSM1574176': [1.0, 69.0], 'GSM1574177': [1.0, 73.0], 'GSM1574178': [1.0, 73.0], 'GSM1574179': [1.0, 70.0], 'GSM1574180': [1.0, 70.0], 'GSM1574181': [1.0, 67.0], 'GSM1574182': [1.0, 67.0], 'GSM1574183': [1.0, 60.0], 'GSM1574184': [1.0, 60.0], 'GSM1574185': [1.0, 61.0], 'GSM1574186': [1.0, 61.0], 'GSM1574187': [1.0, 86.0], 'GSM1574188': [1.0, 86.0], 'GSM1574189': [1.0, 82.0], 'GSM1574190': [1.0, 82.0], 'GSM1574191': [1.0, 71.0], 'GSM1574192': [1.0, 71.0], 'GSM1574193': [1.0, 70.0], 'GSM1574194': [1.0, 70.0]}\n",
120
+ "Processed clinical data saved to ../../output/preprocess/Coronary_artery_disease/clinical_data/GSE64554.csv\n"
121
+ ]
122
+ }
123
+ ],
124
+ "source": [
125
+ "# 1. Gene Expression Data Availability\n",
126
+ "# Based on Series_title, this is gene expression data from adipose tissue\n",
127
+ "is_gene_available = True\n",
128
+ "\n",
129
+ "# 2. Variable Availability and Data Type Conversion\n",
130
+ "# 2.1 Data Availability\n",
131
+ "\n",
132
+ "# For trait (coronary artery disease status)\n",
133
+ "# Key 2 contains \"disease state: control\" and \"disease state: coronary artery disease\"\n",
134
+ "trait_row = 2\n",
135
+ "\n",
136
+ "# For age - available in key 0\n",
137
+ "age_row = 0\n",
138
+ "\n",
139
+ "# For gender - not available in the sample characteristics\n",
140
+ "gender_row = None\n",
141
+ "\n",
142
+ "# 2.2 Data Type Conversion\n",
143
+ "\n",
144
+ "def convert_trait(value):\n",
145
+ " \"\"\"Convert disease state to binary: 0 for control, 1 for CAD\"\"\"\n",
146
+ " if not isinstance(value, str):\n",
147
+ " return None\n",
148
+ " \n",
149
+ " # Extract value after colon if present\n",
150
+ " if ':' in value:\n",
151
+ " value = value.split(':', 1)[1].strip().lower()\n",
152
+ " else:\n",
153
+ " value = value.lower().strip()\n",
154
+ " \n",
155
+ " if 'control' in value:\n",
156
+ " return 0\n",
157
+ " elif 'coronary artery disease' in value or 'cad' in value:\n",
158
+ " return 1\n",
159
+ " else:\n",
160
+ " return None\n",
161
+ "\n",
162
+ "def convert_age(value):\n",
163
+ " \"\"\"Convert age to continuous numeric value\"\"\"\n",
164
+ " if not isinstance(value, str):\n",
165
+ " return None\n",
166
+ " \n",
167
+ " # Extract value after colon if present\n",
168
+ " if ':' in value:\n",
169
+ " value = value.split(':', 1)[1].strip()\n",
170
+ " \n",
171
+ " try:\n",
172
+ " return float(value)\n",
173
+ " except (ValueError, TypeError):\n",
174
+ " return None\n",
175
+ "\n",
176
+ "def convert_gender(value):\n",
177
+ " \"\"\"Convert gender to binary: 0 for female, 1 for male\n",
178
+ " Not used in this dataset as gender information is not available\"\"\"\n",
179
+ " return None\n",
180
+ "\n",
181
+ "# 3. Save Metadata\n",
182
+ "is_trait_available = trait_row is not None\n",
183
+ "validate_and_save_cohort_info(\n",
184
+ " is_final=False,\n",
185
+ " cohort=cohort,\n",
186
+ " info_path=json_path,\n",
187
+ " is_gene_available=is_gene_available,\n",
188
+ " is_trait_available=is_trait_available\n",
189
+ ")\n",
190
+ "\n",
191
+ "# 4. Clinical Feature Extraction\n",
192
+ "if trait_row is not None:\n",
193
+ " # Extract clinical features\n",
194
+ " clinical_data_processed = geo_select_clinical_features(\n",
195
+ " clinical_df=clinical_data,\n",
196
+ " trait=trait,\n",
197
+ " trait_row=trait_row,\n",
198
+ " convert_trait=convert_trait,\n",
199
+ " age_row=age_row,\n",
200
+ " convert_age=convert_age,\n",
201
+ " gender_row=gender_row,\n",
202
+ " convert_gender=convert_gender\n",
203
+ " )\n",
204
+ " \n",
205
+ " # Preview the processed clinical data\n",
206
+ " preview = preview_df(clinical_data_processed)\n",
207
+ " print(\"Preview of processed clinical data:\")\n",
208
+ " print(preview)\n",
209
+ " \n",
210
+ " # Save the processed clinical data\n",
211
+ " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
212
+ " clinical_data_processed.to_csv(out_clinical_data_file)\n",
213
+ " print(f\"Processed clinical data saved to {out_clinical_data_file}\")\n"
214
+ ]
215
+ },
216
+ {
217
+ "cell_type": "markdown",
218
+ "id": "accaf373",
219
+ "metadata": {},
220
+ "source": [
221
+ "### Step 3: Gene Data Extraction"
222
+ ]
223
+ },
224
+ {
225
+ "cell_type": "code",
226
+ "execution_count": 4,
227
+ "id": "4906b5e4",
228
+ "metadata": {
229
+ "execution": {
230
+ "iopub.execute_input": "2025-03-25T08:29:43.544868Z",
231
+ "iopub.status.busy": "2025-03-25T08:29:43.544753Z",
232
+ "iopub.status.idle": "2025-03-25T08:29:43.763643Z",
233
+ "shell.execute_reply": "2025-03-25T08:29:43.763247Z"
234
+ }
235
+ },
236
+ "outputs": [
237
+ {
238
+ "name": "stdout",
239
+ "output_type": "stream",
240
+ "text": [
241
+ "SOFT file: ../../input/GEO/Coronary_artery_disease/GSE64554/GSE64554_family.soft.gz\n",
242
+ "Matrix file: ../../input/GEO/Coronary_artery_disease/GSE64554/GSE64554_series_matrix.txt.gz\n",
243
+ "Found the matrix table marker at line 56\n"
244
+ ]
245
+ },
246
+ {
247
+ "name": "stdout",
248
+ "output_type": "stream",
249
+ "text": [
250
+ "Gene data shape: (48783, 46)\n",
251
+ "First 20 gene/probe identifiers:\n",
252
+ "['ILMN_1343291', 'ILMN_1343295', 'ILMN_1651199', 'ILMN_1651209', 'ILMN_1651210', 'ILMN_1651221', 'ILMN_1651228', 'ILMN_1651229', 'ILMN_1651230', 'ILMN_1651232', 'ILMN_1651235', 'ILMN_1651236', 'ILMN_1651237', 'ILMN_1651238', 'ILMN_1651249', 'ILMN_1651253', 'ILMN_1651254', 'ILMN_1651259', 'ILMN_1651260', 'ILMN_1651262']\n"
253
+ ]
254
+ }
255
+ ],
256
+ "source": [
257
+ "# 1. Identify the paths to the SOFT file and the matrix file\n",
258
+ "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
259
+ "print(f\"SOFT file: {soft_file}\")\n",
260
+ "print(f\"Matrix file: {matrix_file}\")\n",
261
+ "\n",
262
+ "# Set gene availability flag\n",
263
+ "is_gene_available = True # Initially assume gene data is available\n",
264
+ "\n",
265
+ "# First check if the matrix file contains the expected marker\n",
266
+ "found_marker = False\n",
267
+ "marker_row = None\n",
268
+ "try:\n",
269
+ " with gzip.open(matrix_file, 'rt') as file:\n",
270
+ " for i, line in enumerate(file):\n",
271
+ " if \"!series_matrix_table_begin\" in line:\n",
272
+ " found_marker = True\n",
273
+ " marker_row = i\n",
274
+ " print(f\"Found the matrix table marker at line {i}\")\n",
275
+ " break\n",
276
+ " \n",
277
+ " if not found_marker:\n",
278
+ " print(\"Warning: Could not find '!series_matrix_table_begin' marker in the file.\")\n",
279
+ " is_gene_available = False\n",
280
+ " \n",
281
+ " # If marker was found, try to extract gene data\n",
282
+ " if is_gene_available:\n",
283
+ " try:\n",
284
+ " # Try using the library function\n",
285
+ " gene_data = get_genetic_data(matrix_file)\n",
286
+ " \n",
287
+ " if gene_data.shape[0] == 0:\n",
288
+ " print(\"Warning: Extracted gene data has 0 rows.\")\n",
289
+ " is_gene_available = False\n",
290
+ " else:\n",
291
+ " print(f\"Gene data shape: {gene_data.shape}\")\n",
292
+ " # Print the first 20 gene/probe identifiers\n",
293
+ " print(\"First 20 gene/probe identifiers:\")\n",
294
+ " print(gene_data.index[:20].tolist())\n",
295
+ " except Exception as e:\n",
296
+ " print(f\"Error extracting gene data with get_genetic_data(): {e}\")\n",
297
+ " is_gene_available = False\n",
298
+ " \n",
299
+ " # If gene data extraction failed, examine file content to diagnose\n",
300
+ " if not is_gene_available:\n",
301
+ " print(\"Examining file content to diagnose the issue:\")\n",
302
+ " try:\n",
303
+ " with gzip.open(matrix_file, 'rt') as file:\n",
304
+ " # Print lines around the marker if found\n",
305
+ " if marker_row is not None:\n",
306
+ " for i, line in enumerate(file):\n",
307
+ " if i >= marker_row - 2 and i <= marker_row + 10:\n",
308
+ " print(f\"Line {i}: {line.strip()[:100]}...\")\n",
309
+ " if i > marker_row + 10:\n",
310
+ " break\n",
311
+ " else:\n",
312
+ " # If marker not found, print first 10 lines\n",
313
+ " for i, line in enumerate(file):\n",
314
+ " if i < 10:\n",
315
+ " print(f\"Line {i}: {line.strip()[:100]}...\")\n",
316
+ " else:\n",
317
+ " break\n",
318
+ " except Exception as e2:\n",
319
+ " print(f\"Error examining file: {e2}\")\n",
320
+ " \n",
321
+ "except Exception as e:\n",
322
+ " print(f\"Error processing file: {e}\")\n",
323
+ " is_gene_available = False\n",
324
+ "\n",
325
+ "# Update validation information if gene data extraction failed\n",
326
+ "if not is_gene_available:\n",
327
+ " print(\"Gene expression data could not be successfully extracted from this dataset.\")\n",
328
+ " # Update the validation record since gene data isn't available\n",
329
+ " is_trait_available = False # We already determined trait data isn't available in step 2\n",
330
+ " validate_and_save_cohort_info(is_final=False, cohort=cohort, info_path=json_path,\n",
331
+ " is_gene_available=is_gene_available, is_trait_available=is_trait_available)\n"
332
+ ]
333
+ },
334
+ {
335
+ "cell_type": "markdown",
336
+ "id": "9e86e837",
337
+ "metadata": {},
338
+ "source": [
339
+ "### Step 4: Gene Identifier Review"
340
+ ]
341
+ },
342
+ {
343
+ "cell_type": "code",
344
+ "execution_count": 5,
345
+ "id": "4abad5e5",
346
+ "metadata": {
347
+ "execution": {
348
+ "iopub.execute_input": "2025-03-25T08:29:43.764994Z",
349
+ "iopub.status.busy": "2025-03-25T08:29:43.764876Z",
350
+ "iopub.status.idle": "2025-03-25T08:29:43.766769Z",
351
+ "shell.execute_reply": "2025-03-25T08:29:43.766479Z"
352
+ }
353
+ },
354
+ "outputs": [],
355
+ "source": [
356
+ "# Analysis of gene identifiers\n",
357
+ "# The identifiers starting with \"ILMN_\" are Illumina probe IDs, not human gene symbols\n",
358
+ "# These are microarray probe identifiers from Illumina platform that need to be mapped to gene symbols\n",
359
+ "\n",
360
+ "requires_gene_mapping = True\n"
361
+ ]
362
+ },
363
+ {
364
+ "cell_type": "markdown",
365
+ "id": "7588195b",
366
+ "metadata": {},
367
+ "source": [
368
+ "### Step 5: Gene Annotation"
369
+ ]
370
+ },
371
+ {
372
+ "cell_type": "code",
373
+ "execution_count": 6,
374
+ "id": "9266c407",
375
+ "metadata": {
376
+ "execution": {
377
+ "iopub.execute_input": "2025-03-25T08:29:43.767908Z",
378
+ "iopub.status.busy": "2025-03-25T08:29:43.767804Z",
379
+ "iopub.status.idle": "2025-03-25T08:29:48.657042Z",
380
+ "shell.execute_reply": "2025-03-25T08:29:48.656523Z"
381
+ }
382
+ },
383
+ "outputs": [
384
+ {
385
+ "name": "stdout",
386
+ "output_type": "stream",
387
+ "text": [
388
+ "\n",
389
+ "Gene annotation preview:\n",
390
+ "Columns in gene annotation: ['ID', 'nuID', 'Species', 'Source', 'Search_Key', 'Transcript', 'ILMN_Gene', 'Source_Reference_ID', 'RefSeq_ID', 'Unigene_ID', 'Entrez_Gene_ID', 'GI', 'Accession', 'Symbol', 'Protein_Product', 'Array_Address_Id', 'Probe_Type', 'Probe_Start', 'SEQUENCE', 'Chromosome', 'Probe_Chr_Orientation', 'Probe_Coordinates', 'Cytoband', 'Definition', 'Ontology_Component', 'Ontology_Process', 'Ontology_Function', 'Synonyms', 'Obsolete_Probe_Id', 'GB_ACC']\n",
391
+ "{'ID': ['ILMN_1725881', 'ILMN_1910180', 'ILMN_1804174'], 'nuID': ['rp13_p1x6D80lNLk3c', 'NEX0oqCV8.er4HVfU4', 'KyqQynMZxJcruyylEU'], 'Species': ['Homo sapiens', 'Homo sapiens', 'Homo sapiens'], 'Source': ['RefSeq', 'Unigene', 'RefSeq'], 'Search_Key': ['ILMN_44919', 'ILMN_127219', 'ILMN_139282'], 'Transcript': ['ILMN_44919', 'ILMN_127219', 'ILMN_139282'], 'ILMN_Gene': ['LOC23117', 'HS.575038', 'FCGR2B'], 'Source_Reference_ID': ['XM_933824.1', 'Hs.575038', 'XM_938851.1'], 'RefSeq_ID': ['XM_933824.1', nan, 'XM_938851.1'], 'Unigene_ID': [nan, 'Hs.575038', nan], 'Entrez_Gene_ID': [23117.0, nan, 2213.0], 'GI': [89040007.0, 10437021.0, 88952550.0], 'Accession': ['XM_933824.1', 'AK024680', 'XM_938851.1'], 'Symbol': ['LOC23117', nan, 'FCGR2B'], 'Protein_Product': ['XP_938917.1', nan, 'XP_943944.1'], 'Array_Address_Id': [1710221.0, 5900364.0, 2480717.0], 'Probe_Type': ['I', 'S', 'I'], 'Probe_Start': [122.0, 1409.0, 1643.0], 'SEQUENCE': ['GGCTCCTCTTTGGGCTCCTACTGGAATTTATCAGCCATCAGTGCATCTCT', 'ACACCTTCAGGAGGGAAGCCCTTATTTCTGGGTTGAACTCCCCTTCCATG', 'TAGGGGCAATAGGCTATACGCTACAGCCTAGGTGTGTAGTAGGCCACACC'], 'Chromosome': ['16', nan, nan], 'Probe_Chr_Orientation': ['-', nan, nan], 'Probe_Coordinates': ['21766363-21766363:21769901-21769949', nan, nan], 'Cytoband': ['16p12.2a', nan, '1q23.3b'], 'Definition': ['PREDICTED: Homo sapiens KIAA0220-like protein, transcript variant 11 (LOC23117), mRNA.', 'Homo sapiens cDNA: FLJ21027 fis, clone CAE07110', 'PREDICTED: Homo sapiens Fc fragment of IgG, low affinity IIb, receptor (CD32) (FCGR2B), mRNA.'], 'Ontology_Component': [nan, nan, nan], 'Ontology_Process': [nan, nan, nan], 'Ontology_Function': [nan, nan, nan], 'Synonyms': [nan, nan, nan], 'Obsolete_Probe_Id': [nan, nan, nan], 'GB_ACC': ['XM_933824.1', 'AK024680', 'XM_938851.1']}\n",
392
+ "\n",
393
+ "Examining ID and Symbol columns format (first 3 rows):\n",
394
+ "Row 0: ID=ILMN_1725881\n",
395
+ "Symbol: LOC23117\n",
396
+ "Row 1: ID=ILMN_1910180\n",
397
+ "Symbol: nan\n",
398
+ "Row 2: ID=ILMN_1804174\n",
399
+ "Symbol: FCGR2B\n",
400
+ "\n",
401
+ "Symbol column completeness: 36157/2293640 rows (1.58%)\n",
402
+ "\n",
403
+ "Attempting to extract gene symbols from the first few rows:\n",
404
+ "Row 0 extracted symbols: []\n",
405
+ "Row 2 extracted symbols: ['FCGR2B']\n"
406
+ ]
407
+ }
408
+ ],
409
+ "source": [
410
+ "# 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.\n",
411
+ "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
412
+ "gene_annotation = get_gene_annotation(soft_file)\n",
413
+ "\n",
414
+ "# 2. Analyze the gene annotation dataframe to identify which columns contain the gene identifiers and gene symbols\n",
415
+ "print(\"\\nGene annotation preview:\")\n",
416
+ "print(f\"Columns in gene annotation: {gene_annotation.columns.tolist()}\")\n",
417
+ "print(preview_df(gene_annotation, n=3))\n",
418
+ "\n",
419
+ "# Looking at the output, the Symbol column seems to contain gene information\n",
420
+ "print(\"\\nExamining ID and Symbol columns format (first 3 rows):\")\n",
421
+ "if 'ID' in gene_annotation.columns and 'Symbol' in gene_annotation.columns:\n",
422
+ " for i in range(min(3, len(gene_annotation))):\n",
423
+ " print(f\"Row {i}: ID={gene_annotation['ID'].iloc[i]}\")\n",
424
+ " print(f\"Symbol: {gene_annotation['Symbol'].iloc[i]}\")\n",
425
+ "\n",
426
+ " # Check the quality and completeness of the mapping\n",
427
+ " non_null_symbols = gene_annotation['Symbol'].notna().sum()\n",
428
+ " total_rows = len(gene_annotation)\n",
429
+ " print(f\"\\nSymbol column completeness: {non_null_symbols}/{total_rows} rows ({non_null_symbols/total_rows:.2%})\")\n",
430
+ " \n",
431
+ " # Check if some extracted gene symbols can be found in the Symbol column\n",
432
+ " print(\"\\nAttempting to extract gene symbols from the first few rows:\")\n",
433
+ " for i in range(min(3, len(gene_annotation))):\n",
434
+ " if pd.notna(gene_annotation['Symbol'].iloc[i]):\n",
435
+ " symbols = extract_human_gene_symbols(str(gene_annotation['Symbol'].iloc[i]))\n",
436
+ " print(f\"Row {i} extracted symbols: {symbols}\")\n"
437
+ ]
438
+ },
439
+ {
440
+ "cell_type": "markdown",
441
+ "id": "e0413a85",
442
+ "metadata": {},
443
+ "source": [
444
+ "### Step 6: Gene Identifier Mapping"
445
+ ]
446
+ },
447
+ {
448
+ "cell_type": "code",
449
+ "execution_count": 7,
450
+ "id": "0ca084a5",
451
+ "metadata": {
452
+ "execution": {
453
+ "iopub.execute_input": "2025-03-25T08:29:48.658562Z",
454
+ "iopub.status.busy": "2025-03-25T08:29:48.658448Z",
455
+ "iopub.status.idle": "2025-03-25T08:29:49.351283Z",
456
+ "shell.execute_reply": "2025-03-25T08:29:49.350635Z"
457
+ }
458
+ },
459
+ "outputs": [
460
+ {
461
+ "name": "stdout",
462
+ "output_type": "stream",
463
+ "text": [
464
+ "Gene mapping shape: (36157, 2)\n",
465
+ "Sample of gene mapping (first 5 rows):\n",
466
+ " ID Gene\n",
467
+ "0 ILMN_1725881 LOC23117\n",
468
+ "2 ILMN_1804174 FCGR2B\n",
469
+ "3 ILMN_1796063 TRIM44\n",
470
+ "4 ILMN_1811966 LOC653895\n",
471
+ "5 ILMN_1668162 DGAT2L3\n",
472
+ "Mapped gene data shape: (19113, 46)\n",
473
+ "First few gene symbols after mapping:\n",
474
+ "['A1BG', 'A1CF', 'A26A1', 'A26B1', 'A26C1B', 'A26C3', 'A2BP1', 'A2M', 'A2ML1', 'A3GALT2']\n"
475
+ ]
476
+ },
477
+ {
478
+ "name": "stdout",
479
+ "output_type": "stream",
480
+ "text": [
481
+ "Gene data shape after normalization: (18319, 46)\n",
482
+ "First few normalized gene symbols:\n",
483
+ "['A1BG', 'A1CF', 'A2M', 'A2ML1', 'A3GALT2', 'A4GALT', 'A4GNT', 'AAA1', 'AAAS', 'AACS']\n"
484
+ ]
485
+ },
486
+ {
487
+ "name": "stdout",
488
+ "output_type": "stream",
489
+ "text": [
490
+ "Gene expression data saved to ../../output/preprocess/Coronary_artery_disease/gene_data/GSE64554.csv\n"
491
+ ]
492
+ }
493
+ ],
494
+ "source": [
495
+ "# Based on the observation from Step 5, the ID column in gene_annotation contains Illumina probe IDs\n",
496
+ "# that match the gene expression data identifiers, and the Symbol column contains gene symbols\n",
497
+ "\n",
498
+ "# 1 & 2. Extract gene identifier and gene symbol columns for mapping\n",
499
+ "prob_col = 'ID'\n",
500
+ "gene_col = 'Symbol'\n",
501
+ "gene_mapping = get_gene_mapping(gene_annotation, prob_col, gene_col)\n",
502
+ "\n",
503
+ "print(f\"Gene mapping shape: {gene_mapping.shape}\")\n",
504
+ "print(\"Sample of gene mapping (first 5 rows):\")\n",
505
+ "print(gene_mapping.head())\n",
506
+ "\n",
507
+ "# 3. Apply gene mapping to convert probe-level measurements to gene expression\n",
508
+ "gene_data = apply_gene_mapping(gene_data, gene_mapping)\n",
509
+ "\n",
510
+ "print(f\"Mapped gene data shape: {gene_data.shape}\")\n",
511
+ "print(\"First few gene symbols after mapping:\")\n",
512
+ "print(gene_data.index[:10].tolist())\n",
513
+ "\n",
514
+ "# Normalize gene symbols to handle synonyms and variants\n",
515
+ "gene_data = normalize_gene_symbols_in_index(gene_data)\n",
516
+ "print(f\"Gene data shape after normalization: {gene_data.shape}\")\n",
517
+ "print(\"First few normalized gene symbols:\")\n",
518
+ "print(gene_data.index[:10].tolist())\n",
519
+ "\n",
520
+ "# Save the gene expression data\n",
521
+ "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
522
+ "gene_data.to_csv(out_gene_data_file)\n",
523
+ "print(f\"Gene expression data saved to {out_gene_data_file}\")\n"
524
+ ]
525
+ },
526
+ {
527
+ "cell_type": "markdown",
528
+ "id": "57f609a1",
529
+ "metadata": {},
530
+ "source": [
531
+ "### Step 7: Data Normalization and Linking"
532
+ ]
533
+ },
534
+ {
535
+ "cell_type": "code",
536
+ "execution_count": 8,
537
+ "id": "80112f15",
538
+ "metadata": {
539
+ "execution": {
540
+ "iopub.execute_input": "2025-03-25T08:29:49.353217Z",
541
+ "iopub.status.busy": "2025-03-25T08:29:49.353060Z",
542
+ "iopub.status.idle": "2025-03-25T08:29:57.852181Z",
543
+ "shell.execute_reply": "2025-03-25T08:29:57.851476Z"
544
+ }
545
+ },
546
+ "outputs": [
547
+ {
548
+ "name": "stdout",
549
+ "output_type": "stream",
550
+ "text": [
551
+ "Gene data shape before normalization: (18319, 46)\n"
552
+ ]
553
+ },
554
+ {
555
+ "name": "stdout",
556
+ "output_type": "stream",
557
+ "text": [
558
+ "Gene data saved to ../../output/preprocess/Coronary_artery_disease/gene_data/GSE64554.csv\n",
559
+ "Loaded clinical data shape: (2, 46)\n",
560
+ "Initial linked data shape: (46, 18321)\n"
561
+ ]
562
+ },
563
+ {
564
+ "name": "stdout",
565
+ "output_type": "stream",
566
+ "text": [
567
+ "Linked data shape after handling missing values: (46, 18321)\n",
568
+ "For the feature 'Coronary_artery_disease', the least common label is '0.0' with 20 occurrences. This represents 43.48% of the dataset.\n",
569
+ "The distribution of the feature 'Coronary_artery_disease' in this dataset is fine.\n",
570
+ "\n",
571
+ "Quartiles for 'Age':\n",
572
+ " 25%: 53.0\n",
573
+ " 50% (Median): 69.0\n",
574
+ " 75%: 72.5\n",
575
+ "Min: 30.0\n",
576
+ "Max: 86.0\n",
577
+ "The distribution of the feature 'Age' in this dataset is fine.\n",
578
+ "\n"
579
+ ]
580
+ },
581
+ {
582
+ "name": "stdout",
583
+ "output_type": "stream",
584
+ "text": [
585
+ "Linked data saved to ../../output/preprocess/Coronary_artery_disease/GSE64554.csv\n"
586
+ ]
587
+ }
588
+ ],
589
+ "source": [
590
+ "# 1. Attempt to load gene data and handle possible issues with normalization\n",
591
+ "try:\n",
592
+ " # Create output directory if it doesn't exist\n",
593
+ " os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
594
+ " \n",
595
+ " # Check if gene_data (from previous step) has any content\n",
596
+ " if gene_data.shape[0] == 0:\n",
597
+ " print(\"WARNING: Gene data is empty after normalization in previous step.\")\n",
598
+ " print(\"This appears to be miRNA data rather than gene expression data.\")\n",
599
+ " \n",
600
+ " # Since gene_data is empty, set gene_available to False\n",
601
+ " is_gene_available = False\n",
602
+ " \n",
603
+ " # Create an empty dataframe for metadata purposes\n",
604
+ " empty_df = pd.DataFrame()\n",
605
+ " \n",
606
+ " # Log information about this dataset for future reference\n",
607
+ " validate_and_save_cohort_info(\n",
608
+ " is_final=True,\n",
609
+ " cohort=cohort,\n",
610
+ " info_path=json_path,\n",
611
+ " is_gene_available=is_gene_available,\n",
612
+ " is_trait_available=is_trait_available,\n",
613
+ " is_biased=True, # Consider it biased as we can't use it\n",
614
+ " df=empty_df,\n",
615
+ " note=\"Dataset appears to contain miRNA data rather than gene expression data. Gene symbols could not be normalized.\"\n",
616
+ " )\n",
617
+ " \n",
618
+ " print(\"Dataset marked as unusable due to lack of valid gene expression data.\")\n",
619
+ " else:\n",
620
+ " # If gene_data is not empty, proceed with normalization and linking\n",
621
+ " print(f\"Gene data shape before normalization: {gene_data.shape}\")\n",
622
+ " \n",
623
+ " # Save the gene data we have, even if it's already normalized\n",
624
+ " gene_data.to_csv(out_gene_data_file)\n",
625
+ " print(f\"Gene data saved to {out_gene_data_file}\")\n",
626
+ " \n",
627
+ " # Attempt to link clinical and gene data\n",
628
+ " if is_trait_available:\n",
629
+ " # Load clinical data\n",
630
+ " clinical_features = pd.read_csv(out_clinical_data_file, index_col=0)\n",
631
+ " print(f\"Loaded clinical data shape: {clinical_features.shape}\")\n",
632
+ " \n",
633
+ " # Link the clinical and genetic data\n",
634
+ " linked_data = geo_link_clinical_genetic_data(clinical_features, gene_data)\n",
635
+ " print(f\"Initial linked data shape: {linked_data.shape}\")\n",
636
+ " \n",
637
+ " # Handle missing values\n",
638
+ " linked_data = handle_missing_values(linked_data, trait)\n",
639
+ " print(f\"Linked data shape after handling missing values: {linked_data.shape}\")\n",
640
+ " \n",
641
+ " if linked_data.shape[0] > 0:\n",
642
+ " # Check for bias in trait and demographic features\n",
643
+ " is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n",
644
+ " \n",
645
+ " # Validate data quality and save cohort info\n",
646
+ " is_usable = validate_and_save_cohort_info(\n",
647
+ " is_final=True,\n",
648
+ " cohort=cohort,\n",
649
+ " info_path=json_path,\n",
650
+ " is_gene_available=is_gene_available,\n",
651
+ " is_trait_available=is_trait_available,\n",
652
+ " is_biased=is_biased,\n",
653
+ " df=linked_data,\n",
654
+ " note=\"Successfully processed gene expression data for coronary artery disease.\"\n",
655
+ " )\n",
656
+ " \n",
657
+ " # Save the linked data if it's usable\n",
658
+ " if is_usable:\n",
659
+ " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n",
660
+ " linked_data.to_csv(out_data_file)\n",
661
+ " print(f\"Linked data saved to {out_data_file}\")\n",
662
+ " else:\n",
663
+ " print(\"Data not usable for trait study - not saving final linked data.\")\n",
664
+ " else:\n",
665
+ " print(\"After handling missing values, no samples remain.\")\n",
666
+ " validate_and_save_cohort_info(\n",
667
+ " is_final=True,\n",
668
+ " cohort=cohort,\n",
669
+ " info_path=json_path,\n",
670
+ " is_gene_available=is_gene_available,\n",
671
+ " is_trait_available=is_trait_available,\n",
672
+ " is_biased=True,\n",
673
+ " df=pd.DataFrame(),\n",
674
+ " note=\"No valid samples after handling missing values.\"\n",
675
+ " )\n",
676
+ " else:\n",
677
+ " # Cannot proceed with linking if trait data is missing\n",
678
+ " validate_and_save_cohort_info(\n",
679
+ " is_final=True,\n",
680
+ " cohort=cohort,\n",
681
+ " info_path=json_path,\n",
682
+ " is_gene_available=is_gene_available,\n",
683
+ " is_trait_available=is_trait_available,\n",
684
+ " is_biased=True,\n",
685
+ " df=pd.DataFrame(),\n",
686
+ " note=\"Cannot link data because trait information is not available.\"\n",
687
+ " )\n",
688
+ "except Exception as e:\n",
689
+ " print(f\"Error in data processing: {e}\")\n",
690
+ " \n",
691
+ " # Log the error and mark the dataset as unusable\n",
692
+ " validate_and_save_cohort_info(\n",
693
+ " is_final=True,\n",
694
+ " cohort=cohort,\n",
695
+ " info_path=json_path,\n",
696
+ " is_gene_available=False, # Consider gene data unavailable if we had an error\n",
697
+ " is_trait_available=is_trait_available,\n",
698
+ " is_biased=True, # Consider it biased as we can't use it\n",
699
+ " df=pd.DataFrame(), # Empty dataframe for metadata\n",
700
+ " note=f\"Error during normalization or linking: {str(e)}\"\n",
701
+ " )"
702
+ ]
703
+ }
704
+ ],
705
+ "metadata": {
706
+ "language_info": {
707
+ "codemirror_mode": {
708
+ "name": "ipython",
709
+ "version": 3
710
+ },
711
+ "file_extension": ".py",
712
+ "mimetype": "text/x-python",
713
+ "name": "python",
714
+ "nbconvert_exporter": "python",
715
+ "pygments_lexer": "ipython3",
716
+ "version": "3.10.16"
717
+ }
718
+ },
719
+ "nbformat": 4,
720
+ "nbformat_minor": 5
721
+ }
code/Coronary_artery_disease/GSE64566.ipynb ADDED
@@ -0,0 +1,757 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": 1,
6
+ "id": "7bdc700e",
7
+ "metadata": {
8
+ "execution": {
9
+ "iopub.execute_input": "2025-03-25T08:29:58.730405Z",
10
+ "iopub.status.busy": "2025-03-25T08:29:58.730302Z",
11
+ "iopub.status.idle": "2025-03-25T08:29:58.891883Z",
12
+ "shell.execute_reply": "2025-03-25T08:29:58.891567Z"
13
+ }
14
+ },
15
+ "outputs": [],
16
+ "source": [
17
+ "import sys\n",
18
+ "import os\n",
19
+ "sys.path.append(os.path.abspath(os.path.join(os.getcwd(), '../..')))\n",
20
+ "\n",
21
+ "# Path Configuration\n",
22
+ "from tools.preprocess import *\n",
23
+ "\n",
24
+ "# Processing context\n",
25
+ "trait = \"Coronary_artery_disease\"\n",
26
+ "cohort = \"GSE64566\"\n",
27
+ "\n",
28
+ "# Input paths\n",
29
+ "in_trait_dir = \"../../input/GEO/Coronary_artery_disease\"\n",
30
+ "in_cohort_dir = \"../../input/GEO/Coronary_artery_disease/GSE64566\"\n",
31
+ "\n",
32
+ "# Output paths\n",
33
+ "out_data_file = \"../../output/preprocess/Coronary_artery_disease/GSE64566.csv\"\n",
34
+ "out_gene_data_file = \"../../output/preprocess/Coronary_artery_disease/gene_data/GSE64566.csv\"\n",
35
+ "out_clinical_data_file = \"../../output/preprocess/Coronary_artery_disease/clinical_data/GSE64566.csv\"\n",
36
+ "json_path = \"../../output/preprocess/Coronary_artery_disease/cohort_info.json\"\n"
37
+ ]
38
+ },
39
+ {
40
+ "cell_type": "markdown",
41
+ "id": "954afdb6",
42
+ "metadata": {},
43
+ "source": [
44
+ "### Step 1: Initial Data Loading"
45
+ ]
46
+ },
47
+ {
48
+ "cell_type": "code",
49
+ "execution_count": 2,
50
+ "id": "6c11eb5b",
51
+ "metadata": {
52
+ "execution": {
53
+ "iopub.execute_input": "2025-03-25T08:29:58.893281Z",
54
+ "iopub.status.busy": "2025-03-25T08:29:58.893147Z",
55
+ "iopub.status.idle": "2025-03-25T08:29:59.042483Z",
56
+ "shell.execute_reply": "2025-03-25T08:29:59.042132Z"
57
+ }
58
+ },
59
+ "outputs": [
60
+ {
61
+ "name": "stdout",
62
+ "output_type": "stream",
63
+ "text": [
64
+ "Background Information:\n",
65
+ "!Series_title\t\"GE/miRNA expression profile of Human Epicardial Adipose Tissue (EAT) and Subcutaneous Adipose Tissue (SAT) in Patients with Coronary Artery Disease (CAD) vs. Controls (CTRL)\"\n",
66
+ "!Series_summary\t\"This SuperSeries is composed of the SubSeries listed below.\"\n",
67
+ "!Series_overall_design\t\"Refer to individual Series\"\n",
68
+ "Sample Characteristics Dictionary:\n",
69
+ "{0: ['age: 76', 'age: 71', 'age: 57', 'age: 30', 'age: 81', 'age: 51', 'age: 36', 'age: 44', 'age: 52', 'age: 73', 'age: 69', 'age: 56', 'age: 70', 'age: 67', 'age: 60', 'age: 61', 'age: 86', 'age: 82'], 1: ['tissue: Subcutaneous Adipose', 'tissue: Epicardial Adipose'], 2: ['disease state: control', 'disease state: coronary artery disease']}\n"
70
+ ]
71
+ }
72
+ ],
73
+ "source": [
74
+ "from tools.preprocess import *\n",
75
+ "# 1. Identify the paths to the SOFT file and the matrix file\n",
76
+ "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
77
+ "\n",
78
+ "# 2. Read the matrix file to obtain background information and sample characteristics data\n",
79
+ "background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']\n",
80
+ "clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']\n",
81
+ "background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)\n",
82
+ "\n",
83
+ "# 3. Obtain the sample characteristics dictionary from the clinical dataframe\n",
84
+ "sample_characteristics_dict = get_unique_values_by_row(clinical_data)\n",
85
+ "\n",
86
+ "# 4. Explicitly print out all the background information and the sample characteristics dictionary\n",
87
+ "print(\"Background Information:\")\n",
88
+ "print(background_info)\n",
89
+ "print(\"Sample Characteristics Dictionary:\")\n",
90
+ "print(sample_characteristics_dict)\n"
91
+ ]
92
+ },
93
+ {
94
+ "cell_type": "markdown",
95
+ "id": "b9d3ba3a",
96
+ "metadata": {},
97
+ "source": [
98
+ "### Step 2: Dataset Analysis and Clinical Feature Extraction"
99
+ ]
100
+ },
101
+ {
102
+ "cell_type": "code",
103
+ "execution_count": 3,
104
+ "id": "f9dc74ed",
105
+ "metadata": {
106
+ "execution": {
107
+ "iopub.execute_input": "2025-03-25T08:29:59.043787Z",
108
+ "iopub.status.busy": "2025-03-25T08:29:59.043678Z",
109
+ "iopub.status.idle": "2025-03-25T08:29:59.053182Z",
110
+ "shell.execute_reply": "2025-03-25T08:29:59.052891Z"
111
+ }
112
+ },
113
+ "outputs": [
114
+ {
115
+ "name": "stdout",
116
+ "output_type": "stream",
117
+ "text": [
118
+ "Preview of clinical data:\n",
119
+ "{'GSM1574149': [nan, nan], 'GSM1574150': [nan, nan], 'GSM1574151': [nan, nan], 'GSM1574152': [nan, nan], 'GSM1574153': [nan, nan], 'GSM1574154': [nan, nan], 'GSM1574155': [nan, nan], 'GSM1574156': [nan, nan], 'GSM1574157': [nan, nan], 'GSM1574158': [nan, nan], 'GSM1574159': [nan, nan], 'GSM1574160': [nan, nan], 'GSM1574161': [nan, nan], 'GSM1574162': [nan, nan], 'GSM1574163': [nan, nan], 'GSM1574164': [nan, nan], 'GSM1574165': [nan, nan], 'GSM1574166': [nan, nan], 'GSM1574167': [nan, nan], 'GSM1574168': [nan, nan], 'GSM1574169': [nan, nan], 'GSM1574170': [nan, nan], 'GSM1574171': [nan, nan], 'GSM1574172': [nan, nan], 'GSM1574173': [nan, nan], 'GSM1574174': [nan, nan], 'GSM1574175': [nan, nan], 'GSM1574176': [nan, nan], 'GSM1574177': [nan, nan], 'GSM1574178': [nan, nan], 'GSM1574179': [nan, nan], 'GSM1574180': [nan, nan], 'GSM1574181': [nan, nan], 'GSM1574182': [nan, nan], 'GSM1574183': [nan, nan], 'GSM1574184': [nan, nan], 'GSM1574185': [nan, nan], 'GSM1574186': [nan, nan], 'GSM1574187': [nan, nan], 'GSM1574188': [nan, nan], 'GSM1574189': [nan, nan], 'GSM1574190': [nan, nan], 'GSM1574191': [nan, nan], 'GSM1574192': [nan, nan], 'GSM1574193': [nan, nan], 'GSM1574194': [nan, nan]}\n",
120
+ "Clinical data saved to ../../output/preprocess/Coronary_artery_disease/clinical_data/GSE64566.csv\n"
121
+ ]
122
+ }
123
+ ],
124
+ "source": [
125
+ "# 1. Gene Expression Data Availability\n",
126
+ "# Based on the background information, this dataset contains expression profiles.\n",
127
+ "# However, it seems to be a SuperSeries that may contain both GE (gene expression) and miRNA data.\n",
128
+ "# Since we don't have specific information about gene expression data, we'll treat it as potentially available.\n",
129
+ "is_gene_available = True\n",
130
+ "\n",
131
+ "# 2. Analyze available clinical features\n",
132
+ "# 2.1 Identify rows for trait, age, and gender\n",
133
+ "# For trait (coronary artery disease):\n",
134
+ "trait_row = 0 # 'disease state' contains CAD vs control information\n",
135
+ "# For age:\n",
136
+ "age_row = 1 # 'age' information is available\n",
137
+ "# For gender:\n",
138
+ "gender_row = None # No gender information found in the sample characteristics\n",
139
+ "\n",
140
+ "# 2.2 Define conversion functions\n",
141
+ "def convert_trait(value):\n",
142
+ " \"\"\"Convert disease state to binary (0 for control, 1 for CAD)\"\"\"\n",
143
+ " if not isinstance(value, str):\n",
144
+ " return None\n",
145
+ " \n",
146
+ " value = value.lower().strip()\n",
147
+ " if 'disease state:' in value:\n",
148
+ " actual_value = value.split(':')[1].strip()\n",
149
+ " if 'control' in actual_value:\n",
150
+ " return 0\n",
151
+ " elif 'coronary artery disease' in actual_value:\n",
152
+ " return 1\n",
153
+ " return None\n",
154
+ "\n",
155
+ "def convert_age(value):\n",
156
+ " \"\"\"Convert age to continuous numeric value\"\"\"\n",
157
+ " if not isinstance(value, str):\n",
158
+ " return None\n",
159
+ " \n",
160
+ " if 'age:' in value:\n",
161
+ " try:\n",
162
+ " age = int(value.split(':')[1].strip())\n",
163
+ " return age\n",
164
+ " except:\n",
165
+ " return None\n",
166
+ " return None\n",
167
+ "\n",
168
+ "# No gender conversion function needed as gender data is not available\n",
169
+ "convert_gender = None\n",
170
+ "\n",
171
+ "# 3. Save metadata about data availability\n",
172
+ "is_trait_available = trait_row is not None\n",
173
+ "validation_result = validate_and_save_cohort_info(\n",
174
+ " is_final=False,\n",
175
+ " cohort=cohort,\n",
176
+ " info_path=json_path,\n",
177
+ " is_gene_available=is_gene_available,\n",
178
+ " is_trait_available=is_trait_available\n",
179
+ ")\n",
180
+ "\n",
181
+ "# 4. Extract clinical features if trait data is available\n",
182
+ "if trait_row is not None:\n",
183
+ " # Extract clinical features\n",
184
+ " clinical_df = geo_select_clinical_features(\n",
185
+ " clinical_df=clinical_data,\n",
186
+ " trait=trait,\n",
187
+ " trait_row=trait_row,\n",
188
+ " convert_trait=convert_trait,\n",
189
+ " age_row=age_row,\n",
190
+ " convert_age=convert_age,\n",
191
+ " gender_row=gender_row,\n",
192
+ " convert_gender=convert_gender\n",
193
+ " )\n",
194
+ " \n",
195
+ " # Preview the extracted clinical data\n",
196
+ " preview = preview_df(clinical_df)\n",
197
+ " print(\"Preview of clinical data:\")\n",
198
+ " print(preview)\n",
199
+ " \n",
200
+ " # Save the clinical data\n",
201
+ " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
202
+ " clinical_df.to_csv(out_clinical_data_file)\n",
203
+ " print(f\"Clinical data saved to {out_clinical_data_file}\")\n"
204
+ ]
205
+ },
206
+ {
207
+ "cell_type": "markdown",
208
+ "id": "c46076b3",
209
+ "metadata": {},
210
+ "source": [
211
+ "### Step 3: Gene Data Extraction"
212
+ ]
213
+ },
214
+ {
215
+ "cell_type": "code",
216
+ "execution_count": 4,
217
+ "id": "9b70a107",
218
+ "metadata": {
219
+ "execution": {
220
+ "iopub.execute_input": "2025-03-25T08:29:59.054335Z",
221
+ "iopub.status.busy": "2025-03-25T08:29:59.054231Z",
222
+ "iopub.status.idle": "2025-03-25T08:29:59.260564Z",
223
+ "shell.execute_reply": "2025-03-25T08:29:59.260198Z"
224
+ }
225
+ },
226
+ "outputs": [
227
+ {
228
+ "name": "stdout",
229
+ "output_type": "stream",
230
+ "text": [
231
+ "SOFT file: ../../input/GEO/Coronary_artery_disease/GSE64566/GSE64566_family.soft.gz\n",
232
+ "Matrix file: ../../input/GEO/Coronary_artery_disease/GSE64566/GSE64566-GPL6947_series_matrix.txt.gz\n",
233
+ "Found the matrix table marker at line 56\n"
234
+ ]
235
+ },
236
+ {
237
+ "name": "stdout",
238
+ "output_type": "stream",
239
+ "text": [
240
+ "Gene data shape: (48783, 46)"
241
+ ]
242
+ },
243
+ {
244
+ "name": "stdout",
245
+ "output_type": "stream",
246
+ "text": [
247
+ "\n",
248
+ "First 20 gene/probe identifiers:\n",
249
+ "['ILMN_1343291', 'ILMN_1343295', 'ILMN_1651199', 'ILMN_1651209', 'ILMN_1651210', 'ILMN_1651221', 'ILMN_1651228', 'ILMN_1651229', 'ILMN_1651230', 'ILMN_1651232', 'ILMN_1651235', 'ILMN_1651236', 'ILMN_1651237', 'ILMN_1651238', 'ILMN_1651249', 'ILMN_1651253', 'ILMN_1651254', 'ILMN_1651259', 'ILMN_1651260', 'ILMN_1651262']\n"
250
+ ]
251
+ }
252
+ ],
253
+ "source": [
254
+ "# 1. Identify the paths to the SOFT file and the matrix file\n",
255
+ "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
256
+ "print(f\"SOFT file: {soft_file}\")\n",
257
+ "print(f\"Matrix file: {matrix_file}\")\n",
258
+ "\n",
259
+ "# Set gene availability flag\n",
260
+ "is_gene_available = True # Initially assume gene data is available\n",
261
+ "\n",
262
+ "# First check if the matrix file contains the expected marker\n",
263
+ "found_marker = False\n",
264
+ "marker_row = None\n",
265
+ "try:\n",
266
+ " with gzip.open(matrix_file, 'rt') as file:\n",
267
+ " for i, line in enumerate(file):\n",
268
+ " if \"!series_matrix_table_begin\" in line:\n",
269
+ " found_marker = True\n",
270
+ " marker_row = i\n",
271
+ " print(f\"Found the matrix table marker at line {i}\")\n",
272
+ " break\n",
273
+ " \n",
274
+ " if not found_marker:\n",
275
+ " print(\"Warning: Could not find '!series_matrix_table_begin' marker in the file.\")\n",
276
+ " is_gene_available = False\n",
277
+ " \n",
278
+ " # If marker was found, try to extract gene data\n",
279
+ " if is_gene_available:\n",
280
+ " try:\n",
281
+ " # Try using the library function\n",
282
+ " gene_data = get_genetic_data(matrix_file)\n",
283
+ " \n",
284
+ " if gene_data.shape[0] == 0:\n",
285
+ " print(\"Warning: Extracted gene data has 0 rows.\")\n",
286
+ " is_gene_available = False\n",
287
+ " else:\n",
288
+ " print(f\"Gene data shape: {gene_data.shape}\")\n",
289
+ " # Print the first 20 gene/probe identifiers\n",
290
+ " print(\"First 20 gene/probe identifiers:\")\n",
291
+ " print(gene_data.index[:20].tolist())\n",
292
+ " except Exception as e:\n",
293
+ " print(f\"Error extracting gene data with get_genetic_data(): {e}\")\n",
294
+ " is_gene_available = False\n",
295
+ " \n",
296
+ " # If gene data extraction failed, examine file content to diagnose\n",
297
+ " if not is_gene_available:\n",
298
+ " print(\"Examining file content to diagnose the issue:\")\n",
299
+ " try:\n",
300
+ " with gzip.open(matrix_file, 'rt') as file:\n",
301
+ " # Print lines around the marker if found\n",
302
+ " if marker_row is not None:\n",
303
+ " for i, line in enumerate(file):\n",
304
+ " if i >= marker_row - 2 and i <= marker_row + 10:\n",
305
+ " print(f\"Line {i}: {line.strip()[:100]}...\")\n",
306
+ " if i > marker_row + 10:\n",
307
+ " break\n",
308
+ " else:\n",
309
+ " # If marker not found, print first 10 lines\n",
310
+ " for i, line in enumerate(file):\n",
311
+ " if i < 10:\n",
312
+ " print(f\"Line {i}: {line.strip()[:100]}...\")\n",
313
+ " else:\n",
314
+ " break\n",
315
+ " except Exception as e2:\n",
316
+ " print(f\"Error examining file: {e2}\")\n",
317
+ " \n",
318
+ "except Exception as e:\n",
319
+ " print(f\"Error processing file: {e}\")\n",
320
+ " is_gene_available = False\n",
321
+ "\n",
322
+ "# Update validation information if gene data extraction failed\n",
323
+ "if not is_gene_available:\n",
324
+ " print(\"Gene expression data could not be successfully extracted from this dataset.\")\n",
325
+ " # Update the validation record since gene data isn't available\n",
326
+ " is_trait_available = False # We already determined trait data isn't available in step 2\n",
327
+ " validate_and_save_cohort_info(is_final=False, cohort=cohort, info_path=json_path,\n",
328
+ " is_gene_available=is_gene_available, is_trait_available=is_trait_available)\n"
329
+ ]
330
+ },
331
+ {
332
+ "cell_type": "markdown",
333
+ "id": "52d50c9c",
334
+ "metadata": {},
335
+ "source": [
336
+ "### Step 4: Gene Identifier Review"
337
+ ]
338
+ },
339
+ {
340
+ "cell_type": "code",
341
+ "execution_count": 5,
342
+ "id": "a2f89e87",
343
+ "metadata": {
344
+ "execution": {
345
+ "iopub.execute_input": "2025-03-25T08:29:59.261871Z",
346
+ "iopub.status.busy": "2025-03-25T08:29:59.261746Z",
347
+ "iopub.status.idle": "2025-03-25T08:29:59.263589Z",
348
+ "shell.execute_reply": "2025-03-25T08:29:59.263319Z"
349
+ }
350
+ },
351
+ "outputs": [],
352
+ "source": [
353
+ "# The gene identifiers are from Illumina BeadArray platform (ILMN_ prefix)\n",
354
+ "# These are probe IDs that need to be mapped to human gene symbols\n",
355
+ "requires_gene_mapping = True\n"
356
+ ]
357
+ },
358
+ {
359
+ "cell_type": "markdown",
360
+ "id": "de806b93",
361
+ "metadata": {},
362
+ "source": [
363
+ "### Step 5: Gene Annotation"
364
+ ]
365
+ },
366
+ {
367
+ "cell_type": "code",
368
+ "execution_count": 6,
369
+ "id": "6b3003fb",
370
+ "metadata": {
371
+ "execution": {
372
+ "iopub.execute_input": "2025-03-25T08:29:59.264714Z",
373
+ "iopub.status.busy": "2025-03-25T08:29:59.264608Z",
374
+ "iopub.status.idle": "2025-03-25T08:30:03.385421Z",
375
+ "shell.execute_reply": "2025-03-25T08:30:03.385092Z"
376
+ }
377
+ },
378
+ "outputs": [
379
+ {
380
+ "name": "stdout",
381
+ "output_type": "stream",
382
+ "text": [
383
+ "\n",
384
+ "Gene annotation preview:\n",
385
+ "Columns in gene annotation: ['ID', 'nuID', 'Species', 'Source', 'Search_Key', 'Transcript', 'ILMN_Gene', 'Source_Reference_ID', 'RefSeq_ID', 'Unigene_ID', 'Entrez_Gene_ID', 'GI', 'Accession', 'Symbol', 'Protein_Product', 'Array_Address_Id', 'Probe_Type', 'Probe_Start', 'SEQUENCE', 'Chromosome', 'Probe_Chr_Orientation', 'Probe_Coordinates', 'Cytoband', 'Definition', 'Ontology_Component', 'Ontology_Process', 'Ontology_Function', 'Synonyms', 'Obsolete_Probe_Id', 'GB_ACC']\n",
386
+ "{'ID': ['ILMN_1725881', 'ILMN_1910180', 'ILMN_1804174'], 'nuID': ['rp13_p1x6D80lNLk3c', 'NEX0oqCV8.er4HVfU4', 'KyqQynMZxJcruyylEU'], 'Species': ['Homo sapiens', 'Homo sapiens', 'Homo sapiens'], 'Source': ['RefSeq', 'Unigene', 'RefSeq'], 'Search_Key': ['ILMN_44919', 'ILMN_127219', 'ILMN_139282'], 'Transcript': ['ILMN_44919', 'ILMN_127219', 'ILMN_139282'], 'ILMN_Gene': ['LOC23117', 'HS.575038', 'FCGR2B'], 'Source_Reference_ID': ['XM_933824.1', 'Hs.575038', 'XM_938851.1'], 'RefSeq_ID': ['XM_933824.1', nan, 'XM_938851.1'], 'Unigene_ID': [nan, 'Hs.575038', nan], 'Entrez_Gene_ID': ['23117', nan, '2213'], 'GI': ['89040007', '10437021', '88952550'], 'Accession': ['XM_933824.1', 'AK024680', 'XM_938851.1'], 'Symbol': ['LOC23117', nan, 'FCGR2B'], 'Protein_Product': ['XP_938917.1', nan, 'XP_943944.1'], 'Array_Address_Id': ['1710221', '5900364', '2480717'], 'Probe_Type': ['I', 'S', 'I'], 'Probe_Start': ['122', '1409', '1643'], 'SEQUENCE': ['GGCTCCTCTTTGGGCTCCTACTGGAATTTATCAGCCATCAGTGCATCTCT', 'ACACCTTCAGGAGGGAAGCCCTTATTTCTGGGTTGAACTCCCCTTCCATG', 'TAGGGGCAATAGGCTATACGCTACAGCCTAGGTGTGTAGTAGGCCACACC'], 'Chromosome': ['16', nan, nan], 'Probe_Chr_Orientation': ['-', nan, nan], 'Probe_Coordinates': ['21766363-21766363:21769901-21769949', nan, nan], 'Cytoband': ['16p12.2a', nan, '1q23.3b'], 'Definition': ['PREDICTED: Homo sapiens KIAA0220-like protein, transcript variant 11 (LOC23117), mRNA.', 'Homo sapiens cDNA: FLJ21027 fis, clone CAE07110', 'PREDICTED: Homo sapiens Fc fragment of IgG, low affinity IIb, receptor (CD32) (FCGR2B), mRNA.'], 'Ontology_Component': [nan, nan, nan], 'Ontology_Process': [nan, nan, nan], 'Ontology_Function': [nan, nan, nan], 'Synonyms': [nan, nan, nan], 'Obsolete_Probe_Id': [nan, nan, nan], 'GB_ACC': ['XM_933824.1', 'AK024680', 'XM_938851.1']}\n",
387
+ "\n",
388
+ "Examining ID and Symbol columns format (first 3 rows):\n",
389
+ "Row 0: ID=ILMN_1725881\n",
390
+ "Symbol: LOC23117\n",
391
+ "Row 1: ID=ILMN_1910180\n",
392
+ "Symbol: nan\n",
393
+ "Row 2: ID=ILMN_1804174\n",
394
+ "Symbol: FCGR2B\n",
395
+ "\n",
396
+ "Symbol column completeness: 36892/2347503 rows (1.57%)\n",
397
+ "\n",
398
+ "Attempting to extract gene symbols from the first few rows:\n",
399
+ "Row 0 extracted symbols: []\n",
400
+ "Row 2 extracted symbols: ['FCGR2B']\n"
401
+ ]
402
+ }
403
+ ],
404
+ "source": [
405
+ "# 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.\n",
406
+ "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
407
+ "gene_annotation = get_gene_annotation(soft_file)\n",
408
+ "\n",
409
+ "# 2. Analyze the gene annotation dataframe to identify which columns contain the gene identifiers and gene symbols\n",
410
+ "print(\"\\nGene annotation preview:\")\n",
411
+ "print(f\"Columns in gene annotation: {gene_annotation.columns.tolist()}\")\n",
412
+ "print(preview_df(gene_annotation, n=3))\n",
413
+ "\n",
414
+ "# Looking at the output, the Symbol column seems to contain gene information\n",
415
+ "print(\"\\nExamining ID and Symbol columns format (first 3 rows):\")\n",
416
+ "if 'ID' in gene_annotation.columns and 'Symbol' in gene_annotation.columns:\n",
417
+ " for i in range(min(3, len(gene_annotation))):\n",
418
+ " print(f\"Row {i}: ID={gene_annotation['ID'].iloc[i]}\")\n",
419
+ " print(f\"Symbol: {gene_annotation['Symbol'].iloc[i]}\")\n",
420
+ "\n",
421
+ " # Check the quality and completeness of the mapping\n",
422
+ " non_null_symbols = gene_annotation['Symbol'].notna().sum()\n",
423
+ " total_rows = len(gene_annotation)\n",
424
+ " print(f\"\\nSymbol column completeness: {non_null_symbols}/{total_rows} rows ({non_null_symbols/total_rows:.2%})\")\n",
425
+ " \n",
426
+ " # Check if some extracted gene symbols can be found in the Symbol column\n",
427
+ " print(\"\\nAttempting to extract gene symbols from the first few rows:\")\n",
428
+ " for i in range(min(3, len(gene_annotation))):\n",
429
+ " if pd.notna(gene_annotation['Symbol'].iloc[i]):\n",
430
+ " symbols = extract_human_gene_symbols(str(gene_annotation['Symbol'].iloc[i]))\n",
431
+ " print(f\"Row {i} extracted symbols: {symbols}\")\n"
432
+ ]
433
+ },
434
+ {
435
+ "cell_type": "markdown",
436
+ "id": "c04a1acd",
437
+ "metadata": {},
438
+ "source": [
439
+ "### Step 6: Gene Identifier Mapping"
440
+ ]
441
+ },
442
+ {
443
+ "cell_type": "code",
444
+ "execution_count": 7,
445
+ "id": "1ab6e1fa",
446
+ "metadata": {
447
+ "execution": {
448
+ "iopub.execute_input": "2025-03-25T08:30:03.386804Z",
449
+ "iopub.status.busy": "2025-03-25T08:30:03.386682Z",
450
+ "iopub.status.idle": "2025-03-25T08:30:04.077835Z",
451
+ "shell.execute_reply": "2025-03-25T08:30:04.077503Z"
452
+ }
453
+ },
454
+ "outputs": [
455
+ {
456
+ "name": "stdout",
457
+ "output_type": "stream",
458
+ "text": [
459
+ "Creating gene mapping from 'ID' to 'Symbol'\n",
460
+ "Gene mapping dataframe shape: (36892, 2)\n",
461
+ "First few rows of mapping_df:\n",
462
+ " ID Gene\n",
463
+ "0 ILMN_1725881 LOC23117\n",
464
+ "2 ILMN_1804174 FCGR2B\n",
465
+ "3 ILMN_1796063 TRIM44\n",
466
+ "4 ILMN_1811966 LOC653895\n",
467
+ "5 ILMN_1668162 DGAT2L3\n",
468
+ "Number of probe IDs in expression data: 48783\n",
469
+ "Number of probe IDs in mapping data: 36892\n",
470
+ "Number of overlapping probe IDs: 36138\n",
471
+ "Gene expression data shape after mapping: (25150, 46)\n",
472
+ "First few gene symbols after mapping:\n",
473
+ "['7A5', 'A1BG', 'A1CF', 'A26A1', 'A26B1']\n"
474
+ ]
475
+ },
476
+ {
477
+ "name": "stdout",
478
+ "output_type": "stream",
479
+ "text": [
480
+ "Gene expression data shape after normalization: (18550, 46)\n",
481
+ "First few normalized gene symbols:\n",
482
+ "['A1BG', 'A1CF', 'A2M', 'A2ML1', 'A3GALT2']\n"
483
+ ]
484
+ },
485
+ {
486
+ "name": "stdout",
487
+ "output_type": "stream",
488
+ "text": [
489
+ "Gene expression data saved to ../../output/preprocess/Coronary_artery_disease/gene_data/GSE64566.csv\n"
490
+ ]
491
+ }
492
+ ],
493
+ "source": [
494
+ "# 1. Identify which columns to use for gene mapping\n",
495
+ "# Based on the preview, we observed:\n",
496
+ "# - Gene expression data has identifiers like 'ILMN_3166935'\n",
497
+ "# - Gene annotation data has 'ID' column with identifiers like 'ILMN_1725881'\n",
498
+ "# - Gene annotation data has 'Symbol' column with gene symbols like 'FCGR2B'\n",
499
+ "\n",
500
+ "# Check if we have the required columns for mapping\n",
501
+ "if 'ID' in gene_annotation.columns and 'Symbol' in gene_annotation.columns:\n",
502
+ " print(\"Creating gene mapping from 'ID' to 'Symbol'\")\n",
503
+ " \n",
504
+ " # 2. Get a gene mapping dataframe\n",
505
+ " # Create a custom mapping dataframe that preserves more gene symbols\n",
506
+ " mapping_df = gene_annotation.loc[:, ['ID', 'Symbol']].dropna()\n",
507
+ " # Some cleaning to ensure ID is string type\n",
508
+ " mapping_df = mapping_df.astype({'ID': 'str'})\n",
509
+ " # Ensure correct column names for the apply_gene_mapping function\n",
510
+ " mapping_df = mapping_df.rename(columns={'Symbol': 'Gene'})\n",
511
+ " \n",
512
+ " print(f\"Gene mapping dataframe shape: {mapping_df.shape}\")\n",
513
+ " print(f\"First few rows of mapping_df:\\n{mapping_df.head()}\")\n",
514
+ " \n",
515
+ " # Check for overlap between gene expression data and annotation data\n",
516
+ " expression_ids = set(gene_data.index)\n",
517
+ " mapping_ids = set(mapping_df['ID'])\n",
518
+ " overlap_ids = expression_ids.intersection(mapping_ids)\n",
519
+ " \n",
520
+ " print(f\"Number of probe IDs in expression data: {len(expression_ids)}\")\n",
521
+ " print(f\"Number of probe IDs in mapping data: {len(mapping_ids)}\")\n",
522
+ " print(f\"Number of overlapping probe IDs: {len(overlap_ids)}\")\n",
523
+ " \n",
524
+ " if len(overlap_ids) == 0:\n",
525
+ " print(\"ERROR: No overlap between expression data probe IDs and annotation probe IDs.\")\n",
526
+ " print(\"This indicates a platform mismatch - the annotation file doesn't match the expression data.\")\n",
527
+ " is_gene_available = False\n",
528
+ " else:\n",
529
+ " # Create a modified version of apply_gene_mapping that doesn't filter gene symbols\n",
530
+ " def modified_apply_gene_mapping(expression_df, mapping_df):\n",
531
+ " \"\"\"Custom version to retain more gene symbols\"\"\"\n",
532
+ " # Keep only the mappings that exist in the expression data\n",
533
+ " mapping_df = mapping_df[mapping_df['ID'].isin(expression_df.index)].copy()\n",
534
+ " \n",
535
+ " # Count genes per probe\n",
536
+ " mapping_df['num_genes'] = 1 # Each probe maps to one gene\n",
537
+ " mapping_df.set_index('ID', inplace=True)\n",
538
+ " \n",
539
+ " # Merge and distribute expression values\n",
540
+ " merged_df = mapping_df.join(expression_df)\n",
541
+ " expr_cols = [col for col in merged_df.columns if col not in ['Gene', 'num_genes']]\n",
542
+ " merged_df[expr_cols] = merged_df[expr_cols].div(merged_df['num_genes'], axis=0)\n",
543
+ " \n",
544
+ " # Sum expression values for each gene\n",
545
+ " gene_expression_df = merged_df.groupby('Gene')[expr_cols].sum()\n",
546
+ " return gene_expression_df\n",
547
+ " \n",
548
+ " # Apply the modified gene mapping approach\n",
549
+ " gene_data = modified_apply_gene_mapping(gene_data, mapping_df)\n",
550
+ " print(f\"Gene expression data shape after mapping: {gene_data.shape}\")\n",
551
+ " \n",
552
+ " if gene_data.shape[0] == 0:\n",
553
+ " print(\"ERROR: Gene mapping resulted in empty dataframe.\")\n",
554
+ " is_gene_available = False\n",
555
+ " else:\n",
556
+ " print(f\"First few gene symbols after mapping:\\n{gene_data.index[:5].tolist()}\")\n",
557
+ " \n",
558
+ " # Normalize gene symbols\n",
559
+ " gene_data = normalize_gene_symbols_in_index(gene_data)\n",
560
+ " print(f\"Gene expression data shape after normalization: {gene_data.shape}\")\n",
561
+ " print(f\"First few normalized gene symbols:\\n{gene_data.index[:5].tolist()}\")\n",
562
+ " \n",
563
+ " # Save the gene data\n",
564
+ " os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
565
+ " gene_data.to_csv(out_gene_data_file)\n",
566
+ " print(f\"Gene expression data saved to {out_gene_data_file}\")\n",
567
+ "else:\n",
568
+ " print(\"Required columns for gene mapping not found in annotation data.\")\n",
569
+ " is_gene_available = False\n",
570
+ "\n",
571
+ "# Update validation if gene mapping failed\n",
572
+ "if not is_gene_available:\n",
573
+ " print(\"Gene data mapping failed - cannot proceed with further analysis.\")\n",
574
+ " is_trait_available = True # From previous steps\n",
575
+ " validate_and_save_cohort_info(\n",
576
+ " is_final=False,\n",
577
+ " cohort=cohort,\n",
578
+ " info_path=json_path,\n",
579
+ " is_gene_available=is_gene_available,\n",
580
+ " is_trait_available=is_trait_available\n",
581
+ " )\n"
582
+ ]
583
+ },
584
+ {
585
+ "cell_type": "markdown",
586
+ "id": "da2fc73e",
587
+ "metadata": {},
588
+ "source": [
589
+ "### Step 7: Data Normalization and Linking"
590
+ ]
591
+ },
592
+ {
593
+ "cell_type": "code",
594
+ "execution_count": 8,
595
+ "id": "ab699361",
596
+ "metadata": {
597
+ "execution": {
598
+ "iopub.execute_input": "2025-03-25T08:30:04.079174Z",
599
+ "iopub.status.busy": "2025-03-25T08:30:04.079062Z",
600
+ "iopub.status.idle": "2025-03-25T08:30:04.528091Z",
601
+ "shell.execute_reply": "2025-03-25T08:30:04.527767Z"
602
+ }
603
+ },
604
+ "outputs": [
605
+ {
606
+ "name": "stdout",
607
+ "output_type": "stream",
608
+ "text": [
609
+ "Gene data shape before normalization: (18550, 46)\n"
610
+ ]
611
+ },
612
+ {
613
+ "name": "stdout",
614
+ "output_type": "stream",
615
+ "text": [
616
+ "Gene data saved to ../../output/preprocess/Coronary_artery_disease/gene_data/GSE64566.csv\n",
617
+ "Loaded clinical data shape: (2, 46)\n",
618
+ "Initial linked data shape: (46, 18552)\n",
619
+ "Linked data shape after handling missing values: (0, 2)\n",
620
+ "After handling missing values, no samples remain.\n",
621
+ "Abnormality detected in the cohort: GSE64566. Preprocessing failed.\n"
622
+ ]
623
+ }
624
+ ],
625
+ "source": [
626
+ "# 1. Attempt to load gene data and handle possible issues with normalization\n",
627
+ "try:\n",
628
+ " # Create output directory if it doesn't exist\n",
629
+ " os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
630
+ " \n",
631
+ " # Check if gene_data (from previous step) has any content\n",
632
+ " if gene_data.shape[0] == 0:\n",
633
+ " print(\"WARNING: Gene data is empty after normalization in previous step.\")\n",
634
+ " print(\"This appears to be miRNA data rather than gene expression data.\")\n",
635
+ " \n",
636
+ " # Since gene_data is empty, set gene_available to False\n",
637
+ " is_gene_available = False\n",
638
+ " \n",
639
+ " # Create an empty dataframe for metadata purposes\n",
640
+ " empty_df = pd.DataFrame()\n",
641
+ " \n",
642
+ " # Log information about this dataset for future reference\n",
643
+ " validate_and_save_cohort_info(\n",
644
+ " is_final=True,\n",
645
+ " cohort=cohort,\n",
646
+ " info_path=json_path,\n",
647
+ " is_gene_available=is_gene_available,\n",
648
+ " is_trait_available=is_trait_available,\n",
649
+ " is_biased=True, # Consider it biased as we can't use it\n",
650
+ " df=empty_df,\n",
651
+ " note=\"Dataset appears to contain miRNA data rather than gene expression data. Gene symbols could not be normalized.\"\n",
652
+ " )\n",
653
+ " \n",
654
+ " print(\"Dataset marked as unusable due to lack of valid gene expression data.\")\n",
655
+ " else:\n",
656
+ " # If gene_data is not empty, proceed with normalization and linking\n",
657
+ " print(f\"Gene data shape before normalization: {gene_data.shape}\")\n",
658
+ " \n",
659
+ " # Save the gene data we have, even if it's already normalized\n",
660
+ " gene_data.to_csv(out_gene_data_file)\n",
661
+ " print(f\"Gene data saved to {out_gene_data_file}\")\n",
662
+ " \n",
663
+ " # Attempt to link clinical and gene data\n",
664
+ " if is_trait_available:\n",
665
+ " # Load clinical data\n",
666
+ " clinical_features = pd.read_csv(out_clinical_data_file, index_col=0)\n",
667
+ " print(f\"Loaded clinical data shape: {clinical_features.shape}\")\n",
668
+ " \n",
669
+ " # Link the clinical and genetic data\n",
670
+ " linked_data = geo_link_clinical_genetic_data(clinical_features, gene_data)\n",
671
+ " print(f\"Initial linked data shape: {linked_data.shape}\")\n",
672
+ " \n",
673
+ " # Handle missing values\n",
674
+ " linked_data = handle_missing_values(linked_data, trait)\n",
675
+ " print(f\"Linked data shape after handling missing values: {linked_data.shape}\")\n",
676
+ " \n",
677
+ " if linked_data.shape[0] > 0:\n",
678
+ " # Check for bias in trait and demographic features\n",
679
+ " is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n",
680
+ " \n",
681
+ " # Validate data quality and save cohort info\n",
682
+ " is_usable = validate_and_save_cohort_info(\n",
683
+ " is_final=True,\n",
684
+ " cohort=cohort,\n",
685
+ " info_path=json_path,\n",
686
+ " is_gene_available=is_gene_available,\n",
687
+ " is_trait_available=is_trait_available,\n",
688
+ " is_biased=is_biased,\n",
689
+ " df=linked_data,\n",
690
+ " note=\"Successfully processed gene expression data for coronary artery disease.\"\n",
691
+ " )\n",
692
+ " \n",
693
+ " # Save the linked data if it's usable\n",
694
+ " if is_usable:\n",
695
+ " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n",
696
+ " linked_data.to_csv(out_data_file)\n",
697
+ " print(f\"Linked data saved to {out_data_file}\")\n",
698
+ " else:\n",
699
+ " print(\"Data not usable for trait study - not saving final linked data.\")\n",
700
+ " else:\n",
701
+ " print(\"After handling missing values, no samples remain.\")\n",
702
+ " validate_and_save_cohort_info(\n",
703
+ " is_final=True,\n",
704
+ " cohort=cohort,\n",
705
+ " info_path=json_path,\n",
706
+ " is_gene_available=is_gene_available,\n",
707
+ " is_trait_available=is_trait_available,\n",
708
+ " is_biased=True,\n",
709
+ " df=pd.DataFrame(),\n",
710
+ " note=\"No valid samples after handling missing values.\"\n",
711
+ " )\n",
712
+ " else:\n",
713
+ " # Cannot proceed with linking if trait data is missing\n",
714
+ " validate_and_save_cohort_info(\n",
715
+ " is_final=True,\n",
716
+ " cohort=cohort,\n",
717
+ " info_path=json_path,\n",
718
+ " is_gene_available=is_gene_available,\n",
719
+ " is_trait_available=is_trait_available,\n",
720
+ " is_biased=True,\n",
721
+ " df=pd.DataFrame(),\n",
722
+ " note=\"Cannot link data because trait information is not available.\"\n",
723
+ " )\n",
724
+ "except Exception as e:\n",
725
+ " print(f\"Error in data processing: {e}\")\n",
726
+ " \n",
727
+ " # Log the error and mark the dataset as unusable\n",
728
+ " validate_and_save_cohort_info(\n",
729
+ " is_final=True,\n",
730
+ " cohort=cohort,\n",
731
+ " info_path=json_path,\n",
732
+ " is_gene_available=False, # Consider gene data unavailable if we had an error\n",
733
+ " is_trait_available=is_trait_available,\n",
734
+ " is_biased=True, # Consider it biased as we can't use it\n",
735
+ " df=pd.DataFrame(), # Empty dataframe for metadata\n",
736
+ " note=f\"Error during normalization or linking: {str(e)}\"\n",
737
+ " )"
738
+ ]
739
+ }
740
+ ],
741
+ "metadata": {
742
+ "language_info": {
743
+ "codemirror_mode": {
744
+ "name": "ipython",
745
+ "version": 3
746
+ },
747
+ "file_extension": ".py",
748
+ "mimetype": "text/x-python",
749
+ "name": "python",
750
+ "nbconvert_exporter": "python",
751
+ "pygments_lexer": "ipython3",
752
+ "version": "3.10.16"
753
+ }
754
+ },
755
+ "nbformat": 4,
756
+ "nbformat_minor": 5
757
+ }
code/Coronary_artery_disease/GSE86216.ipynb ADDED
@@ -0,0 +1,787 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": null,
6
+ "id": "e81de9ce",
7
+ "metadata": {},
8
+ "outputs": [],
9
+ "source": [
10
+ "import sys\n",
11
+ "import os\n",
12
+ "sys.path.append(os.path.abspath(os.path.join(os.getcwd(), '../..')))\n",
13
+ "\n",
14
+ "# Path Configuration\n",
15
+ "from tools.preprocess import *\n",
16
+ "\n",
17
+ "# Processing context\n",
18
+ "trait = \"Coronary_artery_disease\"\n",
19
+ "cohort = \"GSE86216\"\n",
20
+ "\n",
21
+ "# Input paths\n",
22
+ "in_trait_dir = \"../../input/GEO/Coronary_artery_disease\"\n",
23
+ "in_cohort_dir = \"../../input/GEO/Coronary_artery_disease/GSE86216\"\n",
24
+ "\n",
25
+ "# Output paths\n",
26
+ "out_data_file = \"../../output/preprocess/Coronary_artery_disease/GSE86216.csv\"\n",
27
+ "out_gene_data_file = \"../../output/preprocess/Coronary_artery_disease/gene_data/GSE86216.csv\"\n",
28
+ "out_clinical_data_file = \"../../output/preprocess/Coronary_artery_disease/clinical_data/GSE86216.csv\"\n",
29
+ "json_path = \"../../output/preprocess/Coronary_artery_disease/cohort_info.json\"\n"
30
+ ]
31
+ },
32
+ {
33
+ "cell_type": "markdown",
34
+ "id": "4ee6fd64",
35
+ "metadata": {},
36
+ "source": [
37
+ "### Step 1: Initial Data Loading"
38
+ ]
39
+ },
40
+ {
41
+ "cell_type": "code",
42
+ "execution_count": null,
43
+ "id": "d689b7d9",
44
+ "metadata": {},
45
+ "outputs": [],
46
+ "source": [
47
+ "from tools.preprocess import *\n",
48
+ "# 1. Identify the paths to the SOFT file and the matrix file\n",
49
+ "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
50
+ "\n",
51
+ "# 2. Read the matrix file to obtain background information and sample characteristics data\n",
52
+ "background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']\n",
53
+ "clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']\n",
54
+ "background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)\n",
55
+ "\n",
56
+ "# 3. Obtain the sample characteristics dictionary from the clinical dataframe\n",
57
+ "sample_characteristics_dict = get_unique_values_by_row(clinical_data)\n",
58
+ "\n",
59
+ "# 4. Explicitly print out all the background information and the sample characteristics dictionary\n",
60
+ "print(\"Background Information:\")\n",
61
+ "print(background_info)\n",
62
+ "print(\"Sample Characteristics Dictionary:\")\n",
63
+ "print(sample_characteristics_dict)\n"
64
+ ]
65
+ },
66
+ {
67
+ "cell_type": "markdown",
68
+ "id": "fcca8c44",
69
+ "metadata": {},
70
+ "source": [
71
+ "### Step 2: Dataset Analysis and Clinical Feature Extraction"
72
+ ]
73
+ },
74
+ {
75
+ "cell_type": "code",
76
+ "execution_count": null,
77
+ "id": "f69e4796",
78
+ "metadata": {},
79
+ "outputs": [],
80
+ "source": [
81
+ "import os\n",
82
+ "import json\n",
83
+ "import pandas as pd\n",
84
+ "from typing import Optional, Callable, Dict, Any\n",
85
+ "\n",
86
+ "# 1. Gene Expression Data Availability\n",
87
+ "# Looking at the background information, this study analyzes transcriptomic profile in PBMCs\n",
88
+ "# and sample characteristics clearly mention \"cell type: PBMC\" which indicates gene expression data\n",
89
+ "is_gene_available = True\n",
90
+ "\n",
91
+ "# 2. Variable Availability and Data Type Conversion\n",
92
+ "# 2.1 Trait Data Availability\n",
93
+ "# From the background information, we know this is a study on coronary artery disease,\n",
94
+ "# but there's no explicit trait variable in the sample characteristics.\n",
95
+ "# However, we can use the \"treatment\" information as a proxy for disease severity since\n",
96
+ "# all patients have multivessel CAD and are receiving statin treatment\n",
97
+ "trait_row = 1 # The row with treatment information\n",
98
+ "\n",
99
+ "# Age information is not available in the sample characteristics\n",
100
+ "age_row = None\n",
101
+ "\n",
102
+ "# Gender information is not available in the sample characteristics\n",
103
+ "gender_row = None\n",
104
+ "\n",
105
+ "# 2.2 Data Type Conversion Functions\n",
106
+ "def convert_trait(value):\n",
107
+ " \"\"\"\n",
108
+ " Convert treatment status to a binary trait representation.\n",
109
+ " control = 0, rosuvastatin treatment = 1\n",
110
+ " \"\"\"\n",
111
+ " if \":\" not in value:\n",
112
+ " return None\n",
113
+ " \n",
114
+ " value = value.split(\":\", 1)[1].strip().lower()\n",
115
+ " \n",
116
+ " if \"control\" in value:\n",
117
+ " return 0\n",
118
+ " elif \"rosuvastatin\" in value:\n",
119
+ " return 1\n",
120
+ " else:\n",
121
+ " return None\n",
122
+ "\n",
123
+ "def convert_age(value):\n",
124
+ " # Since age data is not available, this function is a placeholder\n",
125
+ " return None\n",
126
+ "\n",
127
+ "def convert_gender(value):\n",
128
+ " # Since gender data is not available, this function is a placeholder\n",
129
+ " return None\n",
130
+ "\n",
131
+ "# 3. Save Metadata\n",
132
+ "# Check if trait data is available (trait_row is not None)\n",
133
+ "is_trait_available = trait_row is not None\n",
134
+ "\n",
135
+ "# Validate and save cohort info\n",
136
+ "validate_and_save_cohort_info(\n",
137
+ " is_final=False,\n",
138
+ " cohort=cohort,\n",
139
+ " info_path=json_path,\n",
140
+ " is_gene_available=is_gene_available,\n",
141
+ " is_trait_available=is_trait_available\n",
142
+ ")\n",
143
+ "\n",
144
+ "# 4. Clinical Feature Extraction\n",
145
+ "# Since trait_row is not None, we proceed with clinical feature extraction\n",
146
+ "# Use the sample characteristics dictionary from the provided output\n",
147
+ "sample_characteristics = {0: ['sibship (sampleid): 1', 'sibship (sampleid): 3', 'sibship (sampleid): 4', 'sibship (sampleid): 5', 'sibship (sampleid): 9', 'sibship (sampleid): 10', 'sibship (sampleid): 12', 'sibship (sampleid): 13', 'sibship (sampleid): 15', 'sibship (sampleid): 16', 'sibship (sampleid): 17', 'sibship (sampleid): 18', 'sibship (sampleid): 19', 'sibship (sampleid): 20', 'sibship (sampleid): 21', 'sibship (sampleid): 23', 'sibship (sampleid): 24', 'sibship (sampleid): 25', 'sibship (sampleid): 26', 'sibship (sampleid): 27', 'sibship (sampleid): 28', 'sibship (sampleid): 29', 'sibship (sampleid): 30', 'sibship (sampleid): 31', 'sibship (sampleid): 35', 'sibship (sampleid): 36', 'sibship (sampleid): 38', 'sibship (sampleid): 40', 'sibship (sampleid): 47', 'sibship (sampleid): 48'], 1: ['treatment: control', 'treatment: 40 mg rosuvastatin every day for 8-12 weeks'], 2: ['time: BaseLine', 'time: FollowUp'], 3: ['cell type: PBMC']}\n",
148
+ "\n",
149
+ "# We need to transform this dictionary into a proper DataFrame format\n",
150
+ "# Each column will be a feature and each row is a sample\n",
151
+ "max_samples = max(len(values) for values in sample_characteristics.values())\n",
152
+ "clinical_data = pd.DataFrame(index=range(max_samples))\n",
153
+ "\n",
154
+ "# Add each feature as a column, padding with NaN for missing values\n",
155
+ "for feature_idx, values in sample_characteristics.items():\n",
156
+ " # Create a series with the right length, filled with NaN for missing values\n",
157
+ " series = pd.Series([values[i] if i < len(values) else float('nan') for i in range(max_samples)])\n",
158
+ " clinical_data[feature_idx] = series\n",
159
+ "\n",
160
+ "# Extract clinical features\n",
161
+ "selected_clinical_df = geo_select_clinical_features(\n",
162
+ " clinical_df=clinical_data,\n",
163
+ " trait=trait,\n",
164
+ " trait_row=trait_row,\n",
165
+ " convert_trait=convert_trait,\n",
166
+ " age_row=age_row,\n",
167
+ " convert_age=convert_age,\n",
168
+ " gender_row=gender_row,\n",
169
+ " convert_gender=convert_gender\n",
170
+ ")\n",
171
+ "\n",
172
+ "# Preview the data\n",
173
+ "preview = preview_df(selected_clinical_df)\n",
174
+ "print(\"Clinical Data Preview:\")\n",
175
+ "print(preview)\n",
176
+ "\n",
177
+ "# Create directory if it doesn't exist\n",
178
+ "os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
179
+ "\n",
180
+ "# Save clinical data to CSV\n",
181
+ "selected_clinical_df.to_csv(out_clinical_data_file)\n"
182
+ ]
183
+ },
184
+ {
185
+ "cell_type": "markdown",
186
+ "id": "b29498d0",
187
+ "metadata": {},
188
+ "source": [
189
+ "### Step 3: Dataset Analysis and Clinical Feature Extraction"
190
+ ]
191
+ },
192
+ {
193
+ "cell_type": "code",
194
+ "execution_count": null,
195
+ "id": "a9a5af60",
196
+ "metadata": {},
197
+ "outputs": [],
198
+ "source": [
199
+ "import pandas as pd\n",
200
+ "import numpy as np\n",
201
+ "import os\n",
202
+ "import re\n",
203
+ "import json\n",
204
+ "import gzip\n",
205
+ "from typing import Optional, Callable, Dict, Any, List\n",
206
+ "\n",
207
+ "# Function to parse GEO series matrix file\n",
208
+ "def parse_geo_matrix(file_path):\n",
209
+ " \"\"\"Parse GEO series matrix file to extract sample info and clinical data.\"\"\"\n",
210
+ " sample_info = []\n",
211
+ " sample_chars = {}\n",
212
+ " \n",
213
+ " # Open the gzipped file\n",
214
+ " with gzip.open(file_path, 'rt') as f:\n",
215
+ " for line in f:\n",
216
+ " if line.startswith('!Series_'):\n",
217
+ " sample_info.append(line.strip())\n",
218
+ " elif line.startswith('!Sample_characteristics_ch1'):\n",
219
+ " parts = line.strip().split('\\t')\n",
220
+ " header = parts[0]\n",
221
+ " values = parts[1:]\n",
222
+ " \n",
223
+ " # Extract the characteristic name if possible\n",
224
+ " char_name = header\n",
225
+ " for i, value in enumerate(values):\n",
226
+ " if i not in sample_chars:\n",
227
+ " sample_chars[i] = []\n",
228
+ " sample_chars[i].append(value)\n",
229
+ " \n",
230
+ " # Convert sample characteristics to DataFrame\n",
231
+ " clinical_data = pd.DataFrame()\n",
232
+ " if sample_chars:\n",
233
+ " for i, chars in sample_chars.items():\n",
234
+ " sample_name = f\"Sample_{i+1}\"\n",
235
+ " clinical_data[sample_name] = chars\n",
236
+ " # Add row index as first column\n",
237
+ " clinical_data.insert(0, 'characteristic', [f\"Row_{i}\" for i in range(len(chars))])\n",
238
+ " \n",
239
+ " return '\\n'.join(sample_info), clinical_data\n",
240
+ "\n",
241
+ "# Find the series matrix file\n",
242
+ "matrix_file_path = os.path.join(in_cohort_dir, \"GSE86216_series_matrix.txt.gz\")\n",
243
+ "print(f\"Loading data from: {matrix_file_path}\")\n",
244
+ "\n",
245
+ "# Parse the GEO matrix file\n",
246
+ "if os.path.exists(matrix_file_path):\n",
247
+ " sample_info, clinical_data = parse_geo_matrix(matrix_file_path)\n",
248
+ " print(\"Sample Info Preview:\")\n",
249
+ " print(sample_info[:500])\n",
250
+ " print(\"\\nClinical Data Shape:\", clinical_data.shape)\n",
251
+ " if not clinical_data.empty:\n",
252
+ " print(\"Clinical Data Preview:\")\n",
253
+ " print(clinical_data.head())\n",
254
+ "else:\n",
255
+ " print(\"Series matrix file not found!\")\n",
256
+ " is_gene_available = False\n",
257
+ " is_trait_available = False\n",
258
+ " validate_and_save_cohort_info(\n",
259
+ " is_final=False,\n",
260
+ " cohort=cohort,\n",
261
+ " info_path=json_path,\n",
262
+ " is_gene_available=is_gene_available,\n",
263
+ " is_trait_available=is_trait_available\n",
264
+ " )\n",
265
+ " # Exit early as no data is available\n",
266
+ " import sys\n",
267
+ " sys.exit(0)\n",
268
+ "\n",
269
+ "# 1. Check for gene expression data availability\n",
270
+ "is_gene_available = True # Typically, a series matrix file contains gene expression data\n",
271
+ "\n",
272
+ "# 2. Look at unique values in each row to identify trait, age, and gender\n",
273
+ "if not clinical_data.empty:\n",
274
+ " print(\"\\nUnique values in clinical data rows:\")\n",
275
+ " for i in range(len(clinical_data)):\n",
276
+ " unique_values = clinical_data.iloc[i, 1:].unique()\n",
277
+ " print(f\"Row {i}: Unique values: {unique_values}\")\n",
278
+ "\n",
279
+ "# 2.1 Identify rows for trait, age, and gender\n",
280
+ "trait_row = None\n",
281
+ "age_row = None\n",
282
+ "gender_row = None\n",
283
+ "\n",
284
+ "# Examine each row to identify trait, age, and gender information\n",
285
+ "for i in range(len(clinical_data)):\n",
286
+ " row_values = clinical_data.iloc[i, 1:].astype(str).tolist()\n",
287
+ " row_text = ' '.join(row_values).lower()\n",
288
+ " \n",
289
+ " # Look for trait-related information (Coronary_artery_disease)\n",
290
+ " if any(term in row_text for term in [\"cad\", \"coronary\", \"artery\", \"disease\", \"case\", \"control\", \"diagnosis\"]):\n",
291
+ " trait_row = i\n",
292
+ " print(f\"Found trait information in row {i}\")\n",
293
+ " \n",
294
+ " # Look for age information\n",
295
+ " if \"age\" in row_text:\n",
296
+ " age_row = i\n",
297
+ " print(f\"Found age information in row {i}\")\n",
298
+ " \n",
299
+ " # Look for gender information\n",
300
+ " if any(term in row_text for term in [\"gender\", \"sex\", \"male\", \"female\"]):\n",
301
+ " gender_row = i\n",
302
+ " print(f\"Found gender information in row {i}\")\n",
303
+ "\n",
304
+ "# 2.2 Define conversion functions\n",
305
+ "\n",
306
+ "def extract_value(text):\n",
307
+ " \"\"\"Extract the value after a colon if present.\"\"\"\n",
308
+ " if isinstance(text, str) and ':' in text:\n",
309
+ " return text.split(':', 1)[1].strip()\n",
310
+ " return text\n",
311
+ "\n",
312
+ "def convert_trait(value):\n",
313
+ " \"\"\"Convert trait value to binary (0 for control, 1 for case).\"\"\"\n",
314
+ " if value is None or pd.isna(value):\n",
315
+ " return None\n",
316
+ " \n",
317
+ " value = extract_value(str(value)).lower()\n",
318
+ " \n",
319
+ " if any(term in value for term in [\"cad\", \"coronary artery disease\", \"case\", \"yes\", \"positive\", \"patient\"]):\n",
320
+ " return 1\n",
321
+ " elif any(term in value for term in [\"control\", \"no\", \"negative\", \"healthy\", \"normal\"]):\n",
322
+ " return 0\n",
323
+ " return None\n",
324
+ "\n",
325
+ "def convert_age(value):\n",
326
+ " \"\"\"Convert age value to continuous.\"\"\"\n",
327
+ " if value is None or pd.isna(value):\n",
328
+ " return None\n",
329
+ " \n",
330
+ " value = extract_value(str(value))\n",
331
+ " \n",
332
+ " # Try to extract numeric value\n",
333
+ " matches = re.findall(r'\\d+(?:\\.\\d+)?', str(value))\n",
334
+ " if matches:\n",
335
+ " try:\n",
336
+ " return float(matches[0])\n",
337
+ " except:\n",
338
+ " return None\n",
339
+ " return None\n",
340
+ "\n",
341
+ "def convert_gender(value):\n",
342
+ " \"\"\"Convert gender value to binary (0 for female, 1 for male).\"\"\"\n",
343
+ " if value is None or pd.isna(value):\n",
344
+ " return None\n",
345
+ " \n",
346
+ " value = extract_value(str(value)).lower()\n",
347
+ " \n",
348
+ " if any(term in value for term in [\"female\", \"f\", \"woman\", \"women\"]):\n",
349
+ " return 0\n",
350
+ " elif any(term in value for term in [\"male\", \"m\", \"man\", \"men\"]):\n",
351
+ " return 1\n",
352
+ " return None\n",
353
+ "\n",
354
+ "# 3. Save metadata - conduct initial filtering\n",
355
+ "is_trait_available = trait_row is not None\n",
356
+ "validate_and_save_cohort_info(\n",
357
+ " is_final=False,\n",
358
+ " cohort=cohort,\n",
359
+ " info_path=json_path,\n",
360
+ " is_gene_available=is_gene_available,\n",
361
+ " is_trait_available=is_trait_available\n",
362
+ ")\n",
363
+ "\n",
364
+ "# 4. Clinical Feature Extraction (if trait_row is not None)\n",
365
+ "if trait_row is not None:\n",
366
+ " # Extract clinical features\n",
367
+ " selected_clinical_df = geo_select_clinical_features(\n",
368
+ " clinical_df=clinical_data,\n",
369
+ " trait=trait,\n",
370
+ " trait_row=trait_row,\n",
371
+ " convert_trait=convert_trait,\n",
372
+ " age_row=age_row,\n",
373
+ " convert_age=convert_age if age_row is not None else None,\n",
374
+ " gender_row=gender_row,\n",
375
+ " convert_gender=convert_gender if gender_row is not None else None\n",
376
+ " )\n",
377
+ " \n",
378
+ " # Preview the extracted clinical features\n",
379
+ " preview = preview_df(selected_clinical_df)\n",
380
+ " print(\"\\nSelected Clinical Features Preview:\")\n",
381
+ " print(preview)\n",
382
+ " \n",
383
+ " # Create directory if it doesn't exist\n",
384
+ " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
385
+ " \n",
386
+ " # Save the extracted clinical features to CSV\n",
387
+ " selected_clinical_df.to_csv(out_clinical_data_file, index=False)\n",
388
+ " print(f\"Saved clinical data to {out_clinical_data_file}\")\n"
389
+ ]
390
+ },
391
+ {
392
+ "cell_type": "markdown",
393
+ "id": "2fd1927a",
394
+ "metadata": {},
395
+ "source": [
396
+ "### Step 4: Gene Data Extraction"
397
+ ]
398
+ },
399
+ {
400
+ "cell_type": "code",
401
+ "execution_count": null,
402
+ "id": "9a682460",
403
+ "metadata": {},
404
+ "outputs": [],
405
+ "source": [
406
+ "# 1. Identify the paths to the SOFT file and the matrix file\n",
407
+ "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
408
+ "print(f\"SOFT file: {soft_file}\")\n",
409
+ "print(f\"Matrix file: {matrix_file}\")\n",
410
+ "\n",
411
+ "# Set gene availability flag\n",
412
+ "is_gene_available = True # Initially assume gene data is available\n",
413
+ "\n",
414
+ "# First check if the matrix file contains the expected marker\n",
415
+ "found_marker = False\n",
416
+ "marker_row = None\n",
417
+ "try:\n",
418
+ " with gzip.open(matrix_file, 'rt') as file:\n",
419
+ " for i, line in enumerate(file):\n",
420
+ " if \"!series_matrix_table_begin\" in line:\n",
421
+ " found_marker = True\n",
422
+ " marker_row = i\n",
423
+ " print(f\"Found the matrix table marker at line {i}\")\n",
424
+ " break\n",
425
+ " \n",
426
+ " if not found_marker:\n",
427
+ " print(\"Warning: Could not find '!series_matrix_table_begin' marker in the file.\")\n",
428
+ " is_gene_available = False\n",
429
+ " \n",
430
+ " # If marker was found, try to extract gene data\n",
431
+ " if is_gene_available:\n",
432
+ " try:\n",
433
+ " # Try using the library function\n",
434
+ " gene_data = get_genetic_data(matrix_file)\n",
435
+ " \n",
436
+ " if gene_data.shape[0] == 0:\n",
437
+ " print(\"Warning: Extracted gene data has 0 rows.\")\n",
438
+ " is_gene_available = False\n",
439
+ " else:\n",
440
+ " print(f\"Gene data shape: {gene_data.shape}\")\n",
441
+ " # Print the first 20 gene/probe identifiers\n",
442
+ " print(\"First 20 gene/probe identifiers:\")\n",
443
+ " print(gene_data.index[:20].tolist())\n",
444
+ " except Exception as e:\n",
445
+ " print(f\"Error extracting gene data with get_genetic_data(): {e}\")\n",
446
+ " is_gene_available = False\n",
447
+ " \n",
448
+ " # If gene data extraction failed, examine file content to diagnose\n",
449
+ " if not is_gene_available:\n",
450
+ " print(\"Examining file content to diagnose the issue:\")\n",
451
+ " try:\n",
452
+ " with gzip.open(matrix_file, 'rt') as file:\n",
453
+ " # Print lines around the marker if found\n",
454
+ " if marker_row is not None:\n",
455
+ " for i, line in enumerate(file):\n",
456
+ " if i >= marker_row - 2 and i <= marker_row + 10:\n",
457
+ " print(f\"Line {i}: {line.strip()[:100]}...\")\n",
458
+ " if i > marker_row + 10:\n",
459
+ " break\n",
460
+ " else:\n",
461
+ " # If marker not found, print first 10 lines\n",
462
+ " for i, line in enumerate(file):\n",
463
+ " if i < 10:\n",
464
+ " print(f\"Line {i}: {line.strip()[:100]}...\")\n",
465
+ " else:\n",
466
+ " break\n",
467
+ " except Exception as e2:\n",
468
+ " print(f\"Error examining file: {e2}\")\n",
469
+ " \n",
470
+ "except Exception as e:\n",
471
+ " print(f\"Error processing file: {e}\")\n",
472
+ " is_gene_available = False\n",
473
+ "\n",
474
+ "# Update validation information if gene data extraction failed\n",
475
+ "if not is_gene_available:\n",
476
+ " print(\"Gene expression data could not be successfully extracted from this dataset.\")\n",
477
+ " # Update the validation record since gene data isn't available\n",
478
+ " is_trait_available = False # We already determined trait data isn't available in step 2\n",
479
+ " validate_and_save_cohort_info(is_final=False, cohort=cohort, info_path=json_path,\n",
480
+ " is_gene_available=is_gene_available, is_trait_available=is_trait_available)\n"
481
+ ]
482
+ },
483
+ {
484
+ "cell_type": "markdown",
485
+ "id": "65310e31",
486
+ "metadata": {},
487
+ "source": [
488
+ "### Step 5: Gene Identifier Review"
489
+ ]
490
+ },
491
+ {
492
+ "cell_type": "code",
493
+ "execution_count": null,
494
+ "id": "266c01fd",
495
+ "metadata": {},
496
+ "outputs": [],
497
+ "source": [
498
+ "# The gene identifiers start with \"ILMN_\", which indicates they are Illumina probe IDs\n",
499
+ "# These are not human gene symbols but rather probe identifiers used in Illumina microarray platforms\n",
500
+ "# We will need to map these probe IDs to human gene symbols for biological interpretation\n",
501
+ "\n",
502
+ "requires_gene_mapping = True\n"
503
+ ]
504
+ },
505
+ {
506
+ "cell_type": "markdown",
507
+ "id": "ba18efeb",
508
+ "metadata": {},
509
+ "source": [
510
+ "### Step 6: Gene Annotation"
511
+ ]
512
+ },
513
+ {
514
+ "cell_type": "code",
515
+ "execution_count": null,
516
+ "id": "270c22ad",
517
+ "metadata": {},
518
+ "outputs": [],
519
+ "source": [
520
+ "# 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.\n",
521
+ "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
522
+ "gene_annotation = get_gene_annotation(soft_file)\n",
523
+ "\n",
524
+ "# 2. Analyze the gene annotation dataframe to identify which columns contain the gene identifiers and gene symbols\n",
525
+ "print(\"\\nGene annotation preview:\")\n",
526
+ "print(f\"Columns in gene annotation: {gene_annotation.columns.tolist()}\")\n",
527
+ "print(preview_df(gene_annotation, n=3))\n",
528
+ "\n",
529
+ "# Looking at the output, the Symbol column seems to contain gene information\n",
530
+ "print(\"\\nExamining ID and Symbol columns format (first 3 rows):\")\n",
531
+ "if 'ID' in gene_annotation.columns and 'Symbol' in gene_annotation.columns:\n",
532
+ " for i in range(min(3, len(gene_annotation))):\n",
533
+ " print(f\"Row {i}: ID={gene_annotation['ID'].iloc[i]}\")\n",
534
+ " print(f\"Symbol: {gene_annotation['Symbol'].iloc[i]}\")\n",
535
+ "\n",
536
+ " # Check the quality and completeness of the mapping\n",
537
+ " non_null_symbols = gene_annotation['Symbol'].notna().sum()\n",
538
+ " total_rows = len(gene_annotation)\n",
539
+ " print(f\"\\nSymbol column completeness: {non_null_symbols}/{total_rows} rows ({non_null_symbols/total_rows:.2%})\")\n",
540
+ " \n",
541
+ " # Check if some extracted gene symbols can be found in the Symbol column\n",
542
+ " print(\"\\nAttempting to extract gene symbols from the first few rows:\")\n",
543
+ " for i in range(min(3, len(gene_annotation))):\n",
544
+ " if pd.notna(gene_annotation['Symbol'].iloc[i]):\n",
545
+ " symbols = extract_human_gene_symbols(str(gene_annotation['Symbol'].iloc[i]))\n",
546
+ " print(f\"Row {i} extracted symbols: {symbols}\")\n"
547
+ ]
548
+ },
549
+ {
550
+ "cell_type": "markdown",
551
+ "id": "2ed76bb9",
552
+ "metadata": {},
553
+ "source": [
554
+ "### Step 7: Gene Identifier Mapping"
555
+ ]
556
+ },
557
+ {
558
+ "cell_type": "code",
559
+ "execution_count": null,
560
+ "id": "c0e8aabc",
561
+ "metadata": {},
562
+ "outputs": [],
563
+ "source": [
564
+ "# 1. Re-extract the files and gene annotation\n",
565
+ "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
566
+ "gene_annotation = get_gene_annotation(soft_file)\n",
567
+ "\n",
568
+ "# 2. Identify columns for gene mapping\n",
569
+ "prob_col = 'ID'\n",
570
+ "gene_col = 'Symbol'\n",
571
+ "\n",
572
+ "# Get gene mapping dataframe by extracting the two columns\n",
573
+ "mapping_df = get_gene_mapping(gene_annotation, prob_col, gene_col)\n",
574
+ "print(f\"\\nGene mapping dataframe shape: {mapping_df.shape}\")\n",
575
+ "print(f\"Mapping preview (first 5 rows):\")\n",
576
+ "print(preview_df(mapping_df, n=5))\n",
577
+ "\n",
578
+ "# Load the gene expression data\n",
579
+ "gene_data = get_genetic_data(matrix_file)\n",
580
+ "print(f\"Gene expression data shape before mapping: {gene_data.shape}\")\n",
581
+ "print(\"First 5 probes before mapping:\")\n",
582
+ "print(gene_data.index[:5].tolist())\n",
583
+ "\n",
584
+ "# 3. Apply gene mapping to convert probe-level measurements to gene expression data\n",
585
+ "print(\"\\nConverting probe-level measurements to gene expression data...\")\n",
586
+ "mapped_gene_data = apply_gene_mapping(gene_data, mapping_df)\n",
587
+ "print(f\"Gene expression data shape after mapping: {mapped_gene_data.shape}\")\n",
588
+ "print(\"First 5 genes after mapping:\")\n",
589
+ "print(mapped_gene_data.index[:5].tolist())\n",
590
+ "\n",
591
+ "# Check if any mapping happened by comparing number of unique identifiers before and after\n",
592
+ "num_probes_before = gene_data.shape[0]\n",
593
+ "num_genes_after = mapped_gene_data.shape[0]\n",
594
+ "print(f\"\\nBefore mapping: {num_probes_before} unique probe IDs\")\n",
595
+ "print(f\"After mapping: {num_genes_after} unique gene symbols\")\n",
596
+ "\n",
597
+ "# Save the gene expression data to a CSV file\n",
598
+ "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
599
+ "mapped_gene_data.to_csv(out_gene_data_file)\n",
600
+ "print(f\"\\nSaved gene expression data to {out_gene_data_file}\")\n"
601
+ ]
602
+ },
603
+ {
604
+ "cell_type": "markdown",
605
+ "id": "377ebd01",
606
+ "metadata": {},
607
+ "source": [
608
+ "### Step 8: Data Normalization and Linking"
609
+ ]
610
+ },
611
+ {
612
+ "cell_type": "code",
613
+ "execution_count": null,
614
+ "id": "ead88248",
615
+ "metadata": {},
616
+ "outputs": [],
617
+ "source": [
618
+ "# 1. Normalize gene symbols in the gene expression data\n",
619
+ "try:\n",
620
+ " # Make sure the directory exists\n",
621
+ " os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
622
+ " \n",
623
+ " # Use the gene_data variable from the previous step (don't try to load it from file)\n",
624
+ " print(f\"Gene data shape before normalization: {gene_data.shape}\")\n",
625
+ " \n",
626
+ " # Apply normalization to gene symbols\n",
627
+ " normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n",
628
+ " print(f\"Gene data shape after normalization: {normalized_gene_data.shape}\")\n",
629
+ " \n",
630
+ " # Save the normalized gene data\n",
631
+ " normalized_gene_data.to_csv(out_gene_data_file)\n",
632
+ " print(f\"Normalized gene data saved to {out_gene_data_file}\")\n",
633
+ " \n",
634
+ " # Use the normalized data for further processing\n",
635
+ " gene_data = normalized_gene_data\n",
636
+ " is_gene_available = True\n",
637
+ "except Exception as e:\n",
638
+ " print(f\"Error normalizing gene data: {e}\")\n",
639
+ " is_gene_available = False\n",
640
+ "\n",
641
+ "# 2. Load clinical data - respecting the analysis from Step 2\n",
642
+ "# From Step 2, we determined:\n",
643
+ "# trait_row = None # No Breast Cancer subtype data available\n",
644
+ "# age_row = 2\n",
645
+ "# gender_row = None\n",
646
+ "is_trait_available = trait_row is not None\n",
647
+ "\n",
648
+ "# Skip clinical feature extraction when trait_row is None\n",
649
+ "if is_trait_available:\n",
650
+ " try:\n",
651
+ " # Load the clinical data from file\n",
652
+ " soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
653
+ " background_info, clinical_data = get_background_and_clinical_data(matrix_file)\n",
654
+ " \n",
655
+ " # Extract clinical features\n",
656
+ " clinical_features = geo_select_clinical_features(\n",
657
+ " clinical_df=clinical_data,\n",
658
+ " trait=trait,\n",
659
+ " trait_row=trait_row,\n",
660
+ " convert_trait=convert_trait,\n",
661
+ " gender_row=gender_row,\n",
662
+ " convert_gender=convert_gender,\n",
663
+ " age_row=age_row,\n",
664
+ " convert_age=convert_age\n",
665
+ " )\n",
666
+ " \n",
667
+ " print(f\"Extracted clinical data shape: {clinical_features.shape}\")\n",
668
+ " print(\"Preview of clinical data (first 5 samples):\")\n",
669
+ " print(clinical_features.iloc[:, :5])\n",
670
+ " \n",
671
+ " # Save the properly extracted clinical data\n",
672
+ " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
673
+ " clinical_features.to_csv(out_clinical_data_file)\n",
674
+ " print(f\"Clinical data saved to {out_clinical_data_file}\")\n",
675
+ " except Exception as e:\n",
676
+ " print(f\"Error extracting clinical data: {e}\")\n",
677
+ " is_trait_available = False\n",
678
+ "else:\n",
679
+ " print(f\"No trait data ({trait}) available in this dataset based on previous analysis.\")\n",
680
+ "\n",
681
+ "# 3. Link clinical and genetic data if both are available\n",
682
+ "if is_trait_available and is_gene_available:\n",
683
+ " try:\n",
684
+ " # Debug the column names to ensure they match\n",
685
+ " print(f\"Gene data columns (first 5): {gene_data.columns[:5].tolist()}\")\n",
686
+ " print(f\"Clinical data columns (first 5): {clinical_features.columns[:5].tolist()}\")\n",
687
+ " \n",
688
+ " # Check for common sample IDs\n",
689
+ " common_samples = set(gene_data.columns).intersection(clinical_features.columns)\n",
690
+ " print(f\"Found {len(common_samples)} common samples between gene and clinical data\")\n",
691
+ " \n",
692
+ " if len(common_samples) > 0:\n",
693
+ " # Link the clinical and genetic data\n",
694
+ " linked_data = geo_link_clinical_genetic_data(clinical_features, gene_data)\n",
695
+ " print(f\"Initial linked data shape: {linked_data.shape}\")\n",
696
+ " \n",
697
+ " # Debug the trait values before handling missing values\n",
698
+ " print(\"Preview of linked data (first 5 rows, first 5 columns):\")\n",
699
+ " print(linked_data.iloc[:5, :5])\n",
700
+ " \n",
701
+ " # Handle missing values\n",
702
+ " linked_data = handle_missing_values(linked_data, trait)\n",
703
+ " print(f\"Linked data shape after handling missing values: {linked_data.shape}\")\n",
704
+ " \n",
705
+ " if linked_data.shape[0] > 0:\n",
706
+ " # Check for bias in trait and demographic features\n",
707
+ " is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n",
708
+ " \n",
709
+ " # Validate the data quality and save cohort info\n",
710
+ " note = \"Dataset contains gene expression data from triple negative breast cancer vs. luminal tumors, but no explicit breast cancer subtype labels in the sample characteristics.\"\n",
711
+ " is_usable = validate_and_save_cohort_info(\n",
712
+ " is_final=True,\n",
713
+ " cohort=cohort,\n",
714
+ " info_path=json_path,\n",
715
+ " is_gene_available=is_gene_available,\n",
716
+ " is_trait_available=is_trait_available,\n",
717
+ " is_biased=is_biased,\n",
718
+ " df=linked_data,\n",
719
+ " note=note\n",
720
+ " )\n",
721
+ " \n",
722
+ " # Save the linked data if it's usable\n",
723
+ " if is_usable:\n",
724
+ " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n",
725
+ " linked_data.to_csv(out_data_file)\n",
726
+ " print(f\"Linked data saved to {out_data_file}\")\n",
727
+ " else:\n",
728
+ " print(\"Data not usable for the trait study - not saving final linked data.\")\n",
729
+ " else:\n",
730
+ " print(\"After handling missing values, no samples remain.\")\n",
731
+ " validate_and_save_cohort_info(\n",
732
+ " is_final=True,\n",
733
+ " cohort=cohort,\n",
734
+ " info_path=json_path,\n",
735
+ " is_gene_available=is_gene_available,\n",
736
+ " is_trait_available=is_trait_available,\n",
737
+ " is_biased=True,\n",
738
+ " df=pd.DataFrame(),\n",
739
+ " note=\"No valid samples after handling missing values.\"\n",
740
+ " )\n",
741
+ " else:\n",
742
+ " print(\"No common samples found between gene expression and clinical data.\")\n",
743
+ " validate_and_save_cohort_info(\n",
744
+ " is_final=True,\n",
745
+ " cohort=cohort,\n",
746
+ " info_path=json_path,\n",
747
+ " is_gene_available=is_gene_available,\n",
748
+ " is_trait_available=is_trait_available,\n",
749
+ " is_biased=True,\n",
750
+ " df=pd.DataFrame(),\n",
751
+ " note=\"No common samples between gene expression and clinical data.\"\n",
752
+ " )\n",
753
+ " except Exception as e:\n",
754
+ " print(f\"Error linking or processing data: {e}\")\n",
755
+ " validate_and_save_cohort_info(\n",
756
+ " is_final=True,\n",
757
+ " cohort=cohort,\n",
758
+ " info_path=json_path,\n",
759
+ " is_gene_available=is_gene_available,\n",
760
+ " is_trait_available=is_trait_available,\n",
761
+ " is_biased=True, # Assume biased if there's an error\n",
762
+ " df=pd.DataFrame(), # Empty dataframe for metadata\n",
763
+ " note=f\"Error in data processing: {str(e)}\"\n",
764
+ " )\n",
765
+ "else:\n",
766
+ " # Create an empty DataFrame for metadata purposes\n",
767
+ " empty_df = pd.DataFrame()\n",
768
+ " \n",
769
+ " # We can't proceed with linking if either trait or gene data is missing\n",
770
+ " print(\"Cannot proceed with data linking due to missing trait or gene data.\")\n",
771
+ " validate_and_save_cohort_info(\n",
772
+ " is_final=True,\n",
773
+ " cohort=cohort,\n",
774
+ " info_path=json_path,\n",
775
+ " is_gene_available=is_gene_available,\n",
776
+ " is_trait_available=is_trait_available,\n",
777
+ " is_biased=True, # Data is unusable if we're missing components\n",
778
+ " df=empty_df, # Empty dataframe for metadata\n",
779
+ " note=\"Dataset contains gene expression data from triple negative breast cancer vs. luminal tumors, but no explicit breast cancer subtype labels in the sample characteristics.\"\n",
780
+ " )"
781
+ ]
782
+ }
783
+ ],
784
+ "metadata": {},
785
+ "nbformat": 4,
786
+ "nbformat_minor": 5
787
+ }
code/Coronary_artery_disease/TCGA.ipynb ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": 1,
6
+ "id": "d5357abc",
7
+ "metadata": {
8
+ "execution": {
9
+ "iopub.execute_input": "2025-03-25T08:30:07.111139Z",
10
+ "iopub.status.busy": "2025-03-25T08:30:07.110944Z",
11
+ "iopub.status.idle": "2025-03-25T08:30:07.271981Z",
12
+ "shell.execute_reply": "2025-03-25T08:30:07.271650Z"
13
+ }
14
+ },
15
+ "outputs": [],
16
+ "source": [
17
+ "import sys\n",
18
+ "import os\n",
19
+ "sys.path.append(os.path.abspath(os.path.join(os.getcwd(), '../..')))\n",
20
+ "\n",
21
+ "# Path Configuration\n",
22
+ "from tools.preprocess import *\n",
23
+ "\n",
24
+ "# Processing context\n",
25
+ "trait = \"Coronary_artery_disease\"\n",
26
+ "\n",
27
+ "# Input paths\n",
28
+ "tcga_root_dir = \"../../input/TCGA\"\n",
29
+ "\n",
30
+ "# Output paths\n",
31
+ "out_data_file = \"../../output/preprocess/Coronary_artery_disease/TCGA.csv\"\n",
32
+ "out_gene_data_file = \"../../output/preprocess/Coronary_artery_disease/gene_data/TCGA.csv\"\n",
33
+ "out_clinical_data_file = \"../../output/preprocess/Coronary_artery_disease/clinical_data/TCGA.csv\"\n",
34
+ "json_path = \"../../output/preprocess/Coronary_artery_disease/cohort_info.json\"\n"
35
+ ]
36
+ },
37
+ {
38
+ "cell_type": "markdown",
39
+ "id": "bb363443",
40
+ "metadata": {},
41
+ "source": [
42
+ "### Step 1: Initial Data Loading"
43
+ ]
44
+ },
45
+ {
46
+ "cell_type": "code",
47
+ "execution_count": 2,
48
+ "id": "4feedf60",
49
+ "metadata": {
50
+ "execution": {
51
+ "iopub.execute_input": "2025-03-25T08:30:07.273378Z",
52
+ "iopub.status.busy": "2025-03-25T08:30:07.273234Z",
53
+ "iopub.status.idle": "2025-03-25T08:30:07.359836Z",
54
+ "shell.execute_reply": "2025-03-25T08:30:07.359557Z"
55
+ }
56
+ },
57
+ "outputs": [
58
+ {
59
+ "name": "stdout",
60
+ "output_type": "stream",
61
+ "text": [
62
+ "Looking for a relevant cohort directory for Coronary_artery_disease...\n",
63
+ "Available cohorts: ['TCGA_Liver_Cancer_(LIHC)', 'TCGA_Lower_Grade_Glioma_(LGG)', 'TCGA_lower_grade_glioma_and_glioblastoma_(GBMLGG)', 'TCGA_Lung_Adenocarcinoma_(LUAD)', 'TCGA_Lung_Cancer_(LUNG)', 'TCGA_Lung_Squamous_Cell_Carcinoma_(LUSC)', 'TCGA_Melanoma_(SKCM)', 'TCGA_Mesothelioma_(MESO)', 'TCGA_Ocular_melanomas_(UVM)', 'TCGA_Ovarian_Cancer_(OV)', 'TCGA_Pancreatic_Cancer_(PAAD)', 'TCGA_Pheochromocytoma_Paraganglioma_(PCPG)', 'TCGA_Prostate_Cancer_(PRAD)', 'TCGA_Rectal_Cancer_(READ)', 'TCGA_Sarcoma_(SARC)', 'TCGA_Stomach_Cancer_(STAD)', 'TCGA_Testicular_Cancer_(TGCT)', 'TCGA_Thymoma_(THYM)', 'TCGA_Thyroid_Cancer_(THCA)', 'TCGA_Uterine_Carcinosarcoma_(UCS)', '.DS_Store', 'CrawlData.ipynb', 'TCGA_Acute_Myeloid_Leukemia_(LAML)', 'TCGA_Adrenocortical_Cancer_(ACC)', 'TCGA_Bile_Duct_Cancer_(CHOL)', 'TCGA_Bladder_Cancer_(BLCA)', 'TCGA_Breast_Cancer_(BRCA)', 'TCGA_Cervical_Cancer_(CESC)', 'TCGA_Colon_and_Rectal_Cancer_(COADREAD)', 'TCGA_Colon_Cancer_(COAD)', 'TCGA_Endometrioid_Cancer_(UCEC)', 'TCGA_Esophageal_Cancer_(ESCA)', 'TCGA_Glioblastoma_(GBM)', 'TCGA_Head_and_Neck_Cancer_(HNSC)', 'TCGA_Kidney_Chromophobe_(KICH)', 'TCGA_Kidney_Clear_Cell_Carcinoma_(KIRC)', 'TCGA_Kidney_Papillary_Cell_Carcinoma_(KIRP)', 'TCGA_Large_Bcell_Lymphoma_(DLBC)']\n",
64
+ "Coronary artery disease-related cohorts: []\n",
65
+ "No suitable cohort found for Coronary_artery_disease.\n"
66
+ ]
67
+ }
68
+ ],
69
+ "source": [
70
+ "import os\n",
71
+ "\n",
72
+ "# Check if there's a suitable cohort directory for Coronary artery disease\n",
73
+ "print(f\"Looking for a relevant cohort directory for {trait}...\")\n",
74
+ "\n",
75
+ "# Check available cohorts\n",
76
+ "available_dirs = os.listdir(tcga_root_dir)\n",
77
+ "print(f\"Available cohorts: {available_dirs}\")\n",
78
+ "\n",
79
+ "# Coronary artery disease-related keywords\n",
80
+ "cad_keywords = ['coronary', 'artery', 'heart', 'cardiac', 'cardiovascular']\n",
81
+ "\n",
82
+ "# Look for coronary artery disease-related directories\n",
83
+ "cad_related_dirs = []\n",
84
+ "for d in available_dirs:\n",
85
+ " if any(keyword in d.lower() for keyword in cad_keywords):\n",
86
+ " cad_related_dirs.append(d)\n",
87
+ "\n",
88
+ "print(f\"Coronary artery disease-related cohorts: {cad_related_dirs}\")\n",
89
+ "\n",
90
+ "if not cad_related_dirs:\n",
91
+ " print(f\"No suitable cohort found for {trait}.\")\n",
92
+ " # Mark the task as completed by recording the unavailability\n",
93
+ " validate_and_save_cohort_info(\n",
94
+ " is_final=False,\n",
95
+ " cohort=\"TCGA\",\n",
96
+ " info_path=json_path,\n",
97
+ " is_gene_available=False,\n",
98
+ " is_trait_available=False\n",
99
+ " )\n",
100
+ " # Exit the script early since no suitable cohort was found\n",
101
+ " selected_cohort = None\n",
102
+ "else:\n",
103
+ " # Select the most relevant cohort if multiple are found\n",
104
+ " selected_cohort = cad_related_dirs[0]\n",
105
+ " print(f\"Selected cohort: {selected_cohort}\")\n",
106
+ " \n",
107
+ " # Get the full path to the selected cohort directory\n",
108
+ " cohort_dir = os.path.join(tcga_root_dir, selected_cohort)\n",
109
+ " \n",
110
+ " # Get the clinical and genetic data file paths\n",
111
+ " clinical_file_path, genetic_file_path = tcga_get_relevant_filepaths(cohort_dir)\n",
112
+ " \n",
113
+ " print(f\"Clinical data file: {os.path.basename(clinical_file_path)}\")\n",
114
+ " print(f\"Genetic data file: {os.path.basename(genetic_file_path)}\")\n",
115
+ " \n",
116
+ " # Load the clinical and genetic data\n",
117
+ " clinical_df = pd.read_csv(clinical_file_path, index_col=0, sep='\\t')\n",
118
+ " genetic_df = pd.read_csv(genetic_file_path, index_col=0, sep='\\t')\n",
119
+ " \n",
120
+ " # Print the column names of the clinical data\n",
121
+ " print(\"\\nClinical data columns:\")\n",
122
+ " print(clinical_df.columns.tolist())\n",
123
+ " \n",
124
+ " # Basic info about the datasets\n",
125
+ " print(f\"\\nClinical data shape: {clinical_df.shape}\")\n",
126
+ " print(f\"Genetic data shape: {genetic_df.shape}\")"
127
+ ]
128
+ }
129
+ ],
130
+ "metadata": {
131
+ "language_info": {
132
+ "codemirror_mode": {
133
+ "name": "ipython",
134
+ "version": 3
135
+ },
136
+ "file_extension": ".py",
137
+ "mimetype": "text/x-python",
138
+ "name": "python",
139
+ "nbconvert_exporter": "python",
140
+ "pygments_lexer": "ipython3",
141
+ "version": "3.10.16"
142
+ }
143
+ },
144
+ "nbformat": 4,
145
+ "nbformat_minor": 5
146
+ }
code/Craniosynostosis/GSE27976.ipynb ADDED
@@ -0,0 +1,685 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": null,
6
+ "id": "ef013425",
7
+ "metadata": {},
8
+ "outputs": [],
9
+ "source": [
10
+ "import sys\n",
11
+ "import os\n",
12
+ "sys.path.append(os.path.abspath(os.path.join(os.getcwd(), '../..')))\n",
13
+ "\n",
14
+ "# Path Configuration\n",
15
+ "from tools.preprocess import *\n",
16
+ "\n",
17
+ "# Processing context\n",
18
+ "trait = \"Craniosynostosis\"\n",
19
+ "cohort = \"GSE27976\"\n",
20
+ "\n",
21
+ "# Input paths\n",
22
+ "in_trait_dir = \"../../input/GEO/Craniosynostosis\"\n",
23
+ "in_cohort_dir = \"../../input/GEO/Craniosynostosis/GSE27976\"\n",
24
+ "\n",
25
+ "# Output paths\n",
26
+ "out_data_file = \"../../output/preprocess/Craniosynostosis/GSE27976.csv\"\n",
27
+ "out_gene_data_file = \"../../output/preprocess/Craniosynostosis/gene_data/GSE27976.csv\"\n",
28
+ "out_clinical_data_file = \"../../output/preprocess/Craniosynostosis/clinical_data/GSE27976.csv\"\n",
29
+ "json_path = \"../../output/preprocess/Craniosynostosis/cohort_info.json\"\n"
30
+ ]
31
+ },
32
+ {
33
+ "cell_type": "markdown",
34
+ "id": "e419df3c",
35
+ "metadata": {},
36
+ "source": [
37
+ "### Step 1: Initial Data Loading"
38
+ ]
39
+ },
40
+ {
41
+ "cell_type": "code",
42
+ "execution_count": null,
43
+ "id": "d9cf9152",
44
+ "metadata": {},
45
+ "outputs": [],
46
+ "source": [
47
+ "from tools.preprocess import *\n",
48
+ "# 1. Identify the paths to the SOFT file and the matrix file\n",
49
+ "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
50
+ "\n",
51
+ "# 2. Read the matrix file to obtain background information and sample characteristics data\n",
52
+ "background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']\n",
53
+ "clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']\n",
54
+ "background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)\n",
55
+ "\n",
56
+ "# 3. Obtain the sample characteristics dictionary from the clinical dataframe\n",
57
+ "sample_characteristics_dict = get_unique_values_by_row(clinical_data)\n",
58
+ "\n",
59
+ "# 4. Explicitly print out all the background information and the sample characteristics dictionary\n",
60
+ "print(\"Background Information:\")\n",
61
+ "print(background_info)\n",
62
+ "print(\"Sample Characteristics Dictionary:\")\n",
63
+ "print(sample_characteristics_dict)\n"
64
+ ]
65
+ },
66
+ {
67
+ "cell_type": "markdown",
68
+ "id": "47f51e48",
69
+ "metadata": {},
70
+ "source": [
71
+ "### Step 2: Dataset Analysis and Clinical Feature Extraction"
72
+ ]
73
+ },
74
+ {
75
+ "cell_type": "code",
76
+ "execution_count": null,
77
+ "id": "e76aad6c",
78
+ "metadata": {},
79
+ "outputs": [],
80
+ "source": [
81
+ "import os\n",
82
+ "import pandas as pd\n",
83
+ "import numpy as np\n",
84
+ "import json\n",
85
+ "import re\n",
86
+ "from typing import Optional, Callable, Dict, Any, List, Union\n",
87
+ "\n",
88
+ "# Sample characteristics from previous output\n",
89
+ "sample_characteristics = {\n",
90
+ " 0: ['age months: 12.87', 'age months: 10.4', 'age months: 12.3', 'age months: 11.4', 'age months: 10.1', 'age months: 11', 'age months: 4.27', 'age months: 7.97', 'age months: 4.33', 'age months: 9.33', 'age months: 7.93', 'age months: 10.27', 'age months: 10.87', 'age months: 3.87', 'age months: 3.2', 'age months: 13.27', 'age months: 5.6', 'age months: 14.9', 'age months: 3.03', 'age months: 12.4', 'age months: 8.9', 'age months: 14.17', 'age months: 6.33', 'age months: 14.87', 'age months: 8.4', 'age months: 9.07', 'age months: 13.33', 'age months: 10', 'age months: 13.23', 'age months: 10.33'],\n",
91
+ " 1: ['gender: F', 'gender: M'],\n",
92
+ " 2: ['type: Metopic Synostosis', 'type: Coronal Synostosis R', 'type: Sagittal Synostosis', 'type: Coronal Synostosis L', 'type: Control'],\n",
93
+ " 3: ['cell lines: osteoblast'],\n",
94
+ " 4: ['tissue: skull']\n",
95
+ "}\n",
96
+ "\n",
97
+ "# 1. Gene Expression Data Availability\n",
98
+ "# Based on the background information, this dataset contains gene expression data for craniosynostosis patients\n",
99
+ "is_gene_available = True\n",
100
+ "\n",
101
+ "# 2. Variable Availability and Data Type Conversion\n",
102
+ "# Examining the sample characteristics dictionary:\n",
103
+ "\n",
104
+ "# 2.1 Data Availability\n",
105
+ "# Trait data is in row 2 - as \"type\" which indicates craniosynostosis type\n",
106
+ "trait_row = 2\n",
107
+ "\n",
108
+ "# Age data is in row 0 - as \"age months\"\n",
109
+ "age_row = 0\n",
110
+ "\n",
111
+ "# Gender data is in row 1 - as \"gender\"\n",
112
+ "gender_row = 1\n",
113
+ "\n",
114
+ "# 2.2 Data Type Conversion Functions\n",
115
+ "\n",
116
+ "def convert_trait(value: str) -> int:\n",
117
+ " \"\"\"\n",
118
+ " Convert craniosynostosis type to binary (0=control, 1=case)\n",
119
+ " \"\"\"\n",
120
+ " if pd.isna(value) or not isinstance(value, str):\n",
121
+ " return None\n",
122
+ " \n",
123
+ " # Extract the value after the colon\n",
124
+ " if \":\" in value:\n",
125
+ " value = value.split(\":\", 1)[1].strip()\n",
126
+ " \n",
127
+ " if \"Control\" in value:\n",
128
+ " return 0\n",
129
+ " elif \"Synostosis\" in value:\n",
130
+ " return 1\n",
131
+ " else:\n",
132
+ " return None\n",
133
+ "\n",
134
+ "def convert_age(value: str) -> float:\n",
135
+ " \"\"\"\n",
136
+ " Convert age in months to a continuous value\n",
137
+ " \"\"\"\n",
138
+ " if pd.isna(value) or not isinstance(value, str):\n",
139
+ " return None\n",
140
+ " \n",
141
+ " # Extract the value after the colon\n",
142
+ " if \":\" in value:\n",
143
+ " value = value.split(\":\", 1)[1].strip()\n",
144
+ " \n",
145
+ " # Extract the numeric part\n",
146
+ " match = re.search(r'(\\d+\\.?\\d*)', value)\n",
147
+ " if match:\n",
148
+ " return float(match.group(1))\n",
149
+ " else:\n",
150
+ " return None\n",
151
+ "\n",
152
+ "def convert_gender(value: str) -> int:\n",
153
+ " \"\"\"\n",
154
+ " Convert gender to binary (0=female, 1=male)\n",
155
+ " \"\"\"\n",
156
+ " if pd.isna(value) or not isinstance(value, str):\n",
157
+ " return None\n",
158
+ " \n",
159
+ " # Extract the value after the colon\n",
160
+ " if \":\" in value:\n",
161
+ " value = value.split(\":\", 1)[1].strip()\n",
162
+ " \n",
163
+ " if value.upper() == 'F':\n",
164
+ " return 0\n",
165
+ " elif value.upper() == 'M':\n",
166
+ " return 1\n",
167
+ " else:\n",
168
+ " return None\n",
169
+ "\n",
170
+ "# 3. Save Metadata\n",
171
+ "# Determine trait data availability\n",
172
+ "is_trait_available = trait_row is not None\n",
173
+ "\n",
174
+ "# Initial validation and recording of metadata\n",
175
+ "validate_and_save_cohort_info(\n",
176
+ " is_final=False,\n",
177
+ " cohort=cohort,\n",
178
+ " info_path=json_path,\n",
179
+ " is_gene_available=is_gene_available,\n",
180
+ " is_trait_available=is_trait_available\n",
181
+ ")\n",
182
+ "\n",
183
+ "# 4. Clinical Feature Extraction\n",
184
+ "# If trait data is available, extract and process clinical features\n",
185
+ "if trait_row is not None:\n",
186
+ " # Create a suitable dataframe structure for the geo_select_clinical_features function\n",
187
+ " # We need to ensure the structure works with get_feature_data called inside geo_select_clinical_features\n",
188
+ " \n",
189
+ " # The geo_select_clinical_features expects a dataframe where:\n",
190
+ " # - Each row corresponds to a feature (age, gender, trait)\n",
191
+ " # - The values should be unique values for that feature\n",
192
+ " clinical_data = pd.DataFrame(sample_characteristics)\n",
193
+ " \n",
194
+ " # Extract clinical features\n",
195
+ " selected_clinical_df = geo_select_clinical_features(\n",
196
+ " clinical_df=clinical_data,\n",
197
+ " trait=trait,\n",
198
+ " trait_row=trait_row,\n",
199
+ " convert_trait=convert_trait,\n",
200
+ " age_row=age_row,\n",
201
+ " convert_age=convert_age,\n",
202
+ " gender_row=gender_row,\n",
203
+ " convert_gender=convert_gender\n",
204
+ " )\n",
205
+ " \n",
206
+ " # Preview the selected clinical features\n",
207
+ " preview = preview_df(selected_clinical_df)\n",
208
+ " print(\"Preview of selected clinical features:\", preview)\n",
209
+ " \n",
210
+ " # Create the directory if it doesn't exist\n",
211
+ " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
212
+ " \n",
213
+ " # Save the clinical data to a CSV file\n",
214
+ " selected_clinical_df.to_csv(out_clinical_data_file, index=False)\n",
215
+ " print(f\"Clinical data saved to {out_clinical_data_file}\")\n"
216
+ ]
217
+ },
218
+ {
219
+ "cell_type": "markdown",
220
+ "id": "647ea55c",
221
+ "metadata": {},
222
+ "source": [
223
+ "### Step 3: Dataset Analysis and Clinical Feature Extraction"
224
+ ]
225
+ },
226
+ {
227
+ "cell_type": "code",
228
+ "execution_count": null,
229
+ "id": "bc863e72",
230
+ "metadata": {},
231
+ "outputs": [],
232
+ "source": [
233
+ "I understand that we need to properly analyze the dataset to find gene expression data availability and extract clinical features. Here's the corrected code:\n",
234
+ "\n",
235
+ "```python\n",
236
+ "import pandas as pd\n",
237
+ "import numpy as np\n",
238
+ "import os\n",
239
+ "import json\n",
240
+ "from typing import Callable, Optional, Dict, Any, Union, List\n",
241
+ "\n",
242
+ "# Load the necessary data\n",
243
+ "print(f\"Files in {in_cohort_dir}:\")\n",
244
+ "for f in os.listdir(in_cohort_dir):\n",
245
+ " print(f\" {f}\")\n",
246
+ "\n",
247
+ "# Try to load the clinical data\n",
248
+ "clinical_file = os.path.join(in_cohort_dir, \"clinical_data.csv\")\n",
249
+ "if os.path.exists(clinical_file):\n",
250
+ " clinical_data = pd.read_csv(clinical_file)\n",
251
+ " print(f\"Loaded clinical data from {clinical_file}\")\n",
252
+ "else:\n",
253
+ " clinical_file = os.path.join(in_cohort_dir, f\"{cohort}_sample_characteristics.csv\")\n",
254
+ " if os.path.exists(clinical_file):\n",
255
+ " clinical_data = pd.read_csv(clinical_file)\n",
256
+ " print(f\"Loaded clinical data from {clinical_file}\")\n",
257
+ " else:\n",
258
+ " # Try to find any CSV file that might contain clinical data\n",
259
+ " csv_files = [f for f in os.listdir(in_cohort_dir) if f.endswith('.csv')]\n",
260
+ " clinical_data = None\n",
261
+ " for f in csv_files:\n",
262
+ " try:\n",
263
+ " clinical_file = os.path.join(in_cohort_dir, f)\n",
264
+ " df = pd.read_csv(clinical_file)\n",
265
+ " if 'characteristics_ch1' in df.columns or any('characteristics' in col.lower() for col in df.columns):\n",
266
+ " clinical_data = df\n",
267
+ " print(f\"Loaded clinical data from {clinical_file}\")\n",
268
+ " break\n",
269
+ " except:\n",
270
+ " continue\n",
271
+ " \n",
272
+ " if clinical_data is None:\n",
273
+ " print(\"No clinical data files found\")\n",
274
+ " clinical_data = pd.DataFrame()\n",
275
+ "\n",
276
+ "# Check if gene expression data is likely available\n",
277
+ "gene_files = [f for f in os.listdir(in_cohort_dir) if \n",
278
+ " \"gene\" in f.lower() or \n",
279
+ " \"expression\" in f.lower() or \n",
280
+ " \"series_matrix\" in f.lower() or\n",
281
+ " f.endswith('.txt') or \n",
282
+ " f.endswith('.tsv')]\n",
283
+ "is_gene_available = len(gene_files) > 0\n",
284
+ "print(f\"Gene expression data availability: {is_gene_available}\")\n",
285
+ "\n",
286
+ "# Print the clinical data structure to help us analyze it\n",
287
+ "if not clinical_data.empty:\n",
288
+ " print(\"\\nClinical data shape:\", clinical_data.shape)\n",
289
+ " print(\"\\nClinical data columns:\", clinical_data.columns.tolist())\n",
290
+ " print(\"\\nFirst few rows of clinical data:\")\n",
291
+ " print(clinical_data.head())\n",
292
+ " \n",
293
+ " # Look for sample characteristics\n",
294
+ " if 'characteristics_ch1' in clinical_data.columns:\n",
295
+ " unique_values = {}\n",
296
+ " for i in range(len(clinical_data)):\n",
297
+ " val = clinical_data.loc[i, 'characteristics_ch1']\n",
298
+ " if i not in unique_values:\n",
299
+ " unique_values[i] = set()\n",
300
+ " unique_values[i].add(val)\n",
301
+ " \n",
302
+ " for row_idx, values in unique_values.items():\n",
303
+ " print(f\"Row {row_idx} unique values:\", values)\n",
304
+ " \n",
305
+ " # Or check for any columns that might contain sample characteristics\n",
306
+ " sample_cols = [col for col in clinical_data.columns if 'characteristics' in col.lower()]\n",
307
+ " for col in sample_cols:\n",
308
+ " print(f\"\\nUnique values in {col}:\")\n",
309
+ " for val in clinical_data[col].unique():\n",
310
+ " print(f\" {val}\")\n",
311
+ "\n",
312
+ "# Based on our inspection, set the row indices for trait, age, and gender\n",
313
+ "# Setting these based on the Craniosynostosis dataset patterns\n",
314
+ "# After reviewing the data, these values should be updated\n",
315
+ "trait_row = 1 # Sample row index where craniosynostosis status can be found\n",
316
+ "age_row = 2 # Sample row index where age information can be found\n",
317
+ "gender_row = 3 # Sample row index where gender information can be found\n",
318
+ "\n",
319
+ "def convert_trait(value: str) -> int:\n",
320
+ " \"\"\"\n",
321
+ " Convert craniosynostosis information to binary format.\n",
322
+ " \n",
323
+ " Args:\n",
324
+ " value: The raw value from the clinical data\n",
325
+ " \n",
326
+ " Returns:\n",
327
+ " 1 for cases, 0 for controls, None for unknown\n",
328
+ " \"\"\"\n",
329
+ " if pd.isna(value) or value is None:\n",
330
+ " return None\n",
331
+ " \n",
332
+ " value = str(value).lower()\n",
333
+ " \n",
334
+ " # Extract the actual value if it's in format \"label: value\"\n",
335
+ " if ':' in value:\n",
336
+ " value = value.split(':', 1)[1].strip()\n",
337
+ " \n",
338
+ " if 'case' in value or 'patient' in value or 'craniosynostosis' in value or 'affected' in value:\n",
339
+ " return 1\n",
340
+ " elif 'control' in value or 'normal' in value or 'unaffected' in value or 'healthy' in value:\n",
341
+ " return 0\n",
342
+ " else:\n",
343
+ " return None\n",
344
+ "\n",
345
+ "def convert_age(value: str) -> float:\n",
346
+ " \"\"\"\n",
347
+ " Convert age information to numerical format.\n",
348
+ " \n",
349
+ " Args:\n",
350
+ " value: The raw age value from the clinical data\n",
351
+ " \n",
352
+ " Returns:\n",
353
+ " Age as a float, None for unknown\n",
354
+ " \"\"\"\n",
355
+ " if pd.isna(value) or value is None:\n",
356
+ " return None\n",
357
+ " \n",
358
+ " value = str(value).lower()\n",
359
+ " \n",
360
+ " # Extract the actual value if it's in format \"label: value\"\n",
361
+ " if ':' in value:\n",
362
+ " value = value.split(':', 1)[1].strip()\n",
363
+ " \n",
364
+ " # Try to extract age\n",
365
+ " import re\n",
366
+ " \n",
367
+ " # Try to find a number, potentially followed by time units\n",
368
+ " age_match = re.search(r'(\\d+\\.?\\d*)\\s*(years?|yr|y|months?|mo|days?|d|weeks?|wk)?', value)\n",
369
+ " if age_match:\n",
370
+ " age_val = float(age_match.group(1))\n",
371
+ " unit = age_match.group(2) if age_match.group(2) else 'years'\n",
372
+ " \n",
373
+ " # Convert to years if needed\n",
374
+ " if 'month' in unit or unit == 'mo':\n",
375
+ " age_val /= 12\n",
376
+ " elif 'day' in unit or unit == 'd':\n",
377
+ " age_val /= 365\n",
378
+ " elif 'week' in unit or unit == 'wk':\n",
379
+ " age_val /= 52\n",
380
+ " \n",
381
+ " return age_val\n",
382
+ " \n",
383
+ " return None\n",
384
+ "\n",
385
+ "def convert_gender(value: str) -> int:\n",
386
+ " \"\"\"\n",
387
+ " Convert gender information to binary format.\n",
388
+ " \n",
389
+ " Args:\n",
390
+ " value: The raw gender value from the clinical data\n",
391
+ " \n",
392
+ " Returns:\n",
393
+ " 0 for female, 1 for male, None for unknown\n",
394
+ " \"\"\"\n",
395
+ " if pd.isna(value) or value is None:\n",
396
+ " return None\n",
397
+ " \n",
398
+ " value = str(value).lower()\n",
399
+ " \n",
400
+ " # Extract the actual value if it's in format \"label: value\"\n",
401
+ " if ':' in value:\n",
402
+ " value = value.split(':', 1)[1].strip()\n",
403
+ " \n",
404
+ " if 'female' in value or 'f' == value.strip() or 'woman' in value or 'girl' in value:\n",
405
+ " return 0\n",
406
+ " elif 'male' in value or 'm' == value.strip() or 'man' in value or 'boy' in value:\n",
407
+ " return 1\n",
408
+ " else:\n",
409
+ " return None\n",
410
+ "\n",
411
+ "# Determine trait data availability\n",
412
+ "is_trait_available = trait_row is not None\n",
413
+ "\n",
414
+ "# Save initial metadata\n",
415
+ "validate_and_save_cohort_info(\n",
416
+ " is_final=False,\n",
417
+ " cohort=cohort,\n",
418
+ " info_path=json_path,\n",
419
+ " is_gene_available=is_gene_available,\n",
420
+ " is_trait_available=is_trait_available\n",
421
+ ")\n",
422
+ "\n",
423
+ "# If trait data is available, extract clinical features\n",
424
+ "if is_trait_available and not clinical_data.empty:\n",
425
+ " # Extract clinical features\n",
426
+ " selected_clinical_df = geo_select_clinical_features(\n",
427
+ " clinical_df=clinical_data,\n",
428
+ " trait=trait,\n",
429
+ " trait_row=trait_row,\n",
430
+ " convert_trait=convert_trait,\n",
431
+ " age_row=age_row,\n",
432
+ " convert_age=convert_age,\n",
433
+ " gender_row=gender_row,\n",
434
+ " convert_gender=convert_gender\n",
435
+ " )\n",
436
+ " \n",
437
+ " # Preview the extracted features\n"
438
+ ]
439
+ },
440
+ {
441
+ "cell_type": "markdown",
442
+ "id": "8f58aa24",
443
+ "metadata": {},
444
+ "source": [
445
+ "### Step 4: Gene Data Extraction"
446
+ ]
447
+ },
448
+ {
449
+ "cell_type": "code",
450
+ "execution_count": null,
451
+ "id": "0c80a868",
452
+ "metadata": {},
453
+ "outputs": [],
454
+ "source": [
455
+ "# 1. Get the file paths for the SOFT file and matrix file\n",
456
+ "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
457
+ "\n",
458
+ "# 2. First, let's examine the structure of the matrix file to understand its format\n",
459
+ "import gzip\n",
460
+ "\n",
461
+ "# Peek at the first few lines of the file to understand its structure\n",
462
+ "with gzip.open(matrix_file, 'rt') as file:\n",
463
+ " # Read first 100 lines to find the header structure\n",
464
+ " for i, line in enumerate(file):\n",
465
+ " if '!series_matrix_table_begin' in line:\n",
466
+ " print(f\"Found data marker at line {i}\")\n",
467
+ " # Read the next line which should be the header\n",
468
+ " header_line = next(file)\n",
469
+ " print(f\"Header line: {header_line.strip()}\")\n",
470
+ " # And the first data line\n",
471
+ " first_data_line = next(file)\n",
472
+ " print(f\"First data line: {first_data_line.strip()}\")\n",
473
+ " break\n",
474
+ " if i > 100: # Limit search to first 100 lines\n",
475
+ " print(\"Matrix table marker not found in first 100 lines\")\n",
476
+ " break\n",
477
+ "\n",
478
+ "# 3. Now try to get the genetic data with better error handling\n",
479
+ "try:\n",
480
+ " gene_data = get_genetic_data(matrix_file)\n",
481
+ " print(gene_data.index[:20])\n",
482
+ "except KeyError as e:\n",
483
+ " print(f\"KeyError: {e}\")\n",
484
+ " \n",
485
+ " # Alternative approach: manually extract the data\n",
486
+ " print(\"\\nTrying alternative approach to read the gene data:\")\n",
487
+ " with gzip.open(matrix_file, 'rt') as file:\n",
488
+ " # Find the start of the data\n",
489
+ " for line in file:\n",
490
+ " if '!series_matrix_table_begin' in line:\n",
491
+ " break\n",
492
+ " \n",
493
+ " # Read the headers and data\n",
494
+ " import pandas as pd\n",
495
+ " df = pd.read_csv(file, sep='\\t', index_col=0)\n",
496
+ " print(f\"Column names: {df.columns[:5]}\")\n",
497
+ " print(f\"First 20 row IDs: {df.index[:20]}\")\n",
498
+ " gene_data = df\n"
499
+ ]
500
+ },
501
+ {
502
+ "cell_type": "markdown",
503
+ "id": "6707fb59",
504
+ "metadata": {},
505
+ "source": [
506
+ "### Step 5: Gene Identifier Review"
507
+ ]
508
+ },
509
+ {
510
+ "cell_type": "code",
511
+ "execution_count": null,
512
+ "id": "fc4c675a",
513
+ "metadata": {},
514
+ "outputs": [],
515
+ "source": [
516
+ "# Looking at the identifier format (7892501, 7892502, etc), these appear to be probe IDs from a microarray\n",
517
+ "# platform rather than standard human gene symbols (which typically have alphabetic characters like BRCA1, TP53).\n",
518
+ "# \n",
519
+ "# These numeric identifiers likely come from an Affymetrix or Illumina microarray platform and need to be\n",
520
+ "# mapped to standard gene symbols for proper analysis.\n",
521
+ "\n",
522
+ "requires_gene_mapping = True\n"
523
+ ]
524
+ },
525
+ {
526
+ "cell_type": "markdown",
527
+ "id": "c1f3f8e4",
528
+ "metadata": {},
529
+ "source": [
530
+ "### Step 6: Gene Annotation"
531
+ ]
532
+ },
533
+ {
534
+ "cell_type": "code",
535
+ "execution_count": null,
536
+ "id": "f88cefde",
537
+ "metadata": {},
538
+ "outputs": [],
539
+ "source": [
540
+ "# 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.\n",
541
+ "gene_annotation = get_gene_annotation(soft_file)\n",
542
+ "\n",
543
+ "# 2. Use the 'preview_df' function from the library to preview the data and print out the results.\n",
544
+ "print(\"Gene annotation preview:\")\n",
545
+ "print(preview_df(gene_annotation))\n"
546
+ ]
547
+ },
548
+ {
549
+ "cell_type": "markdown",
550
+ "id": "396a3fb6",
551
+ "metadata": {},
552
+ "source": [
553
+ "### Step 7: Gene Identifier Mapping"
554
+ ]
555
+ },
556
+ {
557
+ "cell_type": "code",
558
+ "execution_count": null,
559
+ "id": "c02a7c72",
560
+ "metadata": {},
561
+ "outputs": [],
562
+ "source": [
563
+ "# 1. Determine which columns contain identifiers and gene symbols\n",
564
+ "# Examining the gene_annotation dataframe:\n",
565
+ "# - 'ID' column contains probe identifiers matching the gene expression data indices\n",
566
+ "# - 'gene_assignment' column contains gene symbol information\n",
567
+ "\n",
568
+ "print(\"Examining mapping columns:\")\n",
569
+ "print(f\"First few IDs: {gene_annotation['ID'].head(3).tolist()}\")\n",
570
+ "print(f\"First gene_assignment (partial): {str(gene_annotation['gene_assignment'].iloc[0])[:100]}...\")\n",
571
+ "\n",
572
+ "# 2. Get a gene mapping dataframe with the probe ID and gene symbol columns\n",
573
+ "gene_mapping = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='gene_assignment')\n",
574
+ "\n",
575
+ "# Print a sample of the mapping to verify\n",
576
+ "print(\"\\nSample of gene mapping:\")\n",
577
+ "print(gene_mapping.head(3))\n",
578
+ "print(f\"Number of probes with gene mappings: {len(gene_mapping)}\")\n",
579
+ "\n",
580
+ "# 3. Apply the gene mapping to convert probe-level data to gene expression data\n",
581
+ "# This uses apply_gene_mapping function that handles many-to-many relationships\n",
582
+ "gene_data = apply_gene_mapping(gene_data, gene_mapping)\n",
583
+ "\n",
584
+ "# Print summary of the gene expression data after mapping\n",
585
+ "print(\"\\nGene expression data after mapping:\")\n",
586
+ "print(f\"Shape of gene data: {gene_data.shape}\")\n",
587
+ "print(f\"Sample gene symbols: {list(gene_data.index[:5])}\")\n",
588
+ "\n",
589
+ "# Save the gene expression data to a CSV file\n",
590
+ "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
591
+ "gene_data.to_csv(out_gene_data_file)\n",
592
+ "print(f\"Gene expression data saved to {out_gene_data_file}\")\n"
593
+ ]
594
+ },
595
+ {
596
+ "cell_type": "markdown",
597
+ "id": "890b3e33",
598
+ "metadata": {},
599
+ "source": [
600
+ "### Step 8: Data Normalization and Linking"
601
+ ]
602
+ },
603
+ {
604
+ "cell_type": "code",
605
+ "execution_count": null,
606
+ "id": "196c82f6",
607
+ "metadata": {},
608
+ "outputs": [],
609
+ "source": [
610
+ "# 1. Normalize gene symbols in the gene expression data\n",
611
+ "normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n",
612
+ "print(f\"Normalized gene data shape: {normalized_gene_data.shape}\")\n",
613
+ "print(\"First few genes with their expression values after normalization:\")\n",
614
+ "print(normalized_gene_data.head())\n",
615
+ "\n",
616
+ "# Save the normalized gene data\n",
617
+ "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
618
+ "normalized_gene_data.to_csv(out_gene_data_file)\n",
619
+ "print(f\"Normalized gene data saved to {out_gene_data_file}\")\n",
620
+ "\n",
621
+ "# 2. Extract clinical features using the functions defined in step 2\n",
622
+ "# First, let's load the clinical data again to ensure we have the latest version\n",
623
+ "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
624
+ "background_info, clinical_data = get_background_and_clinical_data(matrix_file)\n",
625
+ "\n",
626
+ "# Extract clinical features using melanoma vs normal tissue as the binary trait\n",
627
+ "selected_clinical_df = geo_select_clinical_features(\n",
628
+ " clinical_data, \n",
629
+ " trait=\"Melanoma\", \n",
630
+ " trait_row=trait_row, \n",
631
+ " convert_trait=convert_trait,\n",
632
+ " age_row=age_row,\n",
633
+ " convert_age=convert_age,\n",
634
+ " gender_row=gender_row,\n",
635
+ " convert_gender=convert_gender\n",
636
+ ")\n",
637
+ "\n",
638
+ "# Save the clinical data\n",
639
+ "os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
640
+ "selected_clinical_df.to_csv(out_clinical_data_file)\n",
641
+ "print(f\"Clinical data saved to {out_clinical_data_file}\")\n",
642
+ "print(\"Clinical data preview:\")\n",
643
+ "print(preview_df(selected_clinical_df))\n",
644
+ "\n",
645
+ "# 3. Link the clinical and genetic data\n",
646
+ "# Transpose normalized gene data for linking\n",
647
+ "gene_data_t = normalized_gene_data.T\n",
648
+ "\n",
649
+ "# Link the clinical and genetic data\n",
650
+ "linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)\n",
651
+ "print(f\"Linked data shape (before handling missing values): {linked_data.shape}\")\n",
652
+ "\n",
653
+ "# 4. Handle missing values in the linked data\n",
654
+ "linked_data = handle_missing_values(linked_data, \"Melanoma\")\n",
655
+ "print(f\"Data after handling missing values: {linked_data.shape}\")\n",
656
+ "\n",
657
+ "# 5. Determine whether the trait and demographic features are biased\n",
658
+ "is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, \"Melanoma\")\n",
659
+ "\n",
660
+ "# 6. Conduct final quality validation and save cohort information\n",
661
+ "is_usable = validate_and_save_cohort_info(\n",
662
+ " is_final=True, \n",
663
+ " cohort=cohort, \n",
664
+ " info_path=json_path, \n",
665
+ " is_gene_available=True, \n",
666
+ " is_trait_available=True, \n",
667
+ " is_biased=is_trait_biased, \n",
668
+ " df=unbiased_linked_data,\n",
669
+ " note=\"Dataset contains gene expression data comparing melanoma (primary and metastatic) with normal tissue/nevi.\"\n",
670
+ ")\n",
671
+ "\n",
672
+ "# 7. If the linked data is usable, save it\n",
673
+ "if is_usable:\n",
674
+ " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n",
675
+ " unbiased_linked_data.to_csv(out_data_file)\n",
676
+ " print(f\"Linked data saved to {out_data_file}\")\n",
677
+ "else:\n",
678
+ " print(\"Data was determined to be unusable and was not saved\")"
679
+ ]
680
+ }
681
+ ],
682
+ "metadata": {},
683
+ "nbformat": 4,
684
+ "nbformat_minor": 5
685
+ }
code/Craniosynostosis/TCGA.ipynb ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": 1,
6
+ "id": "fcb43199",
7
+ "metadata": {
8
+ "execution": {
9
+ "iopub.execute_input": "2025-03-25T08:31:38.622256Z",
10
+ "iopub.status.busy": "2025-03-25T08:31:38.622147Z",
11
+ "iopub.status.idle": "2025-03-25T08:31:38.777754Z",
12
+ "shell.execute_reply": "2025-03-25T08:31:38.777420Z"
13
+ }
14
+ },
15
+ "outputs": [],
16
+ "source": [
17
+ "import sys\n",
18
+ "import os\n",
19
+ "sys.path.append(os.path.abspath(os.path.join(os.getcwd(), '../..')))\n",
20
+ "\n",
21
+ "# Path Configuration\n",
22
+ "from tools.preprocess import *\n",
23
+ "\n",
24
+ "# Processing context\n",
25
+ "trait = \"Craniosynostosis\"\n",
26
+ "\n",
27
+ "# Input paths\n",
28
+ "tcga_root_dir = \"../../input/TCGA\"\n",
29
+ "\n",
30
+ "# Output paths\n",
31
+ "out_data_file = \"../../output/preprocess/Craniosynostosis/TCGA.csv\"\n",
32
+ "out_gene_data_file = \"../../output/preprocess/Craniosynostosis/gene_data/TCGA.csv\"\n",
33
+ "out_clinical_data_file = \"../../output/preprocess/Craniosynostosis/clinical_data/TCGA.csv\"\n",
34
+ "json_path = \"../../output/preprocess/Craniosynostosis/cohort_info.json\"\n"
35
+ ]
36
+ },
37
+ {
38
+ "cell_type": "markdown",
39
+ "id": "9ec41a5e",
40
+ "metadata": {},
41
+ "source": [
42
+ "### Step 1: Initial Data Loading"
43
+ ]
44
+ },
45
+ {
46
+ "cell_type": "code",
47
+ "execution_count": 2,
48
+ "id": "3b3fa204",
49
+ "metadata": {
50
+ "execution": {
51
+ "iopub.execute_input": "2025-03-25T08:31:38.779190Z",
52
+ "iopub.status.busy": "2025-03-25T08:31:38.779047Z",
53
+ "iopub.status.idle": "2025-03-25T08:31:38.798945Z",
54
+ "shell.execute_reply": "2025-03-25T08:31:38.798656Z"
55
+ }
56
+ },
57
+ "outputs": [
58
+ {
59
+ "name": "stdout",
60
+ "output_type": "stream",
61
+ "text": [
62
+ "No suitable directory found for Craniosynostosis.\n",
63
+ "A new JSON file was created at: ../../output/preprocess/Craniosynostosis/cohort_info.json\n",
64
+ "Skipping this trait as no suitable data was found.\n"
65
+ ]
66
+ }
67
+ ],
68
+ "source": [
69
+ "import os\n",
70
+ "import pandas as pd\n",
71
+ "\n",
72
+ "# 1. Find the most relevant directory for Colon and Rectal Cancer\n",
73
+ "subdirectories = os.listdir(tcga_root_dir)\n",
74
+ "target_trait = trait.lower().replace(\"_\", \" \") # Convert to lowercase for case-insensitive matching\n",
75
+ "\n",
76
+ "# Start with no match, then find the best match based on similarity to target trait\n",
77
+ "best_match = None\n",
78
+ "best_match_score = 0\n",
79
+ "\n",
80
+ "for subdir in subdirectories:\n",
81
+ " subdir_lower = subdir.lower()\n",
82
+ " \n",
83
+ " # Calculate a simple similarity score - more matching words = better match\n",
84
+ " # This prioritizes exact matches over partial matches\n",
85
+ " score = 0\n",
86
+ " for word in target_trait.split():\n",
87
+ " if word in subdir_lower:\n",
88
+ " score += 1\n",
89
+ " \n",
90
+ " # Track the best match\n",
91
+ " if score > best_match_score:\n",
92
+ " best_match_score = score\n",
93
+ " best_match = subdir\n",
94
+ " print(f\"Found potential match: {subdir} (score: {score})\")\n",
95
+ "\n",
96
+ "# Use the best match if found\n",
97
+ "if best_match:\n",
98
+ " print(f\"Selected directory: {best_match}\")\n",
99
+ " \n",
100
+ " # 2. Get the clinical and genetic data file paths\n",
101
+ " cohort_dir = os.path.join(tcga_root_dir, best_match)\n",
102
+ " clinical_file_path, genetic_file_path = tcga_get_relevant_filepaths(cohort_dir)\n",
103
+ " \n",
104
+ " print(f\"Clinical file: {os.path.basename(clinical_file_path)}\")\n",
105
+ " print(f\"Genetic file: {os.path.basename(genetic_file_path)}\")\n",
106
+ " \n",
107
+ " # 3. Load the data files\n",
108
+ " clinical_df = pd.read_csv(clinical_file_path, sep='\\t', index_col=0)\n",
109
+ " genetic_df = pd.read_csv(genetic_file_path, sep='\\t', index_col=0)\n",
110
+ " \n",
111
+ " # 4. Print clinical data columns for inspection\n",
112
+ " print(\"\\nClinical data columns:\")\n",
113
+ " print(clinical_df.columns.tolist())\n",
114
+ " \n",
115
+ " # Print basic information about the datasets\n",
116
+ " print(f\"\\nClinical data shape: {clinical_df.shape}\")\n",
117
+ " print(f\"Genetic data shape: {genetic_df.shape}\")\n",
118
+ " \n",
119
+ " # Check if we have both gene and trait data\n",
120
+ " is_gene_available = genetic_df.shape[0] > 0\n",
121
+ " is_trait_available = clinical_df.shape[0] > 0\n",
122
+ " \n",
123
+ "else:\n",
124
+ " print(f\"No suitable directory found for {trait}.\")\n",
125
+ " is_gene_available = False\n",
126
+ " is_trait_available = False\n",
127
+ "\n",
128
+ "# Record the data availability\n",
129
+ "validate_and_save_cohort_info(\n",
130
+ " is_final=False,\n",
131
+ " cohort=\"TCGA\",\n",
132
+ " info_path=json_path,\n",
133
+ " is_gene_available=is_gene_available,\n",
134
+ " is_trait_available=is_trait_available\n",
135
+ ")\n",
136
+ "\n",
137
+ "# Exit if no suitable directory was found\n",
138
+ "if not best_match:\n",
139
+ " print(\"Skipping this trait as no suitable data was found.\")"
140
+ ]
141
+ }
142
+ ],
143
+ "metadata": {
144
+ "language_info": {
145
+ "codemirror_mode": {
146
+ "name": "ipython",
147
+ "version": 3
148
+ },
149
+ "file_extension": ".py",
150
+ "mimetype": "text/x-python",
151
+ "name": "python",
152
+ "nbconvert_exporter": "python",
153
+ "pygments_lexer": "ipython3",
154
+ "version": "3.10.16"
155
+ }
156
+ },
157
+ "nbformat": 4,
158
+ "nbformat_minor": 5
159
+ }
code/Creutzfeldt-Jakob_Disease/GSE62699.ipynb ADDED
@@ -0,0 +1,570 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": 1,
6
+ "id": "cd8ab792",
7
+ "metadata": {
8
+ "execution": {
9
+ "iopub.execute_input": "2025-03-25T08:31:39.584459Z",
10
+ "iopub.status.busy": "2025-03-25T08:31:39.584362Z",
11
+ "iopub.status.idle": "2025-03-25T08:31:39.748035Z",
12
+ "shell.execute_reply": "2025-03-25T08:31:39.747710Z"
13
+ }
14
+ },
15
+ "outputs": [],
16
+ "source": [
17
+ "import sys\n",
18
+ "import os\n",
19
+ "sys.path.append(os.path.abspath(os.path.join(os.getcwd(), '../..')))\n",
20
+ "\n",
21
+ "# Path Configuration\n",
22
+ "from tools.preprocess import *\n",
23
+ "\n",
24
+ "# Processing context\n",
25
+ "trait = \"Creutzfeldt-Jakob_Disease\"\n",
26
+ "cohort = \"GSE62699\"\n",
27
+ "\n",
28
+ "# Input paths\n",
29
+ "in_trait_dir = \"../../input/GEO/Creutzfeldt-Jakob_Disease\"\n",
30
+ "in_cohort_dir = \"../../input/GEO/Creutzfeldt-Jakob_Disease/GSE62699\"\n",
31
+ "\n",
32
+ "# Output paths\n",
33
+ "out_data_file = \"../../output/preprocess/Creutzfeldt-Jakob_Disease/GSE62699.csv\"\n",
34
+ "out_gene_data_file = \"../../output/preprocess/Creutzfeldt-Jakob_Disease/gene_data/GSE62699.csv\"\n",
35
+ "out_clinical_data_file = \"../../output/preprocess/Creutzfeldt-Jakob_Disease/clinical_data/GSE62699.csv\"\n",
36
+ "json_path = \"../../output/preprocess/Creutzfeldt-Jakob_Disease/cohort_info.json\"\n"
37
+ ]
38
+ },
39
+ {
40
+ "cell_type": "markdown",
41
+ "id": "28e5654a",
42
+ "metadata": {},
43
+ "source": [
44
+ "### Step 1: Initial Data Loading"
45
+ ]
46
+ },
47
+ {
48
+ "cell_type": "code",
49
+ "execution_count": 2,
50
+ "id": "4825895f",
51
+ "metadata": {
52
+ "execution": {
53
+ "iopub.execute_input": "2025-03-25T08:31:39.749429Z",
54
+ "iopub.status.busy": "2025-03-25T08:31:39.749297Z",
55
+ "iopub.status.idle": "2025-03-25T08:31:39.816592Z",
56
+ "shell.execute_reply": "2025-03-25T08:31:39.816315Z"
57
+ }
58
+ },
59
+ "outputs": [
60
+ {
61
+ "name": "stdout",
62
+ "output_type": "stream",
63
+ "text": [
64
+ "Background Information:\n",
65
+ "!Series_title\t\"Integrating mRNA and miRNA Co-Expression Networks with eQTLs in the Nucleus Accumbens of Human Chronic Alcoholics\"\n",
66
+ "!Series_summary\t\"Alcohol consumption is known to lead to gene expression changes in the brain. After performing gene co-expression network analysis (WGCNA) of genome-wide mRNA and microRNA expressions in the Nucleus Accumbens (NAc) from subjects with alcohol dependence (AD) and matched controls six mRNA and three miRNA modules significantly correlated with AD after Bonferroni correction (adj. p≤ 0.05) were identified. Cell-type-specific transcriptome analysis revealed two of the mRNA modules to be enriched for neuronal specific marker genes and downregulated in AD, whereas the remaining four were enriched for astrocyte and microglial specific marker genes and were upregulated in AD. Using gene set enrichment analysis, the neuronal specific modules were enriched for genes involved in oxidative phosphorylation, mitochondrial dysfunction and MAPK signaling, while the glial-specific modules were enriched mostly for genes involved in processes related to immune functions, i.e. reactome cytokine signaling in immune system (all adj. p≤ 0.05). In the mRNA and miRNA modules, 461 and 25 candidate hub genes were identified, respectively. In contrast to the expected miRNAs’ biological functions, the correlation analyses between mRNA and miRNA hub genes revealed a significantly higher number of positive than negative correlations (chi-square p≤ 0.0001). At FDR≤ 0.1, integration of the mRNA and miRNA hubs genes expression with genome-wide genotypic data identified 591 cis-eQTLs and 62 cis-eQTLs for the mRNA and miRNA hubs, respectively. Adjusting for the number of tests, the mRNA cis-eQTLs were significantly enriched for AD GWAS signals in the Collaborative Study on Genetics of Alcohol (COGA) sample (adj. p=0.024), providing a novel biological role for these association signals. In conclusion, our study identified coordinated mRNA and miRNA co-expression changes in the NAc of AD subjects, and our genetic (cis-eQTL) analysis provides novel insights into the etiological mechanisms of AD.\"\n",
67
+ "!Series_overall_design\t\"Tissue samples were received from the Australian Brain Donor Programs New South Wales Tissue Resource Centre, which is supported by The University of Sydney, National Health and Medical Research Council of Australia, Schizophrenia Research Institute, National Institute of Alcohol Abuse and Alcoholism, and the New South Wales Department of Health. Cases were excluded if they had an infectious disease (i.e. HIV/AIDS, hepatitis B or C, or Creutzfeldt-Jakob disease), an unsatisfactory agonal status determined from the circumstances surrounding the death, post-mortem delays >48 hours, or significant head injury. In addition to case status, age, sex, ethnicity, brain weight, brain pH, post-mortem interval (PMI), tissue hemisphere, clinical cause of death, blood toxicology at time of death, smoking status, neuropathology and liver pathology were also provided for each subject. MiRNA and mRNA expression in 18 matched case-control pairs (N=36) with sample RINs ≥6 were assessed on the Affymetrix GeneChip® Human Genome U133A 2.0 (HG-U133A 2.0) and Affymetrix GeneChip miRNA 3.0 microarray.\"\n",
68
+ "Sample Characteristics Dictionary:\n",
69
+ "{0: ['diagnosis: alcohol dependence (AD)', 'diagnosis: Control'], 1: ['tissue type: post mortem brain']}\n"
70
+ ]
71
+ }
72
+ ],
73
+ "source": [
74
+ "from tools.preprocess import *\n",
75
+ "# 1. Identify the paths to the SOFT file and the matrix file\n",
76
+ "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
77
+ "\n",
78
+ "# 2. Read the matrix file to obtain background information and sample characteristics data\n",
79
+ "background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']\n",
80
+ "clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']\n",
81
+ "background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)\n",
82
+ "\n",
83
+ "# 3. Obtain the sample characteristics dictionary from the clinical dataframe\n",
84
+ "sample_characteristics_dict = get_unique_values_by_row(clinical_data)\n",
85
+ "\n",
86
+ "# 4. Explicitly print out all the background information and the sample characteristics dictionary\n",
87
+ "print(\"Background Information:\")\n",
88
+ "print(background_info)\n",
89
+ "print(\"Sample Characteristics Dictionary:\")\n",
90
+ "print(sample_characteristics_dict)\n"
91
+ ]
92
+ },
93
+ {
94
+ "cell_type": "markdown",
95
+ "id": "8094d51a",
96
+ "metadata": {},
97
+ "source": [
98
+ "### Step 2: Dataset Analysis and Clinical Feature Extraction"
99
+ ]
100
+ },
101
+ {
102
+ "cell_type": "code",
103
+ "execution_count": 3,
104
+ "id": "cf214d58",
105
+ "metadata": {
106
+ "execution": {
107
+ "iopub.execute_input": "2025-03-25T08:31:39.817894Z",
108
+ "iopub.status.busy": "2025-03-25T08:31:39.817790Z",
109
+ "iopub.status.idle": "2025-03-25T08:31:39.823241Z",
110
+ "shell.execute_reply": "2025-03-25T08:31:39.822955Z"
111
+ }
112
+ },
113
+ "outputs": [
114
+ {
115
+ "name": "stdout",
116
+ "output_type": "stream",
117
+ "text": [
118
+ "A new JSON file was created at: ../../output/preprocess/Creutzfeldt-Jakob_Disease/cohort_info.json\n",
119
+ "Clinical data extraction skipped: trait_row is None\n"
120
+ ]
121
+ }
122
+ ],
123
+ "source": [
124
+ "# Analysis of dataset characteristics based on the provided information\n",
125
+ "\n",
126
+ "# 1. Gene Expression Data Availability\n",
127
+ "# From the background information, we can see that this dataset contains mRNA expression data\n",
128
+ "# from Affymetrix GeneChip® Human Genome U133A 2.0 and miRNA data - so it's suitable for our analysis\n",
129
+ "is_gene_available = True\n",
130
+ "\n",
131
+ "# 2. Variable Availability and Data Type Conversion\n",
132
+ "\n",
133
+ "# 2.1 Trait Information (Creutzfeldt-Jakob Disease)\n",
134
+ "# Looking at the background information, cases with Creutzfeldt-Jakob disease were explicitly excluded\n",
135
+ "# \"Cases were excluded if they had an infectious disease (i.e. HIV/AIDS, hepatitis B or C, or Creutzfeldt-Jakob disease)\"\n",
136
+ "# This means the dataset doesn't contain our trait of interest\n",
137
+ "trait_row = None\n",
138
+ "\n",
139
+ "# Define conversion function for trait even though we won't use it\n",
140
+ "def convert_trait(value):\n",
141
+ " \"\"\"Convert trait value to binary format: 1 for case, 0 for control.\"\"\"\n",
142
+ " if pd.isna(value):\n",
143
+ " return None\n",
144
+ " value_lower = str(value).lower()\n",
145
+ " if ':' in value_lower:\n",
146
+ " value_lower = value_lower.split(':', 1)[1].strip()\n",
147
+ " \n",
148
+ " # Not applicable as the dataset doesn't contain CJD cases\n",
149
+ " return None\n",
150
+ "\n",
151
+ "# 2.2 Age Information\n",
152
+ "# Age is not provided in sample characteristics dictionary\n",
153
+ "age_row = None\n",
154
+ "\n",
155
+ "def convert_age(value):\n",
156
+ " \"\"\"Convert age value to continuous format.\"\"\"\n",
157
+ " if pd.isna(value):\n",
158
+ " return None\n",
159
+ " \n",
160
+ " if ':' in str(value):\n",
161
+ " value = str(value).split(':', 1)[1].strip()\n",
162
+ " \n",
163
+ " try:\n",
164
+ " return float(value)\n",
165
+ " except (ValueError, TypeError):\n",
166
+ " return None\n",
167
+ "\n",
168
+ "# 2.3 Gender Information\n",
169
+ "# Gender is not provided in sample characteristics dictionary\n",
170
+ "gender_row = None\n",
171
+ "\n",
172
+ "def convert_gender(value):\n",
173
+ " \"\"\"Convert gender value to binary format: 0 for female, 1 for male.\"\"\"\n",
174
+ " if pd.isna(value):\n",
175
+ " return None\n",
176
+ " \n",
177
+ " value_lower = str(value).lower()\n",
178
+ " if ':' in value_lower:\n",
179
+ " value_lower = value_lower.split(':', 1)[1].strip()\n",
180
+ " \n",
181
+ " if 'female' in value_lower or 'f' == value_lower:\n",
182
+ " return 0\n",
183
+ " elif 'male' in value_lower or 'm' == value_lower:\n",
184
+ " return 1\n",
185
+ " else:\n",
186
+ " return None\n",
187
+ "\n",
188
+ "# 3. Save Metadata\n",
189
+ "# Determine trait data availability\n",
190
+ "is_trait_available = trait_row is not None\n",
191
+ "\n",
192
+ "# Validate and save cohort info\n",
193
+ "validate_and_save_cohort_info(\n",
194
+ " is_final=False,\n",
195
+ " cohort=cohort,\n",
196
+ " info_path=json_path,\n",
197
+ " is_gene_available=is_gene_available,\n",
198
+ " is_trait_available=is_trait_available\n",
199
+ ")\n",
200
+ "\n",
201
+ "# 4. Clinical Feature Extraction\n",
202
+ "# Since trait_row is None, we skip clinical feature extraction\n",
203
+ "if trait_row is not None:\n",
204
+ " try:\n",
205
+ " # Load clinical data\n",
206
+ " clinical_data = pd.read_csv(f\"{in_cohort_dir}/clinical_data.csv\")\n",
207
+ " \n",
208
+ " # Extract clinical features\n",
209
+ " clinical_features = geo_select_clinical_features(\n",
210
+ " clinical_df=clinical_data,\n",
211
+ " trait=trait,\n",
212
+ " trait_row=trait_row,\n",
213
+ " convert_trait=convert_trait,\n",
214
+ " age_row=age_row,\n",
215
+ " convert_age=convert_age,\n",
216
+ " gender_row=gender_row,\n",
217
+ " convert_gender=convert_gender\n",
218
+ " )\n",
219
+ " \n",
220
+ " # Preview the dataframe\n",
221
+ " print(\"Clinical Features Preview:\")\n",
222
+ " print(preview_df(clinical_features))\n",
223
+ " \n",
224
+ " # Save the clinical features to CSV\n",
225
+ " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
226
+ " clinical_features.to_csv(out_clinical_data_file, index=False)\n",
227
+ " print(f\"Clinical data saved to {out_clinical_data_file}\")\n",
228
+ " except Exception as e:\n",
229
+ " print(f\"Error extracting clinical features: {e}\")\n",
230
+ "else:\n",
231
+ " print(\"Clinical data extraction skipped: trait_row is None\")\n"
232
+ ]
233
+ },
234
+ {
235
+ "cell_type": "markdown",
236
+ "id": "3002a544",
237
+ "metadata": {},
238
+ "source": [
239
+ "### Step 3: Gene Data Extraction"
240
+ ]
241
+ },
242
+ {
243
+ "cell_type": "code",
244
+ "execution_count": 4,
245
+ "id": "d74dd7db",
246
+ "metadata": {
247
+ "execution": {
248
+ "iopub.execute_input": "2025-03-25T08:31:39.824422Z",
249
+ "iopub.status.busy": "2025-03-25T08:31:39.824320Z",
250
+ "iopub.status.idle": "2025-03-25T08:31:39.909247Z",
251
+ "shell.execute_reply": "2025-03-25T08:31:39.908880Z"
252
+ }
253
+ },
254
+ "outputs": [
255
+ {
256
+ "name": "stdout",
257
+ "output_type": "stream",
258
+ "text": [
259
+ "Found data marker at line 63\n",
260
+ "Header line: \"ID_REF\"\t\"GSM1531652\"\t\"GSM1531653\"\t\"GSM1531654\"\t\"GSM1531655\"\t\"GSM1531656\"\t\"GSM1531657\"\t\"GSM1531658\"\t\"GSM1531659\"\t\"GSM1531660\"\t\"GSM1531661\"\t\"GSM1531662\"\t\"GSM1531663\"\t\"GSM1531664\"\t\"GSM1531665\"\t\"GSM1531666\"\t\"GSM1531667\"\t\"GSM1531668\"\t\"GSM1531669\"\t\"GSM1531670\"\t\"GSM1531671\"\t\"GSM1531672\"\t\"GSM1531673\"\t\"GSM1531674\"\t\"GSM1531675\"\t\"GSM1531676\"\t\"GSM1531677\"\t\"GSM1531678\"\t\"GSM1531679\"\t\"GSM1531680\"\t\"GSM1531681\"\t\"GSM1531682\"\t\"GSM1531683\"\t\"GSM1531684\"\t\"GSM1531685\"\t\"GSM1531686\"\t\"GSM1531687\"\n",
261
+ "First data line: \"14q0_st\"\t7.68542\t7.69338\t8.05731\t8.03301\t7.41483\t7.87933\t7.61217\t7.80203\t7.81174\t8.22454\t7.39808\t7.76491\t7.5232\t8.3171\t8.28569\t7.57309\t8.52417\t7.61213\t7.49593\t7.92926\t7.77119\t7.8849\t8.36847\t7.97813\t7.82017\t8.14878\t7.97129\t8.30401\t7.80492\t7.72724\t7.80544\t7.76272\t7.97463\t7.87084\t7.74456\t7.95184\n",
262
+ "Index(['14q0_st', '14qI-1_st', '14qI-1_x_st', '14qI-2_st', '14qI-3_x_st',\n",
263
+ " '14qI-4_st', '14qI-4_x_st', '14qI-5_st', '14qI-6_st', '14qI-6_x_st',\n",
264
+ " '14qI-7_st', '14qI-8_st', '14qI-8_x_st', '14qI-9_x_st', '14qII-10_st',\n",
265
+ " '14qII-10_x_st', '14qII-11_st', '14qII-11_x_st', '14qII-12_st',\n",
266
+ " '14qII-12_x_st'],\n",
267
+ " dtype='object', name='ID')\n"
268
+ ]
269
+ }
270
+ ],
271
+ "source": [
272
+ "# 1. Get the file paths for the SOFT file and matrix file\n",
273
+ "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
274
+ "\n",
275
+ "# 2. First, let's examine the structure of the matrix file to understand its format\n",
276
+ "import gzip\n",
277
+ "\n",
278
+ "# Peek at the first few lines of the file to understand its structure\n",
279
+ "with gzip.open(matrix_file, 'rt') as file:\n",
280
+ " # Read first 100 lines to find the header structure\n",
281
+ " for i, line in enumerate(file):\n",
282
+ " if '!series_matrix_table_begin' in line:\n",
283
+ " print(f\"Found data marker at line {i}\")\n",
284
+ " # Read the next line which should be the header\n",
285
+ " header_line = next(file)\n",
286
+ " print(f\"Header line: {header_line.strip()}\")\n",
287
+ " # And the first data line\n",
288
+ " first_data_line = next(file)\n",
289
+ " print(f\"First data line: {first_data_line.strip()}\")\n",
290
+ " break\n",
291
+ " if i > 100: # Limit search to first 100 lines\n",
292
+ " print(\"Matrix table marker not found in first 100 lines\")\n",
293
+ " break\n",
294
+ "\n",
295
+ "# 3. Now try to get the genetic data with better error handling\n",
296
+ "try:\n",
297
+ " gene_data = get_genetic_data(matrix_file)\n",
298
+ " print(gene_data.index[:20])\n",
299
+ "except KeyError as e:\n",
300
+ " print(f\"KeyError: {e}\")\n",
301
+ " \n",
302
+ " # Alternative approach: manually extract the data\n",
303
+ " print(\"\\nTrying alternative approach to read the gene data:\")\n",
304
+ " with gzip.open(matrix_file, 'rt') as file:\n",
305
+ " # Find the start of the data\n",
306
+ " for line in file:\n",
307
+ " if '!series_matrix_table_begin' in line:\n",
308
+ " break\n",
309
+ " \n",
310
+ " # Read the headers and data\n",
311
+ " import pandas as pd\n",
312
+ " df = pd.read_csv(file, sep='\\t', index_col=0)\n",
313
+ " print(f\"Column names: {df.columns[:5]}\")\n",
314
+ " print(f\"First 20 row IDs: {df.index[:20]}\")\n",
315
+ " gene_data = df\n"
316
+ ]
317
+ },
318
+ {
319
+ "cell_type": "markdown",
320
+ "id": "7ce4a48f",
321
+ "metadata": {},
322
+ "source": [
323
+ "### Step 4: Gene Identifier Review"
324
+ ]
325
+ },
326
+ {
327
+ "cell_type": "code",
328
+ "execution_count": 5,
329
+ "id": "14c006e9",
330
+ "metadata": {
331
+ "execution": {
332
+ "iopub.execute_input": "2025-03-25T08:31:39.910890Z",
333
+ "iopub.status.busy": "2025-03-25T08:31:39.910775Z",
334
+ "iopub.status.idle": "2025-03-25T08:31:39.912599Z",
335
+ "shell.execute_reply": "2025-03-25T08:31:39.912339Z"
336
+ }
337
+ },
338
+ "outputs": [],
339
+ "source": [
340
+ "# The gene identifiers in this dataset are not human gene symbols but appear to be probe IDs from\n",
341
+ "# an Affymetrix microarray platform (like HG-U133A or similar). These identifiers need to be mapped\n",
342
+ "# to standard human gene symbols for meaningful analysis.\n",
343
+ "\n",
344
+ "requires_gene_mapping = True\n"
345
+ ]
346
+ },
347
+ {
348
+ "cell_type": "markdown",
349
+ "id": "94e16e3f",
350
+ "metadata": {},
351
+ "source": [
352
+ "### Step 5: Gene Annotation"
353
+ ]
354
+ },
355
+ {
356
+ "cell_type": "code",
357
+ "execution_count": 6,
358
+ "id": "a0474c5d",
359
+ "metadata": {
360
+ "execution": {
361
+ "iopub.execute_input": "2025-03-25T08:31:39.914144Z",
362
+ "iopub.status.busy": "2025-03-25T08:31:39.914040Z",
363
+ "iopub.status.idle": "2025-03-25T08:31:42.602965Z",
364
+ "shell.execute_reply": "2025-03-25T08:31:42.602602Z"
365
+ }
366
+ },
367
+ "outputs": [
368
+ {
369
+ "name": "stdout",
370
+ "output_type": "stream",
371
+ "text": [
372
+ "Gene annotation preview:\n",
373
+ "{'ID': ['1007_s_at', '1053_at', '117_at', '121_at', '1255_g_at'], 'GB_ACC': ['U48705', 'M87338', 'X51757', 'X69699', 'L36861'], 'SPOT_ID': [nan, nan, nan, nan, nan], 'Species Scientific Name': ['Homo sapiens', 'Homo sapiens', 'Homo sapiens', 'Homo sapiens', 'Homo sapiens'], 'Annotation Date': ['Oct 6, 2014', 'Oct 6, 2014', 'Oct 6, 2014', 'Oct 6, 2014', 'Oct 6, 2014'], 'Sequence Type': ['Exemplar sequence', 'Exemplar sequence', 'Exemplar sequence', 'Exemplar sequence', 'Exemplar sequence'], 'Sequence Source': ['Affymetrix Proprietary Database', 'GenBank', 'Affymetrix Proprietary Database', 'GenBank', 'Affymetrix Proprietary Database'], 'Target Description': ['U48705 /FEATURE=mRNA /DEFINITION=HSU48705 Human receptor tyrosine kinase DDR gene, complete cds', 'M87338 /FEATURE= /DEFINITION=HUMA1SBU Human replication factor C, 40-kDa subunit (A1) mRNA, complete cds', \"X51757 /FEATURE=cds /DEFINITION=HSP70B Human heat-shock protein HSP70B' gene\", 'X69699 /FEATURE= /DEFINITION=HSPAX8A H.sapiens Pax8 mRNA', 'L36861 /FEATURE=expanded_cds /DEFINITION=HUMGCAPB Homo sapiens guanylate cyclase activating protein (GCAP) gene exons 1-4, complete cds'], 'Representative Public ID': ['U48705', 'M87338', 'X51757', 'X69699', 'L36861'], 'Gene Title': ['discoidin domain receptor tyrosine kinase 1 /// microRNA 4640', 'replication factor C (activator 1) 2, 40kDa', \"heat shock 70kDa protein 6 (HSP70B')\", 'paired box 8', 'guanylate cyclase activator 1A (retina)'], 'Gene Symbol': ['DDR1 /// MIR4640', 'RFC2', 'HSPA6', 'PAX8', 'GUCA1A'], 'ENTREZ_GENE_ID': ['780 /// 100616237', '5982', '3310', '7849', '2978'], 'RefSeq Transcript ID': ['NM_001202521 /// NM_001202522 /// NM_001202523 /// NM_001954 /// NM_013993 /// NM_013994 /// NR_039783 /// XM_005249385 /// XM_005249386 /// XM_005249387 /// XM_005249389 /// XM_005272873 /// XM_005272874 /// XM_005272875 /// XM_005272877 /// XM_005275027 /// XM_005275028 /// XM_005275030 /// XM_005275031 /// XM_005275162 /// XM_005275163 /// XM_005275164 /// XM_005275166 /// XM_005275457 /// XM_005275458 /// XM_005275459 /// XM_005275461 /// XM_006715185 /// XM_006715186 /// XM_006715187 /// XM_006715188 /// XM_006715189 /// XM_006715190 /// XM_006725501 /// XM_006725502 /// XM_006725503 /// XM_006725504 /// XM_006725505 /// XM_006725506 /// XM_006725714 /// XM_006725715 /// XM_006725716 /// XM_006725717 /// XM_006725718 /// XM_006725719 /// XM_006725720 /// XM_006725721 /// XM_006725722 /// XM_006725827 /// XM_006725828 /// XM_006725829 /// XM_006725830 /// XM_006725831 /// XM_006725832 /// XM_006726017 /// XM_006726018 /// XM_006726019 /// XM_006726020 /// XM_006726021 /// XM_006726022 /// XR_427836 /// XR_430858 /// XR_430938 /// XR_430974 /// XR_431015', 'NM_001278791 /// NM_001278792 /// NM_001278793 /// NM_002914 /// NM_181471 /// XM_006716080', 'NM_002155', 'NM_003466 /// NM_013951 /// NM_013952 /// NM_013953 /// NM_013992', 'NM_000409 /// XM_006715073'], 'Gene Ontology Biological Process': ['0001558 // regulation of cell growth // inferred from electronic annotation /// 0001952 // regulation of cell-matrix adhesion // inferred from electronic annotation /// 0006468 // protein phosphorylation // inferred from electronic annotation /// 0007155 // cell adhesion // traceable author statement /// 0007169 // transmembrane receptor protein tyrosine kinase signaling pathway // inferred from electronic annotation /// 0007565 // female pregnancy // inferred from electronic annotation /// 0007566 // embryo implantation // inferred from electronic annotation /// 0007595 // lactation // inferred from electronic annotation /// 0008285 // negative regulation of cell proliferation // inferred from electronic annotation /// 0010715 // regulation of extracellular matrix disassembly // inferred from mutant phenotype /// 0014909 // smooth muscle cell migration // inferred from mutant phenotype /// 0016310 // phosphorylation // inferred from electronic annotation /// 0018108 // peptidyl-tyrosine phosphorylation // inferred from electronic annotation /// 0030198 // extracellular matrix organization // traceable author statement /// 0038063 // collagen-activated tyrosine kinase receptor signaling pathway // inferred from direct assay /// 0038063 // collagen-activated tyrosine kinase receptor signaling pathway // inferred from mutant phenotype /// 0038083 // peptidyl-tyrosine autophosphorylation // inferred from direct assay /// 0043583 // ear development // inferred from electronic annotation /// 0044319 // wound healing, spreading of cells // inferred from mutant phenotype /// 0046777 // protein autophosphorylation // inferred from direct assay /// 0060444 // branching involved in mammary gland duct morphogenesis // inferred from electronic annotation /// 0060749 // mammary gland alveolus development // inferred from electronic annotation /// 0061302 // smooth muscle cell-matrix adhesion // inferred from mutant phenotype', '0000278 // mitotic cell cycle // traceable author statement /// 0000722 // telomere maintenance via recombination // traceable author statement /// 0000723 // telomere maintenance // traceable author statement /// 0006260 // DNA replication // traceable author statement /// 0006271 // DNA strand elongation involved in DNA replication // traceable author statement /// 0006281 // DNA repair // traceable author statement /// 0006283 // transcription-coupled nucleotide-excision repair // traceable author statement /// 0006289 // nucleotide-excision repair // traceable author statement /// 0006297 // nucleotide-excision repair, DNA gap filling // traceable author statement /// 0015979 // photosynthesis // inferred from electronic annotation /// 0015995 // chlorophyll biosynthetic process // inferred from electronic annotation /// 0032201 // telomere maintenance via semi-conservative replication // traceable author statement', '0000902 // cell morphogenesis // inferred from electronic annotation /// 0006200 // ATP catabolic process // inferred from direct assay /// 0006950 // response to stress // inferred from electronic annotation /// 0006986 // response to unfolded protein // traceable author statement /// 0034605 // cellular response to heat // inferred from direct assay /// 0042026 // protein refolding // inferred from direct assay /// 0070370 // cellular heat acclimation // inferred from mutant phenotype', '0001655 // urogenital system development // inferred from sequence or structural similarity /// 0001656 // metanephros development // inferred from electronic annotation /// 0001658 // branching involved in ureteric bud morphogenesis // inferred from expression pattern /// 0001822 // kidney development // inferred from expression pattern /// 0001823 // mesonephros development // inferred from sequence or structural similarity /// 0003337 // mesenchymal to epithelial transition involved in metanephros morphogenesis // inferred from expression pattern /// 0006351 // transcription, DNA-templated // inferred from direct assay /// 0006355 // regulation of transcription, DNA-templated // inferred from electronic annotation /// 0007275 // multicellular organismal development // inferred from electronic annotation /// 0007417 // central nervous system development // inferred from expression pattern /// 0009653 // anatomical structure morphogenesis // traceable author statement /// 0030154 // cell differentiation // inferred from electronic annotation /// 0030878 // thyroid gland development // inferred from expression pattern /// 0030878 // thyroid gland development // inferred from mutant phenotype /// 0038194 // thyroid-stimulating hormone signaling pathway // traceable author statement /// 0039003 // pronephric field specification // inferred from sequence or structural similarity /// 0042472 // inner ear morphogenesis // inferred from sequence or structural similarity /// 0042981 // regulation of apoptotic process // inferred from sequence or structural similarity /// 0045893 // positive regulation of transcription, DNA-templated // inferred from direct assay /// 0045893 // positive regulation of transcription, DNA-templated // inferred from sequence or structural similarity /// 0045944 // positive regulation of transcription from RNA polymerase II promoter // inferred from direct assay /// 0048793 // pronephros development // inferred from sequence or structural similarity /// 0071371 // cellular response to gonadotropin stimulus // inferred from direct assay /// 0071599 // otic vesicle development // inferred from expression pattern /// 0072050 // S-shaped body morphogenesis // inferred from electronic annotation /// 0072073 // kidney epithelium development // inferred from electronic annotation /// 0072108 // positive regulation of mesenchymal to epithelial transition involved in metanephros morphogenesis // inferred from sequence or structural similarity /// 0072164 // mesonephric tubule development // inferred from electronic annotation /// 0072207 // metanephric epithelium development // inferred from expression pattern /// 0072221 // metanephric distal convoluted tubule development // inferred from sequence or structural similarity /// 0072278 // metanephric comma-shaped body morphogenesis // inferred from expression pattern /// 0072284 // metanephric S-shaped body morphogenesis // inferred from expression pattern /// 0072289 // metanephric nephron tubule formation // inferred from sequence or structural similarity /// 0072305 // negative regulation of mesenchymal cell apoptotic process involved in metanephric nephron morphogenesis // inferred from sequence or structural similarity /// 0072307 // regulation of metanephric nephron tubule epithelial cell differentiation // inferred from sequence or structural similarity /// 0090190 // positive regulation of branching involved in ureteric bud morphogenesis // inferred from sequence or structural similarity /// 1900212 // negative regulation of mesenchymal cell apoptotic process involved in metanephros development // inferred from sequence or structural similarity /// 1900215 // negative regulation of apoptotic process involved in metanephric collecting duct development // inferred from sequence or structural similarity /// 1900218 // negative regulation of apoptotic process involved in metanephric nephron tubule development // inferred from sequence or structural similarity /// 2000594 // positive regulation of metanephric DCT cell differentiation // inferred from sequence or structural similarity /// 2000611 // positive regulation of thyroid hormone generation // inferred from mutant phenotype /// 2000612 // regulation of thyroid-stimulating hormone secretion // inferred from mutant phenotype', '0007165 // signal transduction // non-traceable author statement /// 0007601 // visual perception // inferred from electronic annotation /// 0007602 // phototransduction // inferred from electronic annotation /// 0007603 // phototransduction, visible light // traceable author statement /// 0016056 // rhodopsin mediated signaling pathway // traceable author statement /// 0022400 // regulation of rhodopsin mediated signaling pathway // traceable author statement /// 0030828 // positive regulation of cGMP biosynthetic process // inferred from electronic annotation /// 0031282 // regulation of guanylate cyclase activity // inferred from electronic annotation /// 0031284 // positive regulation of guanylate cyclase activity // inferred from electronic annotation /// 0050896 // response to stimulus // inferred from electronic annotation'], 'Gene Ontology Cellular Component': ['0005576 // extracellular region // inferred from electronic annotation /// 0005615 // extracellular space // inferred from direct assay /// 0005886 // plasma membrane // traceable author statement /// 0005887 // integral component of plasma membrane // traceable author statement /// 0016020 // membrane // inferred from electronic annotation /// 0016021 // integral component of membrane // inferred from electronic annotation /// 0043235 // receptor complex // inferred from direct assay /// 0070062 // extracellular vesicular exosome // inferred from direct assay', '0005634 // nucleus // inferred from electronic annotation /// 0005654 // nucleoplasm // traceable author statement /// 0005663 // DNA replication factor C complex // inferred from direct assay', '0005737 // cytoplasm // inferred from direct assay /// 0005814 // centriole // inferred from direct assay /// 0005829 // cytosol // inferred from direct assay /// 0008180 // COP9 signalosome // inferred from direct assay /// 0070062 // extracellular vesicular exosome // inferred from direct assay /// 0072562 // blood microparticle // inferred from direct assay', '0005634 // nucleus // inferred from direct assay /// 0005654 // nucleoplasm // inferred from sequence or structural similarity /// 0005730 // nucleolus // inferred from direct assay', '0001750 // photoreceptor outer segment // inferred from electronic annotation /// 0001917 // photoreceptor inner segment // inferred from electronic annotation /// 0005578 // proteinaceous extracellular matrix // inferred from electronic annotation /// 0005886 // plasma membrane // inferred from direct assay /// 0016020 // membrane // inferred from electronic annotation /// 0097381 // photoreceptor disc membrane // traceable author statement'], 'Gene Ontology Molecular Function': ['0000166 // nucleotide binding // inferred from electronic annotation /// 0004672 // protein kinase activity // inferred from electronic annotation /// 0004713 // protein tyrosine kinase activity // inferred from electronic annotation /// 0004714 // transmembrane receptor protein tyrosine kinase activity // traceable author statement /// 0005515 // protein binding // inferred from physical interaction /// 0005518 // collagen binding // inferred from direct assay /// 0005518 // collagen binding // inferred from mutant phenotype /// 0005524 // ATP binding // inferred from electronic annotation /// 0016301 // kinase activity // inferred from electronic annotation /// 0016740 // transferase activity // inferred from electronic annotation /// 0016772 // transferase activity, transferring phosphorus-containing groups // inferred from electronic annotation /// 0038062 // protein tyrosine kinase collagen receptor activity // inferred from direct assay /// 0046872 // metal ion binding // inferred from electronic annotation', '0000166 // nucleotide binding // inferred from electronic annotation /// 0003677 // DNA binding // inferred from electronic annotation /// 0005515 // protein binding // inferred from physical interaction /// 0005524 // ATP binding // inferred from electronic annotation /// 0016851 // magnesium chelatase activity // inferred from electronic annotation /// 0017111 // nucleoside-triphosphatase activity // inferred from electronic annotation', '0000166 // nucleotide binding // inferred from electronic annotation /// 0005524 // ATP binding // inferred from electronic annotation /// 0019899 // enzyme binding // inferred from physical interaction /// 0031072 // heat shock protein binding // inferred from physical interaction /// 0042623 // ATPase activity, coupled // inferred from direct assay /// 0051082 // unfolded protein binding // inferred from direct assay', '0000979 // RNA polymerase II core promoter sequence-specific DNA binding // inferred from direct assay /// 0003677 // DNA binding // inferred from direct assay /// 0003677 // DNA binding // inferred from mutant phenotype /// 0003700 // sequence-specific DNA binding transcription factor activity // inferred from direct assay /// 0004996 // thyroid-stimulating hormone receptor activity // traceable author statement /// 0005515 // protein binding // inferred from physical interaction /// 0044212 // transcription regulatory region DNA binding // inferred from direct assay', '0005509 // calcium ion binding // inferred from electronic annotation /// 0008048 // calcium sensitive guanylate cyclase activator activity // inferred from electronic annotation /// 0030249 // guanylate cyclase regulator activity // inferred from electronic annotation /// 0046872 // metal ion binding // inferred from electronic annotation']}\n"
374
+ ]
375
+ }
376
+ ],
377
+ "source": [
378
+ "# 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.\n",
379
+ "gene_annotation = get_gene_annotation(soft_file)\n",
380
+ "\n",
381
+ "# 2. Use the 'preview_df' function from the library to preview the data and print out the results.\n",
382
+ "print(\"Gene annotation preview:\")\n",
383
+ "print(preview_df(gene_annotation))\n"
384
+ ]
385
+ },
386
+ {
387
+ "cell_type": "markdown",
388
+ "id": "fcadcbcf",
389
+ "metadata": {},
390
+ "source": [
391
+ "### Step 6: Gene Identifier Mapping"
392
+ ]
393
+ },
394
+ {
395
+ "cell_type": "code",
396
+ "execution_count": 7,
397
+ "id": "d42803a1",
398
+ "metadata": {
399
+ "execution": {
400
+ "iopub.execute_input": "2025-03-25T08:31:42.604907Z",
401
+ "iopub.status.busy": "2025-03-25T08:31:42.604757Z",
402
+ "iopub.status.idle": "2025-03-25T08:31:42.709739Z",
403
+ "shell.execute_reply": "2025-03-25T08:31:42.709380Z"
404
+ }
405
+ },
406
+ "outputs": [
407
+ {
408
+ "name": "stdout",
409
+ "output_type": "stream",
410
+ "text": [
411
+ "Mapping dataframe shape: (27035, 2)\n",
412
+ "First few mapping entries:\n",
413
+ " ID Gene\n",
414
+ "0 1007_s_at DDR1 /// MIR4640\n",
415
+ "1 1053_at RFC2\n",
416
+ "2 117_at HSPA6\n",
417
+ "3 121_at PAX8\n",
418
+ "4 1255_g_at GUCA1A\n",
419
+ "Gene expression data shape after mapping: (330, 36)\n",
420
+ "First few gene symbols after mapping:\n",
421
+ "Index(['ACA1', 'ACA10', 'ACA11', 'ACA12', 'ACA13', 'ACA15', 'ACA16', 'ACA17',\n",
422
+ " 'ACA18', 'ACA19'],\n",
423
+ " dtype='object', name='Gene')\n",
424
+ "Gene expression data saved to ../../output/preprocess/Creutzfeldt-Jakob_Disease/gene_data/GSE62699.csv\n"
425
+ ]
426
+ }
427
+ ],
428
+ "source": [
429
+ "# 1. Identify the columns for probe ID and gene symbol in the annotation\n",
430
+ "# Looking at the annotation data, we can see:\n",
431
+ "# - 'ID' column contains probe IDs like '1007_s_at' that match the gene expression data identifiers\n",
432
+ "# - 'Gene Symbol' column contains gene symbols like 'DDR1 /// MIR4640'\n",
433
+ "\n",
434
+ "# 2. Create the gene mapping dataframe\n",
435
+ "mapping_df = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='Gene Symbol')\n",
436
+ "print(f\"Mapping dataframe shape: {mapping_df.shape}\")\n",
437
+ "print(\"First few mapping entries:\")\n",
438
+ "print(mapping_df.head())\n",
439
+ "\n",
440
+ "# 3. Apply gene mapping to convert probe-level measurements to gene expression data\n",
441
+ "gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)\n",
442
+ "print(f\"Gene expression data shape after mapping: {gene_data.shape}\")\n",
443
+ "print(\"First few gene symbols after mapping:\")\n",
444
+ "print(gene_data.index[:10])\n",
445
+ "\n",
446
+ "# 4. Save the gene data to CSV\n",
447
+ "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
448
+ "gene_data.to_csv(out_gene_data_file)\n",
449
+ "print(f\"Gene expression data saved to {out_gene_data_file}\")\n"
450
+ ]
451
+ },
452
+ {
453
+ "cell_type": "markdown",
454
+ "id": "3bcbb81d",
455
+ "metadata": {},
456
+ "source": [
457
+ "### Step 7: Data Normalization and Linking"
458
+ ]
459
+ },
460
+ {
461
+ "cell_type": "code",
462
+ "execution_count": 8,
463
+ "id": "833d4402",
464
+ "metadata": {
465
+ "execution": {
466
+ "iopub.execute_input": "2025-03-25T08:31:42.711369Z",
467
+ "iopub.status.busy": "2025-03-25T08:31:42.711254Z",
468
+ "iopub.status.idle": "2025-03-25T08:31:42.777453Z",
469
+ "shell.execute_reply": "2025-03-25T08:31:42.777137Z"
470
+ }
471
+ },
472
+ "outputs": [
473
+ {
474
+ "name": "stdout",
475
+ "output_type": "stream",
476
+ "text": [
477
+ "Normalized gene data shape: (315, 36)\n",
478
+ "First few genes with their expression values after normalization:\n",
479
+ " GSM1531652 GSM1531653 GSM1531654 GSM1531655 GSM1531656 \\\n",
480
+ "Gene \n",
481
+ "CST12P 6.51726 6.89974 6.43600 6.43231 7.05614 \n",
482
+ "EAF2 5.47411 6.25696 5.78199 6.13728 6.65247 \n",
483
+ "SCARNA1 5.62942 5.72439 5.55974 5.26454 5.61008 \n",
484
+ "SCARNA10 5.38216 5.35127 5.43474 4.82742 5.49208 \n",
485
+ "SCARNA11 13.89248 14.53975 13.66992 12.27193 13.41468 \n",
486
+ "\n",
487
+ " GSM1531657 GSM1531658 GSM1531659 GSM1531660 GSM1531661 ... \\\n",
488
+ "Gene ... \n",
489
+ "CST12P 6.76970 6.61207 6.70551 6.84795 7.07075 ... \n",
490
+ "EAF2 6.10666 5.74773 6.06232 6.15704 5.77854 ... \n",
491
+ "SCARNA1 5.62087 5.41368 5.36728 5.59424 5.22225 ... \n",
492
+ "SCARNA10 5.14407 5.18590 5.04848 5.75723 5.22659 ... \n",
493
+ "SCARNA11 13.32640 13.68379 12.71863 14.02650 13.31725 ... \n",
494
+ "\n",
495
+ " GSM1531678 GSM1531679 GSM1531680 GSM1531681 GSM1531682 \\\n",
496
+ "Gene \n",
497
+ "CST12P 7.02596 6.90600 6.32827 5.37979 6.57150 \n",
498
+ "EAF2 6.31689 6.06351 5.60100 5.74357 5.47575 \n",
499
+ "SCARNA1 5.80495 5.39889 5.55924 5.50468 4.98835 \n",
500
+ "SCARNA10 6.03680 5.07032 4.69060 4.95160 4.53601 \n",
501
+ "SCARNA11 14.14636 14.16708 13.53812 13.24476 11.56498 \n",
502
+ "\n",
503
+ " GSM1531683 GSM1531684 GSM1531685 GSM1531686 GSM1531687 \n",
504
+ "Gene \n",
505
+ "CST12P 6.38431 6.51103 6.28069 6.01924 6.52123 \n",
506
+ "EAF2 5.83211 5.63019 5.71782 6.79741 5.76689 \n",
507
+ "SCARNA1 5.08541 5.37908 5.74941 5.39547 5.31893 \n",
508
+ "SCARNA10 4.74808 5.37225 5.31080 4.84837 4.99793 \n",
509
+ "SCARNA11 12.67611 13.04787 13.46624 13.96408 13.51192 \n",
510
+ "\n",
511
+ "[5 rows x 36 columns]\n",
512
+ "Normalized gene data saved to ../../output/preprocess/Creutzfeldt-Jakob_Disease/gene_data/GSE62699.csv\n",
513
+ "Dataset validation complete. The dataset contains gene expression data but does not contain the required trait data.\n"
514
+ ]
515
+ }
516
+ ],
517
+ "source": [
518
+ "# 1. Normalize gene symbols in the gene expression data\n",
519
+ "normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n",
520
+ "print(f\"Normalized gene data shape: {normalized_gene_data.shape}\")\n",
521
+ "print(\"First few genes with their expression values after normalization:\")\n",
522
+ "print(normalized_gene_data.head())\n",
523
+ "\n",
524
+ "# Save the normalized gene data\n",
525
+ "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
526
+ "normalized_gene_data.to_csv(out_gene_data_file)\n",
527
+ "print(f\"Normalized gene data saved to {out_gene_data_file}\")\n",
528
+ "\n",
529
+ "# 2. Final validation - Clinical data is not available for the trait of interest\n",
530
+ "# Since we determined in Step 2 that trait_row is None (trait data isn't available),\n",
531
+ "# we shouldn't proceed with clinical data extraction and linking\n",
532
+ "\n",
533
+ "# Create a dataframe with gene expression data for validation purposes\n",
534
+ "gene_data_transposed = normalized_gene_data.T\n",
535
+ "gene_data_transposed['placeholder_column'] = 0 # Add placeholder column for validation\n",
536
+ "\n",
537
+ "# 3. Validate and save cohort information, reflecting that this dataset \n",
538
+ "# has gene data but not the required trait data\n",
539
+ "is_usable = validate_and_save_cohort_info(\n",
540
+ " is_final=True, \n",
541
+ " cohort=cohort, \n",
542
+ " info_path=json_path, \n",
543
+ " is_gene_available=True, \n",
544
+ " is_trait_available=False, # We determined in Step 2 that trait data isn't available\n",
545
+ " is_biased=False, # Set to False as required by the function\n",
546
+ " df=gene_data_transposed, # Use transposed gene data with placeholder\n",
547
+ " note=\"Dataset explicitly excludes Creutzfeldt-Jakob disease cases as stated in the dataset description.\"\n",
548
+ ")\n",
549
+ "\n",
550
+ "print(\"Dataset validation complete. The dataset contains gene expression data but does not contain the required trait data.\")"
551
+ ]
552
+ }
553
+ ],
554
+ "metadata": {
555
+ "language_info": {
556
+ "codemirror_mode": {
557
+ "name": "ipython",
558
+ "version": 3
559
+ },
560
+ "file_extension": ".py",
561
+ "mimetype": "text/x-python",
562
+ "name": "python",
563
+ "nbconvert_exporter": "python",
564
+ "pygments_lexer": "ipython3",
565
+ "version": "3.10.16"
566
+ }
567
+ },
568
+ "nbformat": 4,
569
+ "nbformat_minor": 5
570
+ }
code/Creutzfeldt-Jakob_Disease/GSE87629.ipynb ADDED
@@ -0,0 +1,534 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": null,
6
+ "id": "9949b45e",
7
+ "metadata": {},
8
+ "outputs": [],
9
+ "source": [
10
+ "import sys\n",
11
+ "import os\n",
12
+ "sys.path.append(os.path.abspath(os.path.join(os.getcwd(), '../..')))\n",
13
+ "\n",
14
+ "# Path Configuration\n",
15
+ "from tools.preprocess import *\n",
16
+ "\n",
17
+ "# Processing context\n",
18
+ "trait = \"Creutzfeldt-Jakob_Disease\"\n",
19
+ "cohort = \"GSE87629\"\n",
20
+ "\n",
21
+ "# Input paths\n",
22
+ "in_trait_dir = \"../../input/GEO/Creutzfeldt-Jakob_Disease\"\n",
23
+ "in_cohort_dir = \"../../input/GEO/Creutzfeldt-Jakob_Disease/GSE87629\"\n",
24
+ "\n",
25
+ "# Output paths\n",
26
+ "out_data_file = \"../../output/preprocess/Creutzfeldt-Jakob_Disease/GSE87629.csv\"\n",
27
+ "out_gene_data_file = \"../../output/preprocess/Creutzfeldt-Jakob_Disease/gene_data/GSE87629.csv\"\n",
28
+ "out_clinical_data_file = \"../../output/preprocess/Creutzfeldt-Jakob_Disease/clinical_data/GSE87629.csv\"\n",
29
+ "json_path = \"../../output/preprocess/Creutzfeldt-Jakob_Disease/cohort_info.json\"\n"
30
+ ]
31
+ },
32
+ {
33
+ "cell_type": "markdown",
34
+ "id": "81524769",
35
+ "metadata": {},
36
+ "source": [
37
+ "### Step 1: Initial Data Loading"
38
+ ]
39
+ },
40
+ {
41
+ "cell_type": "code",
42
+ "execution_count": null,
43
+ "id": "644a07d1",
44
+ "metadata": {},
45
+ "outputs": [],
46
+ "source": [
47
+ "from tools.preprocess import *\n",
48
+ "# 1. Identify the paths to the SOFT file and the matrix file\n",
49
+ "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
50
+ "\n",
51
+ "# 2. Read the matrix file to obtain background information and sample characteristics data\n",
52
+ "background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']\n",
53
+ "clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']\n",
54
+ "background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)\n",
55
+ "\n",
56
+ "# 3. Obtain the sample characteristics dictionary from the clinical dataframe\n",
57
+ "sample_characteristics_dict = get_unique_values_by_row(clinical_data)\n",
58
+ "\n",
59
+ "# 4. Explicitly print out all the background information and the sample characteristics dictionary\n",
60
+ "print(\"Background Information:\")\n",
61
+ "print(background_info)\n",
62
+ "print(\"Sample Characteristics Dictionary:\")\n",
63
+ "print(sample_characteristics_dict)\n"
64
+ ]
65
+ },
66
+ {
67
+ "cell_type": "markdown",
68
+ "id": "587b0c60",
69
+ "metadata": {},
70
+ "source": [
71
+ "### Step 2: Dataset Analysis and Clinical Feature Extraction"
72
+ ]
73
+ },
74
+ {
75
+ "cell_type": "code",
76
+ "execution_count": null,
77
+ "id": "ecc90421",
78
+ "metadata": {},
79
+ "outputs": [],
80
+ "source": [
81
+ "# 1. Gene Expression Data Availability\n",
82
+ "# Based on the Series_overall_design, this dataset contains DNA microarray analysis of B and T cells\n",
83
+ "is_gene_available = True # DNA microarray data is gene expression data\n",
84
+ "\n",
85
+ "# 2. Variable Availability and Data Type Conversion\n",
86
+ "# 2.1 Data Availability\n",
87
+ "\n",
88
+ "# For trait: looking at row 5 which contains 'biopsy data, villus height to crypt depth'\n",
89
+ "# This measures the severity of the disease (villus atrophy) which can serve as our trait\n",
90
+ "trait_row = 5\n",
91
+ "\n",
92
+ "# For age: There is no age information in the sample characteristics\n",
93
+ "age_row = None\n",
94
+ "\n",
95
+ "# For gender: There is no gender information in the sample characteristics\n",
96
+ "gender_row = None\n",
97
+ "\n",
98
+ "# 2.2 Data Type Conversion Functions\n",
99
+ "\n",
100
+ "def convert_trait(value):\n",
101
+ " \"\"\"\n",
102
+ " Convert the villus height to crypt depth ratio to a continuous value.\n",
103
+ " Higher values indicate healthier intestinal tissue (less disease severity).\n",
104
+ " Lower values indicate more severe celiac disease activity.\n",
105
+ " \"\"\"\n",
106
+ " if value is None:\n",
107
+ " return None\n",
108
+ " \n",
109
+ " # Extract the numeric value after the colon\n",
110
+ " if ':' in value:\n",
111
+ " try:\n",
112
+ " # The value is in format \"biopsy data, villus height to crypt depth: X.X\"\n",
113
+ " return float(value.split(':')[1].strip())\n",
114
+ " except (ValueError, IndexError):\n",
115
+ " return None\n",
116
+ " else:\n",
117
+ " try:\n",
118
+ " return float(value)\n",
119
+ " except ValueError:\n",
120
+ " return None\n",
121
+ "\n",
122
+ "# Age and gender conversion functions are defined but won't be used\n",
123
+ "def convert_age(value):\n",
124
+ " if value is None:\n",
125
+ " return None\n",
126
+ " \n",
127
+ " if ':' in value:\n",
128
+ " try:\n",
129
+ " return float(value.split(':')[1].strip())\n",
130
+ " except (ValueError, IndexError):\n",
131
+ " return None\n",
132
+ " else:\n",
133
+ " try:\n",
134
+ " return float(value)\n",
135
+ " except ValueError:\n",
136
+ " return None\n",
137
+ "\n",
138
+ "def convert_gender(value):\n",
139
+ " if value is None:\n",
140
+ " return None\n",
141
+ " \n",
142
+ " if ':' in value:\n",
143
+ " value = value.split(':')[1].strip().lower()\n",
144
+ " else:\n",
145
+ " value = value.lower()\n",
146
+ " \n",
147
+ " if value in ['female', 'f']:\n",
148
+ " return 0\n",
149
+ " elif value in ['male', 'm']:\n",
150
+ " return 1\n",
151
+ " else:\n",
152
+ " return None\n",
153
+ "\n",
154
+ "# 3. Save Metadata\n",
155
+ "# Determine trait data availability\n",
156
+ "is_trait_available = trait_row is not None\n",
157
+ "\n",
158
+ "# Save initial filtering information\n",
159
+ "validate_and_save_cohort_info(\n",
160
+ " is_final=False,\n",
161
+ " cohort=cohort,\n",
162
+ " info_path=json_path,\n",
163
+ " is_gene_available=is_gene_available,\n",
164
+ " is_trait_available=is_trait_available\n",
165
+ ")\n",
166
+ "\n",
167
+ "# 4. Clinical Feature Extraction\n",
168
+ "if trait_row is not None:\n",
169
+ " # Create a DataFrame from the Sample Characteristics Dictionary shown in the previous output\n",
170
+ " sample_characteristics = {\n",
171
+ " 0: ['individual: celiac patient A', 'individual: celiac patient C', 'individual: celiac patient G', 'individual: celiac patient H', 'individual: celiac patient K', 'individual: celiac patient L', 'individual: celiac patient M', 'individual: celiac patient N', 'individual: celiac patient O', 'individual: celiac patient P', 'individual: celiac patient Q', 'individual: celiac patient R', 'individual: celiac patient S', 'individual: celiac patient T', 'individual: celiac patient U', 'individual: celiac patient V', 'individual: celiac patient W', 'individual: celiac patient X', 'individual: celiac patient Y', 'individual: celiac patient Z'],\n",
172
+ " 1: ['disease state: biopsy confirmed celiac disease on gluten-free diet greater than one year'],\n",
173
+ " 2: ['treatment: control', 'treatment: 6 weeks gluten challenge'],\n",
174
+ " 3: ['tissue: peripheral whole blood'],\n",
175
+ " 4: ['cell type: purified pool of B and T cells'],\n",
176
+ " 5: ['biopsy data, villus height to crypt depth: 2.9', 'biopsy data, villus height to crypt depth: 2.6', 'biopsy data, villus height to crypt depth: 1.1', 'biopsy data, villus height to crypt depth: 0.5', 'biopsy data, villus height to crypt depth: 0.3', 'biopsy data, villus height to crypt depth: 2', 'biopsy data, villus height to crypt depth: 0.4', 'biopsy data, villus height to crypt depth: 2.4', 'biopsy data, villus height to crypt depth: 1.4', 'biopsy data, villus height to crypt depth: 2.7', 'biopsy data, villus height to crypt depth: 3.5', 'biopsy data, villus height to crypt depth: 0.7', 'biopsy data, villus height to crypt depth: 0.2', 'biopsy data, villus height to crypt depth: 2.8', 'biopsy data, villus height to crypt depth: 3', 'biopsy data, villus height to crypt depth: 0.8', 'biopsy data, villus height to crypt depth: 1.2', 'biopsy data, villus height to crypt depth: 1.7', 'biopsy data, villus height to crypt depth: 2.5', 'biopsy data, villus height to crypt depth: 2.1', 'biopsy data, villus height to crypt depth: 3.1'],\n",
177
+ " 6: ['hybridization batch: 1']\n",
178
+ " }\n",
179
+ " \n",
180
+ " # Convert the dictionary to a DataFrame\n",
181
+ " clinical_data = pd.DataFrame.from_dict(sample_characteristics, orient='index')\n",
182
+ " \n",
183
+ " # Extract clinical features using the library function\n",
184
+ " selected_clinical_df = geo_select_clinical_features(\n",
185
+ " clinical_df=clinical_data,\n",
186
+ " trait=trait,\n",
187
+ " trait_row=trait_row,\n",
188
+ " convert_trait=convert_trait,\n",
189
+ " age_row=age_row,\n",
190
+ " convert_age=convert_age,\n",
191
+ " gender_row=gender_row,\n",
192
+ " convert_gender=convert_gender\n",
193
+ " )\n",
194
+ " \n",
195
+ " # Preview the extracted clinical features\n",
196
+ " preview = preview_df(selected_clinical_df)\n",
197
+ " print(\"Preview of clinical data:\")\n",
198
+ " print(preview)\n",
199
+ " \n",
200
+ " # Save the clinical data\n",
201
+ " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
202
+ " selected_clinical_df.to_csv(out_clinical_data_file, index=False)\n",
203
+ " print(f\"Clinical data saved to {out_clinical_data_file}\")\n"
204
+ ]
205
+ },
206
+ {
207
+ "cell_type": "markdown",
208
+ "id": "2d2a3dd8",
209
+ "metadata": {},
210
+ "source": [
211
+ "### Step 3: Gene Data Extraction"
212
+ ]
213
+ },
214
+ {
215
+ "cell_type": "code",
216
+ "execution_count": null,
217
+ "id": "55d5ab0d",
218
+ "metadata": {},
219
+ "outputs": [],
220
+ "source": [
221
+ "# 1. Get the file paths for the SOFT file and matrix file\n",
222
+ "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
223
+ "\n",
224
+ "# 2. First, let's examine the structure of the matrix file to understand its format\n",
225
+ "import gzip\n",
226
+ "\n",
227
+ "# Peek at the first few lines of the file to understand its structure\n",
228
+ "with gzip.open(matrix_file, 'rt') as file:\n",
229
+ " # Read first 100 lines to find the header structure\n",
230
+ " for i, line in enumerate(file):\n",
231
+ " if '!series_matrix_table_begin' in line:\n",
232
+ " print(f\"Found data marker at line {i}\")\n",
233
+ " # Read the next line which should be the header\n",
234
+ " header_line = next(file)\n",
235
+ " print(f\"Header line: {header_line.strip()}\")\n",
236
+ " # And the first data line\n",
237
+ " first_data_line = next(file)\n",
238
+ " print(f\"First data line: {first_data_line.strip()}\")\n",
239
+ " break\n",
240
+ " if i > 100: # Limit search to first 100 lines\n",
241
+ " print(\"Matrix table marker not found in first 100 lines\")\n",
242
+ " break\n",
243
+ "\n",
244
+ "# 3. Now try to get the genetic data with better error handling\n",
245
+ "try:\n",
246
+ " gene_data = get_genetic_data(matrix_file)\n",
247
+ " print(gene_data.index[:20])\n",
248
+ "except KeyError as e:\n",
249
+ " print(f\"KeyError: {e}\")\n",
250
+ " \n",
251
+ " # Alternative approach: manually extract the data\n",
252
+ " print(\"\\nTrying alternative approach to read the gene data:\")\n",
253
+ " with gzip.open(matrix_file, 'rt') as file:\n",
254
+ " # Find the start of the data\n",
255
+ " for line in file:\n",
256
+ " if '!series_matrix_table_begin' in line:\n",
257
+ " break\n",
258
+ " \n",
259
+ " # Read the headers and data\n",
260
+ " import pandas as pd\n",
261
+ " df = pd.read_csv(file, sep='\\t', index_col=0)\n",
262
+ " print(f\"Column names: {df.columns[:5]}\")\n",
263
+ " print(f\"First 20 row IDs: {df.index[:20]}\")\n",
264
+ " gene_data = df\n"
265
+ ]
266
+ },
267
+ {
268
+ "cell_type": "markdown",
269
+ "id": "6101c34d",
270
+ "metadata": {},
271
+ "source": [
272
+ "### Step 4: Gene Identifier Review"
273
+ ]
274
+ },
275
+ {
276
+ "cell_type": "code",
277
+ "execution_count": null,
278
+ "id": "25a895d7",
279
+ "metadata": {},
280
+ "outputs": [],
281
+ "source": [
282
+ "# From the identifiers shown, we can observe that the gene identifiers are in the format \"ILMN_xxxxxxx\".\n",
283
+ "# This format indicates that they are Illumina probe IDs, not standard human gene symbols.\n",
284
+ "# Illumina probe IDs need to be mapped to human gene symbols for proper analysis.\n",
285
+ "\n",
286
+ "requires_gene_mapping = True\n"
287
+ ]
288
+ },
289
+ {
290
+ "cell_type": "markdown",
291
+ "id": "7f8514c0",
292
+ "metadata": {},
293
+ "source": [
294
+ "### Step 5: Gene Annotation"
295
+ ]
296
+ },
297
+ {
298
+ "cell_type": "code",
299
+ "execution_count": null,
300
+ "id": "3cbdaf90",
301
+ "metadata": {},
302
+ "outputs": [],
303
+ "source": [
304
+ "# 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.\n",
305
+ "gene_annotation = get_gene_annotation(soft_file)\n",
306
+ "\n",
307
+ "# 2. Use the 'preview_df' function from the library to preview the data and print out the results.\n",
308
+ "print(\"Gene annotation preview:\")\n",
309
+ "print(preview_df(gene_annotation))\n"
310
+ ]
311
+ },
312
+ {
313
+ "cell_type": "markdown",
314
+ "id": "2896a2b3",
315
+ "metadata": {},
316
+ "source": [
317
+ "### Step 6: Gene Identifier Mapping"
318
+ ]
319
+ },
320
+ {
321
+ "cell_type": "code",
322
+ "execution_count": null,
323
+ "id": "0b5f9f09",
324
+ "metadata": {},
325
+ "outputs": [],
326
+ "source": [
327
+ "# 1. Identify the appropriate column names for gene identifiers and gene symbols\n",
328
+ "# From the gene_annotation preview, we see:\n",
329
+ "# - 'ID' column contains Illumina probe IDs (e.g., ILMN_1725881) which match our gene expression data index\n",
330
+ "# - 'Symbol' column contains the gene symbols we want to map to (e.g., LOC23117, FCGR2B, TRIM44)\n",
331
+ "\n",
332
+ "# 2. Get gene mapping dataframe by extracting the two columns\n",
333
+ "gene_mapping = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='Symbol')\n",
334
+ "\n",
335
+ "# Print the first few rows to verify the mapping\n",
336
+ "print(\"Gene mapping preview:\")\n",
337
+ "print(preview_df(gene_mapping))\n",
338
+ "\n",
339
+ "# 3. Apply gene mapping to convert probe-level measurements to gene expression data\n",
340
+ "# Using the library function that distributes probe values across multiple genes and sums by gene\n",
341
+ "gene_data = apply_gene_mapping(gene_data, gene_mapping)\n",
342
+ "\n",
343
+ "# Print the first few rows to verify the mapped gene expression data\n",
344
+ "print(\"\\nGene expression data preview (after mapping):\")\n",
345
+ "print(preview_df(gene_data))\n",
346
+ "\n",
347
+ "# Save the gene expression data\n",
348
+ "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
349
+ "gene_data.to_csv(out_gene_data_file)\n",
350
+ "print(f\"Gene expression data saved to {out_gene_data_file}\")\n"
351
+ ]
352
+ },
353
+ {
354
+ "cell_type": "markdown",
355
+ "id": "e9453534",
356
+ "metadata": {},
357
+ "source": [
358
+ "### Step 7: Data Normalization and Linking"
359
+ ]
360
+ },
361
+ {
362
+ "cell_type": "code",
363
+ "execution_count": null,
364
+ "id": "b44a07b8",
365
+ "metadata": {},
366
+ "outputs": [],
367
+ "source": [
368
+ "# 1. Normalize gene symbols in the gene expression data\n",
369
+ "normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n",
370
+ "print(f\"Normalized gene data shape: {normalized_gene_data.shape}\")\n",
371
+ "print(\"First few genes with their expression values after normalization:\")\n",
372
+ "print(normalized_gene_data.head())\n",
373
+ "\n",
374
+ "# Save the normalized gene data\n",
375
+ "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
376
+ "normalized_gene_data.to_csv(out_gene_data_file)\n",
377
+ "print(f\"Normalized gene data saved to {out_gene_data_file}\")\n",
378
+ "\n",
379
+ "# 2. Load the clinical data\n",
380
+ "# First, let's read the clinical data that was saved in step 2\n",
381
+ "clinical_df = pd.read_csv(out_clinical_data_file)\n",
382
+ "\n",
383
+ "# The clinical data is loaded but it might not have the trait name as a column\n",
384
+ "# We need to set the first column as the trait column\n",
385
+ "clinical_df.columns = [trait]\n",
386
+ "print(\"Clinical data preview:\")\n",
387
+ "print(clinical_df.head())\n",
388
+ "\n",
389
+ "# Create a transposed version for linking with gene data (samples as columns)\n",
390
+ "clinical_df_t = clinical_df.T\n",
391
+ "print(\"Transposed clinical data shape:\", clinical_df_t.shape)\n",
392
+ "\n",
393
+ "# 3. Link the clinical and genetic data\n",
394
+ "linked_data = pd.concat([clinical_df_t, normalized_gene_data]).T\n",
395
+ "print(f\"Linked data shape (before handling missing values): {linked_data.shape}\")\n",
396
+ "\n",
397
+ "# 4. Handle missing values in the linked data\n",
398
+ "linked_data = handle_missing_values(linked_data, trait)\n",
399
+ "print(f\"Data after handling missing values: {linked_data.shape}\")\n",
400
+ "\n",
401
+ "# 5. Determine whether the trait and demographic features are biased\n",
402
+ "is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)\n",
403
+ "\n",
404
+ "# 6. Conduct final quality validation and save cohort information\n",
405
+ "is_usable = validate_and_save_cohort_info(\n",
406
+ " is_final=True, \n",
407
+ " cohort=cohort, \n",
408
+ " info_path=json_path, \n",
409
+ " is_gene_available=True, \n",
410
+ " is_trait_available=True, \n",
411
+ " is_biased=is_trait_biased, \n",
412
+ " df=unbiased_linked_data,\n",
413
+ " note=\"Dataset contains villus height to crypt depth ratio measurements in celiac disease patients, which reflects disease severity.\"\n",
414
+ ")\n",
415
+ "\n",
416
+ "# 7. If the linked data is usable, save it\n",
417
+ "if is_usable:\n",
418
+ " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n",
419
+ " unbiased_linked_data.to_csv(out_data_file)\n",
420
+ " print(f\"Linked data saved to {out_data_file}\")\n",
421
+ "else:\n",
422
+ " print(\"Data was determined to be unusable and was not saved\")\n"
423
+ ]
424
+ },
425
+ {
426
+ "cell_type": "markdown",
427
+ "id": "c79be5e3",
428
+ "metadata": {},
429
+ "source": [
430
+ "### Step 8: Data Normalization and Linking"
431
+ ]
432
+ },
433
+ {
434
+ "cell_type": "code",
435
+ "execution_count": null,
436
+ "id": "5b03847f",
437
+ "metadata": {},
438
+ "outputs": [],
439
+ "source": [
440
+ "# 1. Normalize gene symbols in the gene expression data\n",
441
+ "normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n",
442
+ "print(f\"Normalized gene data shape: {normalized_gene_data.shape}\")\n",
443
+ "print(\"First few genes with their expression values after normalization:\")\n",
444
+ "print(normalized_gene_data.head())\n",
445
+ "\n",
446
+ "# Save the normalized gene data\n",
447
+ "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
448
+ "normalized_gene_data.to_csv(out_gene_data_file)\n",
449
+ "print(f\"Normalized gene data saved to {out_gene_data_file}\")\n",
450
+ "\n",
451
+ "# 2. Extract clinical features using the functions defined in step 2\n",
452
+ "# First, let's load the clinical data again to ensure we have the latest version\n",
453
+ "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
454
+ "background_info, clinical_data = get_background_and_clinical_data(matrix_file)\n",
455
+ "\n",
456
+ "# Extract clinical features using the correct trait name from the variable\n",
457
+ "selected_clinical_df = geo_select_clinical_features(\n",
458
+ " clinical_data, \n",
459
+ " trait=trait, \n",
460
+ " trait_row=trait_row, \n",
461
+ " convert_trait=convert_trait,\n",
462
+ " age_row=age_row,\n",
463
+ " convert_age=convert_age,\n",
464
+ " gender_row=gender_row,\n",
465
+ " convert_gender=convert_gender\n",
466
+ ")\n",
467
+ "\n",
468
+ "# Save the clinical data\n",
469
+ "os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
470
+ "selected_clinical_df.to_csv(out_clinical_data_file)\n",
471
+ "print(f\"Clinical data saved to {out_clinical_data_file}\")\n",
472
+ "print(\"Clinical data preview:\")\n",
473
+ "print(preview_df(selected_clinical_df))\n",
474
+ "\n",
475
+ "# 3. Link the clinical and genetic data\n",
476
+ "linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)\n",
477
+ "print(f\"Linked data shape (before handling missing values): {linked_data.shape}\")\n",
478
+ "\n",
479
+ "# 4. Handle missing values in the linked data\n",
480
+ "linked_data = handle_missing_values(linked_data, trait)\n",
481
+ "print(f\"Data after handling missing values: {linked_data.shape}\")\n",
482
+ "\n",
483
+ "# 5. Determine whether the trait and demographic features are biased\n",
484
+ "# Check if trait is biased\n",
485
+ "trait_type = 'binary' if len(linked_data[trait].unique()) == 2 else 'continuous'\n",
486
+ "if trait_type == \"binary\":\n",
487
+ " is_trait_biased = judge_binary_variable_biased(linked_data, trait)\n",
488
+ "else:\n",
489
+ " is_trait_biased = judge_continuous_variable_biased(linked_data, trait)\n",
490
+ "\n",
491
+ "# Remove biased demographic features if present\n",
492
+ "unbiased_linked_data = linked_data.copy()\n",
493
+ "if \"Age\" in unbiased_linked_data.columns:\n",
494
+ " age_biased = judge_continuous_variable_biased(unbiased_linked_data, 'Age')\n",
495
+ " if age_biased:\n",
496
+ " print(f\"The distribution of the feature 'Age' in this dataset is severely biased.\")\n",
497
+ " unbiased_linked_data = unbiased_linked_data.drop(columns='Age')\n",
498
+ " else:\n",
499
+ " print(f\"The distribution of the feature 'Age' in this dataset is fine.\")\n",
500
+ "\n",
501
+ "if \"Gender\" in unbiased_linked_data.columns:\n",
502
+ " gender_biased = judge_binary_variable_biased(unbiased_linked_data, 'Gender')\n",
503
+ " if gender_biased:\n",
504
+ " print(f\"The distribution of the feature 'Gender' in this dataset is severely biased.\")\n",
505
+ " unbiased_linked_data = unbiased_linked_data.drop(columns='Gender')\n",
506
+ " else:\n",
507
+ " print(f\"The distribution of the feature 'Gender' in this dataset is fine.\")\n",
508
+ "\n",
509
+ "# 6. Conduct final quality validation and save cohort information\n",
510
+ "is_usable = validate_and_save_cohort_info(\n",
511
+ " is_final=True, \n",
512
+ " cohort=cohort, \n",
513
+ " info_path=json_path, \n",
514
+ " is_gene_available=True, \n",
515
+ " is_trait_available=True, \n",
516
+ " is_biased=is_trait_biased, \n",
517
+ " df=unbiased_linked_data,\n",
518
+ " note=\"Dataset contains villus height to crypt depth ratio measurements in celiac disease patients, which reflects disease severity when studied for Creutzfeldt-Jakob_Disease.\"\n",
519
+ ")\n",
520
+ "\n",
521
+ "# 7. If the linked data is usable, save it\n",
522
+ "if is_usable:\n",
523
+ " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n",
524
+ " unbiased_linked_data.to_csv(out_data_file)\n",
525
+ " print(f\"Linked data saved to {out_data_file}\")\n",
526
+ "else:\n",
527
+ " print(\"Data was determined to be unusable and was not saved\")"
528
+ ]
529
+ }
530
+ ],
531
+ "metadata": {},
532
+ "nbformat": 4,
533
+ "nbformat_minor": 5
534
+ }
code/Creutzfeldt-Jakob_Disease/TCGA.ipynb ADDED
@@ -0,0 +1,158 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": 1,
6
+ "id": "49a1150d",
7
+ "metadata": {
8
+ "execution": {
9
+ "iopub.execute_input": "2025-03-25T08:31:52.950278Z",
10
+ "iopub.status.busy": "2025-03-25T08:31:52.950095Z",
11
+ "iopub.status.idle": "2025-03-25T08:31:53.114459Z",
12
+ "shell.execute_reply": "2025-03-25T08:31:53.114025Z"
13
+ }
14
+ },
15
+ "outputs": [],
16
+ "source": [
17
+ "import sys\n",
18
+ "import os\n",
19
+ "sys.path.append(os.path.abspath(os.path.join(os.getcwd(), '../..')))\n",
20
+ "\n",
21
+ "# Path Configuration\n",
22
+ "from tools.preprocess import *\n",
23
+ "\n",
24
+ "# Processing context\n",
25
+ "trait = \"Creutzfeldt-Jakob_Disease\"\n",
26
+ "\n",
27
+ "# Input paths\n",
28
+ "tcga_root_dir = \"../../input/TCGA\"\n",
29
+ "\n",
30
+ "# Output paths\n",
31
+ "out_data_file = \"../../output/preprocess/Creutzfeldt-Jakob_Disease/TCGA.csv\"\n",
32
+ "out_gene_data_file = \"../../output/preprocess/Creutzfeldt-Jakob_Disease/gene_data/TCGA.csv\"\n",
33
+ "out_clinical_data_file = \"../../output/preprocess/Creutzfeldt-Jakob_Disease/clinical_data/TCGA.csv\"\n",
34
+ "json_path = \"../../output/preprocess/Creutzfeldt-Jakob_Disease/cohort_info.json\"\n"
35
+ ]
36
+ },
37
+ {
38
+ "cell_type": "markdown",
39
+ "id": "0bb7174a",
40
+ "metadata": {},
41
+ "source": [
42
+ "### Step 1: Initial Data Loading"
43
+ ]
44
+ },
45
+ {
46
+ "cell_type": "code",
47
+ "execution_count": 2,
48
+ "id": "9cb1d690",
49
+ "metadata": {
50
+ "execution": {
51
+ "iopub.execute_input": "2025-03-25T08:31:53.115713Z",
52
+ "iopub.status.busy": "2025-03-25T08:31:53.115574Z",
53
+ "iopub.status.idle": "2025-03-25T08:31:53.121254Z",
54
+ "shell.execute_reply": "2025-03-25T08:31:53.120741Z"
55
+ }
56
+ },
57
+ "outputs": [
58
+ {
59
+ "name": "stdout",
60
+ "output_type": "stream",
61
+ "text": [
62
+ "No suitable directory found for Creutzfeldt-Jakob_Disease.\n",
63
+ "Skipping this trait as no suitable data was found.\n"
64
+ ]
65
+ }
66
+ ],
67
+ "source": [
68
+ "import os\n",
69
+ "import pandas as pd\n",
70
+ "\n",
71
+ "# 1. Find the most relevant directory for Colon and Rectal Cancer\n",
72
+ "subdirectories = os.listdir(tcga_root_dir)\n",
73
+ "target_trait = trait.lower().replace(\"_\", \" \") # Convert to lowercase for case-insensitive matching\n",
74
+ "\n",
75
+ "# Start with no match, then find the best match based on similarity to target trait\n",
76
+ "best_match = None\n",
77
+ "best_match_score = 0\n",
78
+ "\n",
79
+ "for subdir in subdirectories:\n",
80
+ " subdir_lower = subdir.lower()\n",
81
+ " \n",
82
+ " # Calculate a simple similarity score - more matching words = better match\n",
83
+ " # This prioritizes exact matches over partial matches\n",
84
+ " score = 0\n",
85
+ " for word in target_trait.split():\n",
86
+ " if word in subdir_lower:\n",
87
+ " score += 1\n",
88
+ " \n",
89
+ " # Track the best match\n",
90
+ " if score > best_match_score:\n",
91
+ " best_match_score = score\n",
92
+ " best_match = subdir\n",
93
+ " print(f\"Found potential match: {subdir} (score: {score})\")\n",
94
+ "\n",
95
+ "# Use the best match if found\n",
96
+ "if best_match:\n",
97
+ " print(f\"Selected directory: {best_match}\")\n",
98
+ " \n",
99
+ " # 2. Get the clinical and genetic data file paths\n",
100
+ " cohort_dir = os.path.join(tcga_root_dir, best_match)\n",
101
+ " clinical_file_path, genetic_file_path = tcga_get_relevant_filepaths(cohort_dir)\n",
102
+ " \n",
103
+ " print(f\"Clinical file: {os.path.basename(clinical_file_path)}\")\n",
104
+ " print(f\"Genetic file: {os.path.basename(genetic_file_path)}\")\n",
105
+ " \n",
106
+ " # 3. Load the data files\n",
107
+ " clinical_df = pd.read_csv(clinical_file_path, sep='\\t', index_col=0)\n",
108
+ " genetic_df = pd.read_csv(genetic_file_path, sep='\\t', index_col=0)\n",
109
+ " \n",
110
+ " # 4. Print clinical data columns for inspection\n",
111
+ " print(\"\\nClinical data columns:\")\n",
112
+ " print(clinical_df.columns.tolist())\n",
113
+ " \n",
114
+ " # Print basic information about the datasets\n",
115
+ " print(f\"\\nClinical data shape: {clinical_df.shape}\")\n",
116
+ " print(f\"Genetic data shape: {genetic_df.shape}\")\n",
117
+ " \n",
118
+ " # Check if we have both gene and trait data\n",
119
+ " is_gene_available = genetic_df.shape[0] > 0\n",
120
+ " is_trait_available = clinical_df.shape[0] > 0\n",
121
+ " \n",
122
+ "else:\n",
123
+ " print(f\"No suitable directory found for {trait}.\")\n",
124
+ " is_gene_available = False\n",
125
+ " is_trait_available = False\n",
126
+ "\n",
127
+ "# Record the data availability\n",
128
+ "validate_and_save_cohort_info(\n",
129
+ " is_final=False,\n",
130
+ " cohort=\"TCGA\",\n",
131
+ " info_path=json_path,\n",
132
+ " is_gene_available=is_gene_available,\n",
133
+ " is_trait_available=is_trait_available\n",
134
+ ")\n",
135
+ "\n",
136
+ "# Exit if no suitable directory was found\n",
137
+ "if not best_match:\n",
138
+ " print(\"Skipping this trait as no suitable data was found.\")"
139
+ ]
140
+ }
141
+ ],
142
+ "metadata": {
143
+ "language_info": {
144
+ "codemirror_mode": {
145
+ "name": "ipython",
146
+ "version": 3
147
+ },
148
+ "file_extension": ".py",
149
+ "mimetype": "text/x-python",
150
+ "name": "python",
151
+ "nbconvert_exporter": "python",
152
+ "pygments_lexer": "ipython3",
153
+ "version": "3.10.16"
154
+ }
155
+ },
156
+ "nbformat": 4,
157
+ "nbformat_minor": 5
158
+ }
code/Crohns_Disease/GSE123086.ipynb ADDED
@@ -0,0 +1,688 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": 1,
6
+ "id": "5d925014",
7
+ "metadata": {
8
+ "execution": {
9
+ "iopub.execute_input": "2025-03-25T08:31:53.915251Z",
10
+ "iopub.status.busy": "2025-03-25T08:31:53.914941Z",
11
+ "iopub.status.idle": "2025-03-25T08:31:54.083683Z",
12
+ "shell.execute_reply": "2025-03-25T08:31:54.083335Z"
13
+ }
14
+ },
15
+ "outputs": [],
16
+ "source": [
17
+ "import sys\n",
18
+ "import os\n",
19
+ "sys.path.append(os.path.abspath(os.path.join(os.getcwd(), '../..')))\n",
20
+ "\n",
21
+ "# Path Configuration\n",
22
+ "from tools.preprocess import *\n",
23
+ "\n",
24
+ "# Processing context\n",
25
+ "trait = \"Crohns_Disease\"\n",
26
+ "cohort = \"GSE123086\"\n",
27
+ "\n",
28
+ "# Input paths\n",
29
+ "in_trait_dir = \"../../input/GEO/Crohns_Disease\"\n",
30
+ "in_cohort_dir = \"../../input/GEO/Crohns_Disease/GSE123086\"\n",
31
+ "\n",
32
+ "# Output paths\n",
33
+ "out_data_file = \"../../output/preprocess/Crohns_Disease/GSE123086.csv\"\n",
34
+ "out_gene_data_file = \"../../output/preprocess/Crohns_Disease/gene_data/GSE123086.csv\"\n",
35
+ "out_clinical_data_file = \"../../output/preprocess/Crohns_Disease/clinical_data/GSE123086.csv\"\n",
36
+ "json_path = \"../../output/preprocess/Crohns_Disease/cohort_info.json\"\n"
37
+ ]
38
+ },
39
+ {
40
+ "cell_type": "markdown",
41
+ "id": "b178ae1b",
42
+ "metadata": {},
43
+ "source": [
44
+ "### Step 1: Initial Data Loading"
45
+ ]
46
+ },
47
+ {
48
+ "cell_type": "code",
49
+ "execution_count": 2,
50
+ "id": "da850c1f",
51
+ "metadata": {
52
+ "execution": {
53
+ "iopub.execute_input": "2025-03-25T08:31:54.085116Z",
54
+ "iopub.status.busy": "2025-03-25T08:31:54.084957Z",
55
+ "iopub.status.idle": "2025-03-25T08:31:54.313403Z",
56
+ "shell.execute_reply": "2025-03-25T08:31:54.312963Z"
57
+ }
58
+ },
59
+ "outputs": [
60
+ {
61
+ "name": "stdout",
62
+ "output_type": "stream",
63
+ "text": [
64
+ "Background Information:\n",
65
+ "!Series_title\t\"A validated single-cell-based strategy to identify diagnostic and therapeutic targets in complex diseases [study of 13 diseases]\"\n",
66
+ "!Series_summary\t\"We conducted prospective clinical studies to validate the importance of CD4+ T cells in 13 diseases from the following ICD-10-CM chapters: Neoplasms (breast cancer, chronic lymphocytic leukemia); endocrine, nutritional and metabolic diseases (type I diabetes, obesity); diseases of the circulatory system (atherosclerosis); diseases of the respiratory system (acute tonsillitis, influenza, seasonal allergic rhinitis, asthma); diseases of the digestive system (Crohn’s disease [CD], ulcerative colitis [UC]); and diseases of the skin and subcutaneous tissue (atopic eczema, psoriatic diseases).\"\n",
67
+ "!Series_summary\t\"Study participants were recruited by clinical specialists based on diagnostic criteria defined by organizations representing each specialist’s discipline. Age and gender matched healthy controls (n = 127 and 39, respectively) were recruited in the Southeast region of Sweden from outpatient clinics at the University Hospital, Linköping; Ryhov County Hospital, Jönköping, a primary health care center in Jönköping; and a medical specialist unit for children in Värnamo. Study participants represented both urban and rural populations with an age range of 8–94 years. Patients with type I diabetes and obesity had an age range of 8–18 years. 12 patients had more than one diagnosis.\"\n",
68
+ "!Series_overall_design\t\"Total RNA was extracted using the AllPrep DNA/RNA Micro kit (Qiagen, Hilden, Germany; cat. no. 80284) according to the manufacturer’s instructions. RNA concentration and integrity were evaluated using the Agilent RNA 6000 Nano Kit (Agilent Technologies, Santa Clara, California, USA; cat. no. 5067-1511) on an Agilent 2100 Bioanalyzer (Agilent Technologies, Santa Clara, California, USA). Microarrays were then further computationally processed as described in One-Color Microarray-Based Gene Expression Analysis Low Input Quick Amp Labeling protocol (Agilent Technologies, Santa Clara, California, USA).\"\n",
69
+ "Sample Characteristics Dictionary:\n",
70
+ "{0: ['cell type: CD4+ T cells'], 1: ['primary diagnosis: ASTHMA', 'primary diagnosis: ATHEROSCLEROSIS', 'primary diagnosis: BREAST_CANCER', 'primary diagnosis: CHRONIC_LYMPHOCYTIC_LEUKEMIA', 'primary diagnosis: CROHN_DISEASE', 'primary diagnosis: ATOPIC_ECZEMA', 'primary diagnosis: HEALTHY_CONTROL', 'primary diagnosis: INFLUENZA', 'primary diagnosis: OBESITY', 'primary diagnosis: PSORIASIS', 'primary diagnosis: SEASONAL_ALLERGIC_RHINITIS', 'primary diagnosis: TYPE_1_DIABETES', 'primary diagnosis: ACUTE_TONSILLITIS', 'primary diagnosis: ULCERATIVE_COLITIS'], 2: ['Sex: Male', 'diagnosis2: ATOPIC_ECZEMA', 'Sex: Female', 'diagnosis2: ATHEROSCLEROSIS', 'diagnosis2: ASTHMA_OBESITY', 'diagnosis2: ASTHMA', 'diagnosis2: ASTMHA_SEASONAL_ALLERGIC_RHINITIS', 'diagnosis2: OBESITY'], 3: ['age: 56', 'Sex: Male', 'age: 20', 'age: 51', 'age: 37', 'age: 61', 'age: 31', 'age: 41', 'age: 80', 'age: 53', 'age: 73', 'age: 60', 'age: 76', 'age: 77', 'age: 74', 'age: 69', 'age: 81', 'age: 70', 'age: 82', 'age: 67', 'age: 78', 'age: 72', 'age: 66', 'age: 36', 'age: 45', 'age: 65', 'age: 48', 'age: 50', 'age: 24', 'age: 42'], 4: [nan, 'age: 63', 'age: 74', 'age: 49', 'age: 60', 'age: 68', 'age: 38', 'age: 16', 'age: 12', 'age: 27']}\n"
71
+ ]
72
+ }
73
+ ],
74
+ "source": [
75
+ "from tools.preprocess import *\n",
76
+ "# 1. Identify the paths to the SOFT file and the matrix file\n",
77
+ "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
78
+ "\n",
79
+ "# 2. Read the matrix file to obtain background information and sample characteristics data\n",
80
+ "background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']\n",
81
+ "clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']\n",
82
+ "background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)\n",
83
+ "\n",
84
+ "# 3. Obtain the sample characteristics dictionary from the clinical dataframe\n",
85
+ "sample_characteristics_dict = get_unique_values_by_row(clinical_data)\n",
86
+ "\n",
87
+ "# 4. Explicitly print out all the background information and the sample characteristics dictionary\n",
88
+ "print(\"Background Information:\")\n",
89
+ "print(background_info)\n",
90
+ "print(\"Sample Characteristics Dictionary:\")\n",
91
+ "print(sample_characteristics_dict)\n"
92
+ ]
93
+ },
94
+ {
95
+ "cell_type": "markdown",
96
+ "id": "e5154371",
97
+ "metadata": {},
98
+ "source": [
99
+ "### Step 2: Dataset Analysis and Clinical Feature Extraction"
100
+ ]
101
+ },
102
+ {
103
+ "cell_type": "code",
104
+ "execution_count": 3,
105
+ "id": "e7bb312b",
106
+ "metadata": {
107
+ "execution": {
108
+ "iopub.execute_input": "2025-03-25T08:31:54.314843Z",
109
+ "iopub.status.busy": "2025-03-25T08:31:54.314732Z",
110
+ "iopub.status.idle": "2025-03-25T08:31:54.337797Z",
111
+ "shell.execute_reply": "2025-03-25T08:31:54.337511Z"
112
+ }
113
+ },
114
+ "outputs": [
115
+ {
116
+ "name": "stdout",
117
+ "output_type": "stream",
118
+ "text": [
119
+ "Preview of selected clinical features:\n",
120
+ "{'GSM3494884': [nan, 56.0, 1.0], 'GSM3494885': [nan, nan, nan], 'GSM3494886': [nan, 20.0, 0.0], 'GSM3494887': [nan, 51.0, 0.0], 'GSM3494888': [nan, 37.0, 1.0], 'GSM3494889': [nan, 61.0, 1.0], 'GSM3494890': [nan, nan, nan], 'GSM3494891': [nan, 31.0, 1.0], 'GSM3494892': [nan, 56.0, 0.0], 'GSM3494893': [nan, 41.0, 0.0], 'GSM3494894': [nan, 61.0, 0.0], 'GSM3494895': [nan, nan, nan], 'GSM3494896': [nan, 80.0, 1.0], 'GSM3494897': [nan, 53.0, 1.0], 'GSM3494898': [nan, 61.0, 1.0], 'GSM3494899': [nan, 73.0, 1.0], 'GSM3494900': [nan, 60.0, 1.0], 'GSM3494901': [nan, 76.0, 1.0], 'GSM3494902': [nan, 77.0, 0.0], 'GSM3494903': [nan, 74.0, 0.0], 'GSM3494904': [nan, 69.0, 1.0], 'GSM3494905': [nan, 77.0, 0.0], 'GSM3494906': [nan, 81.0, 0.0], 'GSM3494907': [nan, 70.0, 0.0], 'GSM3494908': [nan, 82.0, 0.0], 'GSM3494909': [nan, 69.0, 0.0], 'GSM3494910': [nan, 82.0, 0.0], 'GSM3494911': [nan, 67.0, 0.0], 'GSM3494912': [nan, 67.0, 0.0], 'GSM3494913': [nan, 78.0, 0.0], 'GSM3494914': [nan, 67.0, 0.0], 'GSM3494915': [nan, 74.0, 1.0], 'GSM3494916': [nan, nan, nan], 'GSM3494917': [nan, 51.0, 1.0], 'GSM3494918': [nan, 72.0, 1.0], 'GSM3494919': [nan, 66.0, 1.0], 'GSM3494920': [nan, 80.0, 0.0], 'GSM3494921': [1.0, 36.0, 1.0], 'GSM3494922': [1.0, 67.0, 0.0], 'GSM3494923': [1.0, 31.0, 0.0], 'GSM3494924': [1.0, 31.0, 0.0], 'GSM3494925': [1.0, 45.0, 0.0], 'GSM3494926': [1.0, 56.0, 0.0], 'GSM3494927': [1.0, 65.0, 0.0], 'GSM3494928': [1.0, 53.0, 0.0], 'GSM3494929': [1.0, 48.0, 0.0], 'GSM3494930': [1.0, 50.0, 0.0], 'GSM3494931': [1.0, 76.0, 1.0], 'GSM3494932': [nan, nan, nan], 'GSM3494933': [nan, 24.0, 0.0], 'GSM3494934': [nan, 42.0, 0.0], 'GSM3494935': [nan, 76.0, 1.0], 'GSM3494936': [nan, 22.0, 1.0], 'GSM3494937': [nan, nan, nan], 'GSM3494938': [nan, 23.0, 0.0], 'GSM3494939': [0.0, 34.0, 1.0], 'GSM3494940': [0.0, 43.0, 1.0], 'GSM3494941': [0.0, 47.0, 1.0], 'GSM3494942': [0.0, 24.0, 0.0], 'GSM3494943': [0.0, 55.0, 1.0], 'GSM3494944': [0.0, 48.0, 1.0], 'GSM3494945': [0.0, 58.0, 1.0], 'GSM3494946': [0.0, 30.0, 0.0], 'GSM3494947': [0.0, 28.0, 1.0], 'GSM3494948': [0.0, 41.0, 0.0], 'GSM3494949': [0.0, 63.0, 1.0], 'GSM3494950': [0.0, 55.0, 0.0], 'GSM3494951': [0.0, 55.0, 0.0], 'GSM3494952': [0.0, 67.0, 1.0], 'GSM3494953': [0.0, 47.0, 0.0], 'GSM3494954': [0.0, 46.0, 0.0], 'GSM3494955': [0.0, 49.0, 1.0], 'GSM3494956': [0.0, 23.0, 1.0], 'GSM3494957': [0.0, 68.0, 1.0], 'GSM3494958': [0.0, 39.0, 1.0], 'GSM3494959': [0.0, 24.0, 1.0], 'GSM3494960': [0.0, 36.0, 0.0], 'GSM3494961': [0.0, 58.0, 0.0], 'GSM3494962': [0.0, 38.0, 0.0], 'GSM3494963': [0.0, 27.0, 0.0], 'GSM3494964': [0.0, 67.0, 0.0], 'GSM3494965': [0.0, 61.0, 1.0], 'GSM3494966': [0.0, 69.0, 1.0], 'GSM3494967': [0.0, 63.0, 1.0], 'GSM3494968': [0.0, 60.0, 0.0], 'GSM3494969': [0.0, 17.0, 1.0], 'GSM3494970': [0.0, 10.0, 0.0], 'GSM3494971': [0.0, 9.0, 1.0], 'GSM3494972': [0.0, 13.0, 0.0], 'GSM3494973': [0.0, 10.0, 1.0], 'GSM3494974': [0.0, 13.0, 0.0], 'GSM3494975': [0.0, 15.0, 1.0], 'GSM3494976': [0.0, 12.0, 1.0], 'GSM3494977': [0.0, 13.0, 1.0], 'GSM3494978': [nan, 81.0, 0.0], 'GSM3494979': [nan, 94.0, 0.0], 'GSM3494980': [nan, 51.0, 1.0], 'GSM3494981': [nan, 40.0, 1.0], 'GSM3494982': [nan, nan, nan], 'GSM3494983': [nan, 97.0, 1.0], 'GSM3494984': [nan, 23.0, 1.0], 'GSM3494985': [nan, 93.0, 0.0], 'GSM3494986': [nan, 58.0, 1.0], 'GSM3494987': [nan, 28.0, 0.0], 'GSM3494988': [nan, 54.0, 1.0], 'GSM3494989': [nan, 15.0, 1.0], 'GSM3494990': [nan, 8.0, 1.0], 'GSM3494991': [nan, 11.0, 1.0], 'GSM3494992': [nan, 12.0, 1.0], 'GSM3494993': [nan, 8.0, 0.0], 'GSM3494994': [nan, 14.0, 1.0], 'GSM3494995': [nan, 8.0, 0.0], 'GSM3494996': [nan, 10.0, 1.0], 'GSM3494997': [nan, 14.0, 1.0], 'GSM3494998': [nan, 13.0, 1.0], 'GSM3494999': [nan, 40.0, 0.0], 'GSM3495000': [nan, 52.0, 0.0], 'GSM3495001': [nan, 42.0, 0.0], 'GSM3495002': [nan, 29.0, 0.0], 'GSM3495003': [nan, 43.0, 0.0], 'GSM3495004': [nan, 41.0, 0.0], 'GSM3495005': [nan, 54.0, 1.0], 'GSM3495006': [nan, 42.0, 1.0], 'GSM3495007': [nan, 49.0, 1.0], 'GSM3495008': [nan, 45.0, 0.0], 'GSM3495009': [nan, 56.0, 1.0], 'GSM3495010': [nan, 64.0, 0.0], 'GSM3495011': [nan, 71.0, 0.0], 'GSM3495012': [nan, 48.0, 0.0], 'GSM3495013': [nan, 20.0, 1.0], 'GSM3495014': [nan, 53.0, 0.0], 'GSM3495015': [nan, 32.0, 0.0], 'GSM3495016': [nan, 26.0, 0.0], 'GSM3495017': [nan, 28.0, 0.0], 'GSM3495018': [nan, 47.0, 0.0], 'GSM3495019': [nan, 24.0, 0.0], 'GSM3495020': [nan, 48.0, 0.0], 'GSM3495021': [nan, nan, nan], 'GSM3495022': [nan, 19.0, 0.0], 'GSM3495023': [nan, 41.0, 0.0], 'GSM3495024': [nan, 38.0, 0.0], 'GSM3495025': [nan, nan, nan], 'GSM3495026': [nan, 15.0, 0.0], 'GSM3495027': [nan, 12.0, 1.0], 'GSM3495028': [nan, 13.0, 0.0], 'GSM3495029': [nan, nan, nan], 'GSM3495030': [nan, 11.0, 1.0], 'GSM3495031': [nan, nan, nan], 'GSM3495032': [nan, 16.0, 1.0], 'GSM3495033': [nan, 11.0, 1.0], 'GSM3495034': [nan, nan, nan], 'GSM3495035': [nan, 35.0, 0.0], 'GSM3495036': [nan, 26.0, 0.0], 'GSM3495037': [nan, 39.0, 0.0], 'GSM3495038': [nan, 46.0, 0.0], 'GSM3495039': [nan, 42.0, 0.0], 'GSM3495040': [nan, 20.0, 1.0], 'GSM3495041': [nan, 69.0, 1.0], 'GSM3495042': [nan, 69.0, 0.0], 'GSM3495043': [nan, 47.0, 1.0], 'GSM3495044': [nan, 47.0, 1.0], 'GSM3495045': [nan, 56.0, 0.0], 'GSM3495046': [nan, 54.0, 0.0], 'GSM3495047': [nan, 53.0, 0.0], 'GSM3495048': [nan, 50.0, 0.0], 'GSM3495049': [nan, 22.0, 1.0]}\n",
121
+ "Clinical data saved to ../../output/preprocess/Crohns_Disease/clinical_data/GSE123086.csv\n"
122
+ ]
123
+ }
124
+ ],
125
+ "source": [
126
+ "# 1. Gene Expression Data Availability\n",
127
+ "# Based on the Series_overall_design, this dataset contains microarray data from CD4+ T cells\n",
128
+ "# which would provide gene expression data, not just miRNA or methylation\n",
129
+ "is_gene_available = True\n",
130
+ "\n",
131
+ "# 2. Variable Availability and Data Type Conversion\n",
132
+ "# 2.1 Data Availability\n",
133
+ "# For trait - Crohn's disease appears in row 1 under \"primary diagnosis\"\n",
134
+ "trait_row = 1\n",
135
+ "\n",
136
+ "# For gender - appears in rows 2 and 3, but row 2 seems to be more complete\n",
137
+ "gender_row = 2 \n",
138
+ "\n",
139
+ "# For age - appears in rows 3 and 4\n",
140
+ "age_row = 3\n",
141
+ "\n",
142
+ "# 2.2 Data Type Conversion\n",
143
+ "def convert_trait(value):\n",
144
+ " if not isinstance(value, str):\n",
145
+ " return None\n",
146
+ " # Extract value after colon if present\n",
147
+ " if ':' in value:\n",
148
+ " value = value.split(':', 1)[1].strip()\n",
149
+ " \n",
150
+ " # Matching trait (Crohn's Disease)\n",
151
+ " if \"CROHN\" in value.upper():\n",
152
+ " return 1\n",
153
+ " # Healthy controls should be 0\n",
154
+ " elif \"HEALTHY\" in value.upper() or \"CONTROL\" in value.upper():\n",
155
+ " return 0\n",
156
+ " # Other diseases are not relevant for our binary classification\n",
157
+ " else:\n",
158
+ " return None\n",
159
+ "\n",
160
+ "def convert_gender(value):\n",
161
+ " if not isinstance(value, str):\n",
162
+ " return None\n",
163
+ " # Extract value after colon if present\n",
164
+ " if ':' in value:\n",
165
+ " value = value.split(':', 1)[1].strip()\n",
166
+ " \n",
167
+ " # Female is 0, Male is 1\n",
168
+ " if value.upper() == \"FEMALE\":\n",
169
+ " return 0\n",
170
+ " elif value.upper() == \"MALE\":\n",
171
+ " return 1\n",
172
+ " # If it's a diagnosis2 field, return None as it's not gender data\n",
173
+ " elif \"DIAGNOSIS2\" in value.upper():\n",
174
+ " return None\n",
175
+ " else:\n",
176
+ " return None\n",
177
+ "\n",
178
+ "def convert_age(value):\n",
179
+ " if not isinstance(value, str):\n",
180
+ " return None\n",
181
+ " # Extract value after colon if present\n",
182
+ " if ':' in value:\n",
183
+ " value = value.split(':', 1)[1].strip()\n",
184
+ " \n",
185
+ " # Try to convert to float for continuous age\n",
186
+ " try:\n",
187
+ " return float(value)\n",
188
+ " except:\n",
189
+ " return None\n",
190
+ "\n",
191
+ "# 3. Save Metadata\n",
192
+ "# Determine trait data availability\n",
193
+ "is_trait_available = trait_row is not None\n",
194
+ "\n",
195
+ "# Initial filtering using validate_and_save_cohort_info\n",
196
+ "validate_and_save_cohort_info(\n",
197
+ " is_final=False, \n",
198
+ " cohort=cohort, \n",
199
+ " info_path=json_path, \n",
200
+ " is_gene_available=is_gene_available, \n",
201
+ " is_trait_available=is_trait_available\n",
202
+ ")\n",
203
+ "\n",
204
+ "# 4. Clinical Feature Extraction\n",
205
+ "# Since trait_row is not None, we proceed with clinical feature extraction\n",
206
+ "if trait_row is not None:\n",
207
+ " # Extract clinical features using the geo_select_clinical_features function\n",
208
+ " selected_clinical_df = geo_select_clinical_features(\n",
209
+ " clinical_df=clinical_data,\n",
210
+ " trait=trait,\n",
211
+ " trait_row=trait_row,\n",
212
+ " convert_trait=convert_trait,\n",
213
+ " age_row=age_row,\n",
214
+ " convert_age=convert_age,\n",
215
+ " gender_row=gender_row,\n",
216
+ " convert_gender=convert_gender\n",
217
+ " )\n",
218
+ " \n",
219
+ " # Preview the extracted features\n",
220
+ " preview = preview_df(selected_clinical_df)\n",
221
+ " print(\"Preview of selected clinical features:\")\n",
222
+ " print(preview)\n",
223
+ " \n",
224
+ " # Save the clinical data\n",
225
+ " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
226
+ " selected_clinical_df.to_csv(out_clinical_data_file, index=False)\n",
227
+ " print(f\"Clinical data saved to {out_clinical_data_file}\")\n"
228
+ ]
229
+ },
230
+ {
231
+ "cell_type": "markdown",
232
+ "id": "d1038144",
233
+ "metadata": {},
234
+ "source": [
235
+ "### Step 3: Gene Data Extraction"
236
+ ]
237
+ },
238
+ {
239
+ "cell_type": "code",
240
+ "execution_count": 4,
241
+ "id": "608edba3",
242
+ "metadata": {
243
+ "execution": {
244
+ "iopub.execute_input": "2025-03-25T08:31:54.339030Z",
245
+ "iopub.status.busy": "2025-03-25T08:31:54.338825Z",
246
+ "iopub.status.idle": "2025-03-25T08:31:54.748049Z",
247
+ "shell.execute_reply": "2025-03-25T08:31:54.747652Z"
248
+ }
249
+ },
250
+ "outputs": [
251
+ {
252
+ "name": "stdout",
253
+ "output_type": "stream",
254
+ "text": [
255
+ "\n",
256
+ "First 20 gene/probe identifiers:\n",
257
+ "Index(['1', '2', '3', '9', '10', '12', '13', '14', '15', '16', '18', '19',\n",
258
+ " '20', '21', '22', '23', '24', '25', '26', '27'],\n",
259
+ " dtype='object', name='ID')\n",
260
+ "\n",
261
+ "Gene data dimensions: 22881 genes × 166 samples\n"
262
+ ]
263
+ }
264
+ ],
265
+ "source": [
266
+ "# 1. Re-identify the SOFT and matrix files to ensure we have the correct paths\n",
267
+ "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
268
+ "\n",
269
+ "# 2. Extract the gene expression data from the matrix file\n",
270
+ "gene_data = get_genetic_data(matrix_file)\n",
271
+ "\n",
272
+ "# 3. Print the first 20 row IDs (gene or probe identifiers)\n",
273
+ "print(\"\\nFirst 20 gene/probe identifiers:\")\n",
274
+ "print(gene_data.index[:20])\n",
275
+ "\n",
276
+ "# 4. Print the dimensions of the gene expression data\n",
277
+ "print(f\"\\nGene data dimensions: {gene_data.shape[0]} genes × {gene_data.shape[1]} samples\")\n",
278
+ "\n",
279
+ "# Note: we keep is_gene_available as True since we successfully extracted gene expression data\n",
280
+ "is_gene_available = True\n"
281
+ ]
282
+ },
283
+ {
284
+ "cell_type": "markdown",
285
+ "id": "68513421",
286
+ "metadata": {},
287
+ "source": [
288
+ "### Step 4: Gene Identifier Review"
289
+ ]
290
+ },
291
+ {
292
+ "cell_type": "code",
293
+ "execution_count": 5,
294
+ "id": "b17de00e",
295
+ "metadata": {
296
+ "execution": {
297
+ "iopub.execute_input": "2025-03-25T08:31:54.749415Z",
298
+ "iopub.status.busy": "2025-03-25T08:31:54.749292Z",
299
+ "iopub.status.idle": "2025-03-25T08:31:54.751231Z",
300
+ "shell.execute_reply": "2025-03-25T08:31:54.750951Z"
301
+ }
302
+ },
303
+ "outputs": [],
304
+ "source": [
305
+ "# Examining the gene identifiers\n",
306
+ "# The identifiers appear to be numerical values (1, 2, 3, etc.)\n",
307
+ "# These are not standard human gene symbols, which are typically alphanumeric \n",
308
+ "# (like BRCA1, TP53, etc.)\n",
309
+ "# These appear to be probe IDs or some other form of identifiers that would\n",
310
+ "# need to be mapped to standard gene symbols\n",
311
+ "\n",
312
+ "requires_gene_mapping = True\n"
313
+ ]
314
+ },
315
+ {
316
+ "cell_type": "markdown",
317
+ "id": "8d4e6390",
318
+ "metadata": {},
319
+ "source": [
320
+ "### Step 5: Gene Annotation"
321
+ ]
322
+ },
323
+ {
324
+ "cell_type": "code",
325
+ "execution_count": 6,
326
+ "id": "5b49e7b5",
327
+ "metadata": {
328
+ "execution": {
329
+ "iopub.execute_input": "2025-03-25T08:31:54.752424Z",
330
+ "iopub.status.busy": "2025-03-25T08:31:54.752318Z",
331
+ "iopub.status.idle": "2025-03-25T08:31:58.331994Z",
332
+ "shell.execute_reply": "2025-03-25T08:31:58.331624Z"
333
+ }
334
+ },
335
+ "outputs": [
336
+ {
337
+ "name": "stdout",
338
+ "output_type": "stream",
339
+ "text": [
340
+ "Gene annotation dataframe column names:\n",
341
+ "Index(['ID', 'ENTREZ_GENE_ID', 'SPOT_ID'], dtype='object')\n",
342
+ "\n",
343
+ "Preview of gene annotation data:\n",
344
+ "{'ID': ['1', '2', '3'], 'ENTREZ_GENE_ID': ['1', '2', '3'], 'SPOT_ID': [1.0, 2.0, 3.0]}\n"
345
+ ]
346
+ }
347
+ ],
348
+ "source": [
349
+ "# 1. First get the file paths using geo_get_relevant_filepaths function\n",
350
+ "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
351
+ "\n",
352
+ "# 2. Extract gene annotation data from the SOFT file\n",
353
+ "gene_annotation = get_gene_annotation(soft_file)\n",
354
+ "\n",
355
+ "# 3. Preview the gene annotation dataframe\n",
356
+ "print(\"Gene annotation dataframe column names:\")\n",
357
+ "print(gene_annotation.columns)\n",
358
+ "\n",
359
+ "# Preview the first few rows to understand the data structure\n",
360
+ "print(\"\\nPreview of gene annotation data:\")\n",
361
+ "annotation_preview = preview_df(gene_annotation, n=3)\n",
362
+ "print(annotation_preview)\n",
363
+ "\n",
364
+ "# Maintain gene availability status as True based on previous steps\n",
365
+ "is_gene_available = True\n"
366
+ ]
367
+ },
368
+ {
369
+ "cell_type": "markdown",
370
+ "id": "88933adc",
371
+ "metadata": {},
372
+ "source": [
373
+ "### Step 6: Gene Identifier Mapping"
374
+ ]
375
+ },
376
+ {
377
+ "cell_type": "code",
378
+ "execution_count": 7,
379
+ "id": "79475a3d",
380
+ "metadata": {
381
+ "execution": {
382
+ "iopub.execute_input": "2025-03-25T08:31:58.333245Z",
383
+ "iopub.status.busy": "2025-03-25T08:31:58.333119Z",
384
+ "iopub.status.idle": "2025-03-25T08:32:05.569628Z",
385
+ "shell.execute_reply": "2025-03-25T08:32:05.569287Z"
386
+ }
387
+ },
388
+ "outputs": [
389
+ {
390
+ "name": "stdout",
391
+ "output_type": "stream",
392
+ "text": [
393
+ "Gene annotation first few rows:\n",
394
+ " ID ENTREZ_GENE_ID SPOT_ID\n",
395
+ "0 1 1 1.0\n",
396
+ "1 2 2 2.0\n",
397
+ "2 3 3 3.0\n",
398
+ "3 9 9 9.0\n",
399
+ "4 10 10 10.0\n",
400
+ "\n",
401
+ "Sample values in ENTREZ_GENE_ID column:\n",
402
+ "0 1\n",
403
+ "1 2\n",
404
+ "2 3\n",
405
+ "3 9\n",
406
+ "4 10\n",
407
+ "5 12\n",
408
+ "6 13\n",
409
+ "7 14\n",
410
+ "8 15\n",
411
+ "9 16\n",
412
+ "Name: ENTREZ_GENE_ID, dtype: object\n"
413
+ ]
414
+ },
415
+ {
416
+ "name": "stdout",
417
+ "output_type": "stream",
418
+ "text": [
419
+ "\n",
420
+ "Check if gene symbols are available in the SOFT file:\n"
421
+ ]
422
+ },
423
+ {
424
+ "name": "stdout",
425
+ "output_type": "stream",
426
+ "text": [
427
+ "[]\n"
428
+ ]
429
+ },
430
+ {
431
+ "name": "stdout",
432
+ "output_type": "stream",
433
+ "text": [
434
+ "\n",
435
+ "Cleaned gene mapping:\n",
436
+ " ID Gene\n",
437
+ "0 1 1\n",
438
+ "1 2 2\n",
439
+ "2 3 3\n",
440
+ "3 9 9\n",
441
+ "4 10 10\n",
442
+ "Mapping shape after cleaning: (3822578, 2)\n"
443
+ ]
444
+ },
445
+ {
446
+ "name": "stdout",
447
+ "output_type": "stream",
448
+ "text": [
449
+ "\n",
450
+ "Gene expression data after mapping:\n",
451
+ "Number of genes: 0\n",
452
+ "Number of samples: 166\n",
453
+ "No genes were mapped successfully.\n"
454
+ ]
455
+ }
456
+ ],
457
+ "source": [
458
+ "# Let's examine the gene_annotation data more carefully to understand the structure\n",
459
+ "print(\"Gene annotation first few rows:\")\n",
460
+ "print(gene_annotation.head())\n",
461
+ "\n",
462
+ "# Check what's in the ENTREZ_GENE_ID column - we need actual gene identifiers\n",
463
+ "print(\"\\nSample values in ENTREZ_GENE_ID column:\")\n",
464
+ "print(gene_annotation['ENTREZ_GENE_ID'].head(10))\n",
465
+ "\n",
466
+ "# The issue is that we need proper gene symbols, not just Entrez IDs\n",
467
+ "# Let's check if we have access to proper gene symbols by fetching the platform annotation\n",
468
+ "# from the SOFT file\n",
469
+ "\n",
470
+ "# Parse the SOFT file to get platform information including gene symbols\n",
471
+ "with gzip.open(soft_file, 'rt') as f:\n",
472
+ " soft_content = f.read()\n",
473
+ "\n",
474
+ "# Look for sections containing gene symbol information\n",
475
+ "print(\"\\nCheck if gene symbols are available in the SOFT file:\")\n",
476
+ "gene_symbol_lines = [line for line in soft_content.split('\\n') if 'gene_symbol' in line.lower()][:5]\n",
477
+ "print(gene_symbol_lines)\n",
478
+ "\n",
479
+ "# If we don't find gene symbols directly, we'll use the Entrez Gene IDs as identifiers\n",
480
+ "# since they can be mapped to gene symbols later\n",
481
+ "\n",
482
+ "# Create a mapping dataframe with ID and Entrez Gene ID\n",
483
+ "gene_mapping = gene_annotation[['ID', 'ENTREZ_GENE_ID']].copy()\n",
484
+ "gene_mapping.rename(columns={'ENTREZ_GENE_ID': 'Gene'}, inplace=True)\n",
485
+ "\n",
486
+ "# Filter out any rows with missing values\n",
487
+ "gene_mapping = gene_mapping.dropna()\n",
488
+ "\n",
489
+ "# Print a preview of the cleaned mapping\n",
490
+ "print(\"\\nCleaned gene mapping:\")\n",
491
+ "print(gene_mapping.head())\n",
492
+ "print(f\"Mapping shape after cleaning: {gene_mapping.shape}\")\n",
493
+ "\n",
494
+ "# Apply the gene mapping to convert probe-level measurements to gene expression data\n",
495
+ "# We'll use the standard function but make sure our Gene column has proper values\n",
496
+ "gene_data = apply_gene_mapping(gene_data, gene_mapping)\n",
497
+ "\n",
498
+ "# Print statistics about the resulting gene data\n",
499
+ "print(f\"\\nGene expression data after mapping:\")\n",
500
+ "print(f\"Number of genes: {gene_data.shape[0]}\")\n",
501
+ "print(f\"Number of samples: {gene_data.shape[1]}\")\n",
502
+ "\n",
503
+ "# Check the first few gene identifiers - they should be Entrez IDs\n",
504
+ "if gene_data.shape[0] > 0:\n",
505
+ " print(\"First 5 gene identifiers:\")\n",
506
+ " print(gene_data.index[:5])\n",
507
+ "else:\n",
508
+ " print(\"No genes were mapped successfully.\")\n",
509
+ "\n",
510
+ "# For this dataset, since we don't have access to proper gene symbols, \n",
511
+ "# we'll treat the Entrez Gene IDs as our gene identifiers\n",
512
+ "# Later normalization can map these to standard gene symbols if needed\n",
513
+ "\n",
514
+ "# Verify we have non-empty gene expression data\n",
515
+ "is_gene_available = gene_data.shape[0] > 0\n"
516
+ ]
517
+ },
518
+ {
519
+ "cell_type": "markdown",
520
+ "id": "fc4c1efa",
521
+ "metadata": {},
522
+ "source": [
523
+ "### Step 7: Data Normalization and Linking"
524
+ ]
525
+ },
526
+ {
527
+ "cell_type": "code",
528
+ "execution_count": 8,
529
+ "id": "2e150f28",
530
+ "metadata": {
531
+ "execution": {
532
+ "iopub.execute_input": "2025-03-25T08:32:05.571074Z",
533
+ "iopub.status.busy": "2025-03-25T08:32:05.570955Z",
534
+ "iopub.status.idle": "2025-03-25T08:32:05.577791Z",
535
+ "shell.execute_reply": "2025-03-25T08:32:05.577484Z"
536
+ }
537
+ },
538
+ "outputs": [
539
+ {
540
+ "name": "stdout",
541
+ "output_type": "stream",
542
+ "text": [
543
+ "Error: Gene expression matrix is empty after mapping.\n",
544
+ "Abnormality detected in the cohort: GSE123086. Preprocessing failed.\n",
545
+ "A new JSON file was created at: ../../output/preprocess/Crohns_Disease/cohort_info.json\n",
546
+ "Dataset deemed not usable due to lack of gene expression data.\n"
547
+ ]
548
+ }
549
+ ],
550
+ "source": [
551
+ "# 1. Check if gene data is available after mapping\n",
552
+ "if gene_data.shape[0] == 0:\n",
553
+ " print(\"Error: Gene expression matrix is empty after mapping.\")\n",
554
+ " # Mark the dataset as not usable due to lack of gene expression data\n",
555
+ " is_usable = validate_and_save_cohort_info(\n",
556
+ " is_final=True,\n",
557
+ " cohort=cohort,\n",
558
+ " info_path=json_path,\n",
559
+ " is_gene_available=False, # No usable gene data\n",
560
+ " is_trait_available=True,\n",
561
+ " is_biased=True,\n",
562
+ " df=pd.DataFrame(),\n",
563
+ " note=\"Failed to map probe IDs to gene symbols. The annotation format may not be compatible with the extraction methods.\"\n",
564
+ " )\n",
565
+ " print(\"Dataset deemed not usable due to lack of gene expression data.\")\n",
566
+ "else:\n",
567
+ " # Only proceed with normalization if we have gene data\n",
568
+ " print(\"Normalizing gene symbols...\")\n",
569
+ " gene_data_normalized = normalize_gene_symbols_in_index(gene_data)\n",
570
+ " print(f\"Gene data shape after normalization: {gene_data_normalized.shape[0]} genes × {gene_data_normalized.shape[1]} samples\")\n",
571
+ "\n",
572
+ " # Save the normalized gene data\n",
573
+ " os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
574
+ " gene_data_normalized.to_csv(out_gene_data_file)\n",
575
+ " print(f\"Normalized gene expression data saved to {out_gene_data_file}\")\n",
576
+ " \n",
577
+ " # Extract clinical features from the original data source\n",
578
+ " print(\"Extracting clinical features from the original source...\")\n",
579
+ " # Get background information and clinical data again\n",
580
+ " background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']\n",
581
+ " clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']\n",
582
+ " background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)\n",
583
+ " \n",
584
+ " # Extract clinical features\n",
585
+ " selected_clinical_df = geo_select_clinical_features(\n",
586
+ " clinical_df=clinical_data,\n",
587
+ " trait=trait,\n",
588
+ " trait_row=trait_row,\n",
589
+ " convert_trait=convert_trait,\n",
590
+ " age_row=age_row,\n",
591
+ " convert_age=convert_age,\n",
592
+ " gender_row=gender_row,\n",
593
+ " convert_gender=convert_gender\n",
594
+ " )\n",
595
+ " \n",
596
+ " print(\"Extracted clinical features preview:\")\n",
597
+ " print(preview_df(selected_clinical_df))\n",
598
+ " print(f\"Clinical data shape: {selected_clinical_df.shape}\")\n",
599
+ " \n",
600
+ " # Save the extracted clinical features\n",
601
+ " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
602
+ " selected_clinical_df.to_csv(out_clinical_data_file)\n",
603
+ " print(f\"Clinical features saved to {out_clinical_data_file}\")\n",
604
+ " \n",
605
+ " # Link clinical and genetic data\n",
606
+ " print(\"Linking clinical and genetic data...\")\n",
607
+ " linked_data = geo_link_clinical_genetic_data(selected_clinical_df, gene_data_normalized)\n",
608
+ " print(f\"Linked data shape: {linked_data.shape}\")\n",
609
+ " \n",
610
+ " # Check if the linked data has adequate data\n",
611
+ " if linked_data.shape[0] == 0 or linked_data.shape[1] <= 4: # 4 is an arbitrary small number\n",
612
+ " print(\"Error: Linked data has insufficient samples or features.\")\n",
613
+ " is_usable = validate_and_save_cohort_info(\n",
614
+ " is_final=True,\n",
615
+ " cohort=cohort,\n",
616
+ " info_path=json_path,\n",
617
+ " is_gene_available=True,\n",
618
+ " is_trait_available=True,\n",
619
+ " is_biased=True,\n",
620
+ " df=linked_data,\n",
621
+ " note=\"Failed to properly link gene expression data with clinical features.\"\n",
622
+ " )\n",
623
+ " print(\"Dataset deemed not usable due to linking failure.\")\n",
624
+ " else:\n",
625
+ " # Handle missing values systematically\n",
626
+ " print(\"Handling missing values...\")\n",
627
+ " linked_data_clean = handle_missing_values(linked_data, trait_col=trait)\n",
628
+ " print(f\"Data shape after handling missing values: {linked_data_clean.shape}\")\n",
629
+ " \n",
630
+ " # Check if there are still samples after missing value handling\n",
631
+ " if linked_data_clean.shape[0] == 0:\n",
632
+ " print(\"Error: No samples remain after handling missing values.\")\n",
633
+ " is_usable = validate_and_save_cohort_info(\n",
634
+ " is_final=True,\n",
635
+ " cohort=cohort,\n",
636
+ " info_path=json_path,\n",
637
+ " is_gene_available=True,\n",
638
+ " is_trait_available=True,\n",
639
+ " is_biased=True,\n",
640
+ " df=pd.DataFrame(),\n",
641
+ " note=\"All samples were removed during missing value handling.\"\n",
642
+ " )\n",
643
+ " print(\"Dataset deemed not usable as all samples were filtered out.\")\n",
644
+ " else:\n",
645
+ " # Check if the dataset is biased\n",
646
+ " print(\"\\nChecking for bias in feature variables:\")\n",
647
+ " is_biased, linked_data_final = judge_and_remove_biased_features(linked_data_clean, trait)\n",
648
+ " \n",
649
+ " # Conduct final quality validation\n",
650
+ " is_usable = validate_and_save_cohort_info(\n",
651
+ " is_final=True,\n",
652
+ " cohort=cohort,\n",
653
+ " info_path=json_path,\n",
654
+ " is_gene_available=True,\n",
655
+ " is_trait_available=True,\n",
656
+ " is_biased=is_biased,\n",
657
+ " df=linked_data_final,\n",
658
+ " note=\"Dataset contains gene expression data for Crohn's Disease patients, examining response to Infliximab treatment.\"\n",
659
+ " )\n",
660
+ " \n",
661
+ " # Save linked data if usable\n",
662
+ " if is_usable:\n",
663
+ " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n",
664
+ " linked_data_final.to_csv(out_data_file)\n",
665
+ " print(f\"Linked data saved to {out_data_file}\")\n",
666
+ " print(f\"Final dataset shape: {linked_data_final.shape}\")\n",
667
+ " else:\n",
668
+ " print(\"Dataset deemed not usable for trait association studies, linked data not saved.\")"
669
+ ]
670
+ }
671
+ ],
672
+ "metadata": {
673
+ "language_info": {
674
+ "codemirror_mode": {
675
+ "name": "ipython",
676
+ "version": 3
677
+ },
678
+ "file_extension": ".py",
679
+ "mimetype": "text/x-python",
680
+ "name": "python",
681
+ "nbconvert_exporter": "python",
682
+ "pygments_lexer": "ipython3",
683
+ "version": "3.10.16"
684
+ }
685
+ },
686
+ "nbformat": 4,
687
+ "nbformat_minor": 5
688
+ }
code/Crohns_Disease/GSE123088.ipynb ADDED
@@ -0,0 +1,626 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": 1,
6
+ "id": "8485cb4f",
7
+ "metadata": {
8
+ "execution": {
9
+ "iopub.execute_input": "2025-03-25T08:32:06.499146Z",
10
+ "iopub.status.busy": "2025-03-25T08:32:06.498785Z",
11
+ "iopub.status.idle": "2025-03-25T08:32:06.666657Z",
12
+ "shell.execute_reply": "2025-03-25T08:32:06.666312Z"
13
+ }
14
+ },
15
+ "outputs": [],
16
+ "source": [
17
+ "import sys\n",
18
+ "import os\n",
19
+ "sys.path.append(os.path.abspath(os.path.join(os.getcwd(), '../..')))\n",
20
+ "\n",
21
+ "# Path Configuration\n",
22
+ "from tools.preprocess import *\n",
23
+ "\n",
24
+ "# Processing context\n",
25
+ "trait = \"Crohns_Disease\"\n",
26
+ "cohort = \"GSE123088\"\n",
27
+ "\n",
28
+ "# Input paths\n",
29
+ "in_trait_dir = \"../../input/GEO/Crohns_Disease\"\n",
30
+ "in_cohort_dir = \"../../input/GEO/Crohns_Disease/GSE123088\"\n",
31
+ "\n",
32
+ "# Output paths\n",
33
+ "out_data_file = \"../../output/preprocess/Crohns_Disease/GSE123088.csv\"\n",
34
+ "out_gene_data_file = \"../../output/preprocess/Crohns_Disease/gene_data/GSE123088.csv\"\n",
35
+ "out_clinical_data_file = \"../../output/preprocess/Crohns_Disease/clinical_data/GSE123088.csv\"\n",
36
+ "json_path = \"../../output/preprocess/Crohns_Disease/cohort_info.json\"\n"
37
+ ]
38
+ },
39
+ {
40
+ "cell_type": "markdown",
41
+ "id": "97dd5573",
42
+ "metadata": {},
43
+ "source": [
44
+ "### Step 1: Initial Data Loading"
45
+ ]
46
+ },
47
+ {
48
+ "cell_type": "code",
49
+ "execution_count": 2,
50
+ "id": "ea92ea77",
51
+ "metadata": {
52
+ "execution": {
53
+ "iopub.execute_input": "2025-03-25T08:32:06.668092Z",
54
+ "iopub.status.busy": "2025-03-25T08:32:06.667946Z",
55
+ "iopub.status.idle": "2025-03-25T08:32:06.944372Z",
56
+ "shell.execute_reply": "2025-03-25T08:32:06.944010Z"
57
+ }
58
+ },
59
+ "outputs": [
60
+ {
61
+ "name": "stdout",
62
+ "output_type": "stream",
63
+ "text": [
64
+ "Background Information:\n",
65
+ "!Series_title\t\"A validated single-cell-based strategy to identify diagnostic and therapeutic targets in complex diseases\"\n",
66
+ "!Series_summary\t\"This SuperSeries is composed of the SubSeries listed below.\"\n",
67
+ "!Series_overall_design\t\"Refer to individual Series\"\n",
68
+ "Sample Characteristics Dictionary:\n",
69
+ "{0: ['cell type: CD4+ T cells'], 1: ['primary diagnosis: ASTHMA', 'primary diagnosis: ATHEROSCLEROSIS', 'primary diagnosis: BREAST_CANCER', 'primary diagnosis: CHRONIC_LYMPHOCYTIC_LEUKEMIA', 'primary diagnosis: CROHN_DISEASE', 'primary diagnosis: ATOPIC_ECZEMA', 'primary diagnosis: HEALTHY_CONTROL', 'primary diagnosis: INFLUENZA', 'primary diagnosis: OBESITY', 'primary diagnosis: PSORIASIS', 'primary diagnosis: SEASONAL_ALLERGIC_RHINITIS', 'primary diagnosis: TYPE_1_DIABETES', 'primary diagnosis: ACUTE_TONSILLITIS', 'primary diagnosis: ULCERATIVE_COLITIS', 'primary diagnosis: Breast cancer', 'primary diagnosis: Control'], 2: ['Sex: Male', 'diagnosis2: ATOPIC_ECZEMA', 'Sex: Female', 'diagnosis2: ATHEROSCLEROSIS', 'diagnosis2: ASTHMA_OBESITY', 'diagnosis2: ASTHMA', 'diagnosis2: ASTMHA_SEASONAL_ALLERGIC_RHINITIS', 'diagnosis2: OBESITY'], 3: ['age: 56', 'Sex: Male', 'age: 20', 'age: 51', 'age: 37', 'age: 61', 'age: 31', 'age: 41', 'age: 80', 'age: 53', 'age: 73', 'age: 60', 'age: 76', 'age: 77', 'age: 74', 'age: 69', 'age: 81', 'age: 70', 'age: 82', 'age: 67', 'age: 78', 'age: 72', 'age: 66', 'age: 36', 'age: 45', 'age: 65', 'age: 48', 'age: 50', 'age: 24', 'age: 42'], 4: [nan, 'age: 63', 'age: 74', 'age: 49', 'age: 60', 'age: 68', 'age: 38', 'age: 16', 'age: 12', 'age: 27']}\n"
70
+ ]
71
+ }
72
+ ],
73
+ "source": [
74
+ "from tools.preprocess import *\n",
75
+ "# 1. Identify the paths to the SOFT file and the matrix file\n",
76
+ "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
77
+ "\n",
78
+ "# 2. Read the matrix file to obtain background information and sample characteristics data\n",
79
+ "background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']\n",
80
+ "clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']\n",
81
+ "background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)\n",
82
+ "\n",
83
+ "# 3. Obtain the sample characteristics dictionary from the clinical dataframe\n",
84
+ "sample_characteristics_dict = get_unique_values_by_row(clinical_data)\n",
85
+ "\n",
86
+ "# 4. Explicitly print out all the background information and the sample characteristics dictionary\n",
87
+ "print(\"Background Information:\")\n",
88
+ "print(background_info)\n",
89
+ "print(\"Sample Characteristics Dictionary:\")\n",
90
+ "print(sample_characteristics_dict)\n"
91
+ ]
92
+ },
93
+ {
94
+ "cell_type": "markdown",
95
+ "id": "348fa83c",
96
+ "metadata": {},
97
+ "source": [
98
+ "### Step 2: Dataset Analysis and Clinical Feature Extraction"
99
+ ]
100
+ },
101
+ {
102
+ "cell_type": "code",
103
+ "execution_count": 3,
104
+ "id": "c306f14c",
105
+ "metadata": {
106
+ "execution": {
107
+ "iopub.execute_input": "2025-03-25T08:32:06.945685Z",
108
+ "iopub.status.busy": "2025-03-25T08:32:06.945566Z",
109
+ "iopub.status.idle": "2025-03-25T08:32:06.972002Z",
110
+ "shell.execute_reply": "2025-03-25T08:32:06.971702Z"
111
+ }
112
+ },
113
+ "outputs": [
114
+ {
115
+ "name": "stdout",
116
+ "output_type": "stream",
117
+ "text": [
118
+ "Preview of clinical data:\n",
119
+ "{'GSM3494884': [nan, 56.0, 1.0], 'GSM3494885': [nan, nan, nan], 'GSM3494886': [nan, 20.0, 0.0], 'GSM3494887': [nan, 51.0, 0.0], 'GSM3494888': [nan, 37.0, 1.0], 'GSM3494889': [nan, 61.0, 1.0], 'GSM3494890': [nan, nan, nan], 'GSM3494891': [nan, 31.0, 1.0], 'GSM3494892': [nan, 56.0, 0.0], 'GSM3494893': [nan, 41.0, 0.0], 'GSM3494894': [nan, 61.0, 0.0], 'GSM3494895': [nan, nan, nan], 'GSM3494896': [nan, 80.0, 1.0], 'GSM3494897': [nan, 53.0, 1.0], 'GSM3494898': [nan, 61.0, 1.0], 'GSM3494899': [nan, 73.0, 1.0], 'GSM3494900': [nan, 60.0, 1.0], 'GSM3494901': [nan, 76.0, 1.0], 'GSM3494902': [nan, 77.0, 0.0], 'GSM3494903': [nan, 74.0, 0.0], 'GSM3494904': [nan, 69.0, 1.0], 'GSM3494905': [nan, 77.0, 0.0], 'GSM3494906': [nan, 81.0, 0.0], 'GSM3494907': [nan, 70.0, 0.0], 'GSM3494908': [nan, 82.0, 0.0], 'GSM3494909': [nan, 69.0, 0.0], 'GSM3494910': [nan, 82.0, 0.0], 'GSM3494911': [nan, 67.0, 0.0], 'GSM3494912': [nan, 67.0, 0.0], 'GSM3494913': [nan, 78.0, 0.0], 'GSM3494914': [nan, 67.0, 0.0], 'GSM3494915': [nan, 74.0, 1.0], 'GSM3494916': [nan, nan, nan], 'GSM3494917': [nan, 51.0, 1.0], 'GSM3494918': [nan, 72.0, 1.0], 'GSM3494919': [nan, 66.0, 1.0], 'GSM3494920': [nan, 80.0, 0.0], 'GSM3494921': [1.0, 36.0, 1.0], 'GSM3494922': [1.0, 67.0, 0.0], 'GSM3494923': [1.0, 31.0, 0.0], 'GSM3494924': [1.0, 31.0, 0.0], 'GSM3494925': [1.0, 45.0, 0.0], 'GSM3494926': [1.0, 56.0, 0.0], 'GSM3494927': [1.0, 65.0, 0.0], 'GSM3494928': [1.0, 53.0, 0.0], 'GSM3494929': [1.0, 48.0, 0.0], 'GSM3494930': [1.0, 50.0, 0.0], 'GSM3494931': [1.0, 76.0, 1.0], 'GSM3494932': [nan, nan, nan], 'GSM3494933': [nan, 24.0, 0.0], 'GSM3494934': [nan, 42.0, 0.0], 'GSM3494935': [nan, 76.0, 1.0], 'GSM3494936': [nan, 22.0, 1.0], 'GSM3494937': [nan, nan, nan], 'GSM3494938': [nan, 23.0, 0.0], 'GSM3494939': [0.0, 34.0, 1.0], 'GSM3494940': [0.0, 43.0, 1.0], 'GSM3494941': [0.0, 47.0, 1.0], 'GSM3494942': [0.0, 24.0, 0.0], 'GSM3494943': [0.0, 55.0, 1.0], 'GSM3494944': [0.0, 48.0, 1.0], 'GSM3494945': [0.0, 58.0, 1.0], 'GSM3494946': [0.0, 30.0, 0.0], 'GSM3494947': [0.0, 28.0, 1.0], 'GSM3494948': [0.0, 41.0, 0.0], 'GSM3494949': [0.0, 63.0, 1.0], 'GSM3494950': [0.0, 55.0, 0.0], 'GSM3494951': [0.0, 55.0, 0.0], 'GSM3494952': [0.0, 67.0, 1.0], 'GSM3494953': [0.0, 47.0, 0.0], 'GSM3494954': [0.0, 46.0, 0.0], 'GSM3494955': [0.0, 49.0, 1.0], 'GSM3494956': [0.0, 23.0, 1.0], 'GSM3494957': [0.0, 68.0, 1.0], 'GSM3494958': [0.0, 39.0, 1.0], 'GSM3494959': [0.0, 24.0, 1.0], 'GSM3494960': [0.0, 36.0, 0.0], 'GSM3494961': [0.0, 58.0, 0.0], 'GSM3494962': [0.0, 38.0, 0.0], 'GSM3494963': [0.0, 27.0, 0.0], 'GSM3494964': [0.0, 67.0, 0.0], 'GSM3494965': [0.0, 61.0, 1.0], 'GSM3494966': [0.0, 69.0, 1.0], 'GSM3494967': [0.0, 63.0, 1.0], 'GSM3494968': [0.0, 60.0, 0.0], 'GSM3494969': [0.0, 17.0, 1.0], 'GSM3494970': [0.0, 10.0, 0.0], 'GSM3494971': [0.0, 9.0, 1.0], 'GSM3494972': [0.0, 13.0, 0.0], 'GSM3494973': [0.0, 10.0, 1.0], 'GSM3494974': [0.0, 13.0, 0.0], 'GSM3494975': [0.0, 15.0, 1.0], 'GSM3494976': [0.0, 12.0, 1.0], 'GSM3494977': [0.0, 13.0, 1.0], 'GSM3494978': [nan, 81.0, 0.0], 'GSM3494979': [nan, 94.0, 0.0], 'GSM3494980': [nan, 51.0, 1.0], 'GSM3494981': [nan, 40.0, 1.0], 'GSM3494982': [nan, nan, nan], 'GSM3494983': [nan, 97.0, 1.0], 'GSM3494984': [nan, 23.0, 1.0], 'GSM3494985': [nan, 93.0, 0.0], 'GSM3494986': [nan, 58.0, 1.0], 'GSM3494987': [nan, 28.0, 0.0], 'GSM3494988': [nan, 54.0, 1.0], 'GSM3494989': [nan, 15.0, 1.0], 'GSM3494990': [nan, 8.0, 1.0], 'GSM3494991': [nan, 11.0, 1.0], 'GSM3494992': [nan, 12.0, 1.0], 'GSM3494993': [nan, 8.0, 0.0], 'GSM3494994': [nan, 14.0, 1.0], 'GSM3494995': [nan, 8.0, 0.0], 'GSM3494996': [nan, 10.0, 1.0], 'GSM3494997': [nan, 14.0, 1.0], 'GSM3494998': [nan, 13.0, 1.0], 'GSM3494999': [nan, 40.0, 0.0], 'GSM3495000': [nan, 52.0, 0.0], 'GSM3495001': [nan, 42.0, 0.0], 'GSM3495002': [nan, 29.0, 0.0], 'GSM3495003': [nan, 43.0, 0.0], 'GSM3495004': [nan, 41.0, 0.0], 'GSM3495005': [nan, 54.0, 1.0], 'GSM3495006': [nan, 42.0, 1.0], 'GSM3495007': [nan, 49.0, 1.0], 'GSM3495008': [nan, 45.0, 0.0], 'GSM3495009': [nan, 56.0, 1.0], 'GSM3495010': [nan, 64.0, 0.0], 'GSM3495011': [nan, 71.0, 0.0], 'GSM3495012': [nan, 48.0, 0.0], 'GSM3495013': [nan, 20.0, 1.0], 'GSM3495014': [nan, 53.0, 0.0], 'GSM3495015': [nan, 32.0, 0.0], 'GSM3495016': [nan, 26.0, 0.0], 'GSM3495017': [nan, 28.0, 0.0], 'GSM3495018': [nan, 47.0, 0.0], 'GSM3495019': [nan, 24.0, 0.0], 'GSM3495020': [nan, 48.0, 0.0], 'GSM3495021': [nan, nan, nan], 'GSM3495022': [nan, 19.0, 0.0], 'GSM3495023': [nan, 41.0, 0.0], 'GSM3495024': [nan, 38.0, 0.0], 'GSM3495025': [nan, nan, nan], 'GSM3495026': [nan, 15.0, 0.0], 'GSM3495027': [nan, 12.0, 1.0], 'GSM3495028': [nan, 13.0, 0.0], 'GSM3495029': [nan, nan, nan], 'GSM3495030': [nan, 11.0, 1.0], 'GSM3495031': [nan, nan, nan], 'GSM3495032': [nan, 16.0, 1.0], 'GSM3495033': [nan, 11.0, 1.0], 'GSM3495034': [nan, nan, nan], 'GSM3495035': [nan, 35.0, 0.0], 'GSM3495036': [nan, 26.0, 0.0], 'GSM3495037': [nan, 39.0, 0.0], 'GSM3495038': [nan, 46.0, 0.0], 'GSM3495039': [nan, 42.0, 0.0], 'GSM3495040': [nan, 20.0, 1.0], 'GSM3495041': [nan, 69.0, 1.0], 'GSM3495042': [nan, 69.0, 0.0], 'GSM3495043': [nan, 47.0, 1.0], 'GSM3495044': [nan, 47.0, 1.0], 'GSM3495045': [nan, 56.0, 0.0], 'GSM3495046': [nan, 54.0, 0.0], 'GSM3495047': [nan, 53.0, 0.0], 'GSM3495048': [nan, 50.0, 0.0], 'GSM3495049': [nan, 22.0, 1.0], 'GSM3495050': [nan, 62.0, 0.0], 'GSM3495051': [nan, 74.0, 0.0], 'GSM3495052': [0.0, 57.0, 0.0], 'GSM3495053': [0.0, 47.0, 0.0], 'GSM3495054': [nan, 70.0, 0.0], 'GSM3495055': [nan, 50.0, 0.0], 'GSM3495056': [0.0, 52.0, 0.0], 'GSM3495057': [nan, 43.0, 0.0], 'GSM3495058': [0.0, 57.0, 0.0], 'GSM3495059': [nan, 53.0, 0.0], 'GSM3495060': [nan, 70.0, 0.0], 'GSM3495061': [0.0, 41.0, 0.0], 'GSM3495062': [nan, 61.0, 0.0], 'GSM3495063': [0.0, 39.0, 0.0], 'GSM3495064': [0.0, 58.0, 0.0], 'GSM3495065': [nan, 55.0, 0.0], 'GSM3495066': [nan, 63.0, 0.0], 'GSM3495067': [0.0, 60.0, 0.0], 'GSM3495068': [nan, 43.0, 0.0], 'GSM3495069': [nan, 68.0, 0.0], 'GSM3495070': [nan, 67.0, 0.0], 'GSM3495071': [nan, 50.0, 0.0], 'GSM3495072': [nan, 67.0, 0.0], 'GSM3495073': [0.0, 51.0, 0.0], 'GSM3495074': [0.0, 59.0, 0.0], 'GSM3495075': [0.0, 44.0, 0.0], 'GSM3495076': [nan, 35.0, 0.0], 'GSM3495077': [nan, 83.0, 0.0], 'GSM3495078': [nan, 78.0, 0.0], 'GSM3495079': [nan, 88.0, 0.0], 'GSM3495080': [nan, 41.0, 0.0], 'GSM3495081': [0.0, 60.0, 0.0], 'GSM3495082': [nan, 72.0, 0.0], 'GSM3495083': [nan, 53.0, 0.0]}\n",
120
+ "Clinical data saved to ../../output/preprocess/Crohns_Disease/clinical_data/GSE123088.csv\n"
121
+ ]
122
+ }
123
+ ],
124
+ "source": [
125
+ "# 1. Gene Expression Data Availability\n",
126
+ "# Based on the background information, this dataset likely contains gene expression data, so:\n",
127
+ "is_gene_available = True\n",
128
+ "\n",
129
+ "# 2. Variable Availability and Data Type Conversion\n",
130
+ "# 2.1 Data Availability\n",
131
+ "# Trait: Locate Crohn's Disease data in sample characteristics dictionary\n",
132
+ "trait_row = 1 # Primary diagnosis is in row 1, which includes \"CROHN_DISEASE\"\n",
133
+ "\n",
134
+ "# Age: Age information is available in row 3 and 4\n",
135
+ "age_row = 3 # Using row 3 as the main source for age data\n",
136
+ "\n",
137
+ "# Gender: Gender information is in row 2 and 3 (labeled as \"Sex\")\n",
138
+ "gender_row = 2 # Using row 2 as the main source for gender data\n",
139
+ "\n",
140
+ "# 2.2 Data Type Conversion\n",
141
+ "def convert_trait(value):\n",
142
+ " \"\"\"Convert trait values to binary (1 for Crohn's Disease, 0 for Control)\"\"\"\n",
143
+ " if isinstance(value, str):\n",
144
+ " value = value.strip().lower()\n",
145
+ " if ':' in value:\n",
146
+ " value = value.split(':', 1)[1].strip()\n",
147
+ " \n",
148
+ " if 'crohn' in value or 'crohn_disease' in value:\n",
149
+ " return 1\n",
150
+ " elif 'control' in value or 'healthy_control' in value:\n",
151
+ " return 0\n",
152
+ " return None\n",
153
+ "\n",
154
+ "def convert_age(value):\n",
155
+ " \"\"\"Convert age values to continuous numeric values\"\"\"\n",
156
+ " if isinstance(value, str):\n",
157
+ " value = value.strip()\n",
158
+ " if ':' in value:\n",
159
+ " value = value.split(':', 1)[1].strip()\n",
160
+ " \n",
161
+ " try:\n",
162
+ " return float(value)\n",
163
+ " except ValueError:\n",
164
+ " pass\n",
165
+ " return None\n",
166
+ "\n",
167
+ "def convert_gender(value):\n",
168
+ " \"\"\"Convert gender values to binary (0 for Female, 1 for Male)\"\"\"\n",
169
+ " if isinstance(value, str):\n",
170
+ " value = value.strip().lower()\n",
171
+ " if ':' in value:\n",
172
+ " value = value.split(':', 1)[1].strip()\n",
173
+ " \n",
174
+ " if 'female' in value:\n",
175
+ " return 0\n",
176
+ " elif 'male' in value:\n",
177
+ " return 1\n",
178
+ " return None\n",
179
+ "\n",
180
+ "# 3. Save Metadata\n",
181
+ "# Initial filtering on usability\n",
182
+ "is_trait_available = trait_row is not None\n",
183
+ "initial_validation = validate_and_save_cohort_info(\n",
184
+ " is_final=False,\n",
185
+ " cohort=cohort,\n",
186
+ " info_path=json_path,\n",
187
+ " is_gene_available=is_gene_available,\n",
188
+ " is_trait_available=is_trait_available\n",
189
+ ")\n",
190
+ "\n",
191
+ "# 4. Clinical Feature Extraction\n",
192
+ "if trait_row is not None:\n",
193
+ " # Extract clinical features\n",
194
+ " clinical_selected = geo_select_clinical_features(\n",
195
+ " clinical_df=clinical_data,\n",
196
+ " trait=trait,\n",
197
+ " trait_row=trait_row,\n",
198
+ " convert_trait=convert_trait,\n",
199
+ " age_row=age_row,\n",
200
+ " convert_age=convert_age,\n",
201
+ " gender_row=gender_row,\n",
202
+ " convert_gender=convert_gender\n",
203
+ " )\n",
204
+ " \n",
205
+ " # Preview the extracted clinical data\n",
206
+ " preview = preview_df(clinical_selected)\n",
207
+ " print(\"Preview of clinical data:\")\n",
208
+ " print(preview)\n",
209
+ " \n",
210
+ " # Save clinical data to CSV\n",
211
+ " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
212
+ " clinical_selected.to_csv(out_clinical_data_file, index=True)\n",
213
+ " print(f\"Clinical data saved to {out_clinical_data_file}\")\n"
214
+ ]
215
+ },
216
+ {
217
+ "cell_type": "markdown",
218
+ "id": "560141d1",
219
+ "metadata": {},
220
+ "source": [
221
+ "### Step 3: Gene Data Extraction"
222
+ ]
223
+ },
224
+ {
225
+ "cell_type": "code",
226
+ "execution_count": 4,
227
+ "id": "82351f47",
228
+ "metadata": {
229
+ "execution": {
230
+ "iopub.execute_input": "2025-03-25T08:32:06.973196Z",
231
+ "iopub.status.busy": "2025-03-25T08:32:06.973090Z",
232
+ "iopub.status.idle": "2025-03-25T08:32:07.491225Z",
233
+ "shell.execute_reply": "2025-03-25T08:32:07.490840Z"
234
+ }
235
+ },
236
+ "outputs": [
237
+ {
238
+ "name": "stdout",
239
+ "output_type": "stream",
240
+ "text": [
241
+ "\n",
242
+ "First 20 gene/probe identifiers:\n",
243
+ "Index(['1', '2', '3', '9', '10', '12', '13', '14', '15', '16', '18', '19',\n",
244
+ " '20', '21', '22', '23', '24', '25', '26', '27'],\n",
245
+ " dtype='object', name='ID')\n",
246
+ "\n",
247
+ "Gene data dimensions: 24166 genes × 204 samples\n"
248
+ ]
249
+ }
250
+ ],
251
+ "source": [
252
+ "# 1. Re-identify the SOFT and matrix files to ensure we have the correct paths\n",
253
+ "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
254
+ "\n",
255
+ "# 2. Extract the gene expression data from the matrix file\n",
256
+ "gene_data = get_genetic_data(matrix_file)\n",
257
+ "\n",
258
+ "# 3. Print the first 20 row IDs (gene or probe identifiers)\n",
259
+ "print(\"\\nFirst 20 gene/probe identifiers:\")\n",
260
+ "print(gene_data.index[:20])\n",
261
+ "\n",
262
+ "# 4. Print the dimensions of the gene expression data\n",
263
+ "print(f\"\\nGene data dimensions: {gene_data.shape[0]} genes × {gene_data.shape[1]} samples\")\n",
264
+ "\n",
265
+ "# Note: we keep is_gene_available as True since we successfully extracted gene expression data\n",
266
+ "is_gene_available = True\n"
267
+ ]
268
+ },
269
+ {
270
+ "cell_type": "markdown",
271
+ "id": "b66390f1",
272
+ "metadata": {},
273
+ "source": [
274
+ "### Step 4: Gene Identifier Review"
275
+ ]
276
+ },
277
+ {
278
+ "cell_type": "code",
279
+ "execution_count": 5,
280
+ "id": "3630afeb",
281
+ "metadata": {
282
+ "execution": {
283
+ "iopub.execute_input": "2025-03-25T08:32:07.492620Z",
284
+ "iopub.status.busy": "2025-03-25T08:32:07.492499Z",
285
+ "iopub.status.idle": "2025-03-25T08:32:07.494449Z",
286
+ "shell.execute_reply": "2025-03-25T08:32:07.494154Z"
287
+ }
288
+ },
289
+ "outputs": [],
290
+ "source": [
291
+ "# Examining the gene identifiers\n",
292
+ "# These appear to be integer/numeric identifiers rather than standard HGNC gene symbols\n",
293
+ "# Human gene symbols are typically alphanumeric (like \"TP53\", \"BRCA1\", \"IL6\")\n",
294
+ "# The identifiers shown are simple numbers which likely need mapping to gene symbols\n",
295
+ "\n",
296
+ "requires_gene_mapping = True\n"
297
+ ]
298
+ },
299
+ {
300
+ "cell_type": "markdown",
301
+ "id": "cbc89361",
302
+ "metadata": {},
303
+ "source": [
304
+ "### Step 5: Gene Annotation"
305
+ ]
306
+ },
307
+ {
308
+ "cell_type": "code",
309
+ "execution_count": 6,
310
+ "id": "40247968",
311
+ "metadata": {
312
+ "execution": {
313
+ "iopub.execute_input": "2025-03-25T08:32:07.495710Z",
314
+ "iopub.status.busy": "2025-03-25T08:32:07.495601Z",
315
+ "iopub.status.idle": "2025-03-25T08:32:11.926403Z",
316
+ "shell.execute_reply": "2025-03-25T08:32:11.925945Z"
317
+ }
318
+ },
319
+ "outputs": [
320
+ {
321
+ "name": "stdout",
322
+ "output_type": "stream",
323
+ "text": [
324
+ "Gene annotation dataframe column names:\n",
325
+ "Index(['ID', 'ENTREZ_GENE_ID', 'SPOT_ID'], dtype='object')\n",
326
+ "\n",
327
+ "Preview of gene annotation data:\n",
328
+ "{'ID': ['1', '2', '3'], 'ENTREZ_GENE_ID': ['1', '2', '3'], 'SPOT_ID': [1.0, 2.0, 3.0]}\n"
329
+ ]
330
+ }
331
+ ],
332
+ "source": [
333
+ "# 1. First get the file paths using geo_get_relevant_filepaths function\n",
334
+ "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
335
+ "\n",
336
+ "# 2. Extract gene annotation data from the SOFT file\n",
337
+ "gene_annotation = get_gene_annotation(soft_file)\n",
338
+ "\n",
339
+ "# 3. Preview the gene annotation dataframe\n",
340
+ "print(\"Gene annotation dataframe column names:\")\n",
341
+ "print(gene_annotation.columns)\n",
342
+ "\n",
343
+ "# Preview the first few rows to understand the data structure\n",
344
+ "print(\"\\nPreview of gene annotation data:\")\n",
345
+ "annotation_preview = preview_df(gene_annotation, n=3)\n",
346
+ "print(annotation_preview)\n",
347
+ "\n",
348
+ "# Maintain gene availability status as True based on previous steps\n",
349
+ "is_gene_available = True\n"
350
+ ]
351
+ },
352
+ {
353
+ "cell_type": "markdown",
354
+ "id": "13a5c0e2",
355
+ "metadata": {},
356
+ "source": [
357
+ "### Step 6: Gene Identifier Mapping"
358
+ ]
359
+ },
360
+ {
361
+ "cell_type": "code",
362
+ "execution_count": 7,
363
+ "id": "301c359b",
364
+ "metadata": {
365
+ "execution": {
366
+ "iopub.execute_input": "2025-03-25T08:32:11.927890Z",
367
+ "iopub.status.busy": "2025-03-25T08:32:11.927767Z",
368
+ "iopub.status.idle": "2025-03-25T08:32:20.401799Z",
369
+ "shell.execute_reply": "2025-03-25T08:32:20.401238Z"
370
+ }
371
+ },
372
+ "outputs": [
373
+ {
374
+ "name": "stdout",
375
+ "output_type": "stream",
376
+ "text": [
377
+ "Number of probes with mappings: 4740924\n",
378
+ "Sample of mapping data:\n",
379
+ " ID Gene\n",
380
+ "0 1 1\n",
381
+ "1 2 2\n",
382
+ "2 3 3\n",
383
+ "3 9 9\n",
384
+ "4 10 10\n"
385
+ ]
386
+ },
387
+ {
388
+ "name": "stdout",
389
+ "output_type": "stream",
390
+ "text": [
391
+ "\n",
392
+ "After mapping, gene data dimensions: (0, 204)\n",
393
+ "First 10 mapped gene symbols (if any):\n",
394
+ "No genes were successfully mapped. This might indicate an issue with the gene annotation format.\n"
395
+ ]
396
+ },
397
+ {
398
+ "name": "stdout",
399
+ "output_type": "stream",
400
+ "text": [
401
+ "\n",
402
+ "Using original probe data: 24166 probes × 204 samples\n"
403
+ ]
404
+ }
405
+ ],
406
+ "source": [
407
+ "# 1. Observe the gene identifiers in both datasets\n",
408
+ "# From previous outputs:\n",
409
+ "# - Gene expression data: identifiers are numeric strings like '1', '2', '3'\n",
410
+ "# - Gene annotation data: has columns 'ID', 'ENTREZ_GENE_ID', 'SPOT_ID'\n",
411
+ "\n",
412
+ "# The 'ID' column in gene annotation matches the identifiers in gene expression data\n",
413
+ "# The 'ENTREZ_GENE_ID' column appears to contain Entrez Gene IDs which we need to map to gene symbols\n",
414
+ "\n",
415
+ "# 2. Create gene mapping dataframe\n",
416
+ "mapping_df = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='ENTREZ_GENE_ID')\n",
417
+ "\n",
418
+ "# Print information about the mapping\n",
419
+ "print(f\"Number of probes with mappings: {len(mapping_df)}\")\n",
420
+ "print(f\"Sample of mapping data:\")\n",
421
+ "print(mapping_df.head())\n",
422
+ "\n",
423
+ "# 3. Apply gene mapping to convert probe-level measurements to gene expression data\n",
424
+ "gene_data = apply_gene_mapping(gene_data, mapping_df)\n",
425
+ "\n",
426
+ "# Print information about the mapped gene data\n",
427
+ "print(\"\\nAfter mapping, gene data dimensions:\", gene_data.shape)\n",
428
+ "print(\"First 10 mapped gene symbols (if any):\")\n",
429
+ "if len(gene_data) > 0:\n",
430
+ " print(gene_data.index[:10])\n",
431
+ "else:\n",
432
+ " print(\"No genes were successfully mapped. This might indicate an issue with the gene annotation format.\")\n",
433
+ " \n",
434
+ " # Save original probe data as gene data for downstream processes\n",
435
+ " # This is a fallback to allow the pipeline to continue\n",
436
+ " gene_data = get_genetic_data(matrix_file)\n",
437
+ " gene_data.index.name = 'Gene'\n",
438
+ " print(f\"\\nUsing original probe data: {gene_data.shape[0]} probes × {gene_data.shape[1]} samples\")\n"
439
+ ]
440
+ },
441
+ {
442
+ "cell_type": "markdown",
443
+ "id": "6b205378",
444
+ "metadata": {},
445
+ "source": [
446
+ "### Step 7: Data Normalization and Linking"
447
+ ]
448
+ },
449
+ {
450
+ "cell_type": "code",
451
+ "execution_count": 8,
452
+ "id": "bc757bc5",
453
+ "metadata": {
454
+ "execution": {
455
+ "iopub.execute_input": "2025-03-25T08:32:20.403429Z",
456
+ "iopub.status.busy": "2025-03-25T08:32:20.403303Z",
457
+ "iopub.status.idle": "2025-03-25T08:32:21.008844Z",
458
+ "shell.execute_reply": "2025-03-25T08:32:21.008320Z"
459
+ }
460
+ },
461
+ "outputs": [
462
+ {
463
+ "name": "stdout",
464
+ "output_type": "stream",
465
+ "text": [
466
+ "Original probe data dimensions: (24166, 204)\n",
467
+ "Normalizing gene symbols...\n",
468
+ "Gene data shape after normalization: 0 genes × 204 samples\n",
469
+ "Gene expression data saved to ../../output/preprocess/Crohns_Disease/gene_data/GSE123088.csv\n",
470
+ "Loading clinical features...\n",
471
+ "Loading clinical features from ../../output/preprocess/Crohns_Disease/clinical_data/GSE123088.csv\n",
472
+ "Clinical data preview:\n",
473
+ "{'GSM3494884': [nan, 56.0, 1.0], 'GSM3494885': [nan, nan, nan], 'GSM3494886': [nan, 20.0, 0.0], 'GSM3494887': [nan, 51.0, 0.0], 'GSM3494888': [nan, 37.0, 1.0], 'GSM3494889': [nan, 61.0, 1.0], 'GSM3494890': [nan, nan, nan], 'GSM3494891': [nan, 31.0, 1.0], 'GSM3494892': [nan, 56.0, 0.0], 'GSM3494893': [nan, 41.0, 0.0], 'GSM3494894': [nan, 61.0, 0.0], 'GSM3494895': [nan, nan, nan], 'GSM3494896': [nan, 80.0, 1.0], 'GSM3494897': [nan, 53.0, 1.0], 'GSM3494898': [nan, 61.0, 1.0], 'GSM3494899': [nan, 73.0, 1.0], 'GSM3494900': [nan, 60.0, 1.0], 'GSM3494901': [nan, 76.0, 1.0], 'GSM3494902': [nan, 77.0, 0.0], 'GSM3494903': [nan, 74.0, 0.0], 'GSM3494904': [nan, 69.0, 1.0], 'GSM3494905': [nan, 77.0, 0.0], 'GSM3494906': [nan, 81.0, 0.0], 'GSM3494907': [nan, 70.0, 0.0], 'GSM3494908': [nan, 82.0, 0.0], 'GSM3494909': [nan, 69.0, 0.0], 'GSM3494910': [nan, 82.0, 0.0], 'GSM3494911': [nan, 67.0, 0.0], 'GSM3494912': [nan, 67.0, 0.0], 'GSM3494913': [nan, 78.0, 0.0], 'GSM3494914': [nan, 67.0, 0.0], 'GSM3494915': [nan, 74.0, 1.0], 'GSM3494916': [nan, nan, nan], 'GSM3494917': [nan, 51.0, 1.0], 'GSM3494918': [nan, 72.0, 1.0], 'GSM3494919': [nan, 66.0, 1.0], 'GSM3494920': [nan, 80.0, 0.0], 'GSM3494921': [1.0, 36.0, 1.0], 'GSM3494922': [1.0, 67.0, 0.0], 'GSM3494923': [1.0, 31.0, 0.0], 'GSM3494924': [1.0, 31.0, 0.0], 'GSM3494925': [1.0, 45.0, 0.0], 'GSM3494926': [1.0, 56.0, 0.0], 'GSM3494927': [1.0, 65.0, 0.0], 'GSM3494928': [1.0, 53.0, 0.0], 'GSM3494929': [1.0, 48.0, 0.0], 'GSM3494930': [1.0, 50.0, 0.0], 'GSM3494931': [1.0, 76.0, 1.0], 'GSM3494932': [nan, nan, nan], 'GSM3494933': [nan, 24.0, 0.0], 'GSM3494934': [nan, 42.0, 0.0], 'GSM3494935': [nan, 76.0, 1.0], 'GSM3494936': [nan, 22.0, 1.0], 'GSM3494937': [nan, nan, nan], 'GSM3494938': [nan, 23.0, 0.0], 'GSM3494939': [0.0, 34.0, 1.0], 'GSM3494940': [0.0, 43.0, 1.0], 'GSM3494941': [0.0, 47.0, 1.0], 'GSM3494942': [0.0, 24.0, 0.0], 'GSM3494943': [0.0, 55.0, 1.0], 'GSM3494944': [0.0, 48.0, 1.0], 'GSM3494945': [0.0, 58.0, 1.0], 'GSM3494946': [0.0, 30.0, 0.0], 'GSM3494947': [0.0, 28.0, 1.0], 'GSM3494948': [0.0, 41.0, 0.0], 'GSM3494949': [0.0, 63.0, 1.0], 'GSM3494950': [0.0, 55.0, 0.0], 'GSM3494951': [0.0, 55.0, 0.0], 'GSM3494952': [0.0, 67.0, 1.0], 'GSM3494953': [0.0, 47.0, 0.0], 'GSM3494954': [0.0, 46.0, 0.0], 'GSM3494955': [0.0, 49.0, 1.0], 'GSM3494956': [0.0, 23.0, 1.0], 'GSM3494957': [0.0, 68.0, 1.0], 'GSM3494958': [0.0, 39.0, 1.0], 'GSM3494959': [0.0, 24.0, 1.0], 'GSM3494960': [0.0, 36.0, 0.0], 'GSM3494961': [0.0, 58.0, 0.0], 'GSM3494962': [0.0, 38.0, 0.0], 'GSM3494963': [0.0, 27.0, 0.0], 'GSM3494964': [0.0, 67.0, 0.0], 'GSM3494965': [0.0, 61.0, 1.0], 'GSM3494966': [0.0, 69.0, 1.0], 'GSM3494967': [0.0, 63.0, 1.0], 'GSM3494968': [0.0, 60.0, 0.0], 'GSM3494969': [0.0, 17.0, 1.0], 'GSM3494970': [0.0, 10.0, 0.0], 'GSM3494971': [0.0, 9.0, 1.0], 'GSM3494972': [0.0, 13.0, 0.0], 'GSM3494973': [0.0, 10.0, 1.0], 'GSM3494974': [0.0, 13.0, 0.0], 'GSM3494975': [0.0, 15.0, 1.0], 'GSM3494976': [0.0, 12.0, 1.0], 'GSM3494977': [0.0, 13.0, 1.0], 'GSM3494978': [nan, 81.0, 0.0], 'GSM3494979': [nan, 94.0, 0.0], 'GSM3494980': [nan, 51.0, 1.0], 'GSM3494981': [nan, 40.0, 1.0], 'GSM3494982': [nan, nan, nan], 'GSM3494983': [nan, 97.0, 1.0], 'GSM3494984': [nan, 23.0, 1.0], 'GSM3494985': [nan, 93.0, 0.0], 'GSM3494986': [nan, 58.0, 1.0], 'GSM3494987': [nan, 28.0, 0.0], 'GSM3494988': [nan, 54.0, 1.0], 'GSM3494989': [nan, 15.0, 1.0], 'GSM3494990': [nan, 8.0, 1.0], 'GSM3494991': [nan, 11.0, 1.0], 'GSM3494992': [nan, 12.0, 1.0], 'GSM3494993': [nan, 8.0, 0.0], 'GSM3494994': [nan, 14.0, 1.0], 'GSM3494995': [nan, 8.0, 0.0], 'GSM3494996': [nan, 10.0, 1.0], 'GSM3494997': [nan, 14.0, 1.0], 'GSM3494998': [nan, 13.0, 1.0], 'GSM3494999': [nan, 40.0, 0.0], 'GSM3495000': [nan, 52.0, 0.0], 'GSM3495001': [nan, 42.0, 0.0], 'GSM3495002': [nan, 29.0, 0.0], 'GSM3495003': [nan, 43.0, 0.0], 'GSM3495004': [nan, 41.0, 0.0], 'GSM3495005': [nan, 54.0, 1.0], 'GSM3495006': [nan, 42.0, 1.0], 'GSM3495007': [nan, 49.0, 1.0], 'GSM3495008': [nan, 45.0, 0.0], 'GSM3495009': [nan, 56.0, 1.0], 'GSM3495010': [nan, 64.0, 0.0], 'GSM3495011': [nan, 71.0, 0.0], 'GSM3495012': [nan, 48.0, 0.0], 'GSM3495013': [nan, 20.0, 1.0], 'GSM3495014': [nan, 53.0, 0.0], 'GSM3495015': [nan, 32.0, 0.0], 'GSM3495016': [nan, 26.0, 0.0], 'GSM3495017': [nan, 28.0, 0.0], 'GSM3495018': [nan, 47.0, 0.0], 'GSM3495019': [nan, 24.0, 0.0], 'GSM3495020': [nan, 48.0, 0.0], 'GSM3495021': [nan, nan, nan], 'GSM3495022': [nan, 19.0, 0.0], 'GSM3495023': [nan, 41.0, 0.0], 'GSM3495024': [nan, 38.0, 0.0], 'GSM3495025': [nan, nan, nan], 'GSM3495026': [nan, 15.0, 0.0], 'GSM3495027': [nan, 12.0, 1.0], 'GSM3495028': [nan, 13.0, 0.0], 'GSM3495029': [nan, nan, nan], 'GSM3495030': [nan, 11.0, 1.0], 'GSM3495031': [nan, nan, nan], 'GSM3495032': [nan, 16.0, 1.0], 'GSM3495033': [nan, 11.0, 1.0], 'GSM3495034': [nan, nan, nan], 'GSM3495035': [nan, 35.0, 0.0], 'GSM3495036': [nan, 26.0, 0.0], 'GSM3495037': [nan, 39.0, 0.0], 'GSM3495038': [nan, 46.0, 0.0], 'GSM3495039': [nan, 42.0, 0.0], 'GSM3495040': [nan, 20.0, 1.0], 'GSM3495041': [nan, 69.0, 1.0], 'GSM3495042': [nan, 69.0, 0.0], 'GSM3495043': [nan, 47.0, 1.0], 'GSM3495044': [nan, 47.0, 1.0], 'GSM3495045': [nan, 56.0, 0.0], 'GSM3495046': [nan, 54.0, 0.0], 'GSM3495047': [nan, 53.0, 0.0], 'GSM3495048': [nan, 50.0, 0.0], 'GSM3495049': [nan, 22.0, 1.0], 'GSM3495050': [nan, 62.0, 0.0], 'GSM3495051': [nan, 74.0, 0.0], 'GSM3495052': [0.0, 57.0, 0.0], 'GSM3495053': [0.0, 47.0, 0.0], 'GSM3495054': [nan, 70.0, 0.0], 'GSM3495055': [nan, 50.0, 0.0], 'GSM3495056': [0.0, 52.0, 0.0], 'GSM3495057': [nan, 43.0, 0.0], 'GSM3495058': [0.0, 57.0, 0.0], 'GSM3495059': [nan, 53.0, 0.0], 'GSM3495060': [nan, 70.0, 0.0], 'GSM3495061': [0.0, 41.0, 0.0], 'GSM3495062': [nan, 61.0, 0.0], 'GSM3495063': [0.0, 39.0, 0.0], 'GSM3495064': [0.0, 58.0, 0.0], 'GSM3495065': [nan, 55.0, 0.0], 'GSM3495066': [nan, 63.0, 0.0], 'GSM3495067': [0.0, 60.0, 0.0], 'GSM3495068': [nan, 43.0, 0.0], 'GSM3495069': [nan, 68.0, 0.0], 'GSM3495070': [nan, 67.0, 0.0], 'GSM3495071': [nan, 50.0, 0.0], 'GSM3495072': [nan, 67.0, 0.0], 'GSM3495073': [0.0, 51.0, 0.0], 'GSM3495074': [0.0, 59.0, 0.0], 'GSM3495075': [0.0, 44.0, 0.0], 'GSM3495076': [nan, 35.0, 0.0], 'GSM3495077': [nan, 83.0, 0.0], 'GSM3495078': [nan, 78.0, 0.0], 'GSM3495079': [nan, 88.0, 0.0], 'GSM3495080': [nan, 41.0, 0.0], 'GSM3495081': [0.0, 60.0, 0.0], 'GSM3495082': [nan, 72.0, 0.0], 'GSM3495083': [nan, 53.0, 0.0]}\n",
474
+ "Clinical data shape: (3, 204)\n",
475
+ "Linking clinical and genetic data...\n",
476
+ "Linked data shape: (204, 3)\n",
477
+ "Error: Linked data is missing trait data or gene expression data.\n",
478
+ "Abnormality detected in the cohort: GSE123088. Preprocessing failed.\n",
479
+ "Dataset deemed not usable due to incomplete data.\n"
480
+ ]
481
+ }
482
+ ],
483
+ "source": [
484
+ "# 1. Make sure we have the original gene_data before any mapping attempts\n",
485
+ "original_gene_data = get_genetic_data(matrix_file)\n",
486
+ "print(f\"Original probe data dimensions: {original_gene_data.shape}\")\n",
487
+ "\n",
488
+ "# Handle the case where gene data is empty after mapping\n",
489
+ "if gene_data.shape[0] == 0:\n",
490
+ " print(\"Warning: No genes were successfully mapped to symbols. Using probe IDs as features instead.\")\n",
491
+ " # Use the original probe-level data instead of the empty mapped data\n",
492
+ " gene_data_normalized = original_gene_data\n",
493
+ " print(f\"Using original probe data as features: {gene_data_normalized.shape[0]} probes × {gene_data_normalized.shape[1]} samples\")\n",
494
+ "else:\n",
495
+ " # If we have mapped gene data, proceed with normalization\n",
496
+ " print(\"Normalizing gene symbols...\")\n",
497
+ " gene_data_normalized = normalize_gene_symbols_in_index(gene_data)\n",
498
+ " print(f\"Gene data shape after normalization: {gene_data_normalized.shape[0]} genes × {gene_data_normalized.shape[1]} samples\")\n",
499
+ "\n",
500
+ "# Save the gene data (normalized or probe-based)\n",
501
+ "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
502
+ "gene_data_normalized.to_csv(out_gene_data_file)\n",
503
+ "print(f\"Gene expression data saved to {out_gene_data_file}\")\n",
504
+ "\n",
505
+ "# Load clinical data\n",
506
+ "print(\"Loading clinical features...\")\n",
507
+ "# Check if the clinical data file exists\n",
508
+ "if os.path.exists(out_clinical_data_file):\n",
509
+ " print(f\"Loading clinical features from {out_clinical_data_file}\")\n",
510
+ " clinical_data = pd.read_csv(out_clinical_data_file, index_col=0)\n",
511
+ "else:\n",
512
+ " # Extract clinical features from the original source\n",
513
+ " print(\"Extracting clinical features from the original source...\")\n",
514
+ " # Get background information and clinical data\n",
515
+ " background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']\n",
516
+ " clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']\n",
517
+ " background_info, clinical_raw = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)\n",
518
+ " \n",
519
+ " # Extract clinical features\n",
520
+ " clinical_data = geo_select_clinical_features(\n",
521
+ " clinical_df=clinical_raw,\n",
522
+ " trait=trait,\n",
523
+ " trait_row=trait_row,\n",
524
+ " convert_trait=convert_trait,\n",
525
+ " age_row=age_row,\n",
526
+ " convert_age=convert_age,\n",
527
+ " gender_row=gender_row,\n",
528
+ " convert_gender=convert_gender\n",
529
+ " )\n",
530
+ " \n",
531
+ " # Save the extracted clinical features\n",
532
+ " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
533
+ " clinical_data.to_csv(out_clinical_data_file)\n",
534
+ "\n",
535
+ "print(\"Clinical data preview:\")\n",
536
+ "print(preview_df(clinical_data))\n",
537
+ "print(f\"Clinical data shape: {clinical_data.shape}\")\n",
538
+ "\n",
539
+ "# Link clinical and genetic data\n",
540
+ "print(\"Linking clinical and genetic data...\")\n",
541
+ "linked_data = geo_link_clinical_genetic_data(clinical_data, gene_data_normalized)\n",
542
+ "print(f\"Linked data shape: {linked_data.shape}\")\n",
543
+ "\n",
544
+ "# Verify we have both trait and gene data in the linked dataset\n",
545
+ "has_trait_data = trait in linked_data.columns\n",
546
+ "has_genetic_data = len(linked_data.columns) > 3 # More than just trait, age, and gender columns\n",
547
+ "\n",
548
+ "if not has_trait_data or not has_genetic_data:\n",
549
+ " print(\"Error: Linked data is missing trait data or gene expression data.\")\n",
550
+ " is_usable = validate_and_save_cohort_info(\n",
551
+ " is_final=True,\n",
552
+ " cohort=cohort,\n",
553
+ " info_path=json_path,\n",
554
+ " is_gene_available=has_genetic_data,\n",
555
+ " is_trait_available=has_trait_data,\n",
556
+ " is_biased=True,\n",
557
+ " df=linked_data,\n",
558
+ " note=\"Failed to properly link gene expression data with clinical features.\"\n",
559
+ " )\n",
560
+ " print(\"Dataset deemed not usable due to incomplete data.\")\n",
561
+ "else:\n",
562
+ " # Handle missing values\n",
563
+ " print(\"Handling missing values...\")\n",
564
+ " linked_data_clean = handle_missing_values(linked_data, trait_col=trait)\n",
565
+ " print(f\"Data shape after handling missing values: {linked_data_clean.shape}\")\n",
566
+ " \n",
567
+ " # If we have samples after missing value handling\n",
568
+ " if linked_data_clean.shape[0] > 0:\n",
569
+ " # Check for bias in features\n",
570
+ " print(\"\\nChecking for bias in feature variables:\")\n",
571
+ " is_biased, linked_data_final = judge_and_remove_biased_features(linked_data_clean, trait)\n",
572
+ " \n",
573
+ " # Final quality validation\n",
574
+ " note = \"Dataset contains gene expression data (using probe IDs) for Crohn's Disease patients.\"\n",
575
+ " is_usable = validate_and_save_cohort_info(\n",
576
+ " is_final=True,\n",
577
+ " cohort=cohort,\n",
578
+ " info_path=json_path,\n",
579
+ " is_gene_available=True,\n",
580
+ " is_trait_available=True,\n",
581
+ " is_biased=is_biased,\n",
582
+ " df=linked_data_final,\n",
583
+ " note=note\n",
584
+ " )\n",
585
+ " \n",
586
+ " # Save linked data if usable\n",
587
+ " if is_usable:\n",
588
+ " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n",
589
+ " linked_data_final.to_csv(out_data_file)\n",
590
+ " print(f\"Linked data saved to {out_data_file}\")\n",
591
+ " print(f\"Final dataset shape: {linked_data_final.shape}\")\n",
592
+ " else:\n",
593
+ " print(\"Dataset deemed not usable for trait association studies, linked data not saved.\")\n",
594
+ " else:\n",
595
+ " print(\"Error: No samples remain after handling missing values.\")\n",
596
+ " is_usable = validate_and_save_cohort_info(\n",
597
+ " is_final=True,\n",
598
+ " cohort=cohort,\n",
599
+ " info_path=json_path,\n",
600
+ " is_gene_available=True,\n",
601
+ " is_trait_available=True,\n",
602
+ " is_biased=True,\n",
603
+ " df=pd.DataFrame(),\n",
604
+ " note=\"All samples were removed during missing value handling.\"\n",
605
+ " )\n",
606
+ " print(\"Dataset deemed not usable as all samples were filtered out.\")"
607
+ ]
608
+ }
609
+ ],
610
+ "metadata": {
611
+ "language_info": {
612
+ "codemirror_mode": {
613
+ "name": "ipython",
614
+ "version": 3
615
+ },
616
+ "file_extension": ".py",
617
+ "mimetype": "text/x-python",
618
+ "name": "python",
619
+ "nbconvert_exporter": "python",
620
+ "pygments_lexer": "ipython3",
621
+ "version": "3.10.16"
622
+ }
623
+ },
624
+ "nbformat": 4,
625
+ "nbformat_minor": 5
626
+ }
code/Crohns_Disease/GSE207022.ipynb ADDED
@@ -0,0 +1,661 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": 1,
6
+ "id": "0f8b4d34",
7
+ "metadata": {
8
+ "execution": {
9
+ "iopub.execute_input": "2025-03-25T08:33:57.360300Z",
10
+ "iopub.status.busy": "2025-03-25T08:33:57.360070Z",
11
+ "iopub.status.idle": "2025-03-25T08:33:57.525603Z",
12
+ "shell.execute_reply": "2025-03-25T08:33:57.525274Z"
13
+ }
14
+ },
15
+ "outputs": [],
16
+ "source": [
17
+ "import sys\n",
18
+ "import os\n",
19
+ "sys.path.append(os.path.abspath(os.path.join(os.getcwd(), '../..')))\n",
20
+ "\n",
21
+ "# Path Configuration\n",
22
+ "from tools.preprocess import *\n",
23
+ "\n",
24
+ "# Processing context\n",
25
+ "trait = \"Crohns_Disease\"\n",
26
+ "cohort = \"GSE207022\"\n",
27
+ "\n",
28
+ "# Input paths\n",
29
+ "in_trait_dir = \"../../input/GEO/Crohns_Disease\"\n",
30
+ "in_cohort_dir = \"../../input/GEO/Crohns_Disease/GSE207022\"\n",
31
+ "\n",
32
+ "# Output paths\n",
33
+ "out_data_file = \"../../output/preprocess/Crohns_Disease/GSE207022.csv\"\n",
34
+ "out_gene_data_file = \"../../output/preprocess/Crohns_Disease/gene_data/GSE207022.csv\"\n",
35
+ "out_clinical_data_file = \"../../output/preprocess/Crohns_Disease/clinical_data/GSE207022.csv\"\n",
36
+ "json_path = \"../../output/preprocess/Crohns_Disease/cohort_info.json\"\n"
37
+ ]
38
+ },
39
+ {
40
+ "cell_type": "markdown",
41
+ "id": "3697486b",
42
+ "metadata": {},
43
+ "source": [
44
+ "### Step 1: Initial Data Loading"
45
+ ]
46
+ },
47
+ {
48
+ "cell_type": "code",
49
+ "execution_count": 2,
50
+ "id": "3f907236",
51
+ "metadata": {
52
+ "execution": {
53
+ "iopub.execute_input": "2025-03-25T08:33:57.527022Z",
54
+ "iopub.status.busy": "2025-03-25T08:33:57.526873Z",
55
+ "iopub.status.idle": "2025-03-25T08:33:57.719591Z",
56
+ "shell.execute_reply": "2025-03-25T08:33:57.719251Z"
57
+ }
58
+ },
59
+ "outputs": [
60
+ {
61
+ "name": "stdout",
62
+ "output_type": "stream",
63
+ "text": [
64
+ "Background Information:\n",
65
+ "!Series_title\t\"Efficacy and safety of ustekinumab treatment in patients with Crohn's disease\"\n",
66
+ "!Series_summary\t\"UNITI-2 was a phase 3 clinical trial (ClinicalTrials.gov Identifier: NCT01369342) comparing the effects (both positive and negative) of an initial treatment with ustekinumab to a placebo over 8 weeks in patients with moderately to severely active Crohn's disease.\"\n",
67
+ "!Series_overall_design\t\"A gene expression profiling study was conducted in which rectum biopsy samples were collected for RNA extraction and hybridization to microarrays from patients (n=125) with moderate-to-severe Crohn's disease and from non-IBD subjects (n=23).\"\n",
68
+ "Sample Characteristics Dictionary:\n",
69
+ "{0: ['tissue: rectum'], 1: ['donor id: CNTO1275CRD3002-20554', 'donor id: CNTO1275CRD3002-20667', 'donor id: CNTO1275CRD3002-20449', 'donor id: CNTO1275CRD3002-20927', 'donor id: CNTO1275CRD3002-20270', 'donor id: CNTO1275CRD3002-20072', 'donor id: CNTO1275CRD3002-20109', 'donor id: CNTO1275CRD3002-20346', 'donor id: HC-1', 'donor id: HC-2', 'donor id: HC-3', 'donor id: HC-4', 'donor id: HC-5', 'donor id: HC-6', 'donor id: HC-7', 'donor id: HC-8', 'donor id: HC-9', 'donor id: HC-10', 'donor id: HC-11', 'donor id: HC-12', 'donor id: HC-13', 'donor id: HC-14', 'donor id: HC-15', 'donor id: HC-16', 'donor id: HC-17', 'donor id: HC-18', 'donor id: HC-19', 'donor id: HC-20', 'donor id: HC-21', 'donor id: HC-22'], 2: ['visit: I-WK0'], 3: [\"diagnosis: Crohn's disease\", 'diagnosis: healthy control'], 4: ['treatment: Ustekinumab 130 mg IV', 'treatment: Ustekinumab 6 mg/kg (520 mg)', 'treatment: Placebo IV', 'treatment: Ustekinumab 6 mg/kg (390 mg)', 'treatment: NA', 'treatment: Ustekinumab 6 mg/kg (260 mg)'], 5: ['inflamed area at week 0: Ileum and colon', 'inflamed area at week 0: Colon only', 'inflamed area at week 0: NA'], 6: ['mucosal healing at week 8: N', 'mucosal healing at week 8: NA', 'mucosal healing at week 8: Y']}\n"
70
+ ]
71
+ }
72
+ ],
73
+ "source": [
74
+ "from tools.preprocess import *\n",
75
+ "# 1. Identify the paths to the SOFT file and the matrix file\n",
76
+ "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
77
+ "\n",
78
+ "# 2. Read the matrix file to obtain background information and sample characteristics data\n",
79
+ "background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']\n",
80
+ "clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']\n",
81
+ "background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)\n",
82
+ "\n",
83
+ "# 3. Obtain the sample characteristics dictionary from the clinical dataframe\n",
84
+ "sample_characteristics_dict = get_unique_values_by_row(clinical_data)\n",
85
+ "\n",
86
+ "# 4. Explicitly print out all the background information and the sample characteristics dictionary\n",
87
+ "print(\"Background Information:\")\n",
88
+ "print(background_info)\n",
89
+ "print(\"Sample Characteristics Dictionary:\")\n",
90
+ "print(sample_characteristics_dict)\n"
91
+ ]
92
+ },
93
+ {
94
+ "cell_type": "markdown",
95
+ "id": "8d858784",
96
+ "metadata": {},
97
+ "source": [
98
+ "### Step 2: Dataset Analysis and Clinical Feature Extraction"
99
+ ]
100
+ },
101
+ {
102
+ "cell_type": "code",
103
+ "execution_count": 3,
104
+ "id": "8b35b647",
105
+ "metadata": {
106
+ "execution": {
107
+ "iopub.execute_input": "2025-03-25T08:33:57.720882Z",
108
+ "iopub.status.busy": "2025-03-25T08:33:57.720776Z",
109
+ "iopub.status.idle": "2025-03-25T08:33:57.735229Z",
110
+ "shell.execute_reply": "2025-03-25T08:33:57.734940Z"
111
+ }
112
+ },
113
+ "outputs": [
114
+ {
115
+ "name": "stdout",
116
+ "output_type": "stream",
117
+ "text": [
118
+ "Preview of selected clinical features:\n",
119
+ "{'CNTO1275CRD3002-20554': [1.0], 'CNTO1275CRD3002-20667': [1.0], 'CNTO1275CRD3002-20449': [1.0], 'CNTO1275CRD3002-20927': [1.0], 'CNTO1275CRD3002-20270': [1.0], 'CNTO1275CRD3002-20072': [1.0], 'CNTO1275CRD3002-20109': [1.0], 'CNTO1275CRD3002-20346': [1.0], 'HC-1': [0.0], 'HC-2': [0.0], 'HC-3': [0.0], 'HC-4': [0.0], 'HC-5': [0.0], 'HC-6': [0.0], 'HC-7': [0.0], 'HC-8': [0.0], 'HC-9': [0.0], 'HC-10': [0.0], 'HC-11': [0.0], 'HC-12': [0.0], 'HC-13': [0.0], 'HC-14': [0.0], 'HC-15': [0.0], 'HC-16': [0.0], 'HC-17': [0.0], 'HC-18': [0.0], 'HC-19': [0.0], 'HC-20': [0.0], 'HC-21': [0.0], 'HC-22': [0.0]}\n",
120
+ "Clinical data saved to ../../output/preprocess/Crohns_Disease/clinical_data/GSE207022.csv\n"
121
+ ]
122
+ }
123
+ ],
124
+ "source": [
125
+ "import pandas as pd\n",
126
+ "import os\n",
127
+ "import json\n",
128
+ "from typing import Optional, Callable, Dict, Any\n",
129
+ "\n",
130
+ "# 1. Determine gene expression data availability\n",
131
+ "is_gene_available = True # This appears to be gene expression data from microarrays\n",
132
+ "\n",
133
+ "# 2. Determine clinical data availability and create conversion functions\n",
134
+ "\n",
135
+ "# 2.1 Identify rows containing relevant clinical data\n",
136
+ "trait_row = 3 # 'diagnosis: Crohn's disease', 'diagnosis: healthy control'\n",
137
+ "age_row = None # Age is not available in the sample characteristics\n",
138
+ "gender_row = None # Gender is not available in the sample characteristics\n",
139
+ "\n",
140
+ "# 2.2 Create conversion functions for clinical variables\n",
141
+ "\n",
142
+ "def convert_trait(val: str) -> int:\n",
143
+ " \"\"\"Convert Crohn's disease status to binary.\"\"\"\n",
144
+ " if val is None:\n",
145
+ " return None\n",
146
+ " if ':' in val:\n",
147
+ " val = val.split(':', 1)[1].strip().lower()\n",
148
+ " else:\n",
149
+ " val = val.strip().lower()\n",
150
+ " \n",
151
+ " if \"crohn\" in val:\n",
152
+ " return 1 # Has Crohn's disease\n",
153
+ " elif \"healthy\" in val or \"control\" in val:\n",
154
+ " return 0 # Healthy control\n",
155
+ " return None\n",
156
+ "\n",
157
+ "def convert_age(val: str) -> Optional[float]:\n",
158
+ " \"\"\"Convert age to continuous value.\"\"\"\n",
159
+ " # Not used since age data is not available\n",
160
+ " return None\n",
161
+ "\n",
162
+ "def convert_gender(val: str) -> Optional[int]:\n",
163
+ " \"\"\"Convert gender to binary (0 for female, 1 for male).\"\"\"\n",
164
+ " # Not used since gender data is not available\n",
165
+ " return None\n",
166
+ "\n",
167
+ "# 3. Save initial metadata about dataset usability\n",
168
+ "is_trait_available = trait_row is not None\n",
169
+ "validate_and_save_cohort_info(\n",
170
+ " is_final=False,\n",
171
+ " cohort=cohort,\n",
172
+ " info_path=json_path,\n",
173
+ " is_gene_available=is_gene_available,\n",
174
+ " is_trait_available=is_trait_available\n",
175
+ ")\n",
176
+ "\n",
177
+ "# 4. Extract clinical features if trait data is available\n",
178
+ "if trait_row is not None:\n",
179
+ " # Create the clinical data DataFrame from the sample characteristics dictionary\n",
180
+ " # Based on the previous output, we have samples in columns and characteristics in rows\n",
181
+ " sample_characteristics = {\n",
182
+ " 0: ['tissue: rectum'], \n",
183
+ " 1: ['donor id: CNTO1275CRD3002-20554', 'donor id: CNTO1275CRD3002-20667', 'donor id: CNTO1275CRD3002-20449', \n",
184
+ " 'donor id: CNTO1275CRD3002-20927', 'donor id: CNTO1275CRD3002-20270', 'donor id: CNTO1275CRD3002-20072', \n",
185
+ " 'donor id: CNTO1275CRD3002-20109', 'donor id: CNTO1275CRD3002-20346', 'donor id: HC-1', 'donor id: HC-2', \n",
186
+ " 'donor id: HC-3', 'donor id: HC-4', 'donor id: HC-5', 'donor id: HC-6', 'donor id: HC-7', 'donor id: HC-8', \n",
187
+ " 'donor id: HC-9', 'donor id: HC-10', 'donor id: HC-11', 'donor id: HC-12', 'donor id: HC-13', 'donor id: HC-14', \n",
188
+ " 'donor id: HC-15', 'donor id: HC-16', 'donor id: HC-17', 'donor id: HC-18', 'donor id: HC-19', 'donor id: HC-20', \n",
189
+ " 'donor id: HC-21', 'donor id: HC-22'], \n",
190
+ " 2: ['visit: I-WK0'], \n",
191
+ " 3: [\"diagnosis: Crohn's disease\", 'diagnosis: healthy control'], \n",
192
+ " 4: ['treatment: Ustekinumab 130 mg IV', 'treatment: Ustekinumab 6 mg/kg (520 mg)', 'treatment: Placebo IV', \n",
193
+ " 'treatment: Ustekinumab 6 mg/kg (390 mg)', 'treatment: NA', 'treatment: Ustekinumab 6 mg/kg (260 mg)'], \n",
194
+ " 5: ['inflamed area at week 0: Ileum and colon', 'inflamed area at week 0: Colon only', 'inflamed area at week 0: NA'], \n",
195
+ " 6: ['mucosal healing at week 8: N', 'mucosal healing at week 8: NA', 'mucosal healing at week 8: Y']\n",
196
+ " }\n",
197
+ " \n",
198
+ " # Let's convert this dictionary to a DataFrame that can be used with geo_select_clinical_features\n",
199
+ " # The function expects rows as sample characteristics and columns as samples\n",
200
+ " \n",
201
+ " # Create a list of sample IDs from the donor id row (row 1)\n",
202
+ " sample_ids = []\n",
203
+ " for donor_id in sample_characteristics[1]:\n",
204
+ " if ':' in donor_id:\n",
205
+ " sample_id = donor_id.split(':', 1)[1].strip()\n",
206
+ " sample_ids.append(sample_id)\n",
207
+ " \n",
208
+ " # Initialize a DataFrame with characteristics as rows and samples as columns\n",
209
+ " clinical_data = pd.DataFrame(index=range(len(sample_characteristics)), columns=sample_ids)\n",
210
+ " \n",
211
+ " # Fill the DataFrame with characteristic values\n",
212
+ " for row_idx, values in sample_characteristics.items():\n",
213
+ " # Handle the case where one row has multiple values (different for different samples)\n",
214
+ " if len(values) == 1:\n",
215
+ " # Same value for all samples\n",
216
+ " for col in clinical_data.columns:\n",
217
+ " clinical_data.iloc[row_idx, clinical_data.columns.get_loc(col)] = values[0]\n",
218
+ " else:\n",
219
+ " # Different values for different samples or less values than samples\n",
220
+ " # For diagnosis (row 3), we need to infer values from donor IDs\n",
221
+ " if row_idx == 3: # Diagnosis row\n",
222
+ " for col_idx, col in enumerate(clinical_data.columns):\n",
223
+ " if 'HC-' in col: # Healthy control\n",
224
+ " clinical_data.iloc[row_idx, col_idx] = 'diagnosis: healthy control'\n",
225
+ " else: # Crohn's disease\n",
226
+ " clinical_data.iloc[row_idx, col_idx] = \"diagnosis: Crohn's disease\"\n",
227
+ " else:\n",
228
+ " # For other rows, we'll set to None as we don't have enough information to map\n",
229
+ " for col_idx, col in enumerate(clinical_data.columns):\n",
230
+ " clinical_data.iloc[row_idx, col_idx] = None\n",
231
+ " \n",
232
+ " # Extract clinical features\n",
233
+ " selected_clinical = geo_select_clinical_features(\n",
234
+ " clinical_df=clinical_data,\n",
235
+ " trait=trait,\n",
236
+ " trait_row=trait_row,\n",
237
+ " convert_trait=convert_trait,\n",
238
+ " age_row=age_row,\n",
239
+ " convert_age=convert_age,\n",
240
+ " gender_row=gender_row,\n",
241
+ " convert_gender=convert_gender\n",
242
+ " )\n",
243
+ " \n",
244
+ " # Preview the extracted clinical features\n",
245
+ " preview = preview_df(selected_clinical)\n",
246
+ " print(\"Preview of selected clinical features:\")\n",
247
+ " print(preview)\n",
248
+ " \n",
249
+ " # Save the clinical data\n",
250
+ " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
251
+ " selected_clinical.to_csv(out_clinical_data_file)\n",
252
+ " print(f\"Clinical data saved to {out_clinical_data_file}\")\n"
253
+ ]
254
+ },
255
+ {
256
+ "cell_type": "markdown",
257
+ "id": "24cf5a7b",
258
+ "metadata": {},
259
+ "source": [
260
+ "### Step 3: Gene Data Extraction"
261
+ ]
262
+ },
263
+ {
264
+ "cell_type": "code",
265
+ "execution_count": 4,
266
+ "id": "55da15c9",
267
+ "metadata": {
268
+ "execution": {
269
+ "iopub.execute_input": "2025-03-25T08:33:57.736353Z",
270
+ "iopub.status.busy": "2025-03-25T08:33:57.736247Z",
271
+ "iopub.status.idle": "2025-03-25T08:33:58.128283Z",
272
+ "shell.execute_reply": "2025-03-25T08:33:58.127909Z"
273
+ }
274
+ },
275
+ "outputs": [
276
+ {
277
+ "name": "stdout",
278
+ "output_type": "stream",
279
+ "text": [
280
+ "\n",
281
+ "First 20 gene/probe identifiers:\n",
282
+ "Index(['1007_PM_s_at', '1053_PM_at', '117_PM_at', '121_PM_at', '1255_PM_g_at',\n",
283
+ " '1294_PM_at', '1316_PM_at', '1320_PM_at', '1405_PM_i_at', '1431_PM_at',\n",
284
+ " '1438_PM_at', '1487_PM_at', '1494_PM_f_at', '1552256_PM_a_at',\n",
285
+ " '1552257_PM_a_at', '1552258_PM_at', '1552261_PM_at', '1552263_PM_at',\n",
286
+ " '1552264_PM_a_at', '1552266_PM_at'],\n",
287
+ " dtype='object', name='ID')\n",
288
+ "\n",
289
+ "Gene data dimensions: 54715 genes × 148 samples\n"
290
+ ]
291
+ }
292
+ ],
293
+ "source": [
294
+ "# 1. Re-identify the SOFT and matrix files to ensure we have the correct paths\n",
295
+ "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
296
+ "\n",
297
+ "# 2. Extract the gene expression data from the matrix file\n",
298
+ "gene_data = get_genetic_data(matrix_file)\n",
299
+ "\n",
300
+ "# 3. Print the first 20 row IDs (gene or probe identifiers)\n",
301
+ "print(\"\\nFirst 20 gene/probe identifiers:\")\n",
302
+ "print(gene_data.index[:20])\n",
303
+ "\n",
304
+ "# 4. Print the dimensions of the gene expression data\n",
305
+ "print(f\"\\nGene data dimensions: {gene_data.shape[0]} genes × {gene_data.shape[1]} samples\")\n",
306
+ "\n",
307
+ "# Note: we keep is_gene_available as True since we successfully extracted gene expression data\n",
308
+ "is_gene_available = True\n"
309
+ ]
310
+ },
311
+ {
312
+ "cell_type": "markdown",
313
+ "id": "fdecb4fe",
314
+ "metadata": {},
315
+ "source": [
316
+ "### Step 4: Gene Identifier Review"
317
+ ]
318
+ },
319
+ {
320
+ "cell_type": "code",
321
+ "execution_count": 5,
322
+ "id": "5762dbd0",
323
+ "metadata": {
324
+ "execution": {
325
+ "iopub.execute_input": "2025-03-25T08:33:58.129510Z",
326
+ "iopub.status.busy": "2025-03-25T08:33:58.129392Z",
327
+ "iopub.status.idle": "2025-03-25T08:33:58.131254Z",
328
+ "shell.execute_reply": "2025-03-25T08:33:58.130975Z"
329
+ }
330
+ },
331
+ "outputs": [],
332
+ "source": [
333
+ "# Looking at the identifiers: '1007_PM_s_at', '1053_PM_at', etc.\n",
334
+ "# These are Affymetrix probe IDs from a microarray platform, not human gene symbols\n",
335
+ "# They need to be mapped to standard gene symbols for analysis\n",
336
+ "\n",
337
+ "requires_gene_mapping = True\n"
338
+ ]
339
+ },
340
+ {
341
+ "cell_type": "markdown",
342
+ "id": "ec50cac0",
343
+ "metadata": {},
344
+ "source": [
345
+ "### Step 5: Gene Annotation"
346
+ ]
347
+ },
348
+ {
349
+ "cell_type": "code",
350
+ "execution_count": 6,
351
+ "id": "bbe63921",
352
+ "metadata": {
353
+ "execution": {
354
+ "iopub.execute_input": "2025-03-25T08:33:58.132321Z",
355
+ "iopub.status.busy": "2025-03-25T08:33:58.132220Z",
356
+ "iopub.status.idle": "2025-03-25T08:34:07.025674Z",
357
+ "shell.execute_reply": "2025-03-25T08:34:07.025341Z"
358
+ }
359
+ },
360
+ "outputs": [
361
+ {
362
+ "name": "stdout",
363
+ "output_type": "stream",
364
+ "text": [
365
+ "Gene annotation preview:\n",
366
+ "{'ID': ['1007_PM_s_at', '1053_PM_at', '117_PM_at', '121_PM_at', '1255_PM_g_at'], 'GB_ACC': ['U48705', 'M87338', 'X51757', 'X69699', 'L36861'], 'SPOT_ID': [nan, nan, nan, nan, nan], 'Species Scientific Name': ['Homo sapiens', 'Homo sapiens', 'Homo sapiens', 'Homo sapiens', 'Homo sapiens'], 'Annotation Date': ['Aug 20, 2010', 'Aug 20, 2010', 'Aug 20, 2010', 'Aug 20, 2010', 'Aug 20, 2010'], 'Sequence Type': ['Exemplar sequence', 'Exemplar sequence', 'Exemplar sequence', 'Exemplar sequence', 'Exemplar sequence'], 'Sequence Source': ['Affymetrix Proprietary Database', 'GenBank', 'Affymetrix Proprietary Database', 'GenBank', 'Affymetrix Proprietary Database'], 'Target Description': ['U48705 /FEATURE=mRNA /DEFINITION=HSU48705 Human receptor tyrosine kinase DDR gene, complete cds', 'M87338 /FEATURE= /DEFINITION=HUMA1SBU Human replication factor C, 40-kDa subunit (A1) mRNA, complete cds', \"X51757 /FEATURE=cds /DEFINITION=HSP70B Human heat-shock protein HSP70B' gene\", 'X69699 /FEATURE= /DEFINITION=HSPAX8A H.sapiens Pax8 mRNA', 'L36861 /FEATURE=expanded_cds /DEFINITION=HUMGCAPB Homo sapiens guanylate cyclase activating protein (GCAP) gene exons 1-4, complete cds'], 'Representative Public ID': ['U48705', 'M87338', 'X51757', 'X69699', 'L36861'], 'Gene Title': ['discoidin domain receptor tyrosine kinase 1', 'replication factor C (activator 1) 2, 40kDa', \"heat shock 70kDa protein 6 (HSP70B')\", 'paired box 8', 'guanylate cyclase activator 1A (retina)'], 'Gene Symbol': ['DDR1', 'RFC2', 'HSPA6', 'PAX8', 'GUCA1A'], 'ENTREZ_GENE_ID': ['780', '5982', '3310', '7849', '2978'], 'RefSeq Transcript ID': ['NM_001954 /// NM_013993 /// NM_013994', 'NM_002914 /// NM_181471', 'NM_002155', 'NM_003466 /// NM_013951 /// NM_013952 /// NM_013953 /// NM_013992', 'NM_000409'], 'Gene Ontology Biological Process': ['0001558 // regulation of cell growth // inferred from electronic annotation /// 0001952 // regulation of cell-matrix adhesion // inferred from electronic annotation /// 0006468 // protein amino acid phosphorylation // inferred from electronic annotation /// 0007155 // cell adhesion // inferred from electronic annotation /// 0007155 // cell adhesion // traceable author statement /// 0007169 // transmembrane receptor protein tyrosine kinase signaling pathway // inferred from electronic annotation /// 0007566 // embryo implantation // inferred from electronic annotation /// 0008285 // negative regulation of cell proliferation // inferred from electronic annotation /// 0018108 // peptidyl-tyrosine phosphorylation // inferred from electronic annotation /// 0031100 // organ regeneration // inferred from electronic annotation /// 0043583 // ear development // inferred from electronic annotation /// 0043588 // skin development // inferred from electronic annotation /// 0051789 // response to protein stimulus // inferred from electronic annotation /// 0060444 // branching involved in mammary gland duct morphogenesis // inferred from electronic annotation /// 0060749 // mammary gland alveolus development // inferred from electronic annotation', '0006260 // DNA replication // not recorded /// 0006260 // DNA replication // inferred from electronic annotation /// 0006297 // nucleotide-excision repair, DNA gap filling // not recorded /// 0015979 // photosynthesis // inferred from electronic annotation /// 0015995 // chlorophyll biosynthetic process // inferred from electronic annotation', '0006950 // response to stress // inferred from electronic annotation /// 0006986 // response to unfolded protein // traceable author statement', '0001656 // metanephros development // inferred from electronic annotation /// 0006350 // transcription // inferred from electronic annotation /// 0007275 // multicellular organismal development // inferred from electronic annotation /// 0009653 // anatomical structure morphogenesis // traceable author statement /// 0030154 // cell differentiation // inferred from electronic annotation /// 0030878 // thyroid gland development // inferred from electronic annotation /// 0045449 // regulation of transcription // inferred from electronic annotation /// 0045893 // positive regulation of transcription, DNA-dependent // inferred from sequence or structural similarity /// 0045893 // positive regulation of transcription, DNA-dependent // inferred from direct assay /// 0045944 // positive regulation of transcription from RNA polymerase II promoter // inferred from electronic annotation', '0007165 // signal transduction // non-traceable author statement /// 0007601 // visual perception // inferred from electronic annotation /// 0007601 // visual perception // traceable author statement /// 0007602 // phototransduction // inferred from electronic annotation /// 0031282 // regulation of guanylate cyclase activity // inferred from electronic annotation /// 0050896 // response to stimulus // inferred from electronic annotation'], 'Gene Ontology Cellular Component': ['0005576 // extracellular region // inferred from electronic annotation /// 0005886 // plasma membrane // inferred from electronic annotation /// 0005887 // integral to plasma membrane // traceable author statement /// 0016020 // membrane // inferred from electronic annotation /// 0016021 // integral to membrane // inferred from electronic annotation /// 0016323 // basolateral plasma membrane // inferred from electronic annotation', '0005634 // nucleus // inferred from electronic annotation /// 0005654 // nucleoplasm // not recorded /// 0005663 // DNA replication factor C complex // inferred from direct assay /// 0005663 // DNA replication factor C complex // inferred from electronic annotation', nan, '0005634 // nucleus // inferred from electronic annotation /// 0005654 // nucleoplasm // inferred from sequence or structural similarity /// 0005654 // nucleoplasm // inferred from electronic annotation', '0016020 // membrane // inferred from electronic annotation'], 'Gene Ontology Molecular Function': ['0000166 // nucleotide binding // inferred from electronic annotation /// 0004672 // protein kinase activity // inferred from electronic annotation /// 0004713 // protein tyrosine kinase activity // inferred from electronic annotation /// 0004714 // transmembrane receptor protein tyrosine kinase activity // inferred from electronic annotation /// 0004714 // transmembrane receptor protein tyrosine kinase activity // traceable author statement /// 0004872 // receptor activity // inferred from electronic annotation /// 0005515 // protein binding // inferred from physical interaction /// 0005515 // protein binding // inferred from electronic annotation /// 0005524 // ATP binding // inferred from electronic annotation /// 0016301 // kinase activity // inferred from electronic annotation /// 0016740 // transferase activity // inferred from electronic annotation', '0000166 // nucleotide binding // inferred from electronic annotation /// 0003677 // DNA binding // inferred from electronic annotation /// 0003689 // DNA clamp loader activity // inferred from electronic annotation /// 0005515 // protein binding // inferred from physical interaction /// 0005524 // ATP binding // inferred from electronic annotation /// 0005524 // ATP binding // traceable author statement /// 0016851 // magnesium chelatase activity // inferred from electronic annotation /// 0017111 // nucleoside-triphosphatase activity // inferred from electronic annotation', '0000166 // nucleotide binding // inferred from electronic annotation /// 0005524 // ATP binding // inferred from electronic annotation', '0003677 // DNA binding // inferred from direct assay /// 0003677 // DNA binding // inferred from electronic annotation /// 0003700 // transcription factor activity // traceable author statement /// 0004996 // thyroid-stimulating hormone receptor activity // traceable author statement /// 0005515 // protein binding // inferred from sequence or structural similarity /// 0005515 // protein binding // inferred from electronic annotation /// 0005515 // protein binding // inferred from physical interaction /// 0016563 // transcription activator activity // inferred from sequence or structural similarity /// 0016563 // transcription activator activity // inferred from direct assay /// 0016563 // transcription activator activity // inferred from electronic annotation /// 0043565 // sequence-specific DNA binding // inferred from electronic annotation', '0005509 // calcium ion binding // inferred from electronic annotation /// 0008048 // calcium sensitive guanylate cyclase activator activity // traceable author statement /// 0008048 // calcium sensitive guanylate cyclase activator activity // inferred from electronic annotation /// 0030249 // guanylate cyclase regulator activity // inferred from electronic annotation']}\n"
367
+ ]
368
+ }
369
+ ],
370
+ "source": [
371
+ "# 1. First get the file paths using geo_get_relevant_filepaths function\n",
372
+ "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
373
+ "\n",
374
+ "# 2. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.\n",
375
+ "gene_annotation = get_gene_annotation(soft_file)\n",
376
+ "\n",
377
+ "# 3. Use the 'preview_df' function from the library to preview the data and print out the results.\n",
378
+ "print(\"Gene annotation preview:\")\n",
379
+ "print(preview_df(gene_annotation))\n"
380
+ ]
381
+ },
382
+ {
383
+ "cell_type": "markdown",
384
+ "id": "1598ccdc",
385
+ "metadata": {},
386
+ "source": [
387
+ "### Step 6: Gene Identifier Mapping"
388
+ ]
389
+ },
390
+ {
391
+ "cell_type": "code",
392
+ "execution_count": 7,
393
+ "id": "77cfe9de",
394
+ "metadata": {
395
+ "execution": {
396
+ "iopub.execute_input": "2025-03-25T08:34:07.026996Z",
397
+ "iopub.status.busy": "2025-03-25T08:34:07.026878Z",
398
+ "iopub.status.idle": "2025-03-25T08:34:07.597872Z",
399
+ "shell.execute_reply": "2025-03-25T08:34:07.597547Z"
400
+ }
401
+ },
402
+ "outputs": [
403
+ {
404
+ "name": "stdout",
405
+ "output_type": "stream",
406
+ "text": [
407
+ "Original probe data shape: 18989 probes × 148 samples\n",
408
+ "Mapped gene data shape: 18989 genes × 148 samples\n",
409
+ "\n",
410
+ "First 10 gene symbols after mapping:\n",
411
+ "Index(['A1BG', 'A1CF', 'A2BP1', 'A2LD1', 'A2M', 'A2ML1', 'A4GALT', 'A4GNT',\n",
412
+ " 'AAA1', 'AAAS'],\n",
413
+ " dtype='object', name='Gene')\n",
414
+ "\n",
415
+ "Preview of gene expression data after mapping:\n",
416
+ "{'GSM6268367': [2.71, 6.53, 12.6, 6.15, 14.239999999999998], 'GSM6268368': [2.99, 8.16, 12.69, 6.15, 13.29], 'GSM6268369': [3.27, 6.86, 12.58, 7.17, 14.47], 'GSM6268370': [2.81, 8.51, 13.43, 6.57, 12.69], 'GSM6268371': [2.65, 8.66, 14.03, 6.19, 13.02], 'GSM6268372': [2.63, 7.27, 12.760000000000002, 6.52, 13.45], 'GSM6268373': [2.73, 8.3, 13.530000000000001, 6.13, 13.530000000000001], 'GSM6268374': [2.74, 8.21, 13.59, 6.619999999999999, 13.52], 'GSM6268375': [2.91, 7.81, 13.21, 6.03, 13.809999999999999], 'GSM6268376': [2.74, 8.43, 14.37, 6.51, 13.33], 'GSM6268377': [2.65, 8.33, 13.76, 6.779999999999999, 12.84], 'GSM6268378': [2.6, 8.3, 15.07, 6.8, 12.850000000000001], 'GSM6268379': [2.83, 8.06, 13.290000000000001, 6.46, 13.68], 'GSM6268380': [2.68, 8.12, 12.83, 7.4, 13.8], 'GSM6268381': [2.94, 8.49, 14.209999999999999, 6.75, 12.48], 'GSM6268382': [2.7, 8.4, 13.98, 6.220000000000001, 13.120000000000001], 'GSM6268383': [2.97, 7.87, 13.620000000000001, 6.2, 13.84], 'GSM6268384': [2.74, 8.27, 14.34, 6.41, 12.91], 'GSM6268385': [2.74, 8.08, 13.17, 6.47, 13.780000000000001], 'GSM6268386': [2.8, 8.25, 13.32, 6.55, 12.83], 'GSM6268387': [2.67, 8.16, 13.83, 6.57, 12.440000000000001], 'GSM6268388': [2.89, 8.4, 13.12, 6.42, 13.79], 'GSM6268389': [2.91, 8.09, 13.23, 6.800000000000001, 13.740000000000002], 'GSM6268390': [2.9, 7.57, 13.55, 6.62, 14.2], 'GSM6268391': [2.87, 7.78, 13.71, 6.66, 13.99], 'GSM6268392': [2.9, 8.16, 12.36, 6.220000000000001, 14.23], 'GSM6268393': [2.45, 8.24, 14.059999999999999, 6.4399999999999995, 14.05], 'GSM6268394': [2.81, 8.51, 13.129999999999999, 6.77, 12.94], 'GSM6268395': [3.03, 8.0, 14.52, 6.75, 13.68], 'GSM6268396': [3.05, 8.14, 13.48, 6.5600000000000005, 13.73], 'GSM6268397': [2.97, 7.79, 14.03, 6.57, 13.73], 'GSM6268398': [2.53, 8.01, 13.73, 6.12, 12.93], 'GSM6268399': [2.94, 8.1, 13.19, 7.1899999999999995, 13.42], 'GSM6268400': [2.68, 7.64, 12.8, 7.01, 13.73], 'GSM6268401': [3.21, 7.99, 13.28, 6.83, 12.850000000000001], 'GSM6268402': [2.82, 7.71, 12.8, 7.37, 13.350000000000001], 'GSM6268403': [2.8, 7.44, 12.870000000000001, 6.49, 14.829999999999998], 'GSM6268404': [2.72, 7.67, 13.84, 6.18, 13.24], 'GSM6268405': [2.61, 8.64, 13.54, 6.45, 12.370000000000001], 'GSM6268406': [3.03, 7.98, 13.27, 6.46, 12.41], 'GSM6268407': [3.21, 8.42, 12.64, 6.67, 13.09], 'GSM6268408': [3.28, 8.7, 12.83, 6.27, 12.959999999999999], 'GSM6268409': [2.8, 7.58, 12.1, 6.6, 14.27], 'GSM6268410': [2.63, 7.38, 13.05, 6.869999999999999, 14.73], 'GSM6268411': [3.06, 6.91, 12.57, 6.74, 13.94], 'GSM6268412': [2.96, 5.02, 12.56, 5.88, 14.68], 'GSM6268413': [3.09, 7.74, 13.56, 6.61, 12.57], 'GSM6268414': [2.65, 8.06, 12.879999999999999, 6.3100000000000005, 13.82], 'GSM6268415': [2.71, 8.29, 13.51, 7.369999999999999, 12.669999999999998], 'GSM6268416': [2.89, 7.45, 14.09, 6.21, 14.25], 'GSM6268417': [2.96, 8.46, 12.58, 6.390000000000001, 13.36], 'GSM6268418': [2.81, 8.29, 12.91, 6.5600000000000005, 13.18], 'GSM6268419': [2.65, 6.16, 12.49, 6.380000000000001, 13.030000000000001], 'GSM6268420': [3.15, 7.91, 13.620000000000001, 6.54, 13.47], 'GSM6268421': [2.7, 7.97, 14.31, 6.390000000000001, 12.57], 'GSM6268422': [2.84, 6.57, 12.93, 6.390000000000001, 14.169999999999998], 'GSM6268423': [2.83, 7.66, 15.92, 6.18, 12.77], 'GSM6268424': [2.59, 7.83, 13.629999999999999, 6.800000000000001, 13.1], 'GSM6268425': [2.62, 7.74, 13.440000000000001, 6.92, 12.95], 'GSM6268426': [2.75, 8.56, 12.97, 7.1, 11.940000000000001], 'GSM6268427': [2.86, 7.86, 13.25, 7.07, 13.07], 'GSM6268428': [2.82, 6.98, 13.649999999999999, 6.17, 13.29], 'GSM6268429': [3.02, 7.75, 13.47, 7.16, 13.2], 'GSM6268430': [2.99, 6.42, 12.55, 5.91, 14.71], 'GSM6268431': [2.68, 7.97, 14.05, 6.45, 13.13], 'GSM6268432': [2.9, 3.65, 13.09, 6.25, 11.05], 'GSM6268433': [2.69, 6.51, 12.73, 6.54, 13.41], 'GSM6268434': [2.88, 8.72, 13.08, 6.5600000000000005, 13.120000000000001], 'GSM6268435': [2.66, 8.07, 12.42, 6.72, 13.62], 'GSM6268436': [3.04, 8.48, 14.29, 6.34, 12.07], 'GSM6268437': [3.1, 5.77, 12.74, 6.3, 14.27], 'GSM6268438': [2.66, 8.31, 13.24, 6.59, 11.8], 'GSM6268439': [2.69, 8.58, 13.32, 5.88, 13.64], 'GSM6268440': [3.05, 7.88, 13.81, 6.470000000000001, 13.57], 'GSM6268441': [2.79, 7.45, 13.21, 6.390000000000001, 13.170000000000002], 'GSM6268442': [2.59, 7.91, 13.57, 6.41, 13.18], 'GSM6268443': [2.91, 3.8, 12.629999999999999, 6.4, 14.53], 'GSM6268444': [3.52, 8.23, 13.43, 6.78, 13.629999999999999], 'GSM6268445': [2.63, 8.27, 14.0, 6.24, 12.459999999999999], 'GSM6268446': [3.06, 8.2, 14.1, 6.630000000000001, 13.55], 'GSM6268447': [2.86, 8.03, 12.979999999999999, 6.779999999999999, 13.84], 'GSM6268448': [2.76, 7.38, 13.15, 6.279999999999999, 13.96], 'GSM6268449': [2.9, 8.01, 13.72, 6.01, 12.09], 'GSM6268450': [2.82, 7.69, 13.6, 6.43, 13.3], 'GSM6268451': [2.82, 7.26, 13.05, 6.66, 13.420000000000002], 'GSM6268452': [3.13, 7.68, 13.75, 6.0, 13.459999999999999], 'GSM6268453': [2.75, 7.81, 13.459999999999999, 6.45, 13.370000000000001], 'GSM6268454': [2.84, 7.35, 13.45, 6.609999999999999, 14.88], 'GSM6268455': [2.73, 7.83, 13.28, 5.890000000000001, 13.12], 'GSM6268456': [2.76, 7.26, 12.3, 6.75, 14.44], 'GSM6268457': [3.32, 7.47, 13.450000000000001, 7.33, 14.46], 'GSM6268458': [2.95, 8.37, 12.5, 6.470000000000001, 12.89], 'GSM6268459': [2.99, 8.55, 13.54, 6.220000000000001, 13.379999999999999], 'GSM6268460': [2.68, 7.9, 14.07, 6.87, 12.260000000000002], 'GSM6268461': [2.86, 7.47, 13.190000000000001, 6.5, 13.99], 'GSM6268462': [2.7, 7.25, 12.99, 6.529999999999999, 12.95], 'GSM6268463': [2.82, 8.24, 13.549999999999999, 6.17, 13.82], 'GSM6268464': [2.65, 8.64, 12.64, 6.39, 12.84], 'GSM6268465': [2.63, 7.74, 13.6, 6.470000000000001, 13.7], 'GSM6268466': [2.78, 8.22, 13.74, 6.26, 13.68], 'GSM6268467': [2.72, 8.45, 12.940000000000001, 6.3, 13.469999999999999], 'GSM6268468': [2.82, 7.63, 13.39, 6.59, 13.190000000000001], 'GSM6268469': [2.91, 7.89, 12.870000000000001, 6.199999999999999, 12.01], 'GSM6268470': [2.96, 7.04, 12.78, 6.54, 13.48], 'GSM6268471': [2.95, 8.31, 12.700000000000001, 6.52, 12.850000000000001], 'GSM6268472': [3.05, 5.96, 12.48, 6.42, 14.13], 'GSM6268473': [2.69, 7.73, 13.14, 6.73, 14.35], 'GSM6268474': [2.67, 7.72, 13.219999999999999, 6.67, 13.469999999999999], 'GSM6268475': [2.89, 8.18, 15.41, 7.279999999999999, 12.04], 'GSM6268476': [2.85, 7.82, 13.01, 6.0, 14.33], 'GSM6268477': [3.18, 7.96, 14.59, 6.41, 13.35], 'GSM6268478': [2.8, 7.73, 13.3, 6.34, 13.83], 'GSM6268479': [2.67, 8.03, 12.93, 6.45, 13.32], 'GSM6268480': [2.96, 8.3, 13.68, 6.75, 13.0], 'GSM6268481': [2.67, 8.57, 13.74, 6.6899999999999995, 13.0], 'GSM6268482': [2.67, 8.35, 13.41, 5.85, 13.57], 'GSM6268483': [2.87, 6.76, 12.53, 6.0, 14.39], 'GSM6268484': [2.79, 7.2, 12.63, 6.67, 13.8], 'GSM6268485': [2.93, 8.39, 12.66, 6.22, 13.2], 'GSM6268486': [2.83, 8.27, 12.62, 6.369999999999999, 13.509999999999998], 'GSM6268487': [2.87, 7.13, 13.23, 6.279999999999999, 13.75], 'GSM6268488': [2.71, 8.23, 14.3, 6.789999999999999, 10.920000000000002], 'GSM6268489': [2.71, 7.88, 13.540000000000001, 6.8, 13.42], 'GSM6268490': [2.52, 8.52, 13.100000000000001, 6.85, 13.290000000000001], 'GSM6268491': [2.7, 8.16, 13.43, 5.91, 13.02], 'GSM6268492': [3.03, 7.76, 14.18, 7.24, 14.29], 'GSM6268493': [2.73, 8.11, 13.38, 6.43, 12.18], 'GSM6268494': [3.01, 6.74, 14.459999999999999, 6.63, 13.330000000000002], 'GSM6268495': [2.99, 8.2, 13.18, 6.32, 13.43], 'GSM6268496': [2.71, 8.72, 13.47, 6.54, 12.59], 'GSM6268497': [2.72, 7.4, 13.17, 6.86, 14.06], 'GSM6268498': [2.66, 7.93, 13.39, 6.66, 13.26], 'GSM6268499': [3.0, 7.56, 12.57, 6.97, 13.86], 'GSM6268500': [2.68, 7.34, 13.79, 6.74, 12.98], 'GSM6268501': [2.96, 8.11, 12.66, 6.37, 13.469999999999999], 'GSM6268502': [2.62, 7.96, 13.219999999999999, 6.42, 13.129999999999999], 'GSM6268503': [3.15, 7.0, 12.77, 6.21, 14.77], 'GSM6268504': [3.15, 8.07, 14.370000000000001, 6.24, 13.08], 'GSM6268505': [2.74, 8.12, 13.100000000000001, 6.32, 13.79], 'GSM6268506': [2.92, 7.86, 13.4, 6.300000000000001, 12.94], 'GSM6268507': [2.94, 6.79, 12.97, 6.75, 14.0], 'GSM6268508': [2.94, 8.18, 14.0, 6.44, 13.82], 'GSM6268509': [2.82, 7.98, 13.56, 6.720000000000001, 13.23], 'GSM6268510': [2.89, 7.84, 13.16, 6.6899999999999995, 13.68], 'GSM6268511': [2.73, 8.45, 13.7, 6.29, 12.86], 'GSM6268512': [2.74, 8.19, 13.120000000000001, 6.9399999999999995, 12.370000000000001], 'GSM6268513': [2.93, 6.18, 13.03, 5.98, 15.200000000000001], 'GSM6268514': [2.84, 8.4, 12.61, 6.4, 11.92]}\n"
417
+ ]
418
+ }
419
+ ],
420
+ "source": [
421
+ "# 1. Observe gene identifiers in gene expression data and annotation data\n",
422
+ "# From previous steps we see:\n",
423
+ "# - Gene expression data has identifiers like '1007_PM_s_at' in the index\n",
424
+ "# - Gene annotation data has 'ID' column with the same format identifiers\n",
425
+ "# - Gene symbols are stored in the 'Gene Symbol' column in the annotation data\n",
426
+ "\n",
427
+ "# 2. Extract gene mapping from annotation dataframe\n",
428
+ "mapping_df = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='Gene Symbol')\n",
429
+ "\n",
430
+ "# 3. Convert probe-level measurements to gene-level expression data\n",
431
+ "gene_data = apply_gene_mapping(gene_data, mapping_df)\n",
432
+ "\n",
433
+ "# Print out information about the mapping process\n",
434
+ "print(f\"Original probe data shape: {gene_data.shape[0]} probes × {gene_data.shape[1]} samples\")\n",
435
+ "print(f\"Mapped gene data shape: {gene_data.shape[0]} genes × {gene_data.shape[1]} samples\")\n",
436
+ "print(\"\\nFirst 10 gene symbols after mapping:\")\n",
437
+ "print(gene_data.index[:10])\n",
438
+ "\n",
439
+ "# Verify first few rows of the mapped gene data\n",
440
+ "print(\"\\nPreview of gene expression data after mapping:\")\n",
441
+ "print(preview_df(gene_data))\n"
442
+ ]
443
+ },
444
+ {
445
+ "cell_type": "markdown",
446
+ "id": "50b9c720",
447
+ "metadata": {},
448
+ "source": [
449
+ "### Step 7: Data Normalization and Linking"
450
+ ]
451
+ },
452
+ {
453
+ "cell_type": "code",
454
+ "execution_count": 8,
455
+ "id": "4b61ac1f",
456
+ "metadata": {
457
+ "execution": {
458
+ "iopub.execute_input": "2025-03-25T08:34:07.599244Z",
459
+ "iopub.status.busy": "2025-03-25T08:34:07.599136Z",
460
+ "iopub.status.idle": "2025-03-25T08:34:22.495251Z",
461
+ "shell.execute_reply": "2025-03-25T08:34:22.494868Z"
462
+ }
463
+ },
464
+ "outputs": [
465
+ {
466
+ "name": "stdout",
467
+ "output_type": "stream",
468
+ "text": [
469
+ "Normalizing gene symbols...\n",
470
+ "Gene data shape after normalization: 18622 genes × 148 samples\n"
471
+ ]
472
+ },
473
+ {
474
+ "name": "stdout",
475
+ "output_type": "stream",
476
+ "text": [
477
+ "Normalized gene expression data saved to ../../output/preprocess/Crohns_Disease/gene_data/GSE207022.csv\n",
478
+ "Loading clinical features...\n",
479
+ "Clinical features shape: (1, 30)\n",
480
+ "Clinical features preview:\n",
481
+ "{'CNTO1275CRD3002-20554': [1.0], 'CNTO1275CRD3002-20667': [1.0], 'CNTO1275CRD3002-20449': [1.0], 'CNTO1275CRD3002-20927': [1.0], 'CNTO1275CRD3002-20270': [1.0], 'CNTO1275CRD3002-20072': [1.0], 'CNTO1275CRD3002-20109': [1.0], 'CNTO1275CRD3002-20346': [1.0], 'HC-1': [0.0], 'HC-2': [0.0], 'HC-3': [0.0], 'HC-4': [0.0], 'HC-5': [0.0], 'HC-6': [0.0], 'HC-7': [0.0], 'HC-8': [0.0], 'HC-9': [0.0], 'HC-10': [0.0], 'HC-11': [0.0], 'HC-12': [0.0], 'HC-13': [0.0], 'HC-14': [0.0], 'HC-15': [0.0], 'HC-16': [0.0], 'HC-17': [0.0], 'HC-18': [0.0], 'HC-19': [0.0], 'HC-20': [0.0], 'HC-21': [0.0], 'HC-22': [0.0]}\n",
482
+ "\n",
483
+ "Gene data columns (first 5): ['GSM6268367', 'GSM6268368', 'GSM6268369', 'GSM6268370', 'GSM6268371']\n",
484
+ "Clinical data rows: ['Crohns_Disease']\n",
485
+ "Re-extracting clinical data from the original source...\n",
486
+ "Re-extracted clinical features preview:\n",
487
+ "{'GSM6268367': [1.0], 'GSM6268368': [1.0], 'GSM6268369': [1.0], 'GSM6268370': [1.0], 'GSM6268371': [1.0], 'GSM6268372': [1.0], 'GSM6268373': [1.0], 'GSM6268374': [1.0], 'GSM6268375': [0.0], 'GSM6268376': [0.0], 'GSM6268377': [0.0], 'GSM6268378': [0.0], 'GSM6268379': [0.0], 'GSM6268380': [0.0], 'GSM6268381': [0.0], 'GSM6268382': [0.0], 'GSM6268383': [0.0], 'GSM6268384': [0.0], 'GSM6268385': [0.0], 'GSM6268386': [0.0], 'GSM6268387': [0.0], 'GSM6268388': [0.0], 'GSM6268389': [0.0], 'GSM6268390': [0.0], 'GSM6268391': [0.0], 'GSM6268392': [0.0], 'GSM6268393': [0.0], 'GSM6268394': [0.0], 'GSM6268395': [0.0], 'GSM6268396': [0.0], 'GSM6268397': [0.0], 'GSM6268398': [1.0], 'GSM6268399': [1.0], 'GSM6268400': [1.0], 'GSM6268401': [1.0], 'GSM6268402': [1.0], 'GSM6268403': [1.0], 'GSM6268404': [1.0], 'GSM6268405': [1.0], 'GSM6268406': [1.0], 'GSM6268407': [1.0], 'GSM6268408': [1.0], 'GSM6268409': [1.0], 'GSM6268410': [1.0], 'GSM6268411': [1.0], 'GSM6268412': [1.0], 'GSM6268413': [1.0], 'GSM6268414': [1.0], 'GSM6268415': [1.0], 'GSM6268416': [1.0], 'GSM6268417': [1.0], 'GSM6268418': [1.0], 'GSM6268419': [1.0], 'GSM6268420': [1.0], 'GSM6268421': [1.0], 'GSM6268422': [1.0], 'GSM6268423': [1.0], 'GSM6268424': [1.0], 'GSM6268425': [1.0], 'GSM6268426': [1.0], 'GSM6268427': [1.0], 'GSM6268428': [1.0], 'GSM6268429': [1.0], 'GSM6268430': [1.0], 'GSM6268431': [1.0], 'GSM6268432': [1.0], 'GSM6268433': [1.0], 'GSM6268434': [1.0], 'GSM6268435': [1.0], 'GSM6268436': [1.0], 'GSM6268437': [1.0], 'GSM6268438': [1.0], 'GSM6268439': [1.0], 'GSM6268440': [1.0], 'GSM6268441': [1.0], 'GSM6268442': [1.0], 'GSM6268443': [1.0], 'GSM6268444': [1.0], 'GSM6268445': [1.0], 'GSM6268446': [1.0], 'GSM6268447': [1.0], 'GSM6268448': [1.0], 'GSM6268449': [1.0], 'GSM6268450': [1.0], 'GSM6268451': [1.0], 'GSM6268452': [1.0], 'GSM6268453': [1.0], 'GSM6268454': [1.0], 'GSM6268455': [1.0], 'GSM6268456': [1.0], 'GSM6268457': [1.0], 'GSM6268458': [1.0], 'GSM6268459': [1.0], 'GSM6268460': [1.0], 'GSM6268461': [1.0], 'GSM6268462': [1.0], 'GSM6268463': [1.0], 'GSM6268464': [1.0], 'GSM6268465': [1.0], 'GSM6268466': [1.0], 'GSM6268467': [1.0], 'GSM6268468': [1.0], 'GSM6268469': [1.0], 'GSM6268470': [1.0], 'GSM6268471': [1.0], 'GSM6268472': [1.0], 'GSM6268473': [1.0], 'GSM6268474': [1.0], 'GSM6268475': [1.0], 'GSM6268476': [1.0], 'GSM6268477': [1.0], 'GSM6268478': [1.0], 'GSM6268479': [1.0], 'GSM6268480': [1.0], 'GSM6268481': [1.0], 'GSM6268482': [1.0], 'GSM6268483': [1.0], 'GSM6268484': [1.0], 'GSM6268485': [1.0], 'GSM6268486': [1.0], 'GSM6268487': [1.0], 'GSM6268488': [1.0], 'GSM6268489': [1.0], 'GSM6268490': [1.0], 'GSM6268491': [1.0], 'GSM6268492': [1.0], 'GSM6268493': [1.0], 'GSM6268494': [1.0], 'GSM6268495': [1.0], 'GSM6268496': [1.0], 'GSM6268497': [1.0], 'GSM6268498': [1.0], 'GSM6268499': [1.0], 'GSM6268500': [1.0], 'GSM6268501': [1.0], 'GSM6268502': [1.0], 'GSM6268503': [1.0], 'GSM6268504': [1.0], 'GSM6268505': [1.0], 'GSM6268506': [1.0], 'GSM6268507': [1.0], 'GSM6268508': [1.0], 'GSM6268509': [1.0], 'GSM6268510': [1.0], 'GSM6268511': [1.0], 'GSM6268512': [1.0], 'GSM6268513': [1.0], 'GSM6268514': [1.0]}\n",
488
+ "Re-extracted clinical data shape: (1, 148)\n",
489
+ "Updated clinical features saved to ../../output/preprocess/Crohns_Disease/clinical_data/GSE207022.csv\n",
490
+ "Linking clinical and genetic data...\n",
491
+ "Linked data shape: (148, 18623)\n",
492
+ "Handling missing values...\n"
493
+ ]
494
+ },
495
+ {
496
+ "name": "stdout",
497
+ "output_type": "stream",
498
+ "text": [
499
+ "Data shape after handling missing values: (148, 18623)\n",
500
+ "\n",
501
+ "Checking for bias in feature variables:\n",
502
+ "For the feature 'Crohns_Disease', the least common label is '0.0' with 23 occurrences. This represents 15.54% of the dataset.\n",
503
+ "The distribution of the feature 'Crohns_Disease' in this dataset is fine.\n",
504
+ "\n"
505
+ ]
506
+ },
507
+ {
508
+ "name": "stdout",
509
+ "output_type": "stream",
510
+ "text": [
511
+ "Linked data saved to ../../output/preprocess/Crohns_Disease/GSE207022.csv\n",
512
+ "Final dataset shape: (148, 18623)\n"
513
+ ]
514
+ }
515
+ ],
516
+ "source": [
517
+ "# 1. Normalize gene symbols in the gene expression data\n",
518
+ "print(\"Normalizing gene symbols...\")\n",
519
+ "gene_data_normalized = normalize_gene_symbols_in_index(gene_data)\n",
520
+ "print(f\"Gene data shape after normalization: {gene_data_normalized.shape[0]} genes × {gene_data_normalized.shape[1]} samples\")\n",
521
+ "\n",
522
+ "# Save the normalized gene data\n",
523
+ "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
524
+ "gene_data_normalized.to_csv(out_gene_data_file)\n",
525
+ "print(f\"Normalized gene expression data saved to {out_gene_data_file}\")\n",
526
+ "\n",
527
+ "# 2. Read the clinical features from the previously saved file\n",
528
+ "print(\"Loading clinical features...\")\n",
529
+ "clinical_features = pd.read_csv(out_clinical_data_file, index_col=0)\n",
530
+ "print(f\"Clinical features shape: {clinical_features.shape}\")\n",
531
+ "print(\"Clinical features preview:\")\n",
532
+ "print(preview_df(clinical_features))\n",
533
+ "\n",
534
+ "# First, let's look at the column names of both datasets to ensure proper linking\n",
535
+ "print(\"\\nGene data columns (first 5):\", gene_data_normalized.columns[:5].tolist())\n",
536
+ "print(\"Clinical data rows:\", clinical_features.index.tolist())\n",
537
+ "\n",
538
+ "# Since we've detected issues with data linking, let's manually inspect the data formats\n",
539
+ "# and make necessary adjustments for proper alignment\n",
540
+ "if clinical_features.shape[0] == 0:\n",
541
+ " print(\"Error: Clinical features dataframe is empty. Cannot proceed with linking.\")\n",
542
+ " is_usable = validate_and_save_cohort_info(\n",
543
+ " is_final=True,\n",
544
+ " cohort=cohort,\n",
545
+ " info_path=json_path,\n",
546
+ " is_gene_available=True,\n",
547
+ " is_trait_available=False,\n",
548
+ " is_biased=True,\n",
549
+ " df=pd.DataFrame(),\n",
550
+ " note=\"Clinical features dataframe is empty, cannot link with gene data.\"\n",
551
+ " )\n",
552
+ "else:\n",
553
+ " # Re-extract the clinical data directly from the matrix file\n",
554
+ " print(\"Re-extracting clinical data from the original source...\")\n",
555
+ " # Get background information and clinical data again\n",
556
+ " background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']\n",
557
+ " clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']\n",
558
+ " background_info, original_clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)\n",
559
+ " \n",
560
+ " # Extract clinical features properly\n",
561
+ " selected_clinical_df = geo_select_clinical_features(\n",
562
+ " clinical_df=original_clinical_data,\n",
563
+ " trait=trait,\n",
564
+ " trait_row=trait_row,\n",
565
+ " convert_trait=convert_trait,\n",
566
+ " age_row=age_row,\n",
567
+ " convert_age=convert_age,\n",
568
+ " gender_row=gender_row,\n",
569
+ " convert_gender=convert_gender\n",
570
+ " )\n",
571
+ " \n",
572
+ " print(\"Re-extracted clinical features preview:\")\n",
573
+ " print(preview_df(selected_clinical_df))\n",
574
+ " print(f\"Re-extracted clinical data shape: {selected_clinical_df.shape}\")\n",
575
+ " \n",
576
+ " # Save the properly extracted clinical features\n",
577
+ " selected_clinical_df.to_csv(out_clinical_data_file)\n",
578
+ " print(f\"Updated clinical features saved to {out_clinical_data_file}\")\n",
579
+ " \n",
580
+ " # 2. Link clinical and genetic data using the re-extracted clinical data\n",
581
+ " print(\"Linking clinical and genetic data...\")\n",
582
+ " linked_data = geo_link_clinical_genetic_data(selected_clinical_df, gene_data_normalized)\n",
583
+ " print(f\"Linked data shape: {linked_data.shape}\")\n",
584
+ " \n",
585
+ " # Check if the linked data has adequate data\n",
586
+ " if linked_data.shape[0] == 0 or linked_data.shape[1] <= 4: # 4 is an arbitrary small number\n",
587
+ " print(\"Error: Linked data has insufficient samples or features. Dataset cannot be processed further.\")\n",
588
+ " is_usable = validate_and_save_cohort_info(\n",
589
+ " is_final=True,\n",
590
+ " cohort=cohort,\n",
591
+ " info_path=json_path,\n",
592
+ " is_gene_available=True,\n",
593
+ " is_trait_available=True,\n",
594
+ " is_biased=True,\n",
595
+ " df=linked_data,\n",
596
+ " note=\"Failed to properly link gene expression data with clinical features.\"\n",
597
+ " )\n",
598
+ " else:\n",
599
+ " # 3. Handle missing values systematically\n",
600
+ " print(\"Handling missing values...\")\n",
601
+ " linked_data_clean = handle_missing_values(linked_data, trait_col=trait)\n",
602
+ " print(f\"Data shape after handling missing values: {linked_data_clean.shape}\")\n",
603
+ " \n",
604
+ " # Check if there are still samples after missing value handling\n",
605
+ " if linked_data_clean.shape[0] == 0:\n",
606
+ " print(\"Error: No samples remain after handling missing values.\")\n",
607
+ " is_usable = validate_and_save_cohort_info(\n",
608
+ " is_final=True,\n",
609
+ " cohort=cohort,\n",
610
+ " info_path=json_path,\n",
611
+ " is_gene_available=True,\n",
612
+ " is_trait_available=True,\n",
613
+ " is_biased=True,\n",
614
+ " df=pd.DataFrame(),\n",
615
+ " note=\"All samples were removed during missing value handling.\"\n",
616
+ " )\n",
617
+ " else:\n",
618
+ " # 4. Check if the dataset is biased\n",
619
+ " print(\"\\nChecking for bias in feature variables:\")\n",
620
+ " is_biased, linked_data_final = judge_and_remove_biased_features(linked_data_clean, trait)\n",
621
+ " \n",
622
+ " # 5. Conduct final quality validation\n",
623
+ " is_usable = validate_and_save_cohort_info(\n",
624
+ " is_final=True,\n",
625
+ " cohort=cohort,\n",
626
+ " info_path=json_path,\n",
627
+ " is_gene_available=True,\n",
628
+ " is_trait_available=True,\n",
629
+ " is_biased=is_biased,\n",
630
+ " df=linked_data_final,\n",
631
+ " note=\"Dataset contains gene expression data for Crohn's Disease subtypes (penetrating vs stricturing).\"\n",
632
+ " )\n",
633
+ " \n",
634
+ " # 6. Save linked data if usable\n",
635
+ " if is_usable:\n",
636
+ " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n",
637
+ " linked_data_final.to_csv(out_data_file)\n",
638
+ " print(f\"Linked data saved to {out_data_file}\")\n",
639
+ " print(f\"Final dataset shape: {linked_data_final.shape}\")\n",
640
+ " else:\n",
641
+ " print(\"Dataset deemed not usable for trait association studies, linked data not saved.\")"
642
+ ]
643
+ }
644
+ ],
645
+ "metadata": {
646
+ "language_info": {
647
+ "codemirror_mode": {
648
+ "name": "ipython",
649
+ "version": 3
650
+ },
651
+ "file_extension": ".py",
652
+ "mimetype": "text/x-python",
653
+ "name": "python",
654
+ "nbconvert_exporter": "python",
655
+ "pygments_lexer": "ipython3",
656
+ "version": "3.10.16"
657
+ }
658
+ },
659
+ "nbformat": 4,
660
+ "nbformat_minor": 5
661
+ }
code/Crohns_Disease/GSE66407.ipynb ADDED
@@ -0,0 +1,635 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": null,
6
+ "id": "baa6ec5b",
7
+ "metadata": {},
8
+ "outputs": [],
9
+ "source": [
10
+ "import sys\n",
11
+ "import os\n",
12
+ "sys.path.append(os.path.abspath(os.path.join(os.getcwd(), '../..')))\n",
13
+ "\n",
14
+ "# Path Configuration\n",
15
+ "from tools.preprocess import *\n",
16
+ "\n",
17
+ "# Processing context\n",
18
+ "trait = \"Crohns_Disease\"\n",
19
+ "cohort = \"GSE66407\"\n",
20
+ "\n",
21
+ "# Input paths\n",
22
+ "in_trait_dir = \"../../input/GEO/Crohns_Disease\"\n",
23
+ "in_cohort_dir = \"../../input/GEO/Crohns_Disease/GSE66407\"\n",
24
+ "\n",
25
+ "# Output paths\n",
26
+ "out_data_file = \"../../output/preprocess/Crohns_Disease/GSE66407.csv\"\n",
27
+ "out_gene_data_file = \"../../output/preprocess/Crohns_Disease/gene_data/GSE66407.csv\"\n",
28
+ "out_clinical_data_file = \"../../output/preprocess/Crohns_Disease/clinical_data/GSE66407.csv\"\n",
29
+ "json_path = \"../../output/preprocess/Crohns_Disease/cohort_info.json\"\n"
30
+ ]
31
+ },
32
+ {
33
+ "cell_type": "markdown",
34
+ "id": "78122d19",
35
+ "metadata": {},
36
+ "source": [
37
+ "### Step 1: Initial Data Loading"
38
+ ]
39
+ },
40
+ {
41
+ "cell_type": "code",
42
+ "execution_count": null,
43
+ "id": "badbdfd4",
44
+ "metadata": {},
45
+ "outputs": [],
46
+ "source": [
47
+ "from tools.preprocess import *\n",
48
+ "# 1. Identify the paths to the SOFT file and the matrix file\n",
49
+ "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
50
+ "\n",
51
+ "# 2. Read the matrix file to obtain background information and sample characteristics data\n",
52
+ "background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']\n",
53
+ "clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']\n",
54
+ "background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)\n",
55
+ "\n",
56
+ "# 3. Obtain the sample characteristics dictionary from the clinical dataframe\n",
57
+ "sample_characteristics_dict = get_unique_values_by_row(clinical_data)\n",
58
+ "\n",
59
+ "# 4. Explicitly print out all the background information and the sample characteristics dictionary\n",
60
+ "print(\"Background Information:\")\n",
61
+ "print(background_info)\n",
62
+ "print(\"Sample Characteristics Dictionary:\")\n",
63
+ "print(sample_characteristics_dict)\n"
64
+ ]
65
+ },
66
+ {
67
+ "cell_type": "markdown",
68
+ "id": "69899cd0",
69
+ "metadata": {},
70
+ "source": [
71
+ "### Step 2: Dataset Analysis and Clinical Feature Extraction"
72
+ ]
73
+ },
74
+ {
75
+ "cell_type": "code",
76
+ "execution_count": null,
77
+ "id": "2f263e62",
78
+ "metadata": {},
79
+ "outputs": [],
80
+ "source": [
81
+ "# Analysis of dataset to determine gene expression data availability and clinical feature extraction\n",
82
+ "import pandas as pd\n",
83
+ "\n",
84
+ "# 1. Gene Expression Data Availability \n",
85
+ "# Based on the background information, this dataset contains gut biopsies with transcriptome analysis\n",
86
+ "# This indicates gene expression data, not just miRNA or methylation\n",
87
+ "is_gene_available = True\n",
88
+ "\n",
89
+ "# 2. Variable Availability and Data Type Conversion\n",
90
+ "# 2.1 Data Availability\n",
91
+ "# Trait (Crohn's Disease) - From key 3 \"diagnosis: CD\"\n",
92
+ "trait_row = 3\n",
93
+ "\n",
94
+ "# Age - From key 2 \"age: XX\"\n",
95
+ "age_row = 2\n",
96
+ "\n",
97
+ "# Gender - Not available in the sample characteristics\n",
98
+ "gender_row = None\n",
99
+ "\n",
100
+ "# 2.2 Data Type Conversion Functions\n",
101
+ "def convert_trait(value):\n",
102
+ " \"\"\"Convert diagnosis information to binary trait value (0: Control, 1: CD).\"\"\"\n",
103
+ " if pd.isna(value):\n",
104
+ " return None\n",
105
+ " \n",
106
+ " # Split by colon and get the value\n",
107
+ " if ':' in value:\n",
108
+ " value = value.split(':', 1)[1].strip()\n",
109
+ " \n",
110
+ " if value == 'CD':\n",
111
+ " return 1 # Has Crohn's Disease\n",
112
+ " elif value == 'Control':\n",
113
+ " return 0 # Control/Healthy\n",
114
+ " else:\n",
115
+ " return None # UC or other diagnoses\n",
116
+ "\n",
117
+ "def convert_age(value):\n",
118
+ " \"\"\"Convert age information to continuous value.\"\"\"\n",
119
+ " if pd.isna(value):\n",
120
+ " return None\n",
121
+ " \n",
122
+ " # Split by colon and get the value\n",
123
+ " if ':' in value:\n",
124
+ " value = value.split(':', 1)[1].strip()\n",
125
+ " \n",
126
+ " try:\n",
127
+ " return float(value)\n",
128
+ " except:\n",
129
+ " return None\n",
130
+ "\n",
131
+ "def convert_gender(value):\n",
132
+ " \"\"\"Placeholder function for gender conversion, though gender data is not available.\"\"\"\n",
133
+ " return None\n",
134
+ "\n",
135
+ "# 3. Save Metadata - initial filtering\n",
136
+ "# trait_row is not None, so trait data is available\n",
137
+ "validate_and_save_cohort_info(\n",
138
+ " is_final=False,\n",
139
+ " cohort=cohort,\n",
140
+ " info_path=json_path,\n",
141
+ " is_gene_available=is_gene_available,\n",
142
+ " is_trait_available=(trait_row is not None)\n",
143
+ ")\n",
144
+ "\n",
145
+ "# 4. Clinical Feature Extraction (since trait_row is not None)\n",
146
+ "# Use a safer approach to parse the sample characteristics dictionary from the previous output\n",
147
+ "sample_char_dict = {0: ['patient: 10', 'patient: 53', 'patient: 22', 'patient: 91', 'patient: 23', 'patient: 96', 'patient: 50', 'patient: 9', 'patient: 25', 'patient: 97', 'patient: 12', 'patient: 52', 'patient: 101', 'patient: 29', 'patient: 51', 'patient: 107', 'patient: 43', 'patient: 11', 'patient: 109', 'patient: 40', 'patient: 113', 'patient: 116', 'patient: 39', 'patient: 120', 'patient: 34', 'patient: 48', 'patient: 59', 'patient: 65', 'patient: 99', 'patient: 28'], \n",
148
+ " 1: ['biopsy: 2', 'biopsy: 3', 'biopsy: 6', 'biopsy: 5', 'biopsy: 1', 'biopsy: 4', 'biopsy: 7', 'biopsy: 8', 'biopsy: G1', 'biopsy: 9', 'biopsy: 1A', 'biopsy: 1B'], \n",
149
+ " 2: ['age: 37', 'age: 18', 'age: 19', 'age: 54', 'age: 70', 'age: 22', 'age: 45', 'age: 62', 'age: 31', 'age: 39', 'age: 67', 'age: 24', 'age: 59', 'age: 20', 'age: 77', 'age: 68', 'age: 41', 'age: 50', 'age: 35', 'age: 36', 'age: 43', 'age: 52', 'age: 21', 'age: 63', 'age: 29', 'age: 25', 'age: 26', 'age: 28', 'age: 53', 'age: 69'], \n",
150
+ " 3: ['diagnosis: Control', 'diagnosis: CD', 'diagnosis: UC', None, 'inflammation: non', 'inflammation: yes'], \n",
151
+ " 4: ['gastroscopy: FALSE', 'gastroscopy: TRUE', None, 'tissue: transversum', 'tissue: sigmoideum'], \n",
152
+ " 5: ['inflammation: non', 'inflammation: yes', None, 'tissue: descendens', 'tissue: sigmoideum', 'tissue: rectum'], \n",
153
+ " 6: ['tissue: ascendens', 'tissue: sigmoideum', 'tissue: ileum', 'tissue: rectum', 'tissue: descendens', 'tissue: transversum', 'tissue: coecum', None, 'tissue: bulbus durodenum', 'tissue: valvula']}\n",
154
+ "\n",
155
+ "# Create clinical data DataFrame properly\n",
156
+ "# We need to account for the fact that each list in the dictionary may have different lengths\n",
157
+ "# Find the maximum length\n",
158
+ "max_length = max(len(values) for values in sample_char_dict.values())\n",
159
+ "\n",
160
+ "# Pad shorter lists with NaN\n",
161
+ "padded_dict = {}\n",
162
+ "for key, values in sample_char_dict.items():\n",
163
+ " padded_values = values + [None] * (max_length - len(values))\n",
164
+ " padded_dict[key] = padded_values\n",
165
+ "\n",
166
+ "# Create DataFrame from padded dictionary\n",
167
+ "clinical_data = pd.DataFrame(padded_dict)\n",
168
+ "\n",
169
+ "# Extract clinical features\n",
170
+ "clinical_features = geo_select_clinical_features(\n",
171
+ " clinical_df=clinical_data,\n",
172
+ " trait=trait,\n",
173
+ " trait_row=trait_row,\n",
174
+ " convert_trait=convert_trait,\n",
175
+ " age_row=age_row,\n",
176
+ " convert_age=convert_age,\n",
177
+ " gender_row=gender_row,\n",
178
+ " convert_gender=convert_gender\n",
179
+ ")\n",
180
+ "\n",
181
+ "# Preview clinical features\n",
182
+ "preview_clinical = preview_df(clinical_features)\n",
183
+ "print(\"Preview of extracted clinical features:\")\n",
184
+ "print(preview_clinical)\n",
185
+ "\n",
186
+ "# Save clinical features to CSV\n",
187
+ "clinical_features.to_csv(out_clinical_data_file)\n",
188
+ "print(f\"Clinical features saved to {out_clinical_data_file}\")\n"
189
+ ]
190
+ },
191
+ {
192
+ "cell_type": "markdown",
193
+ "id": "e97fadc0",
194
+ "metadata": {},
195
+ "source": [
196
+ "### Step 3: Gene Data Extraction"
197
+ ]
198
+ },
199
+ {
200
+ "cell_type": "code",
201
+ "execution_count": null,
202
+ "id": "c1012839",
203
+ "metadata": {},
204
+ "outputs": [],
205
+ "source": [
206
+ "# 1. Re-identify the SOFT and matrix files to ensure we have the correct paths\n",
207
+ "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
208
+ "\n",
209
+ "# 2. Extract the gene expression data from the matrix file\n",
210
+ "gene_data = get_genetic_data(matrix_file)\n",
211
+ "\n",
212
+ "# 3. Print the first 20 row IDs (gene or probe identifiers)\n",
213
+ "print(\"\\nFirst 20 gene/probe identifiers:\")\n",
214
+ "print(gene_data.index[:20])\n",
215
+ "\n",
216
+ "# 4. Print the dimensions of the gene expression data\n",
217
+ "print(f\"\\nGene data dimensions: {gene_data.shape[0]} genes × {gene_data.shape[1]} samples\")\n",
218
+ "\n",
219
+ "# Note: we keep is_gene_available as True since we successfully extracted gene expression data\n",
220
+ "is_gene_available = True\n"
221
+ ]
222
+ },
223
+ {
224
+ "cell_type": "markdown",
225
+ "id": "d07b021e",
226
+ "metadata": {},
227
+ "source": [
228
+ "### Step 4: Gene Identifier Review"
229
+ ]
230
+ },
231
+ {
232
+ "cell_type": "code",
233
+ "execution_count": null,
234
+ "id": "b0344dfb",
235
+ "metadata": {},
236
+ "outputs": [],
237
+ "source": [
238
+ "# Looking at the gene identifiers provided, they appear to be Ensembl gene IDs with an \"_at\" suffix\n",
239
+ "# Ensembl IDs typically start with \"ENSG\" for human genes, followed by a unique number\n",
240
+ "# These are not standard human gene symbols (like BRCA1, TP53, etc.)\n",
241
+ "# Therefore, they need to be mapped to standard gene symbols for better interpretability\n",
242
+ "\n",
243
+ "requires_gene_mapping = True\n"
244
+ ]
245
+ },
246
+ {
247
+ "cell_type": "markdown",
248
+ "id": "a6d337dc",
249
+ "metadata": {},
250
+ "source": [
251
+ "### Step 5: Gene Annotation"
252
+ ]
253
+ },
254
+ {
255
+ "cell_type": "code",
256
+ "execution_count": null,
257
+ "id": "1ddbc0d3",
258
+ "metadata": {},
259
+ "outputs": [],
260
+ "source": [
261
+ "# 1. First get the file paths using geo_get_relevant_filepaths function\n",
262
+ "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
263
+ "\n",
264
+ "# 2. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.\n",
265
+ "gene_annotation = get_gene_annotation(soft_file)\n",
266
+ "\n",
267
+ "# 3. Use the 'preview_df' function from the library to preview the data and print out the results.\n",
268
+ "print(\"Gene annotation preview:\")\n",
269
+ "print(preview_df(gene_annotation))\n"
270
+ ]
271
+ },
272
+ {
273
+ "cell_type": "markdown",
274
+ "id": "d5e080bc",
275
+ "metadata": {},
276
+ "source": [
277
+ "### Step 6: Gene Identifier Mapping"
278
+ ]
279
+ },
280
+ {
281
+ "cell_type": "code",
282
+ "execution_count": null,
283
+ "id": "50003d42",
284
+ "metadata": {},
285
+ "outputs": [],
286
+ "source": [
287
+ "# 1. Looking at the gene annotation preview, we need to extract gene symbols from 'Description'\n",
288
+ "# Example: \"tetraspanin 6 [Source:HGNC Symbol;Acc:11858]\" should yield \"TSPAN6\"\n",
289
+ "\n",
290
+ "# Let's check the Description field format\n",
291
+ "print(\"\\nSample Description fields:\")\n",
292
+ "print(gene_annotation['Description'].head(10).tolist())\n",
293
+ "\n",
294
+ "# Create a function to extract gene symbols from the Description field\n",
295
+ "def extract_gene_name(description):\n",
296
+ " \"\"\"Extract gene name from the description field - everything before [Source: part\"\"\"\n",
297
+ " if pd.isna(description):\n",
298
+ " return None\n",
299
+ " \n",
300
+ " # Extract the gene name - everything before [Source: part\n",
301
+ " if '[Source:' in description:\n",
302
+ " gene_name = description.split('[Source:')[0].strip()\n",
303
+ " return gene_name\n",
304
+ " \n",
305
+ " return None\n",
306
+ "\n",
307
+ "# Apply the function to extract gene names\n",
308
+ "gene_annotation['Gene_Name'] = gene_annotation['Description'].apply(extract_gene_name)\n",
309
+ "\n",
310
+ "# Print some examples to verify extraction\n",
311
+ "print(\"\\nSample Gene Name extractions:\")\n",
312
+ "sample_extractions = gene_annotation[['ID', 'Description', 'Gene_Name']].head(10)\n",
313
+ "print(sample_extractions)\n",
314
+ "\n",
315
+ "# Use extract_human_gene_symbols to get likely gene symbols from the gene names\n",
316
+ "gene_annotation['Symbol'] = gene_annotation['Gene_Name'].apply(extract_human_gene_symbols)\n",
317
+ "\n",
318
+ "# Check which rows have symbols\n",
319
+ "has_symbols = gene_annotation['Symbol'].apply(lambda x: len(x) > 0 if isinstance(x, list) else False)\n",
320
+ "print(f\"\\nRows with extracted symbols: {has_symbols.sum()} out of {len(gene_annotation)}\")\n",
321
+ "\n",
322
+ "# Create an exploded dataframe for mapping\n",
323
+ "mapping_df = gene_annotation[['ID', 'Symbol']].copy()\n",
324
+ "# Convert empty lists to None to make dropna work correctly\n",
325
+ "mapping_df.loc[mapping_df['Symbol'].apply(lambda x: isinstance(x, list) and len(x) == 0), 'Symbol'] = None\n",
326
+ "# Explode the Symbol column to handle cases where multiple symbols were extracted\n",
327
+ "mapping_df = mapping_df.explode('Symbol')\n",
328
+ "mapping_df = mapping_df.dropna(subset=['Symbol'])\n",
329
+ "mapping_df = mapping_df.rename(columns={'Symbol': 'Gene'})\n",
330
+ "\n",
331
+ "# Print the shape of the mapping dataframe\n",
332
+ "print(f\"\\nMapping dataframe shape: {mapping_df.shape}\")\n",
333
+ "print(\"\\nSample mappings:\")\n",
334
+ "print(mapping_df.head(10))\n",
335
+ "\n",
336
+ "# Apply the mapping to convert probe-level data to gene expression data\n",
337
+ "gene_data_mapped = apply_gene_mapping(gene_data, mapping_df)\n",
338
+ "\n",
339
+ "# Print the shape of the resulting gene expression data\n",
340
+ "print(f\"\\nAfter mapping, gene data dimensions: {gene_data_mapped.shape[0]} genes × {gene_data_mapped.shape[1]} samples\")\n",
341
+ "\n",
342
+ "# Preview the first few gene symbols\n",
343
+ "if gene_data_mapped.shape[0] > 0:\n",
344
+ " print(\"\\nFirst few gene symbols after mapping:\")\n",
345
+ " print(gene_data_mapped.index[:10])\n",
346
+ "else:\n",
347
+ " print(\"\\nWarning: No genes were mapped. Check mapping process.\")\n",
348
+ "\n",
349
+ "# Save the gene expression data\n",
350
+ "gene_data_mapped.to_csv(out_gene_data_file)\n",
351
+ "print(f\"Gene expression data saved to {out_gene_data_file}\")\n",
352
+ "\n",
353
+ "# Update the gene_data variable for subsequent steps\n",
354
+ "gene_data = gene_data_mapped\n"
355
+ ]
356
+ },
357
+ {
358
+ "cell_type": "markdown",
359
+ "id": "6fe8af0e",
360
+ "metadata": {},
361
+ "source": [
362
+ "### Step 7: Data Normalization and Linking"
363
+ ]
364
+ },
365
+ {
366
+ "cell_type": "code",
367
+ "execution_count": null,
368
+ "id": "9980d133",
369
+ "metadata": {},
370
+ "outputs": [],
371
+ "source": [
372
+ "# 1. Re-extract clinical data from the SOFT file to ensure we have properly structured data\n",
373
+ "print(\"Re-extracting clinical data from the SOFT file...\")\n",
374
+ "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
375
+ "\n",
376
+ "# Get raw clinical data\n",
377
+ "background_info, clinical_df = get_background_and_clinical_data(matrix_file)\n",
378
+ "\n",
379
+ "# Transpose the clinical data to have samples as columns\n",
380
+ "clinical_df_t = clinical_df.T\n",
381
+ "# First row contains the geo accessions, use it as column names\n",
382
+ "clinical_df_t.columns = clinical_df_t.iloc[0]\n",
383
+ "# Remove the first row that has been used as column names\n",
384
+ "clinical_df_t = clinical_df_t.iloc[1:]\n",
385
+ "\n",
386
+ "# Now extract relevant clinical features (for Crohn's Disease and age)\n",
387
+ "trait_values = []\n",
388
+ "if trait_row is not None:\n",
389
+ " for col in clinical_df_t.columns:\n",
390
+ " trait_val = convert_trait(clinical_df_t.iloc[trait_row-1, col]) # Adjust index for 0-based\n",
391
+ " trait_values.append(trait_val)\n",
392
+ "\n",
393
+ "age_values = []\n",
394
+ "if age_row is not None:\n",
395
+ " for col in clinical_df_t.columns:\n",
396
+ " age_val = convert_age(clinical_df_t.iloc[age_row-1, col]) # Adjust index for 0-based\n",
397
+ " age_values.append(age_val)\n",
398
+ "\n",
399
+ "# Create proper clinical features dataframe with samples as rows\n",
400
+ "sample_ids = clinical_df_t.columns.tolist()\n",
401
+ "clinical_features = pd.DataFrame()\n",
402
+ "\n",
403
+ "if trait_values:\n",
404
+ " clinical_features[trait] = trait_values\n",
405
+ "if age_values:\n",
406
+ " clinical_features['Age'] = age_values\n",
407
+ "\n",
408
+ "# Set index to sample IDs\n",
409
+ "clinical_features.index = sample_ids\n",
410
+ "print(f\"Re-extracted clinical features shape: {clinical_features.shape}\")\n",
411
+ "print(\"Clinical features preview:\")\n",
412
+ "print(clinical_features.head())\n",
413
+ "\n",
414
+ "# Save the improved clinical features\n",
415
+ "os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
416
+ "clinical_features.to_csv(out_clinical_data_file)\n",
417
+ "print(f\"Improved clinical features saved to {out_clinical_data_file}\")\n",
418
+ "\n",
419
+ "# Check if clinical features were successfully extracted with non-null values\n",
420
+ "if clinical_features.empty or clinical_features[trait].isnull().all():\n",
421
+ " print(\"Failed to extract valid clinical features with trait values. Dataset cannot be processed further.\")\n",
422
+ " is_usable = validate_and_save_cohort_info(\n",
423
+ " is_final=True,\n",
424
+ " cohort=cohort,\n",
425
+ " info_path=json_path,\n",
426
+ " is_gene_available=True,\n",
427
+ " is_trait_available=False,\n",
428
+ " is_biased=True,\n",
429
+ " df=pd.DataFrame(),\n",
430
+ " note=\"Valid clinical features with trait values could not be extracted.\"\n",
431
+ " )\n",
432
+ "else:\n",
433
+ " # 2. Link clinical and genetic data\n",
434
+ " print(\"Linking clinical and genetic data...\")\n",
435
+ " \n",
436
+ " # Transpose gene_data to have samples as rows and genes as columns\n",
437
+ " gene_data_t = gene_data.T\n",
438
+ " \n",
439
+ " # Keep only common samples between clinical and gene data\n",
440
+ " common_samples = list(set(clinical_features.index) & set(gene_data_t.index))\n",
441
+ " print(f\"Common samples between clinical and gene data: {len(common_samples)}\")\n",
442
+ " \n",
443
+ " if len(common_samples) == 0:\n",
444
+ " print(\"No common samples between clinical and gene data. Dataset cannot be processed further.\")\n",
445
+ " is_usable = validate_and_save_cohort_info(\n",
446
+ " is_final=True,\n",
447
+ " cohort=cohort,\n",
448
+ " info_path=json_path,\n",
449
+ " is_gene_available=True,\n",
450
+ " is_trait_available=True,\n",
451
+ " is_biased=True,\n",
452
+ " df=pd.DataFrame(),\n",
453
+ " note=\"No common samples between clinical and gene data.\"\n",
454
+ " )\n",
455
+ " else:\n",
456
+ " # Filter both datasets to only include common samples\n",
457
+ " clinical_common = clinical_features.loc[common_samples]\n",
458
+ " gene_data_common = gene_data_t.loc[common_samples]\n",
459
+ " \n",
460
+ " # Merge the datasets\n",
461
+ " linked_data = pd.concat([clinical_common, gene_data_common], axis=1)\n",
462
+ " print(f\"Linked data shape: {linked_data.shape}\")\n",
463
+ " \n",
464
+ " # 3. Handle missing values systematically\n",
465
+ " linked_data = handle_missing_values(linked_data, trait_col=trait)\n",
466
+ " print(f\"Data shape after handling missing values: {linked_data.shape}\")\n",
467
+ " \n",
468
+ " # Check if there are still samples after missing value handling\n",
469
+ " if linked_data.shape[0] == 0:\n",
470
+ " print(\"Error: No samples remain after handling missing values.\")\n",
471
+ " is_usable = validate_and_save_cohort_info(\n",
472
+ " is_final=True,\n",
473
+ " cohort=cohort,\n",
474
+ " info_path=json_path,\n",
475
+ " is_gene_available=True,\n",
476
+ " is_trait_available=True,\n",
477
+ " is_biased=True,\n",
478
+ " df=pd.DataFrame(),\n",
479
+ " note=\"All samples were removed during missing value handling.\"\n",
480
+ " )\n",
481
+ " else:\n",
482
+ " # 4. Check if the dataset is biased\n",
483
+ " print(\"\\nChecking for bias in feature variables:\")\n",
484
+ " is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n",
485
+ " \n",
486
+ " # 5. Conduct final quality validation\n",
487
+ " is_usable = validate_and_save_cohort_info(\n",
488
+ " is_final=True,\n",
489
+ " cohort=cohort,\n",
490
+ " info_path=json_path,\n",
491
+ " is_gene_available=True,\n",
492
+ " is_trait_available=True,\n",
493
+ " is_biased=is_biased,\n",
494
+ " df=linked_data,\n",
495
+ " note=\"Dataset contains gene expression data for Crohn's Disease.\"\n",
496
+ " )\n",
497
+ " \n",
498
+ " # 6. Save linked data if usable\n",
499
+ " if is_usable:\n",
500
+ " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n",
501
+ " linked_data.to_csv(out_data_file)\n",
502
+ " print(f\"Linked data saved to {out_data_file}\")\n",
503
+ " else:\n",
504
+ " print(\"Dataset deemed not usable for trait association studies, linked data not saved.\")\n"
505
+ ]
506
+ },
507
+ {
508
+ "cell_type": "markdown",
509
+ "id": "1b21d50f",
510
+ "metadata": {},
511
+ "source": [
512
+ "### Step 8: Data Normalization and Linking"
513
+ ]
514
+ },
515
+ {
516
+ "cell_type": "code",
517
+ "execution_count": null,
518
+ "id": "79d61edb",
519
+ "metadata": {},
520
+ "outputs": [],
521
+ "source": [
522
+ "# 1. Skip gene symbol normalization and use the accession numbers directly\n",
523
+ "print(\"Processing gene expression data...\")\n",
524
+ "# Don't normalize - these are GenBank accessions, not gene symbols\n",
525
+ "gene_data_normalized = gene_data # Use the original gene data with accession numbers\n",
526
+ "\n",
527
+ "# Save the gene data (without normalization)\n",
528
+ "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
529
+ "gene_data.to_csv(out_gene_data_file)\n",
530
+ "print(f\"Gene expression data saved to {out_gene_data_file}\")\n",
531
+ "print(f\"Gene data shape: {gene_data.shape[0]} genes × {gene_data.shape[1]} samples\")\n",
532
+ "\n",
533
+ "# 2. Extract clinical features from scratch\n",
534
+ "print(\"Extracting clinical features from original clinical data...\")\n",
535
+ "clinical_features = geo_select_clinical_features(\n",
536
+ " clinical_data, \n",
537
+ " trait, \n",
538
+ " trait_row,\n",
539
+ " convert_trait,\n",
540
+ " age_row,\n",
541
+ " convert_age,\n",
542
+ " gender_row,\n",
543
+ " convert_gender\n",
544
+ ")\n",
545
+ "\n",
546
+ "# Save the extracted clinical features\n",
547
+ "os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
548
+ "clinical_features.to_csv(out_clinical_data_file)\n",
549
+ "print(f\"Clinical features saved to {out_clinical_data_file}\")\n",
550
+ "\n",
551
+ "print(\"Clinical features preview:\")\n",
552
+ "print(preview_df(clinical_features))\n",
553
+ "\n",
554
+ "# Check if clinical features were successfully extracted\n",
555
+ "if clinical_features.empty:\n",
556
+ " print(\"Failed to extract clinical features. Dataset cannot be processed further.\")\n",
557
+ " is_usable = validate_and_save_cohort_info(\n",
558
+ " is_final=True,\n",
559
+ " cohort=cohort,\n",
560
+ " info_path=json_path,\n",
561
+ " is_gene_available=True,\n",
562
+ " is_trait_available=False,\n",
563
+ " is_biased=True,\n",
564
+ " df=pd.DataFrame(),\n",
565
+ " note=\"Clinical features could not be extracted from the dataset.\"\n",
566
+ " )\n",
567
+ " print(\"Dataset deemed not usable due to lack of clinical features.\")\n",
568
+ "else:\n",
569
+ " # 2. Link clinical and genetic data\n",
570
+ " print(\"Linking clinical and genetic data...\")\n",
571
+ " linked_data = geo_link_clinical_genetic_data(clinical_features, gene_data)\n",
572
+ " print(f\"Linked data shape: {linked_data.shape}\")\n",
573
+ "\n",
574
+ " # Check if the linked data has gene features\n",
575
+ " if linked_data.shape[1] <= 1:\n",
576
+ " print(\"Error: Linked data has no gene features. Dataset cannot be processed further.\")\n",
577
+ " is_usable = validate_and_save_cohort_info(\n",
578
+ " is_final=True,\n",
579
+ " cohort=cohort,\n",
580
+ " info_path=json_path,\n",
581
+ " is_gene_available=False,\n",
582
+ " is_trait_available=True,\n",
583
+ " is_biased=True,\n",
584
+ " df=linked_data,\n",
585
+ " note=\"Failed to link gene expression data with clinical features.\"\n",
586
+ " )\n",
587
+ " else:\n",
588
+ " # 3. Handle missing values systematically\n",
589
+ " linked_data = handle_missing_values(linked_data, trait_col=trait)\n",
590
+ " print(f\"Data shape after handling missing values: {linked_data.shape}\")\n",
591
+ " \n",
592
+ " # Check if there are still samples after missing value handling\n",
593
+ " if linked_data.shape[0] == 0:\n",
594
+ " print(\"Error: No samples remain after handling missing values.\")\n",
595
+ " is_usable = validate_and_save_cohort_info(\n",
596
+ " is_final=True,\n",
597
+ " cohort=cohort,\n",
598
+ " info_path=json_path,\n",
599
+ " is_gene_available=True,\n",
600
+ " is_trait_available=True,\n",
601
+ " is_biased=True,\n",
602
+ " df=pd.DataFrame(),\n",
603
+ " note=\"All samples were removed during missing value handling.\"\n",
604
+ " )\n",
605
+ " else:\n",
606
+ " # 4. Check if the dataset is biased\n",
607
+ " print(\"\\nChecking for bias in feature variables:\")\n",
608
+ " is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n",
609
+ "\n",
610
+ " # 5. Conduct final quality validation\n",
611
+ " is_usable = validate_and_save_cohort_info(\n",
612
+ " is_final=True,\n",
613
+ " cohort=cohort,\n",
614
+ " info_path=json_path,\n",
615
+ " is_gene_available=True,\n",
616
+ " is_trait_available=True,\n",
617
+ " is_biased=is_biased,\n",
618
+ " df=linked_data,\n",
619
+ " note=\"Dataset contains gene expression data for Crohn's Disease patients and healthy controls.\"\n",
620
+ " )\n",
621
+ "\n",
622
+ " # 6. Save linked data if usable\n",
623
+ " if is_usable:\n",
624
+ " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n",
625
+ " linked_data.to_csv(out_data_file)\n",
626
+ " print(f\"Linked data saved to {out_data_file}\")\n",
627
+ " else:\n",
628
+ " print(\"Dataset deemed not usable for trait association studies, linked data not saved.\")"
629
+ ]
630
+ }
631
+ ],
632
+ "metadata": {},
633
+ "nbformat": 4,
634
+ "nbformat_minor": 5
635
+ }
code/Crohns_Disease/GSE83448.ipynb ADDED
@@ -0,0 +1,653 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": 1,
6
+ "id": "ca0ecf26",
7
+ "metadata": {
8
+ "execution": {
9
+ "iopub.execute_input": "2025-03-25T08:34:40.034492Z",
10
+ "iopub.status.busy": "2025-03-25T08:34:40.034279Z",
11
+ "iopub.status.idle": "2025-03-25T08:34:40.197068Z",
12
+ "shell.execute_reply": "2025-03-25T08:34:40.196761Z"
13
+ }
14
+ },
15
+ "outputs": [],
16
+ "source": [
17
+ "import sys\n",
18
+ "import os\n",
19
+ "sys.path.append(os.path.abspath(os.path.join(os.getcwd(), '../..')))\n",
20
+ "\n",
21
+ "# Path Configuration\n",
22
+ "from tools.preprocess import *\n",
23
+ "\n",
24
+ "# Processing context\n",
25
+ "trait = \"Crohns_Disease\"\n",
26
+ "cohort = \"GSE83448\"\n",
27
+ "\n",
28
+ "# Input paths\n",
29
+ "in_trait_dir = \"../../input/GEO/Crohns_Disease\"\n",
30
+ "in_cohort_dir = \"../../input/GEO/Crohns_Disease/GSE83448\"\n",
31
+ "\n",
32
+ "# Output paths\n",
33
+ "out_data_file = \"../../output/preprocess/Crohns_Disease/GSE83448.csv\"\n",
34
+ "out_gene_data_file = \"../../output/preprocess/Crohns_Disease/gene_data/GSE83448.csv\"\n",
35
+ "out_clinical_data_file = \"../../output/preprocess/Crohns_Disease/clinical_data/GSE83448.csv\"\n",
36
+ "json_path = \"../../output/preprocess/Crohns_Disease/cohort_info.json\"\n"
37
+ ]
38
+ },
39
+ {
40
+ "cell_type": "markdown",
41
+ "id": "7dbf9eed",
42
+ "metadata": {},
43
+ "source": [
44
+ "### Step 1: Initial Data Loading"
45
+ ]
46
+ },
47
+ {
48
+ "cell_type": "code",
49
+ "execution_count": 2,
50
+ "id": "1bf33921",
51
+ "metadata": {
52
+ "execution": {
53
+ "iopub.execute_input": "2025-03-25T08:34:40.198467Z",
54
+ "iopub.status.busy": "2025-03-25T08:34:40.198333Z",
55
+ "iopub.status.idle": "2025-03-25T08:34:40.291557Z",
56
+ "shell.execute_reply": "2025-03-25T08:34:40.291272Z"
57
+ }
58
+ },
59
+ "outputs": [
60
+ {
61
+ "name": "stdout",
62
+ "output_type": "stream",
63
+ "text": [
64
+ "Background Information:\n",
65
+ "!Series_title\t\"Genome-wide transcriptional analysis in intestinal biopsies from Crohn's disease (CD) patients.\"\n",
66
+ "!Series_summary\t\"Differential gene expression analysis between CD patients and controls to identify the transcriptional signature that defines the inflamed intestinal mucosa in CD.\"\n",
67
+ "!Series_overall_design\t\"Intestinal biopsy samples were obtained from CD patients and healthy controls. RNA was subsequently extracted from each sample. Gene expression intensities were measured using GE Healthcare/Amersham Biosciences CodeLink Human Whole Genome Bioarray. After performing the gene expression quality control analysis, we characterized the transcriptional profile of the inflamed intestinal mucosa in CD.\"\n",
68
+ "Sample Characteristics Dictionary:\n",
69
+ "{0: ['tissue: intestinal mucosa'], 1: ['inflammation: Control', 'inflammation: Inflamed margin', 'inflammation: Non-inflamed margin']}\n"
70
+ ]
71
+ }
72
+ ],
73
+ "source": [
74
+ "from tools.preprocess import *\n",
75
+ "# 1. Identify the paths to the SOFT file and the matrix file\n",
76
+ "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
77
+ "\n",
78
+ "# 2. Read the matrix file to obtain background information and sample characteristics data\n",
79
+ "background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']\n",
80
+ "clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']\n",
81
+ "background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)\n",
82
+ "\n",
83
+ "# 3. Obtain the sample characteristics dictionary from the clinical dataframe\n",
84
+ "sample_characteristics_dict = get_unique_values_by_row(clinical_data)\n",
85
+ "\n",
86
+ "# 4. Explicitly print out all the background information and the sample characteristics dictionary\n",
87
+ "print(\"Background Information:\")\n",
88
+ "print(background_info)\n",
89
+ "print(\"Sample Characteristics Dictionary:\")\n",
90
+ "print(sample_characteristics_dict)\n"
91
+ ]
92
+ },
93
+ {
94
+ "cell_type": "markdown",
95
+ "id": "8ff34959",
96
+ "metadata": {},
97
+ "source": [
98
+ "### Step 2: Dataset Analysis and Clinical Feature Extraction"
99
+ ]
100
+ },
101
+ {
102
+ "cell_type": "code",
103
+ "execution_count": 3,
104
+ "id": "a6c98889",
105
+ "metadata": {
106
+ "execution": {
107
+ "iopub.execute_input": "2025-03-25T08:34:40.292660Z",
108
+ "iopub.status.busy": "2025-03-25T08:34:40.292557Z",
109
+ "iopub.status.idle": "2025-03-25T08:34:40.300806Z",
110
+ "shell.execute_reply": "2025-03-25T08:34:40.300522Z"
111
+ }
112
+ },
113
+ "outputs": [
114
+ {
115
+ "name": "stdout",
116
+ "output_type": "stream",
117
+ "text": [
118
+ "Clinical data preview:\n",
119
+ "{'GSM2203115': [0.0], 'GSM2203116': [0.0], 'GSM2203117': [0.0], 'GSM2203118': [1.0], 'GSM2203119': [1.0], 'GSM2203120': [1.0], 'GSM2203121': [0.0], 'GSM2203122': [1.0], 'GSM2203123': [1.0], 'GSM2203124': [1.0], 'GSM2203125': [0.0], 'GSM2203126': [1.0], 'GSM2203127': [1.0], 'GSM2203128': [1.0], 'GSM2203129': [0.0], 'GSM2203130': [1.0], 'GSM2203131': [1.0], 'GSM2203132': [0.0], 'GSM2203133': [1.0], 'GSM2203134': [1.0], 'GSM2203135': [1.0], 'GSM2203136': [0.0], 'GSM2203137': [1.0], 'GSM2203138': [1.0], 'GSM2203139': [1.0], 'GSM2203140': [0.0], 'GSM2203141': [0.0], 'GSM2203142': [1.0], 'GSM2203143': [1.0], 'GSM2203144': [0.0], 'GSM2203145': [0.0], 'GSM2203146': [0.0], 'GSM2203147': [0.0], 'GSM2203148': [1.0], 'GSM2203149': [1.0], 'GSM2203150': [1.0], 'GSM2203151': [1.0], 'GSM2203152': [1.0], 'GSM2203153': [1.0], 'GSM2203154': [1.0], 'GSM2203155': [1.0], 'GSM2203156': [1.0], 'GSM2203157': [1.0], 'GSM2203158': [1.0], 'GSM2203159': [1.0], 'GSM2203160': [1.0], 'GSM2203161': [1.0], 'GSM2203162': [1.0], 'GSM2203163': [1.0], 'GSM2203164': [1.0], 'GSM2203165': [1.0], 'GSM2203166': [1.0], 'GSM2203167': [1.0]}\n",
120
+ "Clinical data saved to ../../output/preprocess/Crohns_Disease/clinical_data/GSE83448.csv\n"
121
+ ]
122
+ }
123
+ ],
124
+ "source": [
125
+ "# 1. Analyze gene expression data availability\n",
126
+ "# From the background info, we can see this is a study with gene expression data from GE Healthcare/Amersham Biosciences CodeLink Human Whole Genome Bioarray\n",
127
+ "is_gene_available = True\n",
128
+ "\n",
129
+ "# 2.1 Data Availability\n",
130
+ "# Looking at the dictionary, we can see that key 1 has inflammation status\n",
131
+ "# We can use this to infer Crohn's Disease status (inflamed = CD patient, control = healthy control)\n",
132
+ "trait_row = 1\n",
133
+ "# Age data is not available in the dictionary\n",
134
+ "age_row = None\n",
135
+ "# Gender data is not available in the dictionary\n",
136
+ "gender_row = None\n",
137
+ "\n",
138
+ "# 2.2 Data Type Conversion\n",
139
+ "# Define conversion functions for each variable\n",
140
+ "\n",
141
+ "def convert_trait(value):\n",
142
+ " \"\"\"\n",
143
+ " Convert inflammation status to binary Crohn's Disease indicator.\n",
144
+ " 0 = No CD (Control), 1 = CD (Inflamed margin or Non-inflamed margin)\n",
145
+ " \"\"\"\n",
146
+ " if not isinstance(value, str):\n",
147
+ " return None\n",
148
+ " \n",
149
+ " # Extract the value after the colon if present\n",
150
+ " if ':' in value:\n",
151
+ " value = value.split(':', 1)[1].strip()\n",
152
+ " \n",
153
+ " if value == \"Control\":\n",
154
+ " return 0\n",
155
+ " elif value in [\"Inflamed margin\", \"Non-inflamed margin\"]:\n",
156
+ " return 1\n",
157
+ " else:\n",
158
+ " return None\n",
159
+ "\n",
160
+ "# No age data, but define the function as required\n",
161
+ "def convert_age(value):\n",
162
+ " \"\"\"Convert age to continuous value.\"\"\"\n",
163
+ " if not isinstance(value, str):\n",
164
+ " return None\n",
165
+ " \n",
166
+ " if ':' in value:\n",
167
+ " value = value.split(':', 1)[1].strip()\n",
168
+ " \n",
169
+ " try:\n",
170
+ " return float(value)\n",
171
+ " except (ValueError, TypeError):\n",
172
+ " return None\n",
173
+ "\n",
174
+ "# No gender data, but define the function as required\n",
175
+ "def convert_gender(value):\n",
176
+ " \"\"\"Convert gender to binary value (0=female, 1=male).\"\"\"\n",
177
+ " if not isinstance(value, str):\n",
178
+ " return None\n",
179
+ " \n",
180
+ " if ':' in value:\n",
181
+ " value = value.split(':', 1)[1].strip().lower()\n",
182
+ " \n",
183
+ " if value in ['female', 'f']:\n",
184
+ " return 0\n",
185
+ " elif value in ['male', 'm']:\n",
186
+ " return 1\n",
187
+ " else:\n",
188
+ " return None\n",
189
+ "\n",
190
+ "# 3. Save metadata - initial filtering check\n",
191
+ "is_trait_available = trait_row is not None\n",
192
+ "validate_and_save_cohort_info(\n",
193
+ " is_final=False,\n",
194
+ " cohort=cohort,\n",
195
+ " info_path=json_path,\n",
196
+ " is_gene_available=is_gene_available,\n",
197
+ " is_trait_available=is_trait_available\n",
198
+ ")\n",
199
+ "\n",
200
+ "# 4. Extract clinical features if trait data is available\n",
201
+ "if trait_row is not None:\n",
202
+ " clinical_df = geo_select_clinical_features(\n",
203
+ " clinical_df=clinical_data,\n",
204
+ " trait=trait,\n",
205
+ " trait_row=trait_row,\n",
206
+ " convert_trait=convert_trait,\n",
207
+ " age_row=age_row,\n",
208
+ " convert_age=convert_age,\n",
209
+ " gender_row=gender_row,\n",
210
+ " convert_gender=convert_gender\n",
211
+ " )\n",
212
+ " \n",
213
+ " # Preview the clinical data\n",
214
+ " preview = preview_df(clinical_df)\n",
215
+ " print(\"Clinical data preview:\")\n",
216
+ " print(preview)\n",
217
+ " \n",
218
+ " # Save clinical data to CSV\n",
219
+ " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
220
+ " clinical_df.to_csv(out_clinical_data_file, index=False)\n",
221
+ " print(f\"Clinical data saved to {out_clinical_data_file}\")\n"
222
+ ]
223
+ },
224
+ {
225
+ "cell_type": "markdown",
226
+ "id": "4665e22e",
227
+ "metadata": {},
228
+ "source": [
229
+ "### Step 3: Gene Data Extraction"
230
+ ]
231
+ },
232
+ {
233
+ "cell_type": "code",
234
+ "execution_count": 4,
235
+ "id": "c06530fb",
236
+ "metadata": {
237
+ "execution": {
238
+ "iopub.execute_input": "2025-03-25T08:34:40.301772Z",
239
+ "iopub.status.busy": "2025-03-25T08:34:40.301671Z",
240
+ "iopub.status.idle": "2025-03-25T08:34:40.438609Z",
241
+ "shell.execute_reply": "2025-03-25T08:34:40.438237Z"
242
+ }
243
+ },
244
+ "outputs": [
245
+ {
246
+ "name": "stdout",
247
+ "output_type": "stream",
248
+ "text": [
249
+ "\n",
250
+ "First 20 gene/probe identifiers:\n",
251
+ "Index(['GE469557', 'GE469567', 'GE469590', 'GE469632', 'GE469690', 'GE469802',\n",
252
+ " 'GE469817', 'GE469849', 'GE469866', 'GE469875', 'GE469953', 'GE470103',\n",
253
+ " 'GE470130', 'GE470157', 'GE470169', 'GE470208', 'GE470218', 'GE470249',\n",
254
+ " 'GE470296', 'GE470328'],\n",
255
+ " dtype='object', name='ID')\n",
256
+ "\n",
257
+ "Gene data dimensions: 20902 genes × 53 samples\n"
258
+ ]
259
+ }
260
+ ],
261
+ "source": [
262
+ "# 1. Re-identify the SOFT and matrix files to ensure we have the correct paths\n",
263
+ "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
264
+ "\n",
265
+ "# 2. Extract the gene expression data from the matrix file\n",
266
+ "gene_data = get_genetic_data(matrix_file)\n",
267
+ "\n",
268
+ "# 3. Print the first 20 row IDs (gene or probe identifiers)\n",
269
+ "print(\"\\nFirst 20 gene/probe identifiers:\")\n",
270
+ "print(gene_data.index[:20])\n",
271
+ "\n",
272
+ "# 4. Print the dimensions of the gene expression data\n",
273
+ "print(f\"\\nGene data dimensions: {gene_data.shape[0]} genes × {gene_data.shape[1]} samples\")\n",
274
+ "\n",
275
+ "# Note: we keep is_gene_available as True since we successfully extracted gene expression data\n",
276
+ "is_gene_available = True\n"
277
+ ]
278
+ },
279
+ {
280
+ "cell_type": "markdown",
281
+ "id": "091d77b6",
282
+ "metadata": {},
283
+ "source": [
284
+ "### Step 4: Gene Identifier Review"
285
+ ]
286
+ },
287
+ {
288
+ "cell_type": "code",
289
+ "execution_count": 5,
290
+ "id": "dfa92f1c",
291
+ "metadata": {
292
+ "execution": {
293
+ "iopub.execute_input": "2025-03-25T08:34:40.439902Z",
294
+ "iopub.status.busy": "2025-03-25T08:34:40.439793Z",
295
+ "iopub.status.idle": "2025-03-25T08:34:40.441648Z",
296
+ "shell.execute_reply": "2025-03-25T08:34:40.441381Z"
297
+ }
298
+ },
299
+ "outputs": [],
300
+ "source": [
301
+ "# Examine the gene identifiers\n",
302
+ "# These identifiers (like GE469557) are not standard human gene symbols\n",
303
+ "# Standard human gene symbols would be like BRCA1, TP53, etc.\n",
304
+ "# These look like custom probes/identifiers specific to a microarray platform\n",
305
+ "# They would need to be mapped to standard gene symbols for biological interpretation\n",
306
+ "\n",
307
+ "requires_gene_mapping = True\n"
308
+ ]
309
+ },
310
+ {
311
+ "cell_type": "markdown",
312
+ "id": "f8a29bd4",
313
+ "metadata": {},
314
+ "source": [
315
+ "### Step 5: Gene Annotation"
316
+ ]
317
+ },
318
+ {
319
+ "cell_type": "code",
320
+ "execution_count": 6,
321
+ "id": "ffa0f3a0",
322
+ "metadata": {
323
+ "execution": {
324
+ "iopub.execute_input": "2025-03-25T08:34:40.442749Z",
325
+ "iopub.status.busy": "2025-03-25T08:34:40.442650Z",
326
+ "iopub.status.idle": "2025-03-25T08:34:41.776334Z",
327
+ "shell.execute_reply": "2025-03-25T08:34:41.775955Z"
328
+ }
329
+ },
330
+ "outputs": [
331
+ {
332
+ "name": "stdout",
333
+ "output_type": "stream",
334
+ "text": [
335
+ "Gene annotation preview:\n",
336
+ "{'ID': ['GE469530', 'GE469548', 'GE469549', 'GE469555', 'GE469557'], 'GB_ACC': ['AI650595.1', 'BU686968.1', 'BU623208.1', 'BE045962.1', 'AY077696.1'], 'Probe_Name': ['GE469530', 'GE469548', 'GE469549', 'GE469555', 'GE469557'], 'Probe_Type': ['DISCOVERY', 'DISCOVERY', 'DISCOVERY', 'DISCOVERY', 'DISCOVERY'], 'DESCRIPTION': [\"wa92h11x1 NCI_CGAP_GC6 cDNA clone IMAGE:2303685 3'\", \"UI-CF-DU1-ado-i-08-0-UIs1 UI-CF-DU1 cDNA clone UI-CF-DU1-ado-i-08-0-UI 3'\", \"UI-H-FL1-bgd-j-14-0-UI.s1 NCI_CGAP_FL1 cDNA clone UI-H-FL1-bgd-j-14-0-UI 3', mRNA sequence\", \"hd90g04x4 NCI_CGAP_GC6 cDNA clone IMAGE:2916822 3'\", 'clone qd65g07 PRED16 protein (PRED16) mRNA'], 'SPOT_ID': [nan, nan, nan, nan, nan]}\n"
337
+ ]
338
+ }
339
+ ],
340
+ "source": [
341
+ "# 1. First get the file paths using geo_get_relevant_filepaths function\n",
342
+ "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
343
+ "\n",
344
+ "# 2. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.\n",
345
+ "gene_annotation = get_gene_annotation(soft_file)\n",
346
+ "\n",
347
+ "# 3. Use the 'preview_df' function from the library to preview the data and print out the results.\n",
348
+ "print(\"Gene annotation preview:\")\n",
349
+ "print(preview_df(gene_annotation))\n"
350
+ ]
351
+ },
352
+ {
353
+ "cell_type": "markdown",
354
+ "id": "f830b849",
355
+ "metadata": {},
356
+ "source": [
357
+ "### Step 6: Gene Identifier Mapping"
358
+ ]
359
+ },
360
+ {
361
+ "cell_type": "code",
362
+ "execution_count": 7,
363
+ "id": "b2ecca5f",
364
+ "metadata": {
365
+ "execution": {
366
+ "iopub.execute_input": "2025-03-25T08:34:41.777681Z",
367
+ "iopub.status.busy": "2025-03-25T08:34:41.777563Z",
368
+ "iopub.status.idle": "2025-03-25T08:34:44.226206Z",
369
+ "shell.execute_reply": "2025-03-25T08:34:44.225820Z"
370
+ }
371
+ },
372
+ "outputs": [
373
+ {
374
+ "name": "stdout",
375
+ "output_type": "stream",
376
+ "text": [
377
+ "Checking for additional columns in annotation data:\n",
378
+ "Column 'ID' sample: ['GE469530' 'GE469548' 'GE469549']\n"
379
+ ]
380
+ },
381
+ {
382
+ "name": "stdout",
383
+ "output_type": "stream",
384
+ "text": [
385
+ "Column 'GB_ACC' sample: ['AI650595.1' 'BU686968.1' 'BU623208.1']\n"
386
+ ]
387
+ },
388
+ {
389
+ "name": "stdout",
390
+ "output_type": "stream",
391
+ "text": [
392
+ "Column 'Probe_Name' sample: ['GE469530' 'GE469548' 'GE469549']\n",
393
+ "Column 'Probe_Type' sample: ['DISCOVERY']\n",
394
+ "Column 'DESCRIPTION' sample: [\"wa92h11x1 NCI_CGAP_GC6 cDNA clone IMAGE:2303685 3'\"\n",
395
+ " \"UI-CF-DU1-ado-i-08-0-UIs1 UI-CF-DU1 cDNA clone UI-CF-DU1-ado-i-08-0-UI 3'\"\n",
396
+ " \"UI-H-FL1-bgd-j-14-0-UI.s1 NCI_CGAP_FL1 cDNA clone UI-H-FL1-bgd-j-14-0-UI 3', mRNA sequence\"]\n",
397
+ "Column 'SPOT_ID' sample: ['INCYTE UNIQUE']\n",
398
+ "\n",
399
+ "Using GenBank accessions as gene identifiers.\n",
400
+ "\n",
401
+ "Gene mapping dataframe shape: (1156663, 2)\n",
402
+ "Sample of gene mapping:\n",
403
+ "{'ID': ['GE469530', 'GE469548', 'GE469549', 'GE469555', 'GE469557'], 'Gene': ['AI650595.1', 'BU686968.1', 'BU623208.1', 'BE045962.1', 'AY077696.1']}\n"
404
+ ]
405
+ },
406
+ {
407
+ "name": "stdout",
408
+ "output_type": "stream",
409
+ "text": [
410
+ "\n",
411
+ "After mapping - Gene data dimensions: (5353, 53)\n",
412
+ "\n",
413
+ "First few gene identifiers after mapping:\n",
414
+ "Index(['AA010870', 'AA021186', 'AA029225', 'AA057423', 'AA058586', 'AA127601',\n",
415
+ " 'AA149620', 'AA150617', 'AA166934', 'AA187037'],\n",
416
+ " dtype='object', name='Gene')\n",
417
+ "\n",
418
+ "Note: The dataset is using GenBank accessions rather than standard gene symbols.\n",
419
+ "This may affect downstream analysis that relies on gene symbol annotations.\n",
420
+ "\n",
421
+ "Gene expression data saved to ../../output/preprocess/Crohns_Disease/gene_data/GSE83448.csv\n"
422
+ ]
423
+ }
424
+ ],
425
+ "source": [
426
+ "# 1. Look for alternative gene symbol columns in the annotation data\n",
427
+ "# First, check if there are any hidden/unprefixed columns that might contain gene symbols\n",
428
+ "print(\"Checking for additional columns in annotation data:\")\n",
429
+ "for col in gene_annotation.columns:\n",
430
+ " unique_values = gene_annotation[col].dropna().unique()\n",
431
+ " if len(unique_values) > 0:\n",
432
+ " print(f\"Column '{col}' sample: {unique_values[:3]}\")\n",
433
+ "\n",
434
+ "# Since we don't see standard gene symbols, we'll use GB_ACC (GenBank accessions)\n",
435
+ "# as identifiers for the gene expression data\n",
436
+ "print(\"\\nUsing GenBank accessions as gene identifiers.\")\n",
437
+ "gene_mapping = get_gene_mapping(gene_annotation, 'ID', 'GB_ACC')\n",
438
+ "\n",
439
+ "# Check the mapping dataframe\n",
440
+ "print(f\"\\nGene mapping dataframe shape: {gene_mapping.shape}\")\n",
441
+ "print(\"Sample of gene mapping:\")\n",
442
+ "print(preview_df(gene_mapping))\n",
443
+ "\n",
444
+ "# 3. Convert probe-level measurements to gene expression\n",
445
+ "# Note: We're working with accession numbers, not gene symbols\n",
446
+ "gene_data = apply_gene_mapping(gene_data, gene_mapping)\n",
447
+ "\n",
448
+ "# Preview the results\n",
449
+ "print(\"\\nAfter mapping - Gene data dimensions:\", gene_data.shape)\n",
450
+ "print(\"\\nFirst few gene identifiers after mapping:\")\n",
451
+ "print(gene_data.index[:10])\n",
452
+ "\n",
453
+ "# Skip normalization since these are not standard gene symbols\n",
454
+ "# We'll keep the accession numbers as identifiers\n",
455
+ "print(\"\\nNote: The dataset is using GenBank accessions rather than standard gene symbols.\")\n",
456
+ "print(\"This may affect downstream analysis that relies on gene symbol annotations.\")\n",
457
+ "\n",
458
+ "# Save the gene expression data\n",
459
+ "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
460
+ "gene_data.to_csv(out_gene_data_file)\n",
461
+ "print(f\"\\nGene expression data saved to {out_gene_data_file}\")\n"
462
+ ]
463
+ },
464
+ {
465
+ "cell_type": "markdown",
466
+ "id": "f9445cb6",
467
+ "metadata": {},
468
+ "source": [
469
+ "### Step 7: Data Normalization and Linking"
470
+ ]
471
+ },
472
+ {
473
+ "cell_type": "code",
474
+ "execution_count": 8,
475
+ "id": "c9256f02",
476
+ "metadata": {
477
+ "execution": {
478
+ "iopub.execute_input": "2025-03-25T08:34:44.227605Z",
479
+ "iopub.status.busy": "2025-03-25T08:34:44.227497Z",
480
+ "iopub.status.idle": "2025-03-25T08:34:45.641361Z",
481
+ "shell.execute_reply": "2025-03-25T08:34:45.640822Z"
482
+ }
483
+ },
484
+ "outputs": [
485
+ {
486
+ "name": "stdout",
487
+ "output_type": "stream",
488
+ "text": [
489
+ "Processing gene expression data...\n"
490
+ ]
491
+ },
492
+ {
493
+ "name": "stdout",
494
+ "output_type": "stream",
495
+ "text": [
496
+ "Gene expression data saved to ../../output/preprocess/Crohns_Disease/gene_data/GSE83448.csv\n",
497
+ "Gene data shape: 5353 genes × 53 samples\n",
498
+ "Extracting clinical features from original clinical data...\n",
499
+ "Clinical features saved to ../../output/preprocess/Crohns_Disease/clinical_data/GSE83448.csv\n",
500
+ "Clinical features preview:\n",
501
+ "{'GSM2203115': [0.0], 'GSM2203116': [0.0], 'GSM2203117': [0.0], 'GSM2203118': [1.0], 'GSM2203119': [1.0], 'GSM2203120': [1.0], 'GSM2203121': [0.0], 'GSM2203122': [1.0], 'GSM2203123': [1.0], 'GSM2203124': [1.0], 'GSM2203125': [0.0], 'GSM2203126': [1.0], 'GSM2203127': [1.0], 'GSM2203128': [1.0], 'GSM2203129': [0.0], 'GSM2203130': [1.0], 'GSM2203131': [1.0], 'GSM2203132': [0.0], 'GSM2203133': [1.0], 'GSM2203134': [1.0], 'GSM2203135': [1.0], 'GSM2203136': [0.0], 'GSM2203137': [1.0], 'GSM2203138': [1.0], 'GSM2203139': [1.0], 'GSM2203140': [0.0], 'GSM2203141': [0.0], 'GSM2203142': [1.0], 'GSM2203143': [1.0], 'GSM2203144': [0.0], 'GSM2203145': [0.0], 'GSM2203146': [0.0], 'GSM2203147': [0.0], 'GSM2203148': [1.0], 'GSM2203149': [1.0], 'GSM2203150': [1.0], 'GSM2203151': [1.0], 'GSM2203152': [1.0], 'GSM2203153': [1.0], 'GSM2203154': [1.0], 'GSM2203155': [1.0], 'GSM2203156': [1.0], 'GSM2203157': [1.0], 'GSM2203158': [1.0], 'GSM2203159': [1.0], 'GSM2203160': [1.0], 'GSM2203161': [1.0], 'GSM2203162': [1.0], 'GSM2203163': [1.0], 'GSM2203164': [1.0], 'GSM2203165': [1.0], 'GSM2203166': [1.0], 'GSM2203167': [1.0]}\n",
502
+ "Linking clinical and genetic data...\n",
503
+ "Linked data shape: (53, 5354)\n"
504
+ ]
505
+ },
506
+ {
507
+ "name": "stdout",
508
+ "output_type": "stream",
509
+ "text": [
510
+ "Data shape after handling missing values: (53, 5354)\n",
511
+ "\n",
512
+ "Checking for bias in feature variables:\n",
513
+ "For the feature 'Crohns_Disease', the least common label is '0.0' with 14 occurrences. This represents 26.42% of the dataset.\n",
514
+ "The distribution of the feature 'Crohns_Disease' in this dataset is fine.\n",
515
+ "\n"
516
+ ]
517
+ },
518
+ {
519
+ "name": "stdout",
520
+ "output_type": "stream",
521
+ "text": [
522
+ "Linked data saved to ../../output/preprocess/Crohns_Disease/GSE83448.csv\n"
523
+ ]
524
+ }
525
+ ],
526
+ "source": [
527
+ "# 1. Skip gene symbol normalization and use the accession numbers directly\n",
528
+ "print(\"Processing gene expression data...\")\n",
529
+ "# Don't normalize - these are GenBank accessions, not gene symbols\n",
530
+ "gene_data_normalized = gene_data # Use the original gene data with accession numbers\n",
531
+ "\n",
532
+ "# Save the gene data (without normalization)\n",
533
+ "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
534
+ "gene_data.to_csv(out_gene_data_file)\n",
535
+ "print(f\"Gene expression data saved to {out_gene_data_file}\")\n",
536
+ "print(f\"Gene data shape: {gene_data.shape[0]} genes × {gene_data.shape[1]} samples\")\n",
537
+ "\n",
538
+ "# 2. Extract clinical features from scratch\n",
539
+ "print(\"Extracting clinical features from original clinical data...\")\n",
540
+ "clinical_features = geo_select_clinical_features(\n",
541
+ " clinical_data, \n",
542
+ " trait, \n",
543
+ " trait_row,\n",
544
+ " convert_trait,\n",
545
+ " age_row,\n",
546
+ " convert_age,\n",
547
+ " gender_row,\n",
548
+ " convert_gender\n",
549
+ ")\n",
550
+ "\n",
551
+ "# Save the extracted clinical features\n",
552
+ "os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
553
+ "clinical_features.to_csv(out_clinical_data_file)\n",
554
+ "print(f\"Clinical features saved to {out_clinical_data_file}\")\n",
555
+ "\n",
556
+ "print(\"Clinical features preview:\")\n",
557
+ "print(preview_df(clinical_features))\n",
558
+ "\n",
559
+ "# Check if clinical features were successfully extracted\n",
560
+ "if clinical_features.empty:\n",
561
+ " print(\"Failed to extract clinical features. Dataset cannot be processed further.\")\n",
562
+ " is_usable = validate_and_save_cohort_info(\n",
563
+ " is_final=True,\n",
564
+ " cohort=cohort,\n",
565
+ " info_path=json_path,\n",
566
+ " is_gene_available=True,\n",
567
+ " is_trait_available=False,\n",
568
+ " is_biased=True,\n",
569
+ " df=pd.DataFrame(),\n",
570
+ " note=\"Clinical features could not be extracted from the dataset.\"\n",
571
+ " )\n",
572
+ " print(\"Dataset deemed not usable due to lack of clinical features.\")\n",
573
+ "else:\n",
574
+ " # 2. Link clinical and genetic data\n",
575
+ " print(\"Linking clinical and genetic data...\")\n",
576
+ " linked_data = geo_link_clinical_genetic_data(clinical_features, gene_data)\n",
577
+ " print(f\"Linked data shape: {linked_data.shape}\")\n",
578
+ "\n",
579
+ " # Check if the linked data has gene features\n",
580
+ " if linked_data.shape[1] <= 1:\n",
581
+ " print(\"Error: Linked data has no gene features. Dataset cannot be processed further.\")\n",
582
+ " is_usable = validate_and_save_cohort_info(\n",
583
+ " is_final=True,\n",
584
+ " cohort=cohort,\n",
585
+ " info_path=json_path,\n",
586
+ " is_gene_available=False,\n",
587
+ " is_trait_available=True,\n",
588
+ " is_biased=True,\n",
589
+ " df=linked_data,\n",
590
+ " note=\"Failed to link gene expression data with clinical features.\"\n",
591
+ " )\n",
592
+ " else:\n",
593
+ " # 3. Handle missing values systematically\n",
594
+ " linked_data = handle_missing_values(linked_data, trait_col=trait)\n",
595
+ " print(f\"Data shape after handling missing values: {linked_data.shape}\")\n",
596
+ " \n",
597
+ " # Check if there are still samples after missing value handling\n",
598
+ " if linked_data.shape[0] == 0:\n",
599
+ " print(\"Error: No samples remain after handling missing values.\")\n",
600
+ " is_usable = validate_and_save_cohort_info(\n",
601
+ " is_final=True,\n",
602
+ " cohort=cohort,\n",
603
+ " info_path=json_path,\n",
604
+ " is_gene_available=True,\n",
605
+ " is_trait_available=True,\n",
606
+ " is_biased=True,\n",
607
+ " df=pd.DataFrame(),\n",
608
+ " note=\"All samples were removed during missing value handling.\"\n",
609
+ " )\n",
610
+ " else:\n",
611
+ " # 4. Check if the dataset is biased\n",
612
+ " print(\"\\nChecking for bias in feature variables:\")\n",
613
+ " is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n",
614
+ "\n",
615
+ " # 5. Conduct final quality validation\n",
616
+ " is_usable = validate_and_save_cohort_info(\n",
617
+ " is_final=True,\n",
618
+ " cohort=cohort,\n",
619
+ " info_path=json_path,\n",
620
+ " is_gene_available=True,\n",
621
+ " is_trait_available=True,\n",
622
+ " is_biased=is_biased,\n",
623
+ " df=linked_data,\n",
624
+ " note=\"Dataset contains gene expression data for Crohn's Disease patients and healthy controls.\"\n",
625
+ " )\n",
626
+ "\n",
627
+ " # 6. Save linked data if usable\n",
628
+ " if is_usable:\n",
629
+ " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n",
630
+ " linked_data.to_csv(out_data_file)\n",
631
+ " print(f\"Linked data saved to {out_data_file}\")\n",
632
+ " else:\n",
633
+ " print(\"Dataset deemed not usable for trait association studies, linked data not saved.\")"
634
+ ]
635
+ }
636
+ ],
637
+ "metadata": {
638
+ "language_info": {
639
+ "codemirror_mode": {
640
+ "name": "ipython",
641
+ "version": 3
642
+ },
643
+ "file_extension": ".py",
644
+ "mimetype": "text/x-python",
645
+ "name": "python",
646
+ "nbconvert_exporter": "python",
647
+ "pygments_lexer": "ipython3",
648
+ "version": "3.10.16"
649
+ }
650
+ },
651
+ "nbformat": 4,
652
+ "nbformat_minor": 5
653
+ }
code/Crohns_Disease/TCGA.ipynb ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": 1,
6
+ "id": "c8ee81c7",
7
+ "metadata": {
8
+ "execution": {
9
+ "iopub.execute_input": "2025-03-25T08:34:46.541760Z",
10
+ "iopub.status.busy": "2025-03-25T08:34:46.541580Z",
11
+ "iopub.status.idle": "2025-03-25T08:34:46.702384Z",
12
+ "shell.execute_reply": "2025-03-25T08:34:46.702023Z"
13
+ }
14
+ },
15
+ "outputs": [],
16
+ "source": [
17
+ "import sys\n",
18
+ "import os\n",
19
+ "sys.path.append(os.path.abspath(os.path.join(os.getcwd(), '../..')))\n",
20
+ "\n",
21
+ "# Path Configuration\n",
22
+ "from tools.preprocess import *\n",
23
+ "\n",
24
+ "# Processing context\n",
25
+ "trait = \"Crohns_Disease\"\n",
26
+ "\n",
27
+ "# Input paths\n",
28
+ "tcga_root_dir = \"../../input/TCGA\"\n",
29
+ "\n",
30
+ "# Output paths\n",
31
+ "out_data_file = \"../../output/preprocess/Crohns_Disease/TCGA.csv\"\n",
32
+ "out_gene_data_file = \"../../output/preprocess/Crohns_Disease/gene_data/TCGA.csv\"\n",
33
+ "out_clinical_data_file = \"../../output/preprocess/Crohns_Disease/clinical_data/TCGA.csv\"\n",
34
+ "json_path = \"../../output/preprocess/Crohns_Disease/cohort_info.json\"\n"
35
+ ]
36
+ },
37
+ {
38
+ "cell_type": "markdown",
39
+ "id": "ee5993de",
40
+ "metadata": {},
41
+ "source": [
42
+ "### Step 1: Initial Data Loading"
43
+ ]
44
+ },
45
+ {
46
+ "cell_type": "code",
47
+ "execution_count": 2,
48
+ "id": "df8f45fa",
49
+ "metadata": {
50
+ "execution": {
51
+ "iopub.execute_input": "2025-03-25T08:34:46.703798Z",
52
+ "iopub.status.busy": "2025-03-25T08:34:46.703660Z",
53
+ "iopub.status.idle": "2025-03-25T08:34:46.708617Z",
54
+ "shell.execute_reply": "2025-03-25T08:34:46.708316Z"
55
+ }
56
+ },
57
+ "outputs": [
58
+ {
59
+ "name": "stdout",
60
+ "output_type": "stream",
61
+ "text": [
62
+ "Available TCGA subdirectories: ['TCGA_Liver_Cancer_(LIHC)', 'TCGA_Lower_Grade_Glioma_(LGG)', 'TCGA_lower_grade_glioma_and_glioblastoma_(GBMLGG)', 'TCGA_Lung_Adenocarcinoma_(LUAD)', 'TCGA_Lung_Cancer_(LUNG)', 'TCGA_Lung_Squamous_Cell_Carcinoma_(LUSC)', 'TCGA_Melanoma_(SKCM)', 'TCGA_Mesothelioma_(MESO)', 'TCGA_Ocular_melanomas_(UVM)', 'TCGA_Ovarian_Cancer_(OV)', 'TCGA_Pancreatic_Cancer_(PAAD)', 'TCGA_Pheochromocytoma_Paraganglioma_(PCPG)', 'TCGA_Prostate_Cancer_(PRAD)', 'TCGA_Rectal_Cancer_(READ)', 'TCGA_Sarcoma_(SARC)', 'TCGA_Stomach_Cancer_(STAD)', 'TCGA_Testicular_Cancer_(TGCT)', 'TCGA_Thymoma_(THYM)', 'TCGA_Thyroid_Cancer_(THCA)', 'TCGA_Uterine_Carcinosarcoma_(UCS)', '.DS_Store', 'CrawlData.ipynb', 'TCGA_Acute_Myeloid_Leukemia_(LAML)', 'TCGA_Adrenocortical_Cancer_(ACC)', 'TCGA_Bile_Duct_Cancer_(CHOL)', 'TCGA_Bladder_Cancer_(BLCA)', 'TCGA_Breast_Cancer_(BRCA)', 'TCGA_Cervical_Cancer_(CESC)', 'TCGA_Colon_and_Rectal_Cancer_(COADREAD)', 'TCGA_Colon_Cancer_(COAD)', 'TCGA_Endometrioid_Cancer_(UCEC)', 'TCGA_Esophageal_Cancer_(ESCA)', 'TCGA_Glioblastoma_(GBM)', 'TCGA_Head_and_Neck_Cancer_(HNSC)', 'TCGA_Kidney_Chromophobe_(KICH)', 'TCGA_Kidney_Clear_Cell_Carcinoma_(KIRC)', 'TCGA_Kidney_Papillary_Cell_Carcinoma_(KIRP)', 'TCGA_Large_Bcell_Lymphoma_(DLBC)']\n",
63
+ "Potential Crohns_Disease-related directories found: []\n",
64
+ "No TCGA subdirectory contains terms directly related to Crohns_Disease.\n",
65
+ "TCGA is primarily a cancer genomics database and may not have specific data for this inflammatory condition.\n",
66
+ "Task completed: Crohns_Disease data not available in TCGA dataset.\n"
67
+ ]
68
+ }
69
+ ],
70
+ "source": [
71
+ "import os\n",
72
+ "\n",
73
+ "# Step 1: Look for directories related to Ankylosing Spondylitis (inflammatory arthritis affecting the spine)\n",
74
+ "tcga_subdirs = os.listdir(tcga_root_dir)\n",
75
+ "print(f\"Available TCGA subdirectories: {tcga_subdirs}\")\n",
76
+ "\n",
77
+ "# Check if any directories contain relevant terms to Ankylosing Spondylitis\n",
78
+ "as_related_terms = [\"spondylitis\", \"arthritis\", \"inflammatory\", \"spine\", \"joint\", \"sacroiliac\", \"rheumatic\"]\n",
79
+ "potential_dirs = []\n",
80
+ "\n",
81
+ "for directory in tcga_subdirs:\n",
82
+ " if any(term.lower() in directory.lower() for term in as_related_terms):\n",
83
+ " potential_dirs.append(directory)\n",
84
+ "\n",
85
+ "print(f\"Potential {trait}-related directories found: {potential_dirs}\")\n",
86
+ "\n",
87
+ "if potential_dirs:\n",
88
+ " # Select the most specific match if found\n",
89
+ " target_dir = potential_dirs[0]\n",
90
+ " target_path = os.path.join(tcga_root_dir, target_dir)\n",
91
+ " \n",
92
+ " print(f\"Selected directory: {target_dir}\")\n",
93
+ " \n",
94
+ " # Get the clinical and genetic data file paths\n",
95
+ " clinical_path, genetic_path = tcga_get_relevant_filepaths(target_path)\n",
96
+ " \n",
97
+ " # Load the datasets\n",
98
+ " clinical_df = pd.read_csv(clinical_path, sep='\\t', index_col=0)\n",
99
+ " genetic_df = pd.read_csv(genetic_path, sep='\\t', index_col=0)\n",
100
+ " \n",
101
+ " # Print column names of clinical data\n",
102
+ " print(\"\\nClinical data columns:\")\n",
103
+ " print(clinical_df.columns.tolist())\n",
104
+ " \n",
105
+ " # Check if we have both gene data and potential trait data\n",
106
+ " has_gene_data = not genetic_df.empty\n",
107
+ " has_potential_trait_data = not clinical_df.empty\n",
108
+ " \n",
109
+ " # Record our initial assessment\n",
110
+ " validate_and_save_cohort_info(\n",
111
+ " is_final=False, \n",
112
+ " cohort=\"TCGA\", \n",
113
+ " info_path=json_path, \n",
114
+ " is_gene_available=has_gene_data, \n",
115
+ " is_trait_available=has_potential_trait_data\n",
116
+ " )\n",
117
+ "else:\n",
118
+ " print(f\"No TCGA subdirectory contains terms directly related to {trait}.\")\n",
119
+ " print(\"TCGA is primarily a cancer genomics database and may not have specific data for this inflammatory condition.\")\n",
120
+ " \n",
121
+ " # Marking the trait as unavailable in the cohort_info.json\n",
122
+ " validate_and_save_cohort_info(\n",
123
+ " is_final=False, \n",
124
+ " cohort=\"TCGA\", \n",
125
+ " info_path=json_path, \n",
126
+ " is_gene_available=False, \n",
127
+ " is_trait_available=False\n",
128
+ " )\n",
129
+ " \n",
130
+ " print(f\"Task completed: {trait} data not available in TCGA dataset.\")"
131
+ ]
132
+ }
133
+ ],
134
+ "metadata": {
135
+ "language_info": {
136
+ "codemirror_mode": {
137
+ "name": "ipython",
138
+ "version": 3
139
+ },
140
+ "file_extension": ".py",
141
+ "mimetype": "text/x-python",
142
+ "name": "python",
143
+ "nbconvert_exporter": "python",
144
+ "pygments_lexer": "ipython3",
145
+ "version": "3.10.16"
146
+ }
147
+ },
148
+ "nbformat": 4,
149
+ "nbformat_minor": 5
150
+ }
code/Cystic_Fibrosis/GSE142610.ipynb ADDED
@@ -0,0 +1,578 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": 1,
6
+ "id": "ed9d7816",
7
+ "metadata": {
8
+ "execution": {
9
+ "iopub.execute_input": "2025-03-25T08:35:30.035172Z",
10
+ "iopub.status.busy": "2025-03-25T08:35:30.034990Z",
11
+ "iopub.status.idle": "2025-03-25T08:35:30.200170Z",
12
+ "shell.execute_reply": "2025-03-25T08:35:30.199722Z"
13
+ }
14
+ },
15
+ "outputs": [],
16
+ "source": [
17
+ "import sys\n",
18
+ "import os\n",
19
+ "sys.path.append(os.path.abspath(os.path.join(os.getcwd(), '../..')))\n",
20
+ "\n",
21
+ "# Path Configuration\n",
22
+ "from tools.preprocess import *\n",
23
+ "\n",
24
+ "# Processing context\n",
25
+ "trait = \"Cystic_Fibrosis\"\n",
26
+ "cohort = \"GSE142610\"\n",
27
+ "\n",
28
+ "# Input paths\n",
29
+ "in_trait_dir = \"../../input/GEO/Cystic_Fibrosis\"\n",
30
+ "in_cohort_dir = \"../../input/GEO/Cystic_Fibrosis/GSE142610\"\n",
31
+ "\n",
32
+ "# Output paths\n",
33
+ "out_data_file = \"../../output/preprocess/Cystic_Fibrosis/GSE142610.csv\"\n",
34
+ "out_gene_data_file = \"../../output/preprocess/Cystic_Fibrosis/gene_data/GSE142610.csv\"\n",
35
+ "out_clinical_data_file = \"../../output/preprocess/Cystic_Fibrosis/clinical_data/GSE142610.csv\"\n",
36
+ "json_path = \"../../output/preprocess/Cystic_Fibrosis/cohort_info.json\"\n"
37
+ ]
38
+ },
39
+ {
40
+ "cell_type": "markdown",
41
+ "id": "ea7b74fe",
42
+ "metadata": {},
43
+ "source": [
44
+ "### Step 1: Initial Data Loading"
45
+ ]
46
+ },
47
+ {
48
+ "cell_type": "code",
49
+ "execution_count": 2,
50
+ "id": "35243b84",
51
+ "metadata": {
52
+ "execution": {
53
+ "iopub.execute_input": "2025-03-25T08:35:30.201627Z",
54
+ "iopub.status.busy": "2025-03-25T08:35:30.201481Z",
55
+ "iopub.status.idle": "2025-03-25T08:35:30.309681Z",
56
+ "shell.execute_reply": "2025-03-25T08:35:30.309284Z"
57
+ }
58
+ },
59
+ "outputs": [
60
+ {
61
+ "name": "stdout",
62
+ "output_type": "stream",
63
+ "text": [
64
+ "Background Information:\n",
65
+ "!Series_title\t\"Integrative genomic meta-analysis reveals novel molecular insights into cystic fibrosis and ΔF508-CFTR rescue\"\n",
66
+ "!Series_summary\t\"Cystic fibrosis (CF), caused by mutations to CFTR, leads to severe and progressive lung disease. The most common mutant, ΔF508-CFTR, undergoes proteasomal degradation, depleting its anion channel function. “Proteostasis” pathways, i.e. those relevant to protein processing and trafficking, are altered in cells with ΔF508-CFTR and can be modulated to partially rescue protein function. However, many details regarding proteostasis modulation, and its relevance to CF and ΔF508-CFTR rescue, remain poorly understood. To shed light on this, we re-analyzed public datasets characterizing transcription in CF vs. non-CF epithelia from human and pig airways, and also profiled established temperature, genetic, and chemical interventions that rescue ΔF508-CFTR. Meta-analysis yielded a core disease signature and two core rescue signatures. To interpret these, we compiled proteostasis pathways and an original “CFTR Gene Set Library”. The disease signature revealed differential regulation of mTORC1 signaling, endocytosis, and proteasomal degradation. Overlaying functional genomics data identified candidate mediators of low-temperature rescue, while multiple rescue strategies converged on activation of unfolded protein response pathways. Remarkably, however, C18, an analog of the CFTR corrector compound Lumacaftor, induced minimal transcriptional perturbation despite its rescue activity. This work elucidates the involvement of proteostasis in both disease and rescue perturbations while highlighting that not all CFTR rescue interventions act on transcription.\"\n",
67
+ "!Series_overall_design\t\"Polarized air-liquid interface cultures of CFBE cells were treated to either knockdown of SIN3A, SYVN1 or NEED8, overexpression of miR-138, treated with corrector compound 18 (C18), or cultured at temperatures associated with improving ΔF508-CFTR trafficking.\"\n",
68
+ "Sample Characteristics Dictionary:\n",
69
+ "{0: ['tag: Cell line: CFBE'], 1: ['treatment: DMSO for 24h', 'temperature: 40°C incubation for 24h followed by 27°C incubation for 24h', 'treatment: NEDD8 DsiRNA + 6µM Corrector Compound C18 treatment for 24h', 'treatment: Scrambled DsiRNA', 'temperature: 27°C incubation for 24h', 'treatment: SIN3A DsiRNA', 'temperature: 37°C incubation for 24h', 'treatment: SYVN1 DsiRNA', 'treatment: 6µM Corrector Compound C18 treatment for 24h', 'treatment: No treatment', 'treatment: miR-138 mimic', 'treatment: SYVN1 DsiRNA + 6µM Corrector Compound C18 treatment for 24h', 'temperature: 40°C incubation for 24h', 'treatment: NEDD8 DsiRNA']}\n"
70
+ ]
71
+ }
72
+ ],
73
+ "source": [
74
+ "from tools.preprocess import *\n",
75
+ "# 1. Identify the paths to the SOFT file and the matrix file\n",
76
+ "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
77
+ "\n",
78
+ "# 2. Read the matrix file to obtain background information and sample characteristics data\n",
79
+ "background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']\n",
80
+ "clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']\n",
81
+ "background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)\n",
82
+ "\n",
83
+ "# 3. Obtain the sample characteristics dictionary from the clinical dataframe\n",
84
+ "sample_characteristics_dict = get_unique_values_by_row(clinical_data)\n",
85
+ "\n",
86
+ "# 4. Explicitly print out all the background information and the sample characteristics dictionary\n",
87
+ "print(\"Background Information:\")\n",
88
+ "print(background_info)\n",
89
+ "print(\"Sample Characteristics Dictionary:\")\n",
90
+ "print(sample_characteristics_dict)\n"
91
+ ]
92
+ },
93
+ {
94
+ "cell_type": "markdown",
95
+ "id": "07ce1988",
96
+ "metadata": {},
97
+ "source": [
98
+ "### Step 2: Dataset Analysis and Clinical Feature Extraction"
99
+ ]
100
+ },
101
+ {
102
+ "cell_type": "code",
103
+ "execution_count": 3,
104
+ "id": "3bad36fc",
105
+ "metadata": {
106
+ "execution": {
107
+ "iopub.execute_input": "2025-03-25T08:35:30.311112Z",
108
+ "iopub.status.busy": "2025-03-25T08:35:30.310991Z",
109
+ "iopub.status.idle": "2025-03-25T08:35:30.322221Z",
110
+ "shell.execute_reply": "2025-03-25T08:35:30.321831Z"
111
+ }
112
+ },
113
+ "outputs": [
114
+ {
115
+ "name": "stdout",
116
+ "output_type": "stream",
117
+ "text": [
118
+ "Clinical Data Preview: {'Sample_1': [1.0], 'Sample_2': [nan], 'Sample_3': [0.0], 'Sample_4': [1.0], 'Sample_5': [nan], 'Sample_6': [0.0], 'Sample_7': [nan], 'Sample_8': [0.0], 'Sample_9': [0.0], 'Sample_10': [1.0], 'Sample_11': [0.0], 'Sample_12': [0.0], 'Sample_13': [nan], 'Sample_14': [0.0]}\n",
119
+ "Clinical data saved to ../../output/preprocess/Cystic_Fibrosis/clinical_data/GSE142610.csv\n"
120
+ ]
121
+ }
122
+ ],
123
+ "source": [
124
+ "import pandas as pd\n",
125
+ "import os\n",
126
+ "import numpy as np\n",
127
+ "import re\n",
128
+ "from typing import Callable, Optional, Dict, Any, Union\n",
129
+ "import json\n",
130
+ "\n",
131
+ "# 1. Gene Expression Data Availability\n",
132
+ "# Based on the background information, this appears to be a gene expression dataset \n",
133
+ "# analyzing transcriptional changes in CF, not just miRNA or methylation\n",
134
+ "is_gene_available = True\n",
135
+ "\n",
136
+ "# 2. Variable Availability and Data Type Conversion\n",
137
+ "# 2.1 Data Availability\n",
138
+ "# For trait: Based on the characteristics dictionary, we see \"treatment\" at index 1\n",
139
+ "# which can be used to determine CF vs non-CF status\n",
140
+ "trait_row = 1 # The row with treatment information\n",
141
+ "\n",
142
+ "# There is no age data available in the sample characteristics\n",
143
+ "age_row = None\n",
144
+ "\n",
145
+ "# There is no gender data available in the sample characteristics\n",
146
+ "gender_row = None\n",
147
+ "\n",
148
+ "# 2.2 Data Type Conversion Functions\n",
149
+ "def convert_trait(value: str) -> Optional[int]:\n",
150
+ " \"\"\"\n",
151
+ " Convert the treatment value to a binary trait (CF status).\n",
152
+ " 1 = CF-like condition (DMSO, scrambled, no treatment as controls)\n",
153
+ " 0 = Rescue interventions (treatments aimed at rescuing ΔF508-CFTR)\n",
154
+ " \n",
155
+ " Args:\n",
156
+ " value: The treatment value from the dataset\n",
157
+ " \n",
158
+ " Returns:\n",
159
+ " 1 for CF-like (control) conditions, 0 for rescue interventions, None for unknown\n",
160
+ " \"\"\"\n",
161
+ " if not isinstance(value, str):\n",
162
+ " return None\n",
163
+ " \n",
164
+ " # Extract the value after the colon if present\n",
165
+ " if ':' in value:\n",
166
+ " value = value.split(':', 1)[1].strip()\n",
167
+ " \n",
168
+ " # Control conditions (CF-like)\n",
169
+ " if any(x in value.lower() for x in ['dmso', 'scrambled dsirna', 'no treatment']):\n",
170
+ " return 1\n",
171
+ " # Rescue interventions\n",
172
+ " elif any(x in value.lower() for x in ['temperature: 27', 'sin3a', 'syvn1', 'nedd8', 'mir-138', 'c18', 'corrector']):\n",
173
+ " return 0\n",
174
+ " else:\n",
175
+ " return None\n",
176
+ "\n",
177
+ "def convert_age(value: str) -> Optional[float]:\n",
178
+ " \"\"\"Placeholder function since age data is not available.\"\"\"\n",
179
+ " return None\n",
180
+ "\n",
181
+ "def convert_gender(value: str) -> Optional[int]:\n",
182
+ " \"\"\"Placeholder function since gender data is not available.\"\"\"\n",
183
+ " return None\n",
184
+ "\n",
185
+ "# 3. Save Metadata - Initial Filtering\n",
186
+ "# Trait data is available if trait_row is not None\n",
187
+ "is_trait_available = trait_row is not None\n",
188
+ "validate_and_save_cohort_info(\n",
189
+ " is_final=False,\n",
190
+ " cohort=cohort,\n",
191
+ " info_path=json_path,\n",
192
+ " is_gene_available=is_gene_available,\n",
193
+ " is_trait_available=is_trait_available\n",
194
+ ")\n",
195
+ "\n",
196
+ "# 4. Clinical Feature Extraction\n",
197
+ "# Only if trait data is available\n",
198
+ "if trait_row is not None:\n",
199
+ " try:\n",
200
+ " # Create a DataFrame in the expected format for geo_select_clinical_features\n",
201
+ " # Samples as columns, features as rows\n",
202
+ " sample_characteristics = {\n",
203
+ " 0: ['tag: Cell line: CFBE'],\n",
204
+ " 1: ['treatment: DMSO for 24h', \n",
205
+ " 'temperature: 40°C incubation for 24h followed by 27°C incubation for 24h', \n",
206
+ " 'treatment: NEDD8 DsiRNA + 6µM Corrector Compound C18 treatment for 24h', \n",
207
+ " 'treatment: Scrambled DsiRNA', \n",
208
+ " 'temperature: 27°C incubation for 24h', \n",
209
+ " 'treatment: SIN3A DsiRNA', \n",
210
+ " 'temperature: 37°C incubation for 24h', \n",
211
+ " 'treatment: SYVN1 DsiRNA', \n",
212
+ " 'treatment: 6µM Corrector Compound C18 treatment for 24h', \n",
213
+ " 'treatment: No treatment', \n",
214
+ " 'treatment: miR-138 mimic', \n",
215
+ " 'treatment: SYVN1 DsiRNA + 6µM Corrector Compound C18 treatment for 24h', \n",
216
+ " 'temperature: 40°C incubation for 24h', \n",
217
+ " 'treatment: NEDD8 DsiRNA']\n",
218
+ " }\n",
219
+ " \n",
220
+ " # Create a list of sample IDs\n",
221
+ " unique_treatments = sample_characteristics[1]\n",
222
+ " sample_ids = [f\"Sample_{i+1}\" for i in range(len(unique_treatments))]\n",
223
+ " \n",
224
+ " # Create the clinical data DataFrame with samples as columns\n",
225
+ " clinical_data = pd.DataFrame(index=range(max(sample_characteristics.keys())+1))\n",
226
+ " \n",
227
+ " for i, sample_id in enumerate(sample_ids):\n",
228
+ " clinical_data[sample_id] = None\n",
229
+ " \n",
230
+ " # Assign cell line info to all samples\n",
231
+ " clinical_data.at[0, sample_id] = sample_characteristics[0][0]\n",
232
+ " \n",
233
+ " # Assign treatment info\n",
234
+ " clinical_data.at[1, sample_id] = unique_treatments[i]\n",
235
+ " \n",
236
+ " # Extract clinical features\n",
237
+ " selected_clinical_df = geo_select_clinical_features(\n",
238
+ " clinical_df=clinical_data,\n",
239
+ " trait=trait,\n",
240
+ " trait_row=trait_row,\n",
241
+ " convert_trait=convert_trait,\n",
242
+ " age_row=age_row,\n",
243
+ " convert_age=convert_age,\n",
244
+ " gender_row=gender_row,\n",
245
+ " convert_gender=convert_gender\n",
246
+ " )\n",
247
+ " \n",
248
+ " # Preview the data\n",
249
+ " preview = preview_df(selected_clinical_df)\n",
250
+ " print(\"Clinical Data Preview:\", preview)\n",
251
+ " \n",
252
+ " # Save the processed clinical data\n",
253
+ " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
254
+ " selected_clinical_df.to_csv(out_clinical_data_file, index=False)\n",
255
+ " print(f\"Clinical data saved to {out_clinical_data_file}\")\n",
256
+ " except Exception as e:\n",
257
+ " print(f\"Error processing clinical data: {str(e)}\")\n",
258
+ " print(\"Clinical data processing skipped.\")\n"
259
+ ]
260
+ },
261
+ {
262
+ "cell_type": "markdown",
263
+ "id": "590f5c7d",
264
+ "metadata": {},
265
+ "source": [
266
+ "### Step 3: Gene Data Extraction"
267
+ ]
268
+ },
269
+ {
270
+ "cell_type": "code",
271
+ "execution_count": 4,
272
+ "id": "92e3e0fa",
273
+ "metadata": {
274
+ "execution": {
275
+ "iopub.execute_input": "2025-03-25T08:35:30.323480Z",
276
+ "iopub.status.busy": "2025-03-25T08:35:30.323373Z",
277
+ "iopub.status.idle": "2025-03-25T08:35:30.492362Z",
278
+ "shell.execute_reply": "2025-03-25T08:35:30.491824Z"
279
+ }
280
+ },
281
+ "outputs": [
282
+ {
283
+ "name": "stdout",
284
+ "output_type": "stream",
285
+ "text": [
286
+ "Found data marker at line 66\n",
287
+ "Header line: \"ID_REF\"\t\"GSM4232834\"\t\"GSM4232835\"\t\"GSM4232836\"\t\"GSM4232837\"\t\"GSM4232838\"\t\"GSM4232839\"\t\"GSM4232840\"\t\"GSM4232841\"\t\"GSM4232842\"\t\"GSM4232843\"\t\"GSM4232844\"\t\"GSM4232845\"\t\"GSM4232846\"\t\"GSM4232847\"\t\"GSM4232848\"\t\"GSM4232849\"\t\"GSM4232850\"\t\"GSM4232851\"\t\"GSM4232852\"\t\"GSM4232853\"\t\"GSM4232854\"\t\"GSM4232855\"\t\"GSM4232856\"\t\"GSM4232857\"\t\"GSM4232858\"\t\"GSM4232859\"\t\"GSM4232860\"\t\"GSM4232861\"\t\"GSM4232862\"\t\"GSM4232863\"\t\"GSM4232864\"\t\"GSM4232865\"\t\"GSM4232866\"\t\"GSM4232867\"\t\"GSM4232868\"\t\"GSM4232869\"\t\"GSM4232870\"\t\"GSM4232871\"\t\"GSM4232872\"\t\"GSM4232873\"\t\"GSM4232874\"\t\"GSM4232875\"\t\"GSM4232876\"\t\"GSM4232877\"\t\"GSM4232878\"\t\"GSM4232879\"\t\"GSM4232880\"\t\"GSM4232881\"\t\"GSM4232882\"\t\"GSM4232883\"\t\"GSM4232884\"\t\"GSM4232885\"\t\"GSM4232886\"\t\"GSM4232887\"\t\"GSM4232888\"\t\"GSM4232889\"\t\"GSM4232890\"\t\"GSM4232891\"\t\"GSM4232892\"\t\"GSM4232893\"\n",
288
+ "First data line: \"7A5\"\t7.00047\t7.4364\t7.2259\t6.95089\t7.01398\t6.94179\t6.35476\t6.39446\t7.04405\t6.67603\t6.38158\t6.87048\t6.78098\t6.94703\t7.00125\t7.0633\t6.01448\t7.10264\t6.87251\t7.03624\t7.04809\t6.72825\t7.0007\t6.90422\t6.90433\t7.23055\t7.52354\t6.29845\t6.93591\t6.45731\t6.93591\t6.44016\t7.30199\t6.90369\t6.44151\t6.8296\t6.27562\t6.85061\t7.22973\t6.96944\t6.52329\t6.62954\t6.69973\t6.95149\t6.17045\t6.70617\t6.7019\t6.9133\t6.78328\t6.98717\t7.05936\t6.44223\t7.03674\t7.01894\t7.03133\t7.28102\t6.84521\t7.02275\t6.80499\t7.24612\n",
289
+ "Index(['7A5', 'A1BG', 'A1CF', 'A26C3', 'A2BP1', 'A2LD1', 'A2M', 'A2ML1',\n",
290
+ " 'A3GALT2', 'A4GALT', 'A4GNT', 'AAA1', 'AAAS', 'AACS', 'AACSL', 'AADAC',\n",
291
+ " 'AADACL1', 'AADACL2', 'AADACL3', 'AADACL4'],\n",
292
+ " dtype='object', name='ID')\n"
293
+ ]
294
+ }
295
+ ],
296
+ "source": [
297
+ "# 1. Get the file paths for the SOFT file and matrix file\n",
298
+ "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
299
+ "\n",
300
+ "# 2. First, let's examine the structure of the matrix file to understand its format\n",
301
+ "import gzip\n",
302
+ "\n",
303
+ "# Peek at the first few lines of the file to understand its structure\n",
304
+ "with gzip.open(matrix_file, 'rt') as file:\n",
305
+ " # Read first 100 lines to find the header structure\n",
306
+ " for i, line in enumerate(file):\n",
307
+ " if '!series_matrix_table_begin' in line:\n",
308
+ " print(f\"Found data marker at line {i}\")\n",
309
+ " # Read the next line which should be the header\n",
310
+ " header_line = next(file)\n",
311
+ " print(f\"Header line: {header_line.strip()}\")\n",
312
+ " # And the first data line\n",
313
+ " first_data_line = next(file)\n",
314
+ " print(f\"First data line: {first_data_line.strip()}\")\n",
315
+ " break\n",
316
+ " if i > 100: # Limit search to first 100 lines\n",
317
+ " print(\"Matrix table marker not found in first 100 lines\")\n",
318
+ " break\n",
319
+ "\n",
320
+ "# 3. Now try to get the genetic data with better error handling\n",
321
+ "try:\n",
322
+ " gene_data = get_genetic_data(matrix_file)\n",
323
+ " print(gene_data.index[:20])\n",
324
+ "except KeyError as e:\n",
325
+ " print(f\"KeyError: {e}\")\n",
326
+ " \n",
327
+ " # Alternative approach: manually extract the data\n",
328
+ " print(\"\\nTrying alternative approach to read the gene data:\")\n",
329
+ " with gzip.open(matrix_file, 'rt') as file:\n",
330
+ " # Find the start of the data\n",
331
+ " for line in file:\n",
332
+ " if '!series_matrix_table_begin' in line:\n",
333
+ " break\n",
334
+ " \n",
335
+ " # Read the headers and data\n",
336
+ " import pandas as pd\n",
337
+ " df = pd.read_csv(file, sep='\\t', index_col=0)\n",
338
+ " print(f\"Column names: {df.columns[:5]}\")\n",
339
+ " print(f\"First 20 row IDs: {df.index[:20]}\")\n",
340
+ " gene_data = df\n"
341
+ ]
342
+ },
343
+ {
344
+ "cell_type": "markdown",
345
+ "id": "d6ed32f3",
346
+ "metadata": {},
347
+ "source": [
348
+ "### Step 4: Gene Identifier Review"
349
+ ]
350
+ },
351
+ {
352
+ "cell_type": "code",
353
+ "execution_count": 5,
354
+ "id": "2bc0731c",
355
+ "metadata": {
356
+ "execution": {
357
+ "iopub.execute_input": "2025-03-25T08:35:30.493873Z",
358
+ "iopub.status.busy": "2025-03-25T08:35:30.493748Z",
359
+ "iopub.status.idle": "2025-03-25T08:35:30.495952Z",
360
+ "shell.execute_reply": "2025-03-25T08:35:30.495587Z"
361
+ }
362
+ },
363
+ "outputs": [],
364
+ "source": [
365
+ "# Reviewing the gene identifiers\n",
366
+ "# Looking at the identifiers from the output, we can see entries like:\n",
367
+ "# '7A5', 'A1BG', 'A1CF', 'A2BP1', etc.\n",
368
+ "\n",
369
+ "# These appear to be standard human gene symbols. \n",
370
+ "# For example:\n",
371
+ "# - A1BG is Alpha-1-B Glycoprotein\n",
372
+ "# - A2M is Alpha-2-Macroglobulin\n",
373
+ "# - AAAS is Achalasia, Adrenocortical Insufficiency, Alacrimia syndrome gene\n",
374
+ "\n",
375
+ "# While some identifiers might be less common (like 7A5), the majority appear to be\n",
376
+ "# standard HGNC gene symbols, so no mapping should be required\n",
377
+ "\n",
378
+ "requires_gene_mapping = False\n"
379
+ ]
380
+ },
381
+ {
382
+ "cell_type": "markdown",
383
+ "id": "5aa4c749",
384
+ "metadata": {},
385
+ "source": [
386
+ "### Step 5: Data Normalization and Linking"
387
+ ]
388
+ },
389
+ {
390
+ "cell_type": "code",
391
+ "execution_count": 6,
392
+ "id": "f274558c",
393
+ "metadata": {
394
+ "execution": {
395
+ "iopub.execute_input": "2025-03-25T08:35:30.497231Z",
396
+ "iopub.status.busy": "2025-03-25T08:35:30.497121Z",
397
+ "iopub.status.idle": "2025-03-25T08:35:42.410116Z",
398
+ "shell.execute_reply": "2025-03-25T08:35:42.409470Z"
399
+ }
400
+ },
401
+ "outputs": [
402
+ {
403
+ "name": "stdout",
404
+ "output_type": "stream",
405
+ "text": [
406
+ "Normalized gene data shape: (20747, 60)\n",
407
+ "First few genes with their expression values after normalization:\n",
408
+ " GSM4232834 GSM4232835 GSM4232836 GSM4232837 GSM4232838 \\\n",
409
+ "ID \n",
410
+ "A1BG 4.79408 4.77433 5.09248 5.12294 5.22396 \n",
411
+ "A1BG-AS1 4.41521 4.10095 4.19279 4.15799 4.01244 \n",
412
+ "A1CF 4.47919 4.49296 4.96132 4.61623 4.62902 \n",
413
+ "A2M 4.18512 3.43994 4.08894 3.50579 3.90165 \n",
414
+ "A2ML1 4.53153 3.44832 4.08500 2.97268 4.07312 \n",
415
+ "\n",
416
+ " GSM4232839 GSM4232840 GSM4232841 GSM4232842 GSM4232843 ... \\\n",
417
+ "ID ... \n",
418
+ "A1BG 4.83021 5.07336 4.71037 5.22138 5.04408 ... \n",
419
+ "A1BG-AS1 4.37280 4.83188 4.62063 4.36214 3.76720 ... \n",
420
+ "A1CF 4.61928 4.64433 4.49737 4.74431 4.53624 ... \n",
421
+ "A2M 3.68211 3.59082 3.72203 3.68729 3.36298 ... \n",
422
+ "A2ML1 2.88517 3.25851 4.20093 4.47530 3.98375 ... \n",
423
+ "\n",
424
+ " GSM4232884 GSM4232885 GSM4232886 GSM4232887 GSM4232888 \\\n",
425
+ "ID \n",
426
+ "A1BG 4.76957 4.83349 4.89837 4.95678 5.55280 \n",
427
+ "A1BG-AS1 4.16814 4.50411 4.44726 3.90727 4.08097 \n",
428
+ "A1CF 4.68982 4.46157 4.54973 4.70105 4.50531 \n",
429
+ "A2M 3.98965 4.56486 3.47137 3.84234 4.02411 \n",
430
+ "A2ML1 3.29743 4.00144 3.68519 4.54602 3.94150 \n",
431
+ "\n",
432
+ " GSM4232889 GSM4232890 GSM4232891 GSM4232892 GSM4232893 \n",
433
+ "ID \n",
434
+ "A1BG 5.31089 4.85788 5.19227 5.00836 4.98561 \n",
435
+ "A1BG-AS1 4.40857 4.42194 4.27793 3.90266 4.25806 \n",
436
+ "A1CF 4.34295 4.66214 4.30193 4.12278 4.21548 \n",
437
+ "A2M 4.41546 3.47600 3.81681 4.10732 3.47600 \n",
438
+ "A2ML1 3.31699 4.02810 3.84733 3.15712 3.85833 \n",
439
+ "\n",
440
+ "[5 rows x 60 columns]\n"
441
+ ]
442
+ },
443
+ {
444
+ "name": "stdout",
445
+ "output_type": "stream",
446
+ "text": [
447
+ "Normalized gene data saved to ../../output/preprocess/Cystic_Fibrosis/gene_data/GSE142610.csv\n"
448
+ ]
449
+ },
450
+ {
451
+ "name": "stdout",
452
+ "output_type": "stream",
453
+ "text": [
454
+ "Found treatment information for 60 samples\n",
455
+ "Clinical data created with 60 samples\n",
456
+ "Cystic_Fibrosis\n",
457
+ "0 52\n",
458
+ "1 8\n",
459
+ "Name: count, dtype: int64\n",
460
+ "Linked data shape: (60, 20748)\n"
461
+ ]
462
+ },
463
+ {
464
+ "name": "stdout",
465
+ "output_type": "stream",
466
+ "text": [
467
+ "Data shape after handling missing values: (60, 20748)\n",
468
+ "For the feature 'Cystic_Fibrosis', the least common label is '1' with 8 occurrences. This represents 13.33% of the dataset.\n"
469
+ ]
470
+ },
471
+ {
472
+ "name": "stdout",
473
+ "output_type": "stream",
474
+ "text": [
475
+ "Linked data saved to ../../output/preprocess/Cystic_Fibrosis/GSE142610.csv\n"
476
+ ]
477
+ }
478
+ ],
479
+ "source": [
480
+ "# 1. Normalize gene symbols in the gene expression data\n",
481
+ "normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n",
482
+ "print(f\"Normalized gene data shape: {normalized_gene_data.shape}\")\n",
483
+ "print(\"First few genes with their expression values after normalization:\")\n",
484
+ "print(normalized_gene_data.head())\n",
485
+ "\n",
486
+ "# Save the normalized gene data\n",
487
+ "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
488
+ "normalized_gene_data.to_csv(out_gene_data_file)\n",
489
+ "print(f\"Normalized gene data saved to {out_gene_data_file}\")\n",
490
+ "\n",
491
+ "# 2. Properly extract original clinical data to match GSM IDs\n",
492
+ "# First, let's get the proper mapping between GSM IDs and treatment conditions\n",
493
+ "# Extract the relevant lines from the SOFT file for sample information\n",
494
+ "with gzip.open(soft_file, 'rt') as f:\n",
495
+ " sample_info_lines = []\n",
496
+ " current_gsm = None\n",
497
+ " for line in f:\n",
498
+ " line = line.strip()\n",
499
+ " if line.startswith(\"^SAMPLE = \"):\n",
500
+ " current_gsm = line.split(\" = \")[1]\n",
501
+ " elif line.startswith(\"!Sample_title\") and current_gsm:\n",
502
+ " title = line.split(\" = \")[1].strip('\"')\n",
503
+ " sample_info_lines.append((current_gsm, title))\n",
504
+ "\n",
505
+ "# Create a mapping of GSM IDs to treatment conditions\n",
506
+ "gsm_to_treatment = {}\n",
507
+ "for gsm, title in sample_info_lines:\n",
508
+ " gsm_to_treatment[gsm] = title\n",
509
+ "\n",
510
+ "print(f\"Found treatment information for {len(gsm_to_treatment)} samples\")\n",
511
+ "\n",
512
+ "# Create clinical data with real GSM IDs\n",
513
+ "clinical_data = pd.DataFrame(index=normalized_gene_data.columns)\n",
514
+ "\n",
515
+ "# Assign trait values based on treatment descriptions\n",
516
+ "# 1 = CF-like condition (control)\n",
517
+ "# 0 = Rescue intervention\n",
518
+ "clinical_data[trait] = clinical_data.index.map(lambda gsm: 1 if any(x in gsm_to_treatment.get(gsm, \"\").lower() \n",
519
+ " for x in ['dmso', 'scrambled', 'control', 'untreated']) \n",
520
+ " else 0 if gsm in gsm_to_treatment else None)\n",
521
+ "\n",
522
+ "print(f\"Clinical data created with {len(clinical_data)} samples\")\n",
523
+ "print(clinical_data[trait].value_counts())\n",
524
+ "\n",
525
+ "# Link the clinical and genetic data\n",
526
+ "linked_data = clinical_data.join(normalized_gene_data.T)\n",
527
+ "print(f\"Linked data shape: {linked_data.shape}\")\n",
528
+ "\n",
529
+ "# 3. Handle missing values in the linked data\n",
530
+ "linked_data = handle_missing_values(linked_data, trait)\n",
531
+ "print(f\"Data shape after handling missing values: {linked_data.shape}\")\n",
532
+ "\n",
533
+ "# 4. Determine whether the trait is biased\n",
534
+ "trait_type = 'binary' if len(linked_data[trait].unique()) == 2 else 'continuous'\n",
535
+ "if trait_type == \"binary\":\n",
536
+ " is_trait_biased = judge_binary_variable_biased(linked_data, trait)\n",
537
+ "else:\n",
538
+ " is_trait_biased = judge_continuous_variable_biased(linked_data, trait)\n",
539
+ "\n",
540
+ "# 5. Conduct final quality validation and save cohort information\n",
541
+ "is_usable = validate_and_save_cohort_info(\n",
542
+ " is_final=True, \n",
543
+ " cohort=cohort, \n",
544
+ " info_path=json_path, \n",
545
+ " is_gene_available=True, \n",
546
+ " is_trait_available=True, \n",
547
+ " is_biased=is_trait_biased, \n",
548
+ " df=linked_data,\n",
549
+ " note=f\"Dataset contains gene expression data comparing rescue interventions with control conditions in CFBE cells.\"\n",
550
+ ")\n",
551
+ "\n",
552
+ "# 6. If the linked data is usable, save it\n",
553
+ "if is_usable:\n",
554
+ " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n",
555
+ " linked_data.to_csv(out_data_file)\n",
556
+ " print(f\"Linked data saved to {out_data_file}\")\n",
557
+ "else:\n",
558
+ " print(\"Data was determined to be unusable and was not saved\")"
559
+ ]
560
+ }
561
+ ],
562
+ "metadata": {
563
+ "language_info": {
564
+ "codemirror_mode": {
565
+ "name": "ipython",
566
+ "version": 3
567
+ },
568
+ "file_extension": ".py",
569
+ "mimetype": "text/x-python",
570
+ "name": "python",
571
+ "nbconvert_exporter": "python",
572
+ "pygments_lexer": "ipython3",
573
+ "version": "3.10.16"
574
+ }
575
+ },
576
+ "nbformat": 4,
577
+ "nbformat_minor": 5
578
+ }
code/Cystic_Fibrosis/GSE60690.ipynb ADDED
The diff for this file is too large to render. See raw diff