File size: 29,784 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
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "ac2d1d5e",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:31:11.226771Z",
     "iopub.status.busy": "2025-03-25T08:31:11.226596Z",
     "iopub.status.idle": "2025-03-25T08:31:11.393247Z",
     "shell.execute_reply": "2025-03-25T08:31:11.392890Z"
    }
   },
   "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 = \"GSE213313\"\n",
    "\n",
    "# Input paths\n",
    "in_trait_dir = \"../../input/GEO/COVID-19\"\n",
    "in_cohort_dir = \"../../input/GEO/COVID-19/GSE213313\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/COVID-19/GSE213313.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/COVID-19/gene_data/GSE213313.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/COVID-19/clinical_data/GSE213313.csv\"\n",
    "json_path = \"../../output/preprocess/COVID-19/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "41d885f6",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "c17b6736",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:31:11.394731Z",
     "iopub.status.busy": "2025-03-25T08:31:11.394586Z",
     "iopub.status.idle": "2025-03-25T08:31:11.548047Z",
     "shell.execute_reply": "2025-03-25T08:31:11.547665Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Background Information:\n",
      "!Series_title\t\"Serial whole blood transcriptomic analysis demonstrates activation of neutrophils, platelets and coagulation in severe and critical COVID-19 – submitted\"\n",
      "!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",
      "!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",
      "!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",
      "!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",
      "!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",
      "Sample Characteristics Dictionary:\n",
      "{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"
     ]
    }
   ],
   "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": "8d9140fd",
   "metadata": {},
   "source": [
    "### Step 2: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "db007bc6",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:31:11.549298Z",
     "iopub.status.busy": "2025-03-25T08:31:11.549183Z",
     "iopub.status.idle": "2025-03-25T08:31:11.553812Z",
     "shell.execute_reply": "2025-03-25T08:31:11.553508Z"
    }
   },
   "outputs": [],
   "source": [
    "import os\n",
    "import pandas as pd\n",
    "import re\n",
    "import json\n",
    "from typing import Callable, Optional, Dict, Any\n",
    "\n",
    "# 1. Gene Expression Data Availability\n",
    "# Based on the background information, this is a microarray analysis of whole blood RNA samples\n",
    "# which indicates gene expression data should be available\n",
    "is_gene_available = True\n",
    "\n",
    "# 2. Variable Availability and Data Type Conversion\n",
    "\n",
    "# 2.1 Data Availability\n",
    "# For trait (COVID-19 severity):\n",
    "# From the sample characteristics dictionary, key 2 contains severity information\n",
    "trait_row = 2\n",
    "\n",
    "# For age:\n",
    "# There is no age information in the sample characteristics dictionary\n",
    "age_row = None\n",
    "\n",
    "# For gender:\n",
    "# There is no gender information in the sample characteristics dictionary\n",
    "gender_row = None\n",
    "\n",
    "# 2.2 Data Type Conversion\n",
    "\n",
    "# Function to convert trait values (severity)\n",
    "def convert_trait(value):\n",
    "    if not isinstance(value, str):\n",
    "        return None\n",
    "    \n",
    "    # Extract the value after colon if present\n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip()\n",
    "    \n",
    "    # Convert severity to binary (0 for Non-critical/Healthy, 1 for Critical)\n",
    "    if 'critical' in value.lower():\n",
    "        return 1\n",
    "    elif 'non-critical' in value.lower() or 'healthy' in value.lower():\n",
    "        return 0\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "# Function to convert age (not available in this dataset)\n",
    "def convert_age(value):\n",
    "    return None\n",
    "\n",
    "# Function to convert gender (not available in this dataset)\n",
    "def convert_gender(value):\n",
    "    return None\n",
    "\n",
    "# 3. Save Metadata\n",
    "# Conduct initial filtering on usability\n",
    "is_trait_available = trait_row is not None\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",
    "if trait_row is not None:\n",
    "    # Load the clinical data first (assuming it's available from previous steps)\n",
    "    if os.path.exists(os.path.join(in_cohort_dir, \"clinical_data.csv\")):\n",
    "        clinical_data = pd.read_csv(os.path.join(in_cohort_dir, \"clinical_data.csv\"))\n",
    "        \n",
    "        # Extract clinical features using the provided function\n",
    "        selected_clinical = geo_select_clinical_features(\n",
    "            clinical_df=clinical_data,\n",
    "            trait=trait,\n",
    "            trait_row=trait_row,\n",
    "            convert_trait=convert_trait,\n",
    "            age_row=age_row,\n",
    "            convert_age=convert_age,\n",
    "            gender_row=gender_row,\n",
    "            convert_gender=convert_gender\n",
    "        )\n",
    "        \n",
    "        # Preview the selected clinical data\n",
    "        preview = preview_df(selected_clinical)\n",
    "        print(\"Preview of selected clinical data:\")\n",
    "        print(preview)\n",
    "        \n",
    "        # Save the selected clinical data to the specified output file\n",
    "        os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
    "        selected_clinical.to_csv(out_clinical_data_file, index=False)\n",
    "        print(f\"Clinical data saved to {out_clinical_data_file}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e3338e91",
   "metadata": {},
   "source": [
    "### Step 3: Gene Data Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "4eec8559",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:31:11.554978Z",
     "iopub.status.busy": "2025-03-25T08:31:11.554865Z",
     "iopub.status.idle": "2025-03-25T08:31:11.828902Z",
     "shell.execute_reply": "2025-03-25T08:31:11.828504Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "SOFT file: ../../input/GEO/COVID-19/GSE213313/GSE213313_family.soft.gz\n",
      "Matrix file: ../../input/GEO/COVID-19/GSE213313/GSE213313_series_matrix.txt.gz\n",
      "Found the matrix table marker at line 66\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene data shape: (25469, 94)\n",
      "First 20 gene/probe identifiers:\n",
      "['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"
     ]
    }
   ],
   "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": "3d14ffdc",
   "metadata": {},
   "source": [
    "### Step 4: Gene Identifier Review"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "ab06f05b",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:31:11.830252Z",
     "iopub.status.busy": "2025-03-25T08:31:11.830128Z",
     "iopub.status.idle": "2025-03-25T08:31:11.832075Z",
     "shell.execute_reply": "2025-03-25T08:31:11.831770Z"
    }
   },
   "outputs": [],
   "source": [
    "# These identifiers (A_19_P...) are Agilent microarray probe IDs, not human gene symbols\n",
    "# They need to be mapped to official gene symbols for downstream analysis\n",
    "requires_gene_mapping = True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3de4cadf",
   "metadata": {},
   "source": [
    "### Step 5: Gene Annotation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "ed052b4b",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:31:11.833236Z",
     "iopub.status.busy": "2025-03-25T08:31:11.833119Z",
     "iopub.status.idle": "2025-03-25T08:31:15.716377Z",
     "shell.execute_reply": "2025-03-25T08:31:15.716022Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "Gene annotation preview:\n",
      "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",
      "{'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",
      "\n",
      "Examining gene mapping columns:\n",
      "Column 'ID' examples:\n",
      "Example 1: GE_BrightCorner\n",
      "Example 2: DarkCorner\n",
      "Example 3: A_21_P0014386\n",
      "Example 4: A_33_P3396872\n",
      "Example 5: A_33_P3267760\n",
      "\n",
      "Column 'GENE_SYMBOL' examples:\n",
      "Example 1: nan\n",
      "Example 2: nan\n",
      "Example 3: nan\n",
      "Example 4: CPED1\n",
      "Example 5: BCOR\n",
      "\n",
      "Gene symbol column completeness: 48862/2452521 rows (1.99%)\n",
      "\n",
      "Columns identified for gene mapping:\n",
      "- 'ID': Contains probe IDs\n",
      "- 'GENE_SYMBOL': Contains gene symbols for mapping\n"
     ]
    }
   ],
   "source": [
    "# 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.\n",
    "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
    "gene_annotation = get_gene_annotation(soft_file)\n",
    "\n",
    "# 2. Analyze the gene annotation dataframe to identify which columns contain the gene identifiers and gene symbols\n",
    "print(\"\\nGene annotation preview:\")\n",
    "print(f\"Columns in gene annotation: {gene_annotation.columns.tolist()}\")\n",
    "print(preview_df(gene_annotation, n=3))\n",
    "\n",
    "# Examine the GENE_SYMBOL column which contains gene symbol information\n",
    "print(\"\\nExamining gene mapping columns:\")\n",
    "print(\"Column 'ID' examples:\")\n",
    "id_samples = gene_annotation['ID'].head(5).tolist()\n",
    "for i, sample in enumerate(id_samples):\n",
    "    print(f\"Example {i+1}: {sample}\")\n",
    "\n",
    "print(\"\\nColumn 'GENE_SYMBOL' examples:\")\n",
    "if 'GENE_SYMBOL' in gene_annotation.columns:\n",
    "    # Display a few examples of the GENE_SYMBOL column\n",
    "    symbol_samples = gene_annotation['GENE_SYMBOL'].head(5).tolist()\n",
    "    for i, sample in enumerate(symbol_samples):\n",
    "        print(f\"Example {i+1}: {sample}\")\n",
    "    \n",
    "    # Check the quality and completeness of the GENE_SYMBOL column\n",
    "    non_null_symbols = gene_annotation['GENE_SYMBOL'].notna().sum()\n",
    "    total_rows = len(gene_annotation)\n",
    "    print(f\"\\nGene symbol column completeness: {non_null_symbols}/{total_rows} rows ({non_null_symbols/total_rows:.2%})\")\n",
    "    \n",
    "    # Identify the columns needed for gene mapping\n",
    "    print(\"\\nColumns identified for gene mapping:\")\n",
    "    print(\"- 'ID': Contains probe IDs\")\n",
    "    print(\"- 'GENE_SYMBOL': Contains gene symbols for mapping\")\n",
    "else:\n",
    "    print(\"Error: 'GENE_SYMBOL' column not found in annotation data.\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "af076b8f",
   "metadata": {},
   "source": [
    "### Step 6: Gene Identifier Mapping"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "62dbfb65",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:31:15.717762Z",
     "iopub.status.busy": "2025-03-25T08:31:15.717628Z",
     "iopub.status.idle": "2025-03-25T08:31:16.864550Z",
     "shell.execute_reply": "2025-03-25T08:31:16.864104Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene mapping shape: (48862, 2)\n",
      "Gene mapping preview:\n",
      "{'ID': ['A_33_P3396872', 'A_33_P3267760', 'A_32_P194264', 'A_23_P153745', 'A_21_P0014180'], 'Gene': ['CPED1', 'BCOR', 'CHAC2', 'IFI30', 'GPR146']}\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene expression data shape after mapping: (17305, 94)\n",
      "First few gene symbols after mapping:\n",
      "['A1BG', 'A1BG-AS1', 'A2M-AS1', 'A4GALT', 'AAAS', 'AAAS-1', 'AACS', 'AADACL3', 'AADACP1', 'AAED1']\n",
      "Gene expression data shape after normalization: (14593, 94)\n",
      "First few normalized gene symbols:\n",
      "['A1BG', 'A1BG-AS1', 'A2M-AS1', 'A4GALT', 'AAAS', 'AACS', 'AADACL3', 'AADACP1', 'AAGAB', 'AAK1']\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene expression data saved to ../../output/preprocess/COVID-19/gene_data/GSE213313.csv\n"
     ]
    }
   ],
   "source": [
    "# 1. Identify which columns to use for mapping\n",
    "# From the gene expression data output, we have IDs like A_19_P00315452\n",
    "# From the gene annotation data, we see the 'ID' column contains similar identifiers\n",
    "# and 'GENE_SYMBOL' contains the human gene symbols we need to map to\n",
    "\n",
    "# 2. Get gene mapping dataframe by extracting the required columns\n",
    "prob_col = 'ID'\n",
    "gene_col = 'GENE_SYMBOL'\n",
    "\n",
    "# Extract the mapping between probe IDs and gene symbols\n",
    "gene_mapping = get_gene_mapping(gene_annotation, prob_col, gene_col)\n",
    "print(f\"Gene mapping shape: {gene_mapping.shape}\")\n",
    "print(\"Gene mapping preview:\")\n",
    "print(preview_df(gene_mapping, n=5))\n",
    "\n",
    "# 3. Convert probe-level measurements to gene expression values\n",
    "# Apply the gene mapping to convert from probe IDs to gene symbols\n",
    "gene_data = apply_gene_mapping(gene_data, gene_mapping)\n",
    "print(f\"Gene expression data shape after mapping: {gene_data.shape}\")\n",
    "print(\"First few gene symbols after mapping:\")\n",
    "print(list(gene_data.index[:10]))\n",
    "\n",
    "# Normalize gene symbols to handle synonyms\n",
    "gene_data = normalize_gene_symbols_in_index(gene_data)\n",
    "print(f\"Gene expression data shape after normalization: {gene_data.shape}\")\n",
    "print(\"First few normalized gene symbols:\")\n",
    "print(list(gene_data.index[:10]))\n",
    "\n",
    "# Save gene data to the specified output file\n",
    "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
    "gene_data.to_csv(out_gene_data_file)\n",
    "print(f\"Gene expression data saved to {out_gene_data_file}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "49061ebc",
   "metadata": {},
   "source": [
    "### Step 7: Data Normalization and Linking"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "89299b2c",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:31:16.865937Z",
     "iopub.status.busy": "2025-03-25T08:31:16.865802Z",
     "iopub.status.idle": "2025-03-25T08:31:25.439581Z",
     "shell.execute_reply": "2025-03-25T08:31:25.438944Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene data shape after normalization: (14593, 94)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Normalized gene data saved to ../../output/preprocess/COVID-19/gene_data/GSE213313.csv\n",
      "Clinical features saved to ../../output/preprocess/COVID-19/clinical_data/GSE213313.csv\n",
      "Clinical features preview:\n",
      "{'COVID-19': [1.0, 1.0, 1.0, 1.0, 1.0]}\n",
      "Linked data shape: (94, 14594)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Linked data shape after handling missing values: (94, 14594)\n",
      "For the feature 'COVID-19', the least common label is '0.0' with 11 occurrences. This represents 11.70% of the dataset.\n",
      "The distribution of the feature 'COVID-19' in this dataset is fine.\n",
      "\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Linked data saved to ../../output/preprocess/COVID-19/GSE213313.csv\n"
     ]
    }
   ],
   "source": [
    "# 1. Normalize gene symbols in the gene expression data\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",
    "# 2. Extract clinical features using the previously identified feature rows\n",
    "# Use the clinical data from Step 1 and the row identifiers from Step 2\n",
    "clinical_features = geo_select_clinical_features(\n",
    "    clinical_data,\n",
    "    trait=trait,\n",
    "    trait_row=trait_row,\n",
    "    convert_trait=convert_trait,\n",
    "    age_row=age_row,\n",
    "    convert_age=convert_age,\n",
    "    gender_row=gender_row,\n",
    "    convert_gender=convert_gender\n",
    ")\n",
    "\n",
    "# Create directory for clinical data output\n",
    "os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
    "\n",
    "# Save the clinical features\n",
    "clinical_features.to_csv(out_clinical_data_file)\n",
    "print(f\"Clinical features saved to {out_clinical_data_file}\")\n",
    "\n",
    "# Preview the clinical features\n",
    "clinical_features_preview = preview_df(clinical_features.T)\n",
    "print(\"Clinical features preview:\")\n",
    "print(clinical_features_preview)\n",
    "\n",
    "# 3. Link clinical and genetic data\n",
    "linked_data = geo_link_clinical_genetic_data(clinical_features, normalized_gene_data)\n",
    "print(f\"Linked data shape: {linked_data.shape}\")\n",
    "\n",
    "# 4. Handle missing values in the linked data\n",
    "linked_data = handle_missing_values(linked_data, trait)\n",
    "print(f\"Linked data shape after handling missing values: {linked_data.shape}\")\n",
    "\n",
    "# 5. Determine if trait and demographic features are biased\n",
    "is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n",
    "\n",
    "# 6. Validate and save cohort info\n",
    "is_usable = 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=True,  # We have trait data as identified in Step 2\n",
    "    is_biased=is_biased,\n",
    "    df=linked_data,\n",
    "    note=\"Dataset contains gene expression data for COVID-19 severity analysis.\"\n",
    ")\n",
    "\n",
    "# 7. Save the linked data if it's usable\n",
    "if is_usable:\n",
    "    # Create output directory if it doesn't exist\n",
    "    os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n",
    "    \n",
    "    # Save the linked data\n",
    "    linked_data.to_csv(out_data_file)\n",
    "    print(f\"Linked data saved to {out_data_file}\")\n",
    "else:\n",
    "    print(\"Linked data not saved due to quality issues.\")"
   ]
  }
 ],
 "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
}