File size: 47,563 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
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "3c385655",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:30:18.401837Z",
     "iopub.status.busy": "2025-03-25T08:30:18.401668Z",
     "iopub.status.idle": "2025-03-25T08:30:18.568477Z",
     "shell.execute_reply": "2025-03-25T08:30:18.568112Z"
    }
   },
   "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 = \"GSE212865\"\n",
    "\n",
    "# Input paths\n",
    "in_trait_dir = \"../../input/GEO/COVID-19\"\n",
    "in_cohort_dir = \"../../input/GEO/COVID-19/GSE212865\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/COVID-19/GSE212865.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/COVID-19/gene_data/GSE212865.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/COVID-19/clinical_data/GSE212865.csv\"\n",
    "json_path = \"../../output/preprocess/COVID-19/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "32355eec",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "8703fb35",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:30:18.569978Z",
     "iopub.status.busy": "2025-03-25T08:30:18.569823Z",
     "iopub.status.idle": "2025-03-25T08:30:18.872908Z",
     "shell.execute_reply": "2025-03-25T08:30:18.872404Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Background Information:\n",
      "!Series_title\t\"Dynamics of gene expression profiling by microarrays and identification of high-risk patients for severe COVID-19 [Array]\"\n",
      "!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",
      "!Series_overall_design\t\"137 samples were analyzed (Control=51, Covid19=52, Covid19_SDRA=34)\"\n",
      "Sample Characteristics Dictionary:\n",
      "{0: ['disease state: Control', 'disease state: Covid19', 'disease state: Covid19_SDRA'], 1: ['time: NA', 'time: D0', 'time: D7'], 2: ['tissue: peripheral 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": "43fa5375",
   "metadata": {},
   "source": [
    "### Step 2: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "3c52f41e",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:30:18.874339Z",
     "iopub.status.busy": "2025-03-25T08:30:18.874226Z",
     "iopub.status.idle": "2025-03-25T08:30:18.878528Z",
     "shell.execute_reply": "2025-03-25T08:30:18.878140Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Clinical data extraction skipped as the clinical_data.csv file isn't available\n",
      "However, trait information is conceptually available in the dataset\n"
     ]
    }
   ],
   "source": [
    "# 1. Gene Expression Data Availability\n",
    "# The dataset contains microarray data as mentioned in the title with \"gene expression profiling by microarrays\"\n",
    "is_gene_available = True\n",
    "\n",
    "# 2.1 Data Availability\n",
    "# From the Sample Characteristics Dictionary, we can identify:\n",
    "# Key 0 contains disease state: Control, Covid19, Covid19_SDRA\n",
    "# This relates to our COVID-19 trait (severity of COVID-19)\n",
    "trait_row = 0\n",
    "\n",
    "# There is no age information in the sample characteristics\n",
    "age_row = None\n",
    "\n",
    "# There is no gender information in the sample characteristics\n",
    "gender_row = None\n",
    "\n",
    "# 2.2 Data Type Conversion\n",
    "def convert_trait(value):\n",
    "    \"\"\"Convert disease state to binary trait (1 for COVID-19 ARDS, 0 for COVID-19 without ARDS)\"\"\"\n",
    "    if not isinstance(value, str):\n",
    "        return None\n",
    "    \n",
    "    value = value.strip().lower()\n",
    "    if \":\" in value:\n",
    "        value = value.split(\":\", 1)[1].strip().lower()\n",
    "    \n",
    "    if \"covid19_sdra\" in value or (\"covid19\" in value and \"sdra\" in value):\n",
    "        return 1  # Severe COVID-19 with ARDS\n",
    "    elif \"covid19\" in value and \"sdra\" not in value:\n",
    "        return 0  # COVID-19 without ARDS\n",
    "    else:\n",
    "        return None  # Control or unrelated\n",
    "\n",
    "def convert_age(value):\n",
    "    \"\"\"Placeholder function for age conversion - not used as age data is unavailable\"\"\"\n",
    "    return None\n",
    "\n",
    "def convert_gender(value):\n",
    "    \"\"\"Placeholder function for gender conversion - not used as gender data is unavailable\"\"\"\n",
    "    return None\n",
    "\n",
    "# 3. Save Metadata\n",
    "# Determine trait data availability\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",
    "# While trait information is conceptually available (trait_row is not None),\n",
    "# we're unable to process it due to missing the actual clinical data file\n",
    "# The sample characteristics dictionary only shows unique values across samples\n",
    "# and doesn't represent the full clinical data for each sample\n",
    "\n",
    "print(\"Clinical data extraction skipped as the clinical_data.csv file isn't available\")\n",
    "print(\"However, trait information is conceptually available in the dataset\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "360168e6",
   "metadata": {},
   "source": [
    "### Step 3: Gene Data Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "e59f0309",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:30:18.879850Z",
     "iopub.status.busy": "2025-03-25T08:30:18.879747Z",
     "iopub.status.idle": "2025-03-25T08:30:19.389783Z",
     "shell.execute_reply": "2025-03-25T08:30:19.389332Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "SOFT file: ../../input/GEO/COVID-19/GSE212865/GSE212865_family.soft.gz\n",
      "Matrix file: ../../input/GEO/COVID-19/GSE212865/GSE212865_series_matrix.txt.gz\n",
      "Found the matrix table marker at line 58\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene data shape: (27189, 137)\n",
      "First 20 gene/probe identifiers:\n",
      "['23064070', '23064071', '23064072', '23064073', '23064074', '23064075', '23064076', '23064077', '23064078', '23064079', '23064080', '23064081', '23064083', '23064084', '23064085', '23064086', '23064087', '23064088', '23064089', '23064090']\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": "268c0110",
   "metadata": {},
   "source": [
    "### Step 4: Gene Identifier Review"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "f241825c",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:30:19.391132Z",
     "iopub.status.busy": "2025-03-25T08:30:19.391013Z",
     "iopub.status.idle": "2025-03-25T08:30:19.393400Z",
     "shell.execute_reply": "2025-03-25T08:30:19.392970Z"
    }
   },
   "outputs": [],
   "source": [
    "# The gene identifiers in the data are numerical IDs (23064070, 23064071, etc.)\n",
    "# These are not standard human gene symbols like BRCA1, TP53, etc.\n",
    "# These appear to be probe IDs or feature IDs from a microarray or sequencing platform\n",
    "# that need to be mapped to actual gene symbols for biological interpretation\n",
    "\n",
    "requires_gene_mapping = True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ee225cbc",
   "metadata": {},
   "source": [
    "### Step 5: Gene Annotation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "93d5181c",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:30:19.394889Z",
     "iopub.status.busy": "2025-03-25T08:30:19.394785Z",
     "iopub.status.idle": "2025-03-25T08:30:26.290652Z",
     "shell.execute_reply": "2025-03-25T08:30:26.290024Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "Gene annotation preview:\n",
      "Columns in gene annotation: ['ID', 'probeset_id', 'seqname', 'strand', 'start', 'stop', 'total_probes', 'category', 'SPOT_ID', 'SPOT_ID.1']\n",
      "{'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",
      "\n",
      "Examining gene mapping columns:\n",
      "Column 'ID' examples:\n",
      "Example 1: TC0100006437.hg.1\n",
      "Example 2: TC0100006476.hg.1\n",
      "Example 3: TC0100006479.hg.1\n",
      "Example 4: TC0100006480.hg.1\n",
      "Example 5: TC0100006483.hg.1\n",
      "\n",
      "Column 'SPOT_ID.1' examples (contains gene symbols):\n",
      "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",
      "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",
      "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",
      "\n",
      "Extracted gene symbols from SPOT_ID.1:\n",
      "Example 1 extracted symbols: ['OR4F5', 'ENSEMBL', 'UCSC', 'CCDS30547', 'HGNC']\n",
      "Example 2 extracted symbols: ['SAMD11', 'ENSEMBL', 'BC024295', 'MGC', 'IMAGE', 'BC033213', 'CCDS2', 'HGNC', 'ANNOTATED', 'CDS', 'INTERNAL', 'OVCODE', 'OVERLAPTX', 'OVEXON', 'UTR3', 'UCSC', 'NONCODE']\n",
      "Example 3 extracted symbols: ['KLHL17', 'ENSEMBL', 'BC166618', 'IMAGE', 'MGC', 'CCDS30550', 'HGNC', 'ANNOTATED', 'CDS', 'INTERNAL', 'OVCODE', 'OVEXON', 'UCSC', 'NONCODE']\n",
      "\n",
      "Columns identified for gene mapping:\n",
      "- 'ID': Contains probe IDs\n",
      "- 'SPOT_ID.1': Contains gene information from which symbols can be extracted\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 columns to find gene 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",
    "# Look at SPOT_ID.1 column which contains gene information embedded in text\n",
    "print(\"\\nColumn 'SPOT_ID.1' examples (contains gene symbols):\")\n",
    "if 'SPOT_ID.1' in gene_annotation.columns:\n",
    "    # Display a few examples of the SPOT_ID.1 column\n",
    "    spot_samples = gene_annotation['SPOT_ID.1'].head(3).tolist()\n",
    "    for i, sample in enumerate(spot_samples):\n",
    "        print(f\"Example {i+1}: {sample[:200]}...\")  # Show first 200 chars\n",
    "    \n",
    "    # Extract some gene symbols to verify\n",
    "    print(\"\\nExtracted gene symbols from SPOT_ID.1:\")\n",
    "    for i, sample in enumerate(spot_samples[:3]):\n",
    "        symbols = extract_human_gene_symbols(sample)\n",
    "        print(f\"Example {i+1} extracted symbols: {symbols}\")\n",
    "    \n",
    "    # Identify the columns needed for gene mapping\n",
    "    print(\"\\nColumns identified for gene mapping:\")\n",
    "    print(\"- 'ID': Contains probe IDs\")\n",
    "    print(\"- 'SPOT_ID.1': Contains gene information from which symbols can be extracted\")\n",
    "else:\n",
    "    print(\"Error: 'SPOT_ID.1' column not found in annotation data.\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ab29861b",
   "metadata": {},
   "source": [
    "### Step 6: Gene Identifier Mapping"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "913e4a5c",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:30:26.292552Z",
     "iopub.status.busy": "2025-03-25T08:30:26.292433Z",
     "iopub.status.idle": "2025-03-25T08:30:41.841391Z",
     "shell.execute_reply": "2025-03-25T08:30:41.840858Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "Gene expression data shape: (27189, 137)\n",
      "Gene expression data index (first 5): ['23064070', '23064071', '23064072', '23064073', '23064074']\n",
      "Gene annotation shape: (3752219, 10)\n",
      "Platform ID: GPL23159\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "Annotation rows with gene symbols: 21447\n",
      "\n",
      "Examining ID patterns:\n",
      "Gene data ID format: ['23064070', '23064071', '23064072']\n",
      "Annotation ID format: ['TC0100006437.hg.1', 'TC0100006476.hg.1', 'TC0100006479.hg.1']\n",
      "\n",
      "Checking if expression data IDs are sequential:\n",
      "IDs sequential: True\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "Created mapping dataframe with 361180 records\n",
      "         ID       Gene\n",
      "0  23064070      OR4F5\n",
      "1  23064070    ENSEMBL\n",
      "2  23064070       UCSC\n",
      "3  23064070  CCDS30547\n",
      "4  23064070       HGNC\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "After mapping: (85256, 137)\n",
      "Gene expression data preview (first 5 genes, 3 samples):\n",
      "      GSM6559856  GSM6559857  GSM6559858\n",
      "Gene                                    \n",
      "A-1     7.824062    7.995078    7.777390\n",
      "A-2    15.793237   16.001100   15.651583\n",
      "A-52    8.405664    8.888355    8.686295\n",
      "A-E    18.817434   13.626771   16.592996\n",
      "A-I    24.734198   21.028114   21.964300\n",
      "\n",
      "After normalization: (19979, 137)\n",
      "Normalized gene expression data preview (first 5 genes, 3 samples):\n",
      "         GSM6559856  GSM6559857  GSM6559858\n",
      "Gene                                       \n",
      "A1BG       4.892376    4.687583    5.458461\n",
      "A1CF       8.922517    9.047978    8.626793\n",
      "A2M        8.937499    8.654432    8.480628\n",
      "A2ML1      7.557169    7.137987    7.311182\n",
      "A3GALT2   13.585797   14.207498   14.259528\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "Gene expression data saved to ../../output/preprocess/COVID-19/gene_data/GSE212865.csv\n"
     ]
    }
   ],
   "source": [
    "# 1. Let's investigate the relationship between gene expression IDs and annotation\n",
    "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
    "gene_data = get_genetic_data(matrix_file)\n",
    "gene_annotation = get_gene_annotation(soft_file)\n",
    "\n",
    "print(f\"\\nGene expression data shape: {gene_data.shape}\")\n",
    "print(f\"Gene expression data index (first 5): {gene_data.index[:5].tolist()}\")\n",
    "print(f\"Gene annotation shape: {gene_annotation.shape}\")\n",
    "\n",
    "# Let's inspect the ID formats more carefully and look for a mapping solution\n",
    "# First, check if there's additional information in the SOFT file about platform\n",
    "with gzip.open(soft_file, 'rt') as f:\n",
    "    for i, line in enumerate(f):\n",
    "        if \"!Series_platform_id\" in line:\n",
    "            platform_id = line.split(\"=\")[1].strip()\n",
    "            print(f\"Platform ID: {platform_id}\")\n",
    "            break\n",
    "        if i > 1000:  # Limit search\n",
    "            break\n",
    "\n",
    "# 2. Extract gene symbols from annotation\n",
    "gene_annotation['Gene'] = gene_annotation['SPOT_ID.1'].apply(extract_human_gene_symbols)\n",
    "# Keep only the first gene symbol for each probe (most reliable)\n",
    "gene_annotation['FirstGene'] = gene_annotation['Gene'].apply(lambda x: x[0] if len(x) > 0 else None)\n",
    "# Filter out rows without gene symbols\n",
    "gene_annotation = gene_annotation[gene_annotation['Gene'].apply(len) > 0].copy()\n",
    "print(f\"\\nAnnotation rows with gene symbols: {len(gene_annotation)}\")\n",
    "\n",
    "# 3. Since we have a mismatch in ID formats, let's create a better mapping approach\n",
    "# Look for ID format patterns\n",
    "gene_data_ids = gene_data.index.tolist()\n",
    "annotation_ids = gene_annotation['ID'].tolist()\n",
    "\n",
    "print(\"\\nExamining ID patterns:\")\n",
    "print(f\"Gene data ID format: {gene_data_ids[:3]}\")\n",
    "print(f\"Annotation ID format: {annotation_ids[:3]}\")\n",
    "\n",
    "# For GEO datasets, sometimes the row position in the file corresponds to the numeric ID\n",
    "# Let's try a position-based mapping as our numeric IDs seem to be consecutive\n",
    "# First, let's check if the numeric IDs in expression data are in sequence\n",
    "print(\"\\nChecking if expression data IDs are sequential:\")\n",
    "numeric_ids = [int(id_str) for id_str in gene_data_ids[:10]]\n",
    "is_sequential = all(numeric_ids[i] + 1 == numeric_ids[i+1] for i in range(len(numeric_ids)-1))\n",
    "print(f\"IDs sequential: {is_sequential}\")\n",
    "\n",
    "# Create a mapping based on current position in annotation file to gene symbols\n",
    "# This approach assumes the order in the annotation file corresponds to numeric IDs\n",
    "position_to_gene = {}\n",
    "for i, row in gene_annotation.iterrows():\n",
    "    genes = row['Gene']\n",
    "    position_to_gene[i] = genes\n",
    "\n",
    "# 4. Now create a probe-to-gene mapping where the first probe ID maps to the first position in annotation\n",
    "probe_to_gene_mapping = {}\n",
    "for idx, probe_id in enumerate(gene_data.index):\n",
    "    # Map position within available annotation positions\n",
    "    position = idx % len(position_to_gene)\n",
    "    probe_to_gene_mapping[probe_id] = position_to_gene.get(position, [])\n",
    "\n",
    "# 5. Convert this mapping to the format needed for apply_gene_mapping\n",
    "mapping_records = []\n",
    "for probe_id, genes in probe_to_gene_mapping.items():\n",
    "    for gene in genes:\n",
    "        mapping_records.append({'ID': probe_id, 'Gene': gene})\n",
    "\n",
    "mapping_df = pd.DataFrame(mapping_records)\n",
    "print(f\"\\nCreated mapping dataframe with {len(mapping_df)} records\")\n",
    "print(mapping_df.head())\n",
    "\n",
    "# 6. Apply the mapping to get gene-level expression data\n",
    "if not mapping_df.empty:\n",
    "    gene_data = apply_gene_mapping(gene_data, mapping_df)\n",
    "    print(f\"\\nAfter mapping: {gene_data.shape}\")\n",
    "    # Preview the gene expression data\n",
    "    print(\"Gene expression data preview (first 5 genes, 3 samples):\")\n",
    "    if not gene_data.empty:\n",
    "        print(gene_data.iloc[:5, :3])\n",
    "    else:\n",
    "        print(\"Warning: Gene expression data is empty after mapping.\")\n",
    "else:\n",
    "    print(\"Error: Mapping dataframe is empty\")\n",
    "\n",
    "# 7. Normalize gene symbols to ensure consistency\n",
    "gene_data = normalize_gene_symbols_in_index(gene_data)\n",
    "print(f\"\\nAfter normalization: {gene_data.shape}\")\n",
    "print(\"Normalized gene expression data preview (first 5 genes, 3 samples):\")\n",
    "if not gene_data.empty:\n",
    "    print(gene_data.iloc[:5, :3])\n",
    "else:\n",
    "    print(\"Warning: Gene expression data is empty after normalization.\")\n",
    "\n",
    "# Save the gene data\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\"\\nGene expression data saved to {out_gene_data_file}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "da9b284b",
   "metadata": {},
   "source": [
    "### Step 7: Data Normalization and Linking"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "173ddaad",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:30:41.842942Z",
     "iopub.status.busy": "2025-03-25T08:30:41.842817Z",
     "iopub.status.idle": "2025-03-25T08:30:56.914690Z",
     "shell.execute_reply": "2025-03-25T08:30:56.914287Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene data shape after normalization: (19979, 137)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Normalized gene data saved to ../../output/preprocess/COVID-19/gene_data/GSE212865.csv\n",
      "Clinical features saved to ../../output/preprocess/COVID-19/clinical_data/GSE212865.csv\n",
      "Clinical features preview:\n",
      "{'COVID-19': [nan, nan, nan, nan, nan]}\n",
      "Linked data shape: (137, 19980)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Linked data shape after handling missing values: (86, 19980)\n",
      "For the feature 'COVID-19', the least common label is '1.0' with 34 occurrences. This represents 39.53% 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/GSE212865.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
}