File size: 33,924 Bytes
7ae1978
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "71ac4024",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:40:10.693645Z",
     "iopub.status.busy": "2025-03-25T05:40:10.693407Z",
     "iopub.status.idle": "2025-03-25T05:40:10.861671Z",
     "shell.execute_reply": "2025-03-25T05:40:10.861278Z"
    }
   },
   "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 = \"Height\"\n",
    "cohort = \"GSE101710\"\n",
    "\n",
    "# Input paths\n",
    "in_trait_dir = \"../../input/GEO/Height\"\n",
    "in_cohort_dir = \"../../input/GEO/Height/GSE101710\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/Height/GSE101710.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/Height/gene_data/GSE101710.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/Height/clinical_data/GSE101710.csv\"\n",
    "json_path = \"../../output/preprocess/Height/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d9ea1f6f",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "a33ad8ae",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:40:10.863175Z",
     "iopub.status.busy": "2025-03-25T05:40:10.863017Z",
     "iopub.status.idle": "2025-03-25T05:40:11.189176Z",
     "shell.execute_reply": "2025-03-25T05:40:11.188828Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Background Information:\n",
      "!Series_title\t\"Gene expression analysis of Influenza vaccine response in Young and Old - Year 5\"\n",
      "!Series_summary\t\"We profiled gene expression from a stratified cohort of subjects to define influenza vaccine response in Young and Old\"\n",
      "!Series_overall_design\t\"Differential gene expression by human PBMCs from Healthy Adults receiving Influenza Vaccination (Fluvirin, Novartis). Healthy adults (older >65, younger 21-30 years) were recruited at seasonal Influenza Vaccination clinics organized by Yale University Health Services during October to December of 2014 – 2015 seasons. With informed consent, healthy individuals were recruited as per a protocol approved by Human Investigations Committee of the Yale University School of Medicine. Each subject was evaluated by a screening questionnaire determining self-reported demographic information, height, weight, medications and comorbid conditions. Participants with acute illness two weeks prior to vaccination were excluded from study. Blood samples were collected into BD Vacutainer Sodium Heparin tube at four different time points, once prior to administration of vaccine and three time points after vaccination on days 2, 7 and 28. Peripheral Blood Mononuclear Cells (PBMC) were isolated from heparinized blood using Histopaque 1077 in gradient centrifugation. About 1.0x10^7 freshly isolated PBMC were lysed in Triso and immediately stored in -800C. Total RNA in aqueous phase of Trisol - Chloroform was isolated in an automated QiaCube instrument using miRNeasy according to manufacturer’s instructions. Integrity of RNA samples were assessed by Agilent 2100 BioAnalyser Samples were processed for cRNA generation using Illumina TotalPrep cRNA Amplification Kit and subsequently hybridized to Human HT12-V4.0 BeadChip at Yale Center for Genomic Analysis (YGCA).\"\n",
      "!Series_overall_design\t\"\"\n",
      "!Series_overall_design\t\"The current data set, together with GSE59654, GSE59635, GSE59743, and GSE101709, represents subsets of the same overall study\"\n",
      "Sample Characteristics Dictionary:\n",
      "{0: ['subject status: Healthy Adults receiving Influenza Vaccination'], 1: ['age group: Older', 'age group: Frail', 'age group: Young'], 2: ['blood draw date: day 0; prior to administration of vaccine', 'blood draw date: after vaccination day 2', 'blood draw date: after vaccination day 7', 'blood draw date: after vaccination day 28', 'blood draw date: after vaccination day 25', 'blood draw date: after vaccination day 37', 'blood draw date: after vaccination day 41'], 3: ['cell type: Peripheral Blood Mononuclear Cells (PBMC)'], 4: ['immport_expsamp_acc: ImmPort:ES1167372', 'immport_expsamp_acc: ImmPort:ES1167373', 'immport_expsamp_acc: ImmPort:ES1167374', 'immport_expsamp_acc: ImmPort:ES1167375', 'immport_expsamp_acc: ImmPort:ES1167376', 'immport_expsamp_acc: ImmPort:ES1167377', 'immport_expsamp_acc: ImmPort:ES1167378', 'immport_expsamp_acc: ImmPort:ES1167379', 'immport_expsamp_acc: ImmPort:ES1167380', 'immport_expsamp_acc: ImmPort:ES1167381', 'immport_expsamp_acc: ImmPort:ES1167382', 'immport_expsamp_acc: ImmPort:ES1167383', 'immport_expsamp_acc: ImmPort:ES1167384', 'immport_expsamp_acc: ImmPort:ES1167385', 'immport_expsamp_acc: ImmPort:ES1167386', 'immport_expsamp_acc: ImmPort:ES1167387', 'immport_expsamp_acc: ImmPort:ES1167388', 'immport_expsamp_acc: ImmPort:ES1167389', 'immport_expsamp_acc: ImmPort:ES1167390', 'immport_expsamp_acc: ImmPort:ES1167391', 'immport_expsamp_acc: ImmPort:ES1167392', 'immport_expsamp_acc: ImmPort:ES1167393', 'immport_expsamp_acc: ImmPort:ES1167394', 'immport_expsamp_acc: ImmPort:ES1167395', 'immport_expsamp_acc: ImmPort:ES1167396', 'immport_expsamp_acc: ImmPort:ES1167397', 'immport_expsamp_acc: ImmPort:ES1167398', 'immport_expsamp_acc: ImmPort:ES1167399', 'immport_expsamp_acc: ImmPort:ES1167400', 'immport_expsamp_acc: ImmPort:ES1167401']}\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": "2a85bcd4",
   "metadata": {},
   "source": [
    "### Step 2: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "39c28fc9",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:40:11.190462Z",
     "iopub.status.busy": "2025-03-25T05:40:11.190342Z",
     "iopub.status.idle": "2025-03-25T05:40:11.198270Z",
     "shell.execute_reply": "2025-03-25T05:40:11.197935Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "False"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import pandas as pd\n",
    "import os\n",
    "import re\n",
    "from typing import Optional, Any, Dict, Callable\n",
    "\n",
    "# 1. Gene Expression Data Availability\n",
    "# Based on background information, this dataset contains gene expression data from Illumina HT12-V4.0 BeadChip\n",
    "is_gene_available = True\n",
    "\n",
    "# 2. Variable Availability and Data Type Conversion\n",
    "# 2.1 Data Availability\n",
    "\n",
    "# For height (our trait): The background info mentions height was collected in screening questionnaire\n",
    "# But looking at the sample characteristics, there's no direct height data\n",
    "trait_row = None  # Height data is not available in the sample characteristics\n",
    "\n",
    "# For age: Age group is available in row 1 \n",
    "age_row = 1  # Contains \"age group: Older\", \"age group: Frail\", \"age group: Young\"\n",
    "\n",
    "# For gender: No gender information in the sample characteristics\n",
    "gender_row = None  # Gender data is not available\n",
    "\n",
    "# 2.2 Data Type Conversion\n",
    "\n",
    "# Define conversion functions for each variable\n",
    "def convert_trait(value: str) -> Optional[float]:\n",
    "    \"\"\"Convert height data to float (continuous). Not used in this dataset.\"\"\"\n",
    "    if value is None or pd.isna(value):\n",
    "        return None\n",
    "    \n",
    "    # Extract value after colon if present\n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip()\n",
    "    \n",
    "    try:\n",
    "        return float(value)\n",
    "    except (ValueError, TypeError):\n",
    "        return None\n",
    "\n",
    "def convert_age(value: str) -> Optional[int]:\n",
    "    \"\"\"Convert age group to binary (0 for Young, 1 for Older/Frail).\"\"\"\n",
    "    if value is None or pd.isna(value):\n",
    "        return None\n",
    "    \n",
    "    # Extract value after colon if present\n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip()\n",
    "    \n",
    "    value = value.lower()\n",
    "    if 'young' in value:\n",
    "        return 0\n",
    "    elif 'older' in value or 'frail' in value:\n",
    "        return 1\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "def convert_gender(value: str) -> Optional[int]:\n",
    "    \"\"\"Convert gender to binary (0 for female, 1 for male). Not used in this dataset.\"\"\"\n",
    "    if value is None or pd.isna(value):\n",
    "        return None\n",
    "    \n",
    "    # Extract value after colon if present\n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip()\n",
    "    \n",
    "    value = value.lower()\n",
    "    if 'female' in value or 'f' == value:\n",
    "        return 0\n",
    "    elif 'male' in value or 'm' == value:\n",
    "        return 1\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "# 3. Save Metadata\n",
    "# is_trait_available is False since trait_row is None\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",
    "# We skip this step since trait_row is None (no height data available)\n",
    "# If we had trait data, we would execute:\n",
    "# if trait_row is not None:\n",
    "#     # Assuming clinical_data is loaded from a previous step\n",
    "#     clinical_data = pd.read_csv(os.path.join(in_cohort_dir, \"clinical_data.csv\"))\n",
    "#     selected_clinical_df = 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 if age_row is not None else None,\n",
    "#         gender_row=gender_row,\n",
    "#         convert_gender=convert_gender if gender_row is not None else None\n",
    "#     )\n",
    "#     \n",
    "#     # Preview the dataframe\n",
    "#     preview = preview_df(selected_clinical_df)\n",
    "#     print(preview)\n",
    "#     \n",
    "#     # Save the clinical data\n",
    "#     os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
    "#     selected_clinical_df.to_csv(out_clinical_data_file, index=False)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7b7182cb",
   "metadata": {},
   "source": [
    "### Step 3: Gene Data Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "1d75ee47",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:40:11.199389Z",
     "iopub.status.busy": "2025-03-25T05:40:11.199277Z",
     "iopub.status.idle": "2025-03-25T05:40:11.715881Z",
     "shell.execute_reply": "2025-03-25T05:40:11.715495Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Extracting gene data from matrix file:\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Successfully extracted gene data with 46892 rows\n",
      "First 20 gene IDs:\n",
      "Index(['ILMN_1343291', 'ILMN_1343295', 'ILMN_1651199', 'ILMN_1651209',\n",
      "       'ILMN_1651210', 'ILMN_1651221', 'ILMN_1651228', 'ILMN_1651229',\n",
      "       'ILMN_1651230', 'ILMN_1651232', 'ILMN_1651235', 'ILMN_1651236',\n",
      "       'ILMN_1651237', 'ILMN_1651238', 'ILMN_1651249', 'ILMN_1651253',\n",
      "       'ILMN_1651254', 'ILMN_1651259', 'ILMN_1651260', 'ILMN_1651262'],\n",
      "      dtype='object', name='ID')\n",
      "\n",
      "Gene expression data available: True\n"
     ]
    }
   ],
   "source": [
    "# 1. Get the file paths for the SOFT file and matrix file\n",
    "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
    "\n",
    "# 2. Extract gene expression data from the matrix file\n",
    "try:\n",
    "    print(\"Extracting gene data from matrix file:\")\n",
    "    gene_data = get_genetic_data(matrix_file)\n",
    "    if gene_data.empty:\n",
    "        print(\"Extracted gene expression data is empty\")\n",
    "        is_gene_available = False\n",
    "    else:\n",
    "        print(f\"Successfully extracted gene data with {len(gene_data.index)} rows\")\n",
    "        print(\"First 20 gene IDs:\")\n",
    "        print(gene_data.index[:20])\n",
    "        is_gene_available = True\n",
    "except Exception as e:\n",
    "    print(f\"Error extracting gene data: {e}\")\n",
    "    print(\"This dataset appears to have an empty or malformed gene expression matrix\")\n",
    "    is_gene_available = False\n",
    "\n",
    "print(f\"\\nGene expression data available: {is_gene_available}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "430a6a09",
   "metadata": {},
   "source": [
    "### Step 4: Gene Identifier Review"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "8f0878d5",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:40:11.717182Z",
     "iopub.status.busy": "2025-03-25T05:40:11.717051Z",
     "iopub.status.idle": "2025-03-25T05:40:11.719025Z",
     "shell.execute_reply": "2025-03-25T05:40:11.718693Z"
    }
   },
   "outputs": [],
   "source": [
    "# These are Illumina microarray probe identifiers (ILMN_*), not human gene symbols.\n",
    "# They need to be mapped to official gene symbols for biological interpretation.\n",
    "\n",
    "requires_gene_mapping = True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7e8b2636",
   "metadata": {},
   "source": [
    "### Step 5: Gene Annotation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "fb407d5b",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:40:11.720203Z",
     "iopub.status.busy": "2025-03-25T05:40:11.720089Z",
     "iopub.status.idle": "2025-03-25T05:40:12.690269Z",
     "shell.execute_reply": "2025-03-25T05:40:12.689866Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Examining SOFT file structure:\n",
      "Line 0: ^DATABASE = GeoMiame\n",
      "Line 1: !Database_name = Gene Expression Omnibus (GEO)\n",
      "Line 2: !Database_institute = NCBI NLM NIH\n",
      "Line 3: !Database_web_link = http://www.ncbi.nlm.nih.gov/geo\n",
      "Line 4: !Database_email = [email protected]\n",
      "Line 5: ^SERIES = GSE101710\n",
      "Line 6: !Series_title = Gene expression analysis of Influenza vaccine response in Young and Old - Year 5\n",
      "Line 7: !Series_geo_accession = GSE101710\n",
      "Line 8: !Series_status = Public on May 26 2019\n",
      "Line 9: !Series_submission_date = Jul 20 2017\n",
      "Line 10: !Series_last_update_date = Jul 25 2021\n",
      "Line 11: !Series_pubmed_id = 30239628\n",
      "Line 12: !Series_pubmed_id = 32060136\n",
      "Line 13: !Series_summary = We profiled gene expression from a stratified cohort of subjects to define influenza vaccine response in Young and Old\n",
      "Line 14: !Series_overall_design = Differential gene expression by human PBMCs from Healthy Adults receiving Influenza Vaccination (Fluvirin, Novartis). Healthy adults (older >65, younger 21-30 years) were recruited at seasonal Influenza Vaccination clinics organized by Yale University Health Services during October to December of 2014 – 2015 seasons. With informed consent, healthy individuals were recruited as per a protocol approved by Human Investigations Committee of the Yale University School of Medicine. Each subject was evaluated by a screening questionnaire determining self-reported demographic information, height, weight, medications and comorbid conditions. Participants with acute illness two weeks prior to vaccination were excluded from study. Blood samples were collected into BD Vacutainer Sodium Heparin tube at four different time points, once prior to administration of vaccine and three time points after vaccination on days 2, 7 and 28. Peripheral Blood Mononuclear Cells (PBMC) were isolated from heparinized blood using Histopaque 1077 in gradient centrifugation. About 1.0x10^7 freshly isolated PBMC were lysed in Triso and immediately stored in -800C. Total RNA in aqueous phase of Trisol - Chloroform was isolated in an automated QiaCube instrument using miRNeasy according to manufacturer’s instructions. Integrity of RNA samples were assessed by Agilent 2100 BioAnalyser Samples were processed for cRNA generation using Illumina TotalPrep cRNA Amplification Kit and subsequently hybridized to Human HT12-V4.0 BeadChip at Yale Center for Genomic Analysis (YGCA).\n",
      "Line 15: !Series_overall_design =\n",
      "Line 16: !Series_overall_design = The current data set, together with GSE59654, GSE59635, GSE59743, and GSE101709, represents subsets of the same overall study\n",
      "Line 17: !Series_type = Expression profiling by array\n",
      "Line 18: !Series_contributor = Albert,C,Shaw\n",
      "Line 19: !Series_contributor = Subhasis,,Mohanty\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "Gene annotation preview:\n",
      "{'ID': ['ILMN_1343048', 'ILMN_1343049', 'ILMN_1343050', 'ILMN_1343052', 'ILMN_1343059'], 'Species': [nan, nan, nan, nan, nan], 'Source': [nan, nan, nan, nan, nan], 'Search_Key': [nan, nan, nan, nan, nan], 'Transcript': [nan, nan, nan, nan, nan], 'ILMN_Gene': [nan, nan, nan, nan, nan], 'Source_Reference_ID': [nan, nan, nan, nan, nan], 'RefSeq_ID': [nan, nan, nan, nan, nan], 'Unigene_ID': [nan, nan, nan, nan, nan], 'Entrez_Gene_ID': [nan, nan, nan, nan, nan], 'GI': [nan, nan, nan, nan, nan], 'Accession': [nan, nan, nan, nan, nan], 'Symbol': ['phage_lambda_genome', 'phage_lambda_genome', 'phage_lambda_genome:low', 'phage_lambda_genome:low', 'thrB'], 'Protein_Product': [nan, nan, nan, nan, 'thrB'], 'Probe_Id': [nan, nan, nan, nan, nan], 'Array_Address_Id': [5090180, 6510136, 7560739, 1450438, 1240647], 'Probe_Type': [nan, nan, nan, nan, nan], 'Probe_Start': [nan, nan, nan, nan, nan], 'SEQUENCE': ['GAATAAAGAACAATCTGCTGATGATCCCTCCGTGGATCTGATTCGTGTAA', 'CCATGTGATACGAGGGCGCGTAGTTTGCATTATCGTTTTTATCGTTTCAA', 'CCGACAGATGTATGTAAGGCCAACGTGCTCAAATCTTCATACAGAAAGAT', 'TCTGTCACTGTCAGGAAAGTGGTAAAACTGCAACTCAATTACTGCAATGC', 'CTTGTGCCTGAGCTGTCAAAAGTAGAGCACGTCGCCGAGATGAAGGGCGC'], 'Chromosome': [nan, nan, nan, nan, nan], 'Probe_Chr_Orientation': [nan, nan, nan, nan, nan], 'Probe_Coordinates': [nan, nan, nan, nan, nan], 'Cytoband': [nan, nan, nan, nan, nan], 'Definition': [nan, nan, nan, nan, nan], 'Ontology_Component': [nan, nan, nan, nan, nan], 'Ontology_Process': [nan, nan, nan, nan, nan], 'Ontology_Function': [nan, nan, nan, nan, nan], 'Synonyms': [nan, nan, nan, nan, nan], 'Obsolete_Probe_Id': [nan, nan, nan, nan, nan], 'GB_ACC': [nan, nan, nan, nan, nan]}\n"
     ]
    }
   ],
   "source": [
    "# 1. Let's first examine the structure of the SOFT file before trying to parse it\n",
    "import gzip\n",
    "\n",
    "# Look at the first few lines of the SOFT file to understand its structure\n",
    "print(\"Examining SOFT file structure:\")\n",
    "try:\n",
    "    with gzip.open(soft_file, 'rt') as file:\n",
    "        # Read first 20 lines to understand the file structure\n",
    "        for i, line in enumerate(file):\n",
    "            if i < 20:\n",
    "                print(f\"Line {i}: {line.strip()}\")\n",
    "            else:\n",
    "                break\n",
    "except Exception as e:\n",
    "    print(f\"Error reading SOFT file: {e}\")\n",
    "\n",
    "# 2. Now let's try a more robust approach to extract the gene annotation\n",
    "# Instead of using the library function which failed, we'll implement a custom approach\n",
    "try:\n",
    "    # First, look for the platform section which contains gene annotation\n",
    "    platform_data = []\n",
    "    with gzip.open(soft_file, 'rt') as file:\n",
    "        in_platform_section = False\n",
    "        for line in file:\n",
    "            if line.startswith('^PLATFORM'):\n",
    "                in_platform_section = True\n",
    "                continue\n",
    "            if in_platform_section and line.startswith('!platform_table_begin'):\n",
    "                # Next line should be the header\n",
    "                header = next(file).strip()\n",
    "                platform_data.append(header)\n",
    "                # Read until the end of the platform table\n",
    "                for table_line in file:\n",
    "                    if table_line.startswith('!platform_table_end'):\n",
    "                        break\n",
    "                    platform_data.append(table_line.strip())\n",
    "                break\n",
    "    \n",
    "    # If we found platform data, convert it to a DataFrame\n",
    "    if platform_data:\n",
    "        import pandas as pd\n",
    "        import io\n",
    "        platform_text = '\\n'.join(platform_data)\n",
    "        gene_annotation = pd.read_csv(io.StringIO(platform_text), delimiter='\\t', \n",
    "                                      low_memory=False, on_bad_lines='skip')\n",
    "        print(\"\\nGene annotation preview:\")\n",
    "        print(preview_df(gene_annotation))\n",
    "    else:\n",
    "        print(\"Could not find platform table in SOFT file\")\n",
    "        \n",
    "        # Try an alternative approach - extract mapping from other sections\n",
    "        with gzip.open(soft_file, 'rt') as file:\n",
    "            for line in file:\n",
    "                if 'ANNOTATION information' in line or 'annotation information' in line:\n",
    "                    print(f\"Found annotation information: {line.strip()}\")\n",
    "                if line.startswith('!Platform_title') or line.startswith('!platform_title'):\n",
    "                    print(f\"Platform title: {line.strip()}\")\n",
    "            \n",
    "except Exception as e:\n",
    "    print(f\"Error processing gene annotation: {e}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a8672103",
   "metadata": {},
   "source": [
    "### Step 6: Gene Identifier Mapping"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "c648fd21",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:40:12.691729Z",
     "iopub.status.busy": "2025-03-25T05:40:12.691595Z",
     "iopub.status.idle": "2025-03-25T05:40:14.180602Z",
     "shell.execute_reply": "2025-03-25T05:40:14.180206Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Created gene mapping with 44837 rows\n",
      "Gene mapping preview:\n",
      "             ID                     Gene\n",
      "0  ILMN_1343048      phage_lambda_genome\n",
      "1  ILMN_1343049      phage_lambda_genome\n",
      "2  ILMN_1343050  phage_lambda_genome:low\n",
      "3  ILMN_1343052  phage_lambda_genome:low\n",
      "4  ILMN_1343059                     thrB\n",
      "\n",
      "Applying gene mapping to convert probe-level data to gene-level data...\n",
      "Successfully converted to gene-level data with 21344 genes\n",
      "First 10 gene symbols:\n",
      "Index(['A1BG', 'A1CF', 'A26C3', 'A2BP1', 'A2LD1', 'A2M', 'A2ML1', 'A3GALT2',\n",
      "       'A4GALT', 'A4GNT'],\n",
      "      dtype='object', name='Gene')\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene expression data saved to ../../output/preprocess/Height/gene_data/GSE101710.csv\n"
     ]
    }
   ],
   "source": [
    "# 1. Identify the correct columns for mapping\n",
    "# From the gene annotation preview, we can see:\n",
    "# - 'ID' contains the Illumina probe identifiers (ILMN_*)\n",
    "# - 'Symbol' contains gene symbols\n",
    "\n",
    "# 2. Create gene mapping dataframe\n",
    "gene_mapping = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='Symbol')\n",
    "print(f\"Created gene mapping with {len(gene_mapping)} rows\")\n",
    "print(\"Gene mapping preview:\")\n",
    "print(gene_mapping.head())\n",
    "\n",
    "# 3. Apply the gene mapping to convert probe-level data to gene-level data\n",
    "# This handles the many-to-many relationship between probes and genes\n",
    "try:\n",
    "    print(\"\\nApplying gene mapping to convert probe-level data to gene-level data...\")\n",
    "    gene_data = apply_gene_mapping(gene_data, gene_mapping)\n",
    "    \n",
    "    print(f\"Successfully converted to gene-level data with {len(gene_data)} genes\")\n",
    "    print(\"First 10 gene symbols:\")\n",
    "    print(gene_data.index[:10])\n",
    "    \n",
    "    # Check if the dataset has non-empty gene data\n",
    "    if gene_data.empty:\n",
    "        print(\"Warning: No genes were successfully mapped\")\n",
    "        is_gene_available = False\n",
    "    else:\n",
    "        is_gene_available = True\n",
    "        \n",
    "    # Save the gene expression 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\"Gene expression data saved to {out_gene_data_file}\")\n",
    "    \n",
    "except Exception as e:\n",
    "    print(f\"Error in gene mapping: {e}\")\n",
    "    is_gene_available = False\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2bc40526",
   "metadata": {},
   "source": [
    "### Step 7: Data Normalization and Linking"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "1ac71355",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:40:14.182021Z",
     "iopub.status.busy": "2025-03-25T05:40:14.181882Z",
     "iopub.status.idle": "2025-03-25T05:40:14.814558Z",
     "shell.execute_reply": "2025-03-25T05:40:14.814205Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene data shape before normalization: (46893, 79)\n",
      "Gene data shape after normalization: (0, 79)\n",
      "Normalized gene data saved to ../../output/preprocess/Height/gene_data/GSE101710.csv\n",
      "Clinical data saved to ../../output/preprocess/Height/clinical_data/GSE101710.csv\n",
      "Linked data shape: (79, 2)\n",
      "Abnormality detected in the cohort: GSE101710. Preprocessing failed.\n",
      "Dataset usability: False\n",
      "Dataset does not contain Height data and cannot be used for association studies.\n"
     ]
    }
   ],
   "source": [
    "import numpy as np\n",
    "import os\n",
    "import gzip\n",
    "\n",
    "# 1. Extract gene expression data using the alternative approach that worked in Step 3\n",
    "with gzip.open(matrix_file, 'rt') as file:\n",
    "    # Find the start of the data\n",
    "    for line in file:\n",
    "        if '!series_matrix_table_begin' in line:\n",
    "            break\n",
    "            \n",
    "    # Read the headers and data\n",
    "    gene_data = pd.read_csv(file, sep='\\t', index_col=0)\n",
    "\n",
    "# Check if we have gene data before proceeding\n",
    "if gene_data.empty:\n",
    "    print(\"No gene expression data found in the matrix file.\")\n",
    "    is_gene_available = False\n",
    "else:\n",
    "    is_gene_available = True\n",
    "    print(f\"Gene data shape before normalization: {gene_data.shape}\")\n",
    "\n",
    "    # Normalize gene symbols using the NCBI Gene database information\n",
    "    try:\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",
    "        # Save the normalized gene data to the output file\n",
    "        os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
    "        normalized_gene_data.to_csv(out_gene_data_file)\n",
    "        print(f\"Normalized gene data saved to {out_gene_data_file}\")\n",
    "    except Exception as e:\n",
    "        print(f\"Error normalizing gene data: {e}\")\n",
    "        is_gene_available = False\n",
    "        normalized_gene_data = gene_data  # Use original data if normalization fails\n",
    "\n",
    "# 2. Link clinical and genetic data\n",
    "# In Step 2, we determined that Height data is not available in this dataset (trait_row = None)\n",
    "# Create a minimal clinical dataframe with the trait column (containing NaNs)\n",
    "if is_gene_available:\n",
    "    sample_ids = gene_data.columns\n",
    "    minimal_clinical_df = pd.DataFrame(index=sample_ids)\n",
    "    minimal_clinical_df[trait] = np.nan  # Add the trait column with NaN values\n",
    "\n",
    "    # If we have age and gender data from Step 2, add those columns\n",
    "    if age_row is not None:\n",
    "        minimal_clinical_df['Age'] = get_feature_data(clinical_data, age_row, 'Age', convert_age).iloc[0]\n",
    "\n",
    "    if gender_row is not None:\n",
    "        minimal_clinical_df['Gender'] = get_feature_data(clinical_data, gender_row, 'Gender', convert_gender).iloc[0]\n",
    "\n",
    "    minimal_clinical_df.index.name = 'Sample'\n",
    "\n",
    "    # Save this minimal clinical data for reference\n",
    "    os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
    "    minimal_clinical_df.to_csv(out_clinical_data_file)\n",
    "    print(f\"Clinical data saved to {out_clinical_data_file}\")\n",
    "\n",
    "    # Create a linked dataset \n",
    "    if is_gene_available and normalized_gene_data is not None:\n",
    "        linked_data = pd.concat([minimal_clinical_df, normalized_gene_data.T], axis=1)\n",
    "        linked_data.index.name = 'Sample'\n",
    "        print(f\"Linked data shape: {linked_data.shape}\")\n",
    "    else:\n",
    "        linked_data = minimal_clinical_df\n",
    "        print(\"No gene data to link with clinical data.\")\n",
    "else:\n",
    "    # Create a minimal dataframe with just the trait for the validation step\n",
    "    linked_data = pd.DataFrame({trait: [np.nan]})\n",
    "    print(\"No gene data available, creating minimal dataframe for validation.\")\n",
    "\n",
    "# 4 & 5. Validate and save cohort information\n",
    "# Since trait_row was None in Step 2, we know Height data is not available\n",
    "is_trait_available = False  # Height data is not available\n",
    "\n",
    "note = \"Dataset contains gene expression data but no Height measurements. This dataset is not usable for studying Height associations.\"\n",
    "\n",
    "# For datasets without trait data, we set is_biased to False\n",
    "# This indicates the dataset is not usable due to missing trait data, not due to bias\n",
    "is_biased = False\n",
    "\n",
    "# Final validation\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=note\n",
    ")\n",
    "\n",
    "# 6. Since there is no trait data, the dataset is not usable for our association study\n",
    "# So we should not save it to out_data_file\n",
    "print(f\"Dataset usability: {is_usable}\")\n",
    "if is_usable:\n",
    "    os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n",
    "    linked_data.to_csv(out_data_file)\n",
    "    print(f\"Linked data saved to {out_data_file}\")\n",
    "else:\n",
    "    print(\"Dataset does not contain Height data and cannot be used for association studies.\")"
   ]
  }
 ],
 "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
}