File size: 28,001 Bytes
e4183cf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "a9eb8e58",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:31:33.983464Z",
     "iopub.status.busy": "2025-03-25T08:31:33.983232Z",
     "iopub.status.idle": "2025-03-25T08:31:34.146265Z",
     "shell.execute_reply": "2025-03-25T08:31:34.145925Z"
    }
   },
   "outputs": [],
   "source": [
    "import sys\n",
    "import os\n",
    "sys.path.append(os.path.abspath(os.path.join(os.getcwd(), '../..')))\n",
    "\n",
    "# Path Configuration\n",
    "from tools.preprocess import *\n",
    "\n",
    "# Processing context\n",
    "trait = \"COVID-19\"\n",
    "cohort = \"GSE273225\"\n",
    "\n",
    "# Input paths\n",
    "in_trait_dir = \"../../input/GEO/COVID-19\"\n",
    "in_cohort_dir = \"../../input/GEO/COVID-19/GSE273225\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/COVID-19/GSE273225.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/COVID-19/gene_data/GSE273225.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/COVID-19/clinical_data/GSE273225.csv\"\n",
    "json_path = \"../../output/preprocess/COVID-19/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6bda55a8",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "a3031a2c",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:31:34.147637Z",
     "iopub.status.busy": "2025-03-25T08:31:34.147507Z",
     "iopub.status.idle": "2025-03-25T08:31:34.158834Z",
     "shell.execute_reply": "2025-03-25T08:31:34.158558Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Background Information:\n",
      "!Series_title\t\"The effect of rewarming ischemia on tissue transcriptome signatures: a clinical observational study in lung transplantation\"\n",
      "!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",
      "!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",
      "!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",
      "!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",
      "!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",
      "!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",
      "!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",
      "!Series_overall_design\t\"References\"\n",
      "!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",
      "!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",
      "!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",
      "Sample Characteristics Dictionary:\n",
      "{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"
     ]
    }
   ],
   "source": [
    "from tools.preprocess import *\n",
    "# 1. Identify the paths to the SOFT file and the matrix file\n",
    "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
    "\n",
    "# 2. Read the matrix file to obtain background information and sample characteristics data\n",
    "background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']\n",
    "clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']\n",
    "background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)\n",
    "\n",
    "# 3. Obtain the sample characteristics dictionary from the clinical dataframe\n",
    "sample_characteristics_dict = get_unique_values_by_row(clinical_data)\n",
    "\n",
    "# 4. Explicitly print out all the background information and the sample characteristics dictionary\n",
    "print(\"Background Information:\")\n",
    "print(background_info)\n",
    "print(\"Sample Characteristics Dictionary:\")\n",
    "print(sample_characteristics_dict)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "911cf4e9",
   "metadata": {},
   "source": [
    "### Step 2: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "2cc40cc0",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:31:34.159832Z",
     "iopub.status.busy": "2025-03-25T08:31:34.159732Z",
     "iopub.status.idle": "2025-03-25T08:31:34.165513Z",
     "shell.execute_reply": "2025-03-25T08:31:34.165250Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "False"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 1. Gene Expression Data Availability\n",
    "# Based on the Series_overall_design and the overall structure, this study includes\n",
    "# gene expression data using nCounter digital gene expression analysis with the Immunology V2 panel\n",
    "# This targets 579 immune system-associated genes, which is suitable for our analysis\n",
    "is_gene_available = True\n",
    "\n",
    "# 2. Variable Availability and Data Type Conversion\n",
    "# 2.1 Trait related data - Check for COVID-19 related data\n",
    "# Looking at the background info, this is a lung transplantation study with no indication of COVID-19\n",
    "# The study is about rewarming ischemia time during lung transplantation\n",
    "trait_row = None  # No COVID-19 data available\n",
    "\n",
    "# 2.2 Age data\n",
    "# Available in key 3 as \"donor age (y): XX\"\n",
    "age_row = 3\n",
    "\n",
    "def convert_age(value):\n",
    "    \"\"\"Convert age value to numeric (continuous)\"\"\"\n",
    "    if value is None:\n",
    "        return None\n",
    "    try:\n",
    "        # Extract the number after the colon\n",
    "        if \":\" in value:\n",
    "            age_str = value.split(\":\")[1].strip()\n",
    "            return float(age_str)\n",
    "        return None\n",
    "    except:\n",
    "        return None\n",
    "\n",
    "# 2.3 Gender data\n",
    "# Available in key 4 as \"donor sex: male/female\"\n",
    "gender_row = 4\n",
    "\n",
    "def convert_gender(value):\n",
    "    \"\"\"Convert gender information to binary (0 for female, 1 for male)\"\"\"\n",
    "    if value is None:\n",
    "        return None\n",
    "    try:\n",
    "        # Extract the gender after the colon\n",
    "        if \":\" in value:\n",
    "            gender = value.split(\":\")[1].strip().lower()\n",
    "            if gender == \"female\":\n",
    "                return 0\n",
    "            elif gender == \"male\":\n",
    "                return 1\n",
    "        return None\n",
    "    except:\n",
    "        return None\n",
    "\n",
    "# For completeness, define convert_trait even though we don't have COVID-19 data\n",
    "def convert_trait(value):\n",
    "    \"\"\"\n",
    "    Convert trait information to binary.\n",
    "    This is a placeholder as there's no COVID-19 data in this dataset.\n",
    "    \"\"\"\n",
    "    return None\n",
    "\n",
    "# 3. Save Metadata\n",
    "# Determine if trait data is available (it's not)\n",
    "is_trait_available = trait_row is not None\n",
    "\n",
    "# Validate and save cohort info\n",
    "validate_and_save_cohort_info(\n",
    "    is_final=False,\n",
    "    cohort=cohort,\n",
    "    info_path=json_path,\n",
    "    is_gene_available=is_gene_available,\n",
    "    is_trait_available=is_trait_available\n",
    ")\n",
    "\n",
    "# 4. Clinical Feature Extraction\n",
    "# Skip this step as trait_row is None (trait data not available)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d6b6c4f7",
   "metadata": {},
   "source": [
    "### Step 3: Gene Data Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "de320944",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:31:34.166474Z",
     "iopub.status.busy": "2025-03-25T08:31:34.166376Z",
     "iopub.status.idle": "2025-03-25T08:31:34.185433Z",
     "shell.execute_reply": "2025-03-25T08:31:34.185157Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "SOFT file: ../../input/GEO/COVID-19/GSE273225/GSE273225_family.soft.gz\n",
      "Matrix file: ../../input/GEO/COVID-19/GSE273225/GSE273225_series_matrix.txt.gz\n",
      "Found the matrix table marker at line 80\n",
      "Gene data shape: (608, 118)\n",
      "First 20 gene/probe identifiers:\n",
      "['ABCB1', 'ABCF1', 'ABL1', 'ADA', 'AHR', 'AICDA', 'AIRE', 'ALAS1', 'APP', 'ARG1', 'ARG2', 'ARHGDIB', 'ATG10', 'ATG12', 'ATG16L1', 'ATG5', 'ATG7', 'ATM', 'B2M', 'B3GAT1']\n"
     ]
    }
   ],
   "source": [
    "# 1. Identify the paths to the SOFT file and the matrix file\n",
    "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
    "print(f\"SOFT file: {soft_file}\")\n",
    "print(f\"Matrix file: {matrix_file}\")\n",
    "\n",
    "# Set gene availability flag\n",
    "is_gene_available = True  # Initially assume gene data is available\n",
    "\n",
    "# First check if the matrix file contains the expected marker\n",
    "found_marker = False\n",
    "marker_row = None\n",
    "try:\n",
    "    with gzip.open(matrix_file, 'rt') as file:\n",
    "        for i, line in enumerate(file):\n",
    "            if \"!series_matrix_table_begin\" in line:\n",
    "                found_marker = True\n",
    "                marker_row = i\n",
    "                print(f\"Found the matrix table marker at line {i}\")\n",
    "                break\n",
    "    \n",
    "    if not found_marker:\n",
    "        print(\"Warning: Could not find '!series_matrix_table_begin' marker in the file.\")\n",
    "        is_gene_available = False\n",
    "        \n",
    "    # If marker was found, try to extract gene data\n",
    "    if is_gene_available:\n",
    "        try:\n",
    "            # Try using the library function\n",
    "            gene_data = get_genetic_data(matrix_file)\n",
    "            \n",
    "            if gene_data.shape[0] == 0:\n",
    "                print(\"Warning: Extracted gene data has 0 rows.\")\n",
    "                is_gene_available = False\n",
    "            else:\n",
    "                print(f\"Gene data shape: {gene_data.shape}\")\n",
    "                # Print the first 20 gene/probe identifiers\n",
    "                print(\"First 20 gene/probe identifiers:\")\n",
    "                print(gene_data.index[:20].tolist())\n",
    "        except Exception as e:\n",
    "            print(f\"Error extracting gene data with get_genetic_data(): {e}\")\n",
    "            is_gene_available = False\n",
    "    \n",
    "    # If gene data extraction failed, examine file content to diagnose\n",
    "    if not is_gene_available:\n",
    "        print(\"Examining file content to diagnose the issue:\")\n",
    "        try:\n",
    "            with gzip.open(matrix_file, 'rt') as file:\n",
    "                # Print lines around the marker if found\n",
    "                if marker_row is not None:\n",
    "                    for i, line in enumerate(file):\n",
    "                        if i >= marker_row - 2 and i <= marker_row + 10:\n",
    "                            print(f\"Line {i}: {line.strip()[:100]}...\")\n",
    "                        if i > marker_row + 10:\n",
    "                            break\n",
    "                else:\n",
    "                    # If marker not found, print first 10 lines\n",
    "                    for i, line in enumerate(file):\n",
    "                        if i < 10:\n",
    "                            print(f\"Line {i}: {line.strip()[:100]}...\")\n",
    "                        else:\n",
    "                            break\n",
    "        except Exception as e2:\n",
    "            print(f\"Error examining file: {e2}\")\n",
    "        \n",
    "except Exception as e:\n",
    "    print(f\"Error processing file: {e}\")\n",
    "    is_gene_available = False\n",
    "\n",
    "# Update validation information if gene data extraction failed\n",
    "if not is_gene_available:\n",
    "    print(\"Gene expression data could not be successfully extracted from this dataset.\")\n",
    "    # Update the validation record since gene data isn't available\n",
    "    is_trait_available = False  # We already determined trait data isn't available in step 2\n",
    "    validate_and_save_cohort_info(is_final=False, cohort=cohort, info_path=json_path,\n",
    "                                 is_gene_available=is_gene_available, is_trait_available=is_trait_available)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "85ebb7e3",
   "metadata": {},
   "source": [
    "### Step 4: Gene Identifier Review"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "bf908218",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:31:34.186389Z",
     "iopub.status.busy": "2025-03-25T08:31:34.186289Z",
     "iopub.status.idle": "2025-03-25T08:31:34.187912Z",
     "shell.execute_reply": "2025-03-25T08:31:34.187646Z"
    }
   },
   "outputs": [],
   "source": [
    "# Review gene identifiers\n",
    "# These identifiers appear to be standard human gene symbols\n",
    "# Examples like ABCB1, B2M, ATM are all recognized human gene symbols\n",
    "\n",
    "requires_gene_mapping = False\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "65fea1b9",
   "metadata": {},
   "source": [
    "### Step 5: Data Normalization and Linking"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "2861f96c",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:31:34.188847Z",
     "iopub.status.busy": "2025-03-25T08:31:34.188750Z",
     "iopub.status.idle": "2025-03-25T08:31:34.300193Z",
     "shell.execute_reply": "2025-03-25T08:31:34.299817Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene data shape after normalization: (576, 118)\n",
      "Normalized gene data saved to ../../output/preprocess/COVID-19/gene_data/GSE273225.csv\n",
      "Abnormality detected in the cohort: GSE273225. Preprocessing failed.\n",
      "Processing complete. Gene data saved but no clinical data linking possible due to missing trait information.\n"
     ]
    }
   ],
   "source": [
    "# 1. Normalize gene symbols and prepare for linking\n",
    "try:\n",
    "    # Normalize gene symbols\n",
    "    normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n",
    "    print(f\"Gene data shape after normalization: {normalized_gene_data.shape}\")\n",
    "    \n",
    "    # Create output directory if it doesn't exist\n",
    "    os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
    "    \n",
    "    # Save the normalized gene data\n",
    "    normalized_gene_data.to_csv(out_gene_data_file)\n",
    "    print(f\"Normalized gene data saved to {out_gene_data_file}\")\n",
    "    \n",
    "    # Since we identified in Step 2 that there's no COVID-19 data available in this dataset\n",
    "    # (trait_row is None), we cannot proceed with linking clinical and genetic data\n",
    "    is_trait_available = False if 'trait_row' not in locals() else (trait_row is not None)\n",
    "    \n",
    "    # Validate data quality and save cohort info\n",
    "    validate_and_save_cohort_info(\n",
    "        is_final=True,\n",
    "        cohort=cohort,\n",
    "        info_path=json_path,\n",
    "        is_gene_available=is_gene_available,\n",
    "        is_trait_available=is_trait_available,\n",
    "        is_biased=True,  # Set to True as we don't have trait data for analysis\n",
    "        df=pd.DataFrame(),  # Empty DataFrame since we don't have linked data\n",
    "        note=\"Gene expression data available but no COVID-19 trait data in this lung transplantation dataset.\"\n",
    "    )\n",
    "    \n",
    "    print(\"Processing complete. Gene data saved but no clinical data linking possible due to missing trait information.\")\n",
    "    \n",
    "except Exception as e:\n",
    "    print(f\"Error in data processing: {e}\")\n",
    "    \n",
    "    # Log the error and mark the dataset as unusable\n",
    "    validate_and_save_cohort_info(\n",
    "        is_final=True,\n",
    "        cohort=cohort,\n",
    "        info_path=json_path,\n",
    "        is_gene_available=False,\n",
    "        is_trait_available=False,\n",
    "        is_biased=True,\n",
    "        df=pd.DataFrame(),\n",
    "        note=f\"Error during normalization or processing: {str(e)}\"\n",
    "    )"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.16"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}