File size: 34,853 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
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "90b91c33",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:30:08.205938Z",
     "iopub.status.busy": "2025-03-25T08:30:08.205452Z",
     "iopub.status.idle": "2025-03-25T08:30:08.371351Z",
     "shell.execute_reply": "2025-03-25T08:30:08.371023Z"
    }
   },
   "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 = \"GSE185658\"\n",
    "\n",
    "# Input paths\n",
    "in_trait_dir = \"../../input/GEO/COVID-19\"\n",
    "in_cohort_dir = \"../../input/GEO/COVID-19/GSE185658\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/COVID-19/GSE185658.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/COVID-19/gene_data/GSE185658.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/COVID-19/clinical_data/GSE185658.csv\"\n",
    "json_path = \"../../output/preprocess/COVID-19/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "362d1a18",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "ebb746c0",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:30:08.372719Z",
     "iopub.status.busy": "2025-03-25T08:30:08.372580Z",
     "iopub.status.idle": "2025-03-25T08:30:08.483771Z",
     "shell.execute_reply": "2025-03-25T08:30:08.483483Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Background Information:\n",
      "!Series_title\t\"Rhinovirus-induced epithelial RIG-I inflammasome suppresses antiviral immunity and promotes inflammation in asthma and COVID-19\"\n",
      "!Series_summary\t\"Balanced immune responses in airways of patients with asthma are crucial to succesful clearance of viral infection and proper asthma control.\"\n",
      "!Series_summary\t\"We used microarrays to detail the global programme of gene expression data from bronchial brushings from control individuals and patients with asthma after rhinovirus infection in vivo.\"\n",
      "!Series_overall_design\t\"Bronchial brushings from control individuals and patients with asthma around two weeks before (day -14) and four days after (day 4) experimental in vivo rhinovirus infection were used for RNA isolation and hybrydyzation with Affymetric microarrays.\"\n",
      "Sample Characteristics Dictionary:\n",
      "{0: ['time: DAY14', 'time: DAY4'], 1: ['group: AsthmaHDM', 'group: AsthmaHDMNeg', 'group: Healthy'], 2: ['donor: DJ144', 'donor: DJ113', 'donor: DJ139', 'donor: DJ129', 'donor: DJ134', 'donor: DJ114', 'donor: DJ81', 'donor: DJ60', 'donor: DJ73', 'donor: DJ136', 'donor: DJ92', 'donor: DJ47', 'donor: DJ125', 'donor: DJ148', 'donor: DJ121', 'donor: DJ116', 'donor: DJ86', 'donor: DJ126', 'donor: DJ48', 'donor: DJ67', 'donor: DJ56', 'donor: DJ61', 'donor: DJ75', 'donor: DJ101']}\n"
     ]
    }
   ],
   "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": "4128a79e",
   "metadata": {},
   "source": [
    "### Step 2: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "753acb1a",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:30:08.484915Z",
     "iopub.status.busy": "2025-03-25T08:30:08.484810Z",
     "iopub.status.idle": "2025-03-25T08:30:08.489842Z",
     "shell.execute_reply": "2025-03-25T08:30:08.489574Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "A new JSON file was created at: ../../output/preprocess/COVID-19/cohort_info.json\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "False"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 1. Gene Expression Data Availability\n",
    "# Based on the background information, this is microarray data from bronchial brushings\n",
    "# which indicates gene expression data is available\n",
    "is_gene_available = True\n",
    "\n",
    "# 2. Variable Availability and Data Type Conversion\n",
    "# 2.1 Data Availability\n",
    "# After reviewing the data, it's clear this dataset is about asthma and rhinovirus, not COVID-19\n",
    "# Therefore, the COVID-19 trait we're interested in is not available in this dataset\n",
    "trait_row = None  # COVID-19 trait information is not available\n",
    "age_row = None  # Age information is not available\n",
    "gender_row = None  # Gender information is not available\n",
    "\n",
    "# 2.2 Data Type Conversion\n",
    "def convert_trait(value):\n",
    "    \"\"\"Convert trait information to binary values for COVID-19\"\"\"\n",
    "    # Since the trait is not available, this function won't be used\n",
    "    return None\n",
    "\n",
    "def convert_age(value):\n",
    "    \"\"\"Convert age information to continuous values\"\"\"\n",
    "    # Not applicable as age data is not available\n",
    "    return None\n",
    "\n",
    "def convert_gender(value):\n",
    "    \"\"\"Convert gender information to binary values\"\"\"\n",
    "    # Not applicable as gender data is not available\n",
    "    return None\n",
    "\n",
    "# 3. Save Metadata\n",
    "# Determine trait data availability\n",
    "is_trait_available = trait_row is not None\n",
    "\n",
    "# Conduct initial filtering and save metadata\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 since trait_row is None (COVID-19 trait data is not available)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d74c5573",
   "metadata": {},
   "source": [
    "### Step 3: Gene Data Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "df48e103",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:30:08.490923Z",
     "iopub.status.busy": "2025-03-25T08:30:08.490823Z",
     "iopub.status.idle": "2025-03-25T08:30:08.660942Z",
     "shell.execute_reply": "2025-03-25T08:30:08.660574Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "SOFT file: ../../input/GEO/COVID-19/GSE185658/GSE185658_family.soft.gz\n",
      "Matrix file: ../../input/GEO/COVID-19/GSE185658/GSE185658_series_matrix.txt.gz\n",
      "Found the matrix table marker at line 63\n",
      "Gene data shape: (32321, 48)\n",
      "First 20 gene/probe identifiers:\n",
      "['7892501', '7892502', '7892503', '7892504', '7892505', '7892506', '7892507', '7892508', '7892509', '7892510', '7892511', '7892512', '7892513', '7892514', '7892515', '7892516', '7892517', '7892518', '7892519', '7892520']\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": "1a30a9dc",
   "metadata": {},
   "source": [
    "### Step 4: Gene Identifier Review"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "bbd75804",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:30:08.662213Z",
     "iopub.status.busy": "2025-03-25T08:30:08.662097Z",
     "iopub.status.idle": "2025-03-25T08:30:08.663939Z",
     "shell.execute_reply": "2025-03-25T08:30:08.663668Z"
    }
   },
   "outputs": [],
   "source": [
    "# These don't appear to be human gene symbols but rather probe identifiers from a microarray platform\n",
    "# They are numeric identifiers that likely need to be mapped to gene symbols\n",
    "# Based on my biomedical knowledge, human gene symbols are typically alphanumeric (like BRCA1, TP53, etc.)\n",
    "# These look like Illumina BeadChip probe IDs which require mapping to standard gene symbols\n",
    "\n",
    "requires_gene_mapping = True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9f5d354a",
   "metadata": {},
   "source": [
    "### Step 5: Gene Annotation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "20684cd7",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:30:08.665140Z",
     "iopub.status.busy": "2025-03-25T08:30:08.664954Z",
     "iopub.status.idle": "2025-03-25T08:30:11.838183Z",
     "shell.execute_reply": "2025-03-25T08:30:11.837861Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "Gene annotation preview:\n",
      "Columns in gene annotation: ['ID', 'GB_LIST', 'SPOT_ID', 'seqname', 'RANGE_GB', 'RANGE_STRAND', 'RANGE_START', 'RANGE_STOP', 'total_probes', 'gene_assignment', 'mrna_assignment', 'category']\n",
      "{'ID': ['7896736', '7896738', '7896740'], 'GB_LIST': [nan, nan, 'NM_001004195,NM_001005240,NM_001005484,BC136848,BC136867,BC136907,BC136908'], 'SPOT_ID': ['chr1:53049-54936', 'chr1:63015-63887', 'chr1:69091-70008'], 'seqname': ['chr1', 'chr1', 'chr1'], 'RANGE_GB': ['NC_000001.10', 'NC_000001.10', 'NC_000001.10'], 'RANGE_STRAND': ['+', '+', '+'], 'RANGE_START': ['53049', '63015', '69091'], 'RANGE_STOP': ['54936', '63887', '70008'], 'total_probes': [7.0, 31.0, 24.0], 'gene_assignment': ['---', 'ENST00000328113 // OR4G2P // olfactory receptor, family 4, subfamily G, member 2 pseudogene // --- // --- /// ENST00000492842 // OR4G11P // olfactory receptor, family 4, subfamily G, member 11 pseudogene // --- // --- /// ENST00000588632 // OR4G1P // olfactory receptor, family 4, subfamily G, member 1 pseudogene // --- // ---', 'NM_001004195 // OR4F4 // olfactory receptor, family 4, subfamily F, member 4 // 15q26.3 // 26682 /// NM_001005240 // OR4F17 // olfactory receptor, family 4, subfamily F, member 17 // 19p13.3 // 81099 /// NM_001005484 // OR4F5 // olfactory receptor, family 4, subfamily F, member 5 // 1p36.33 // 79501 /// ENST00000318050 // OR4F17 // olfactory receptor, family 4, subfamily F, member 17 // 19p13.3 // 81099 /// ENST00000326183 // OR4F4 // olfactory receptor, family 4, subfamily F, member 4 // 15q26.3 // 26682 /// ENST00000335137 // OR4F5 // olfactory receptor, family 4, subfamily F, member 5 // 1p36.33 // 79501 /// ENST00000585993 // OR4F17 // olfactory receptor, family 4, subfamily F, member 17 // 19p13.3 // 81099 /// BC136848 // OR4F17 // olfactory receptor, family 4, subfamily F, member 17 // 19p13.3 // 81099 /// BC136867 // OR4F17 // olfactory receptor, family 4, subfamily F, member 17 // 19p13.3 // 81099 /// BC136907 // OR4F4 // olfactory receptor, family 4, subfamily F, member 4 // 15q26.3 // 26682 /// BC136908 // OR4F4 // olfactory receptor, family 4, subfamily F, member 4 // 15q26.3 // 26682'], 'mrna_assignment': ['NONHSAT060105 // NONCODE // Non-coding transcript identified by NONCODE // chr1 // 100 // 100 // 7 // 7 // 0', 'ENST00000328113 // ENSEMBL // havana:known chromosome:GRCh38:15:101926805:101927707:-1 gene:ENSG00000183909 gene_biotype:unprocessed_pseudogene transcript_biotype:unprocessed_pseudogene // chr1 // 100 // 100 // 31 // 31 // 0 /// ENST00000492842 // ENSEMBL // havana:known chromosome:GRCh38:1:62948:63887:1 gene:ENSG00000240361 gene_biotype:unprocessed_pseudogene transcript_biotype:unprocessed_pseudogene // chr1 // 100 // 100 // 31 // 31 // 0 /// ENST00000588632 // ENSEMBL // havana:known chromosome:GRCh38:19:104535:105471:1 gene:ENSG00000267310 gene_biotype:unprocessed_pseudogene transcript_biotype:unprocessed_pseudogene // chr1 // 100 // 100 // 31 // 31 // 0 /// NONHSAT000016 // NONCODE // Non-coding transcript identified by NONCODE: Linc // chr1 // 100 // 100 // 31 // 31 // 0 /// NONHSAT051704 // NONCODE // Non-coding transcript identified by NONCODE: Linc // chr1 // 100 // 100 // 31 // 31 // 0 /// NONHSAT060106 // NONCODE // Non-coding transcript identified by NONCODE: Linc // chr1 // 100 // 100 // 31 // 31 // 0', 'NM_001004195 // RefSeq // Homo sapiens olfactory receptor, family 4, subfamily F, member 4 (OR4F4), mRNA. // chr1 // 100 // 100 // 24 // 24 // 0 /// NM_001005240 // RefSeq // Homo sapiens olfactory receptor, family 4, subfamily F, member 17 (OR4F17), mRNA. // chr1 // 100 // 100 // 24 // 24 // 0 /// NM_001005484 // RefSeq // Homo sapiens olfactory receptor, family 4, subfamily F, member 5 (OR4F5), mRNA. // chr1 // 100 // 100 // 24 // 24 // 0 /// ENST00000318050 // ENSEMBL // ensembl:known chromosome:GRCh38:19:110643:111696:1 gene:ENSG00000176695 gene_biotype:protein_coding transcript_biotype:protein_coding // chr1 // 100 // 100 // 24 // 24 // 0 /// ENST00000326183 // ENSEMBL // ensembl_havana_transcript:known chromosome:GRCh38:15:101922042:101923095:-1 gene:ENSG00000177693 gene_biotype:protein_coding transcript_biotype:protein_coding // chr1 // 100 // 100 // 24 // 24 // 0 /// ENST00000335137 // ENSEMBL // ensembl_havana_transcript:known chromosome:GRCh38:1:69091:70008:1 gene:ENSG00000186092 gene_biotype:protein_coding transcript_biotype:protein_coding // chr1 // 100 // 100 // 24 // 24 // 0 /// ENST00000585993 // ENSEMBL // havana:known chromosome:GRCh38:19:107461:111696:1 gene:ENSG00000176695 gene_biotype:protein_coding transcript_biotype:protein_coding // chr1 // 100 // 100 // 24 // 24 // 0 /// BC136848 // GenBank // Homo sapiens olfactory receptor, family 4, subfamily F, member 17, mRNA (cDNA clone MGC:168462 IMAGE:9020839), complete cds. // chr1 // 100 // 100 // 24 // 24 // 0 /// BC136867 // GenBank // Homo sapiens olfactory receptor, family 4, subfamily F, member 17, mRNA (cDNA clone MGC:168481 IMAGE:9020858), complete cds. // chr1 // 100 // 100 // 24 // 24 // 0 /// BC136907 // GenBank // Homo sapiens olfactory receptor, family 4, subfamily F, member 4, mRNA (cDNA clone MGC:168521 IMAGE:9020898), complete cds. // chr1 // 100 // 100 // 24 // 24 // 0 /// BC136908 // GenBank // Homo sapiens olfactory receptor, family 4, subfamily F, member 4, mRNA (cDNA clone MGC:168522 IMAGE:9020899), complete cds. // chr1 // 100 // 100 // 24 // 24 // 0 /// ENST00000618231 // ENSEMBL // havana:known chromosome:GRCh38:19:110613:111417:1 gene:ENSG00000176695 gene_biotype:protein_coding transcript_biotype:retained_intron // chr1 // 100 // 88 // 21 // 21 // 0'], 'category': ['main', 'main', 'main']}\n",
      "\n",
      "Examining gene mapping columns:\n",
      "Column 'ID' examples:\n",
      "Example 1: 7896736\n",
      "Example 2: 7896738\n",
      "Example 3: 7896740\n",
      "Example 4: 7896742\n",
      "Example 5: 7896744\n",
      "\n",
      "Column 'gene_assignment' examples (contains gene symbols):\n",
      "Example 1: ---...\n",
      "Example 2: ENST00000328113 // OR4G2P // olfactory receptor, family 4, subfamily G, member 2 pseudogene // --- // --- /// ENST00000492842 // OR4G11P // olfactory receptor, family 4, subfamily G, member 11 pseudog...\n",
      "Example 3: NM_001004195 // OR4F4 // olfactory receptor, family 4, subfamily F, member 4 // 15q26.3 // 26682 /// NM_001005240 // OR4F17 // olfactory receptor, family 4, subfamily F, member 17 // 19p13.3 // 81099 ...\n",
      "\n",
      "Extracted gene symbols from gene_assignment:\n",
      "Example 1 extracted symbols: []\n",
      "Example 2 extracted symbols: ['OR4G2P', 'OR4G11P', 'OR4G1P']\n",
      "Example 3 extracted symbols: ['OR4F4', 'OR4F17', 'OR4F5', 'BC136848', 'BC136867', 'BC136907', 'BC136908']\n",
      "\n",
      "Columns identified for gene mapping:\n",
      "- 'ID': Contains probe IDs\n",
      "- 'gene_assignment': 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 gene_assignment column which contains gene symbols embedded in text\n",
    "print(\"\\nColumn 'gene_assignment' examples (contains gene symbols):\")\n",
    "if 'gene_assignment' in gene_annotation.columns:\n",
    "    # Display a few examples of the gene_assignment column\n",
    "    gene_samples = gene_annotation['gene_assignment'].head(3).tolist()\n",
    "    for i, sample in enumerate(gene_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 gene_assignment:\")\n",
    "    for i, sample in enumerate(gene_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(\"- 'gene_assignment': Contains gene information from which symbols can be extracted\")\n",
    "else:\n",
    "    print(\"Error: 'gene_assignment' column not found in annotation data.\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "702952b7",
   "metadata": {},
   "source": [
    "### Step 6: Gene Identifier Mapping"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "4e59efc4",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:30:11.839495Z",
     "iopub.status.busy": "2025-03-25T08:30:11.839369Z",
     "iopub.status.idle": "2025-03-25T08:30:15.668497Z",
     "shell.execute_reply": "2025-03-25T08:30:15.668165Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Sample gene mapping (before filtering):\n",
      "        ID                                               Gene\n",
      "0  7896736                                                 []\n",
      "1  7896738                          [OR4G2P, OR4G11P, OR4G1P]\n",
      "2  7896740  [OR4F4, OR4F17, OR4F5, OR4F17, OR4F4, OR4F5, O...\n",
      "3  7896742  [LOC728323, LOC101060626, LOC101060626, LOC101...\n",
      "4  7896744  [OR4F29, OR4F3, OR4F16, OR4F21, OR4F21, OR4F3,...\n",
      "Mapping entries with gene symbols: 25293\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Number of probe IDs in mapping that match expression data: 24520\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Original expression data shape: (32321, 48)\n",
      "Gene mapping entries: 25293\n",
      "Resulting gene expression data shape: (25745, 48)\n",
      "First 10 gene symbols: ['MT-TM', 'FAM87B', 'FAM87A', 'LINC01128', 'SAMD11', 'KLHL17', 'PLEKHN1', 'ISG15', 'AGRN', 'MIR200B']\n"
     ]
    }
   ],
   "source": [
    "# 1. Analyze the gene identifiers in the expression data and gene annotation data\n",
    "# Based on the preview, the 'ID' column in gene_annotation corresponds to the probe IDs in gene_data\n",
    "# The gene symbols are in the 'gene_assignment' column and need to be extracted\n",
    "\n",
    "# Define a more specific extraction function for this dataset format\n",
    "def extract_genes_from_assignment(text):\n",
    "    \"\"\"Extract gene symbols from gene_assignment field with specific format handling for this dataset\"\"\"\n",
    "    if not isinstance(text, str) or text == '---':\n",
    "        return []\n",
    "    \n",
    "    genes = []\n",
    "    # Gene symbols appear after '//' in the format \"ID // GENE // description\"\n",
    "    parts = text.split('///')\n",
    "    for part in parts:\n",
    "        subparts = part.split('//')\n",
    "        if len(subparts) > 1 and len(subparts[1].strip()) > 0:\n",
    "            gene = subparts[1].strip()\n",
    "            if gene != '---':\n",
    "                genes.append(gene)\n",
    "    return genes\n",
    "\n",
    "# 2. Create the gene mapping dataframe\n",
    "# We'll use the 'ID' column and extract gene symbols from 'gene_assignment' column\n",
    "mapping_df = gene_annotation[['ID', 'gene_assignment']].copy()\n",
    "\n",
    "# Process the mapping dataframe\n",
    "mapping_df = mapping_df.dropna(subset=['gene_assignment'])  # Drop rows without gene assignments\n",
    "\n",
    "# Use our custom extraction function instead of the generic one\n",
    "mapping_df['Gene'] = mapping_df['gene_assignment'].apply(extract_genes_from_assignment)\n",
    "\n",
    "# Check intermediate results\n",
    "print(\"Sample gene mapping (before filtering):\")\n",
    "print(mapping_df[['ID', 'Gene']].head(5))\n",
    "\n",
    "# Only keep rows that have at least one gene symbol\n",
    "mapping_df = mapping_df[mapping_df['Gene'].apply(len) > 0]\n",
    "print(f\"Mapping entries with gene symbols: {len(mapping_df)}\")\n",
    "\n",
    "# Make sure IDs are strings\n",
    "mapping_df['ID'] = mapping_df['ID'].astype(str)\n",
    "\n",
    "# 3. Apply gene mapping to convert probe-level measurements to gene expression data\n",
    "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
    "expression_df = get_genetic_data(matrix_file)\n",
    "\n",
    "# Check if our probe IDs match the expression data index\n",
    "common_ids = set(mapping_df['ID']) & set(expression_df.index.astype(str))\n",
    "print(f\"Number of probe IDs in mapping that match expression data: {len(common_ids)}\")\n",
    "\n",
    "# Create a custom mapping function for debugging\n",
    "def custom_map_probes_to_genes():\n",
    "    # Dictionary to store summed expression values for each gene\n",
    "    gene_expr = {}\n",
    "    \n",
    "    # Process each probe\n",
    "    for idx, row in mapping_df.iterrows():\n",
    "        probe_id = row['ID']\n",
    "        genes = row['Gene']\n",
    "        \n",
    "        # Skip if probe not in expression data\n",
    "        if probe_id not in expression_df.index:\n",
    "            continue\n",
    "            \n",
    "        # Skip if no genes to map to\n",
    "        if len(genes) == 0:\n",
    "            continue\n",
    "            \n",
    "        # Get probe expression values\n",
    "        probe_values = expression_df.loc[probe_id].to_dict()\n",
    "        \n",
    "        # Distribute expression values among genes\n",
    "        weight = 1.0 / len(genes)\n",
    "        for gene in genes:\n",
    "            if gene not in gene_expr:\n",
    "                gene_expr[gene] = {col: 0 for col in expression_df.columns}\n",
    "            \n",
    "            # Add weighted expression to each gene\n",
    "            for col, val in probe_values.items():\n",
    "                gene_expr[gene][col] += val * weight\n",
    "    \n",
    "    # Convert to dataframe\n",
    "    result = pd.DataFrame.from_dict(gene_expr, orient='index')\n",
    "    return result\n",
    "\n",
    "# Try our custom mapping approach for more control over the process\n",
    "gene_data = custom_map_probes_to_genes()\n",
    "\n",
    "# Print information about the mapping and resulting gene expression data\n",
    "print(f\"Original expression data shape: {expression_df.shape}\")\n",
    "print(f\"Gene mapping entries: {len(mapping_df)}\")\n",
    "print(f\"Resulting gene expression data shape: {gene_data.shape}\")\n",
    "if gene_data.shape[0] > 0:\n",
    "    print(f\"First 10 gene symbols: {gene_data.index[:10].tolist()}\")\n",
    "else:\n",
    "    print(\"No gene symbols were mapped successfully.\")\n",
    "\n",
    "# If custom mapping failed, try using the library function with explicit exploded mapping\n",
    "if gene_data.shape[0] == 0:\n",
    "    print(\"Trying alternative mapping approach with exploded mapping dataframe...\")\n",
    "    \n",
    "    # Create an exploded version with one gene per row\n",
    "    exploded_df = mapping_df.explode('Gene')\n",
    "    exploded_df = exploded_df[exploded_df['Gene'] != '']  # Remove empty strings\n",
    "    \n",
    "    # Apply the gene mapping using the library function\n",
    "    gene_data = apply_gene_mapping(expression_df, exploded_df[['ID', 'Gene']])\n",
    "    \n",
    "    print(f\"Resulting gene expression data shape with exploded mapping: {gene_data.shape}\")\n",
    "    if gene_data.shape[0] > 0:\n",
    "        print(f\"First 10 gene symbols: {gene_data.index[:10].tolist()}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e989347a",
   "metadata": {},
   "source": [
    "### Step 7: Data Normalization and Linking"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "b80d42b3",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:30:15.669829Z",
     "iopub.status.busy": "2025-03-25T08:30:15.669713Z",
     "iopub.status.idle": "2025-03-25T08:30:16.550758Z",
     "shell.execute_reply": "2025-03-25T08:30:16.550380Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene data shape after normalization: (24776, 48)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Normalized gene data saved to ../../output/preprocess/COVID-19/gene_data/GSE185658.csv\n",
      "No clinical data available for the trait of interest.\n",
      "Abnormality detected in the cohort: GSE185658. Preprocessing failed.\n",
      "Linked data not saved due to quality issues.\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. Check if clinical data is available before trying to extract features\n",
    "if trait_row is not None:\n",
    "    # Extract clinical features only if trait_row exists\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",
    "    # Save clinical features\n",
    "    os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
    "    clinical_features.to_csv(out_clinical_data_file)\n",
    "    print(f\"Clinical features saved to {out_clinical_data_file}\")\n",
    "    \n",
    "    # Link clinical and genetic data\n",
    "    linked_data = geo_link_clinical_genetic_data(clinical_features, normalized_gene_data)\n",
    "    \n",
    "    # Handle missing values and check for bias\n",
    "    linked_data = handle_missing_values(linked_data, trait)\n",
    "    is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n",
    "else:\n",
    "    # No clinical data available\n",
    "    print(\"No clinical data available for the trait of interest.\")\n",
    "    linked_data = pd.DataFrame()  # Empty dataframe\n",
    "    is_biased = True  # Dataset is biased since we have no trait data\n",
    "\n",
    "# 6. Validate and save cohort info\n",
    "is_trait_available = trait_row is not None\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=is_trait_available,\n",
    "    is_biased=is_biased,\n",
    "    df=linked_data,\n",
    "    note=\"Dataset contains gene expression data but lacks COVID-19 trait information.\"\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
}