File size: 32,132 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
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "0230e186",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:28:11.946552Z",
     "iopub.status.busy": "2025-03-25T08:28:11.946340Z",
     "iopub.status.idle": "2025-03-25T08:28:12.105585Z",
     "shell.execute_reply": "2025-03-25T08:28:12.105277Z"
    }
   },
   "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 = \"Coronary_artery_disease\"\n",
    "cohort = \"GSE234398\"\n",
    "\n",
    "# Input paths\n",
    "in_trait_dir = \"../../input/GEO/Coronary_artery_disease\"\n",
    "in_cohort_dir = \"../../input/GEO/Coronary_artery_disease/GSE234398\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/Coronary_artery_disease/GSE234398.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/Coronary_artery_disease/gene_data/GSE234398.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/Coronary_artery_disease/clinical_data/GSE234398.csv\"\n",
    "json_path = \"../../output/preprocess/Coronary_artery_disease/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1c82b7fc",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "2c0f82b2",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:28:12.106992Z",
     "iopub.status.busy": "2025-03-25T08:28:12.106851Z",
     "iopub.status.idle": "2025-03-25T08:28:12.282411Z",
     "shell.execute_reply": "2025-03-25T08:28:12.282074Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Background Information:\n",
      "!Series_title\t\"Analysis of  gene expression of LPS-stimulated monocyte from CAD patients\"\n",
      "!Series_summary\t\"Data for the publication 'Identification of a Gene Network Driving the Attenuated Monocyte Response to Lipopolysaccharide of Hypertensive Coronary Artery Disease Patients'.\"\n",
      "!Series_summary\t\"Dissection of the impact of CVD risk factors on monocyte phenotype at the gene expression level, and in particular on their response to trauma and infection response.\"\n",
      "!Series_summary\t\"For any questions about the dataset, please contact Erik Biessen‘s Lab, Department of Pathology, Cardiovascular Research Institute Maastricht (CARIM), Maastricht University Medical Center, Maastricht, Netherlands\"\n",
      "!Series_overall_design\t\"Total RNA obtained from LPS stimulated monocytes of CAD patients.\"\n",
      "Sample Characteristics Dictionary:\n",
      "{0: ['cell type: monocytes'], 1: ['Sex: male', 'Sex: female'], 2: ['age: 78', 'age: 50', 'age: 67', 'age: 74', 'age: 60', 'age: 72', 'age: 73', 'age: 77', 'age: 56', 'age: 51', 'age: 66', 'age: 65', 'age: 63', 'age: 71', 'age: 57', 'age: 75', 'age: 64', 'age: 39', 'age: 40']}\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": "f5184adf",
   "metadata": {},
   "source": [
    "### Step 2: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "b8fcadee",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:28:12.283688Z",
     "iopub.status.busy": "2025-03-25T08:28:12.283582Z",
     "iopub.status.idle": "2025-03-25T08:28:12.293360Z",
     "shell.execute_reply": "2025-03-25T08:28:12.293081Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Clinical Data Preview:\n",
      "{'GSM7466724': [1.0, 78.0, 1.0], 'GSM7466725': [1.0, 78.0, 1.0], 'GSM7466726': [1.0, 50.0, 0.0], 'GSM7466727': [1.0, 67.0, 0.0], 'GSM7466728': [1.0, 74.0, 0.0], 'GSM7466729': [1.0, 60.0, 1.0], 'GSM7466730': [1.0, 72.0, 1.0], 'GSM7466731': [1.0, 67.0, 1.0], 'GSM7466732': [1.0, 67.0, 1.0], 'GSM7466733': [1.0, 73.0, 1.0], 'GSM7466734': [1.0, 77.0, 0.0], 'GSM7466735': [1.0, 78.0, 0.0], 'GSM7466736': [1.0, 56.0, 1.0], 'GSM7466737': [1.0, 51.0, 1.0], 'GSM7466738': [1.0, 78.0, 1.0], 'GSM7466739': [1.0, 66.0, 1.0], 'GSM7466740': [1.0, 65.0, 1.0], 'GSM7466741': [1.0, 51.0, 1.0], 'GSM7466742': [1.0, 63.0, 0.0], 'GSM7466743': [1.0, 60.0, 0.0], 'GSM7466744': [1.0, 71.0, 1.0], 'GSM7466745': [1.0, 57.0, 0.0], 'GSM7466746': [1.0, 73.0, 1.0], 'GSM7466747': [1.0, 75.0, 0.0], 'GSM7466748': [1.0, 72.0, 0.0], 'GSM7466749': [1.0, 74.0, 0.0], 'GSM7466750': [1.0, 64.0, 0.0], 'GSM7466751': [1.0, 39.0, 1.0], 'GSM7466752': [1.0, 78.0, 0.0], 'GSM7466753': [1.0, 57.0, 1.0], 'GSM7466754': [1.0, 74.0, 0.0], 'GSM7466755': [1.0, 75.0, 0.0], 'GSM7466756': [1.0, 67.0, 0.0], 'GSM7466757': [1.0, 63.0, 0.0], 'GSM7466758': [1.0, 71.0, 1.0], 'GSM7466759': [1.0, 72.0, 1.0], 'GSM7466760': [1.0, 40.0, 1.0], 'GSM7466761': [1.0, 63.0, 1.0], 'GSM7466762': [1.0, 73.0, 0.0], 'GSM7466763': [1.0, 77.0, 1.0], 'GSM7466764': [1.0, 50.0, 0.0], 'GSM7466765': [1.0, 73.0, 0.0], 'GSM7466766': [1.0, 72.0, 1.0], 'GSM7466767': [1.0, 56.0, 1.0], 'GSM7466768': [1.0, 56.0, 0.0], 'GSM7466769': [1.0, 64.0, 0.0], 'GSM7466770': [1.0, 66.0, 1.0], 'GSM7466771': [1.0, 65.0, 1.0], 'GSM7466772': [1.0, 63.0, 1.0], 'GSM7466773': [1.0, 56.0, 1.0]}\n",
      "Clinical data saved to ../../output/preprocess/Coronary_artery_disease/clinical_data/GSE234398.csv\n"
     ]
    }
   ],
   "source": [
    "# 1. Gene Expression Data Availability\n",
    "# Based on the background information, this dataset contains gene expression data from LPS-stimulated monocytes\n",
    "is_gene_available = True\n",
    "\n",
    "# 2. Variable Availability and Data Type Conversion\n",
    "# 2.1 Data Availability\n",
    "# Trait: From the background info, this dataset is specifically about CAD patients\n",
    "# We can use row 0 to represent all samples as having CAD (even though it doesn't explicitly state CAD)\n",
    "trait_row = 0  # All samples are CAD patients as per the background information\n",
    "\n",
    "# Age: This is available in row 2\n",
    "age_row = 2\n",
    "\n",
    "# Gender: This is available in row 1\n",
    "gender_row = 1\n",
    "\n",
    "# 2.2 Data Type Conversion\n",
    "def convert_trait(value):\n",
    "    # All samples are CAD patients according to the background info\n",
    "    return 1  # Binary: 1 = has CAD\n",
    "\n",
    "def convert_age(value):\n",
    "    if \":\" in value:\n",
    "        value = value.split(\":\", 1)[1].strip()\n",
    "    try:\n",
    "        return float(value)  # Convert to continuous numeric value\n",
    "    except (ValueError, TypeError):\n",
    "        return None\n",
    "\n",
    "def convert_gender(value):\n",
    "    if \":\" in value:\n",
    "        value = value.split(\":\", 1)[1].strip().lower()\n",
    "    if value == \"male\":\n",
    "        return 1\n",
    "    elif value == \"female\":\n",
    "        return 0\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "# 3. Save Metadata - initial filtering\n",
    "is_trait_available = trait_row is not None\n",
    "validate_and_save_cohort_info(\n",
    "    is_final=False,\n",
    "    cohort=cohort,\n",
    "    info_path=json_path,\n",
    "    is_gene_available=is_gene_available,\n",
    "    is_trait_available=is_trait_available\n",
    ")\n",
    "\n",
    "# 4. Clinical Feature Extraction\n",
    "if trait_row is not None:\n",
    "    # Extract clinical features\n",
    "    clinical_selected = geo_select_clinical_features(\n",
    "        clinical_df=clinical_data,\n",
    "        trait=trait,\n",
    "        trait_row=trait_row,\n",
    "        convert_trait=convert_trait,\n",
    "        age_row=age_row,\n",
    "        convert_age=convert_age,\n",
    "        gender_row=gender_row,\n",
    "        convert_gender=convert_gender\n",
    "    )\n",
    "    \n",
    "    # Preview the data\n",
    "    preview = preview_df(clinical_selected)\n",
    "    print(\"Clinical Data Preview:\")\n",
    "    print(preview)\n",
    "    \n",
    "    # Save to file\n",
    "    clinical_selected.to_csv(out_clinical_data_file)\n",
    "    print(f\"Clinical data saved to {out_clinical_data_file}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "af810ea2",
   "metadata": {},
   "source": [
    "### Step 3: Gene Data Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "9ab59c05",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:28:12.294447Z",
     "iopub.status.busy": "2025-03-25T08:28:12.294346Z",
     "iopub.status.idle": "2025-03-25T08:28:12.540618Z",
     "shell.execute_reply": "2025-03-25T08:28:12.540240Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "SOFT file: ../../input/GEO/Coronary_artery_disease/GSE234398/GSE234398_family.soft.gz\n",
      "Matrix file: ../../input/GEO/Coronary_artery_disease/GSE234398/GSE234398_series_matrix.txt.gz\n",
      "Found the matrix table marker at line 63\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene data shape: (47231, 50)\n",
      "First 20 gene/probe identifiers:\n",
      "['ILMN_1343291', 'ILMN_1343295', 'ILMN_1651199', 'ILMN_1651209', 'ILMN_1651210', 'ILMN_1651221', 'ILMN_1651228', 'ILMN_1651229', 'ILMN_1651230', 'ILMN_1651232', 'ILMN_1651235', 'ILMN_1651236', 'ILMN_1651237', 'ILMN_1651238', 'ILMN_1651249', 'ILMN_1651253', 'ILMN_1651254', 'ILMN_1651259', 'ILMN_1651260', 'ILMN_1651262']\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": "25e3e77f",
   "metadata": {},
   "source": [
    "### Step 4: Gene Identifier Review"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "9effad6c",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:28:12.541949Z",
     "iopub.status.busy": "2025-03-25T08:28:12.541830Z",
     "iopub.status.idle": "2025-03-25T08:28:12.543688Z",
     "shell.execute_reply": "2025-03-25T08:28:12.543421Z"
    }
   },
   "outputs": [],
   "source": [
    "# Examining the gene identifiers\n",
    "# The identifiers with prefix 'ILMN_' are Illumina probe IDs, not human gene symbols\n",
    "# These are probe IDs from Illumina microarray platforms and need to be mapped to gene symbols\n",
    "\n",
    "requires_gene_mapping = True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2df6206b",
   "metadata": {},
   "source": [
    "### Step 5: Gene Annotation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "00c3c38a",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:28:12.544775Z",
     "iopub.status.busy": "2025-03-25T08:28:12.544677Z",
     "iopub.status.idle": "2025-03-25T08:28:17.704922Z",
     "shell.execute_reply": "2025-03-25T08:28:17.704544Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "Gene annotation preview:\n",
      "Columns in gene annotation: ['ID', 'Species', 'Source', 'Search_Key', 'Transcript', 'ILMN_Gene', 'Source_Reference_ID', 'RefSeq_ID', 'Unigene_ID', 'Entrez_Gene_ID', 'GI', 'Accession', 'Symbol', 'Protein_Product', 'Probe_Id', 'Array_Address_Id', 'Probe_Type', 'Probe_Start', 'SEQUENCE', 'Chromosome', 'Probe_Chr_Orientation', 'Probe_Coordinates', 'Cytoband', 'Definition', 'Ontology_Component', 'Ontology_Process', 'Ontology_Function', 'Synonyms', 'Obsolete_Probe_Id', 'GB_ACC']\n",
      "{'ID': ['ILMN_1343048', 'ILMN_1343049', 'ILMN_1343050'], 'Species': [nan, nan, nan], 'Source': [nan, nan, nan], 'Search_Key': [nan, nan, nan], 'Transcript': [nan, nan, nan], 'ILMN_Gene': [nan, nan, nan], 'Source_Reference_ID': [nan, nan, nan], 'RefSeq_ID': [nan, nan, nan], 'Unigene_ID': [nan, nan, nan], 'Entrez_Gene_ID': [nan, nan, nan], 'GI': [nan, nan, nan], 'Accession': [nan, nan, nan], 'Symbol': ['phage_lambda_genome', 'phage_lambda_genome', 'phage_lambda_genome:low'], 'Protein_Product': [nan, nan, nan], 'Probe_Id': [nan, nan, nan], 'Array_Address_Id': [5090180.0, 6510136.0, 7560739.0], 'Probe_Type': [nan, nan, nan], 'Probe_Start': [nan, nan, nan], 'SEQUENCE': ['GAATAAAGAACAATCTGCTGATGATCCCTCCGTGGATCTGATTCGTGTAA', 'CCATGTGATACGAGGGCGCGTAGTTTGCATTATCGTTTTTATCGTTTCAA', 'CCGACAGATGTATGTAAGGCCAACGTGCTCAAATCTTCATACAGAAAGAT'], 'Chromosome': [nan, nan, nan], 'Probe_Chr_Orientation': [nan, nan, nan], 'Probe_Coordinates': [nan, nan, nan], 'Cytoband': [nan, nan, nan], 'Definition': [nan, nan, nan], 'Ontology_Component': [nan, nan, nan], 'Ontology_Process': [nan, nan, nan], 'Ontology_Function': [nan, nan, nan], 'Synonyms': [nan, nan, nan], 'Obsolete_Probe_Id': [nan, nan, nan], 'GB_ACC': [nan, nan, nan]}\n",
      "\n",
      "Examining mapping information (first 5 rows):\n",
      "Row 0: ID=ILMN_1343048, Symbol=phage_lambda_genome\n",
      "Row 1: ID=ILMN_1343049, Symbol=phage_lambda_genome\n",
      "Row 2: ID=ILMN_1343050, Symbol=phage_lambda_genome:low\n",
      "Row 3: ID=ILMN_1343052, Symbol=phage_lambda_genome:low\n",
      "Row 4: ID=ILMN_1343059, Symbol=thrB\n",
      "\n",
      "Symbol column completeness: 44837/2409707 rows (1.86%)\n",
      "\n",
      "Columns identified for gene mapping:\n",
      "- 'ID': Contains Illumina probe IDs (e.g., ILMN_*)\n",
      "- 'Symbol': Contains gene symbols\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 ID and Symbol columns that appear to contain the mapping information\n",
    "print(\"\\nExamining mapping information (first 5 rows):\")\n",
    "if 'ID' in gene_annotation.columns and 'Symbol' in gene_annotation.columns:\n",
    "    for i in range(min(5, len(gene_annotation))):\n",
    "        print(f\"Row {i}: ID={gene_annotation['ID'].iloc[i]}, Symbol={gene_annotation['Symbol'].iloc[i]}\")\n",
    "    \n",
    "    # Check the quality and completeness of the mapping\n",
    "    non_null_symbols = gene_annotation['Symbol'].notna().sum()\n",
    "    total_rows = len(gene_annotation)\n",
    "    print(f\"\\nSymbol column completeness: {non_null_symbols}/{total_rows} rows ({non_null_symbols/total_rows:.2%})\")\n",
    "    \n",
    "    # Identify the columns needed for gene mapping\n",
    "    print(\"\\nColumns identified for gene mapping:\")\n",
    "    print(\"- 'ID': Contains Illumina probe IDs (e.g., ILMN_*)\")\n",
    "    print(\"- 'Symbol': Contains gene symbols\")\n",
    "else:\n",
    "    print(\"Error: Required mapping columns ('ID' and/or 'Symbol') not found in annotation data.\")\n",
    "    print(\"Available columns:\", gene_annotation.columns.tolist())\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f60fdb5b",
   "metadata": {},
   "source": [
    "### Step 6: Gene Identifier Mapping"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "0abd3b48",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:28:17.706270Z",
     "iopub.status.busy": "2025-03-25T08:28:17.706149Z",
     "iopub.status.idle": "2025-03-25T08:28:18.789831Z",
     "shell.execute_reply": "2025-03-25T08:28:18.789454Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene mapping dataframe shape: (44837, 2)\n",
      "First 5 rows of gene mapping:\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"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene expression data shape: (47231, 50)\n",
      "Gene data after mapping shape: (21372, 50)\n",
      "First 10 gene symbols after mapping:\n",
      "['A1BG', 'A1CF', 'A26C3', 'A2BP1', 'A2LD1', 'A2M', 'A2ML1', 'A3GALT2', 'A4GALT', 'A4GNT']\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene expression data saved to ../../output/preprocess/Coronary_artery_disease/gene_data/GSE234398.csv\n"
     ]
    }
   ],
   "source": [
    "# 1. Based on the gene annotation data, I see that 'ID' contains Illumina probe IDs (like ILMN_*) which match \n",
    "# the gene identifiers in the gene expression data, and 'Symbol' contains the gene symbols we need to map to.\n",
    "\n",
    "# 2. Extract the two columns from gene annotation for mapping\n",
    "# Get the SOFT and matrix files again (for consistency with previous steps)\n",
    "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
    "\n",
    "# Extract the gene annotation data - already done in previous step\n",
    "# gene_annotation = get_gene_annotation(soft_file)\n",
    "\n",
    "# Get the gene mapping dataframe using the library function\n",
    "gene_mapping = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='Symbol')\n",
    "print(f\"Gene mapping dataframe shape: {gene_mapping.shape}\")\n",
    "print(\"First 5 rows of gene mapping:\")\n",
    "print(gene_mapping.head())\n",
    "\n",
    "# Extract gene expression data - already done in previous step\n",
    "gene_expression = get_genetic_data(matrix_file)\n",
    "print(f\"Gene expression data shape: {gene_expression.shape}\")\n",
    "\n",
    "# 3. Apply gene mapping to convert probe-level measurements to gene expression data\n",
    "gene_data = apply_gene_mapping(gene_expression, gene_mapping)\n",
    "print(f\"Gene data after mapping shape: {gene_data.shape}\")\n",
    "print(\"First 10 gene symbols after mapping:\")\n",
    "print(gene_data.index[:10].tolist())\n",
    "\n",
    "# Save the processed gene data\n",
    "gene_data.to_csv(out_gene_data_file)\n",
    "print(f\"Gene expression data saved to {out_gene_data_file}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "deb34098",
   "metadata": {},
   "source": [
    "### Step 7: Data Normalization and Linking"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "d8b04473",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:28:18.791224Z",
     "iopub.status.busy": "2025-03-25T08:28:18.791103Z",
     "iopub.status.idle": "2025-03-25T08:28:25.771337Z",
     "shell.execute_reply": "2025-03-25T08:28:25.771017Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene data shape before normalization: (21372, 50)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene data saved to ../../output/preprocess/Coronary_artery_disease/gene_data/GSE234398.csv\n",
      "Loaded clinical data shape: (3, 50)\n",
      "Initial linked data shape: (50, 21375)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Linked data shape after handling missing values: (50, 21375)\n",
      "Quartiles for 'Coronary_artery_disease':\n",
      "  25%: 1.0\n",
      "  50% (Median): 1.0\n",
      "  75%: 1.0\n",
      "Min: 1.0\n",
      "Max: 1.0\n",
      "The distribution of the feature 'Coronary_artery_disease' in this dataset is severely biased.\n",
      "\n",
      "Quartiles for 'Age':\n",
      "  25%: 60.0\n",
      "  50% (Median): 67.0\n",
      "  75%: 73.0\n",
      "Min: 39.0\n",
      "Max: 78.0\n",
      "The distribution of the feature 'Age' in this dataset is fine.\n",
      "\n",
      "For the feature 'Gender', the least common label is '0.0' with 22 occurrences. This represents 44.00% of the dataset.\n",
      "The distribution of the feature 'Gender' in this dataset is fine.\n",
      "\n",
      "Data not usable for trait study - not saving final linked data.\n"
     ]
    }
   ],
   "source": [
    "# 1. Attempt to load gene data and handle possible issues with normalization\n",
    "try:\n",
    "    # Create output directory if it doesn't exist\n",
    "    os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
    "    \n",
    "    # Check if gene_data (from previous step) has any content\n",
    "    if gene_data.shape[0] == 0:\n",
    "        print(\"WARNING: Gene data is empty after normalization in previous step.\")\n",
    "        print(\"This appears to be miRNA data rather than gene expression data.\")\n",
    "        \n",
    "        # Since gene_data is empty, set gene_available to False\n",
    "        is_gene_available = False\n",
    "        \n",
    "        # Create an empty dataframe for metadata purposes\n",
    "        empty_df = pd.DataFrame()\n",
    "        \n",
    "        # Log information about this dataset for future reference\n",
    "        validate_and_save_cohort_info(\n",
    "            is_final=True,\n",
    "            cohort=cohort,\n",
    "            info_path=json_path,\n",
    "            is_gene_available=is_gene_available,\n",
    "            is_trait_available=is_trait_available,\n",
    "            is_biased=True,  # Consider it biased as we can't use it\n",
    "            df=empty_df,\n",
    "            note=\"Dataset appears to contain miRNA data rather than gene expression data. Gene symbols could not be normalized.\"\n",
    "        )\n",
    "        \n",
    "        print(\"Dataset marked as unusable due to lack of valid gene expression data.\")\n",
    "    else:\n",
    "        # If gene_data is not empty, proceed with normalization and linking\n",
    "        print(f\"Gene data shape before normalization: {gene_data.shape}\")\n",
    "        \n",
    "        # Save the gene data we have, even if it's already normalized\n",
    "        gene_data.to_csv(out_gene_data_file)\n",
    "        print(f\"Gene data saved to {out_gene_data_file}\")\n",
    "        \n",
    "        # Attempt to link clinical and gene data\n",
    "        if is_trait_available:\n",
    "            # Load clinical data\n",
    "            clinical_features = pd.read_csv(out_clinical_data_file, index_col=0)\n",
    "            print(f\"Loaded clinical data shape: {clinical_features.shape}\")\n",
    "            \n",
    "            # Link the clinical and genetic data\n",
    "            linked_data = geo_link_clinical_genetic_data(clinical_features, gene_data)\n",
    "            print(f\"Initial linked data shape: {linked_data.shape}\")\n",
    "            \n",
    "            # Handle missing values\n",
    "            linked_data = handle_missing_values(linked_data, trait)\n",
    "            print(f\"Linked data shape after handling missing values: {linked_data.shape}\")\n",
    "            \n",
    "            if linked_data.shape[0] > 0:\n",
    "                # Check for bias in trait and demographic features\n",
    "                is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n",
    "                \n",
    "                # Validate data quality 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=is_trait_available,\n",
    "                    is_biased=is_biased,\n",
    "                    df=linked_data,\n",
    "                    note=\"Successfully processed gene expression data for coronary artery disease.\"\n",
    "                )\n",
    "                \n",
    "                # Save the linked data if it's 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(\"Data not usable for trait study - not saving final linked data.\")\n",
    "            else:\n",
    "                print(\"After handling missing values, no samples remain.\")\n",
    "                validate_and_save_cohort_info(\n",
    "                    is_final=True,\n",
    "                    cohort=cohort,\n",
    "                    info_path=json_path,\n",
    "                    is_gene_available=is_gene_available,\n",
    "                    is_trait_available=is_trait_available,\n",
    "                    is_biased=True,\n",
    "                    df=pd.DataFrame(),\n",
    "                    note=\"No valid samples after handling missing values.\"\n",
    "                )\n",
    "        else:\n",
    "            # Cannot proceed with linking if trait data is missing\n",
    "            validate_and_save_cohort_info(\n",
    "                is_final=True,\n",
    "                cohort=cohort,\n",
    "                info_path=json_path,\n",
    "                is_gene_available=is_gene_available,\n",
    "                is_trait_available=is_trait_available,\n",
    "                is_biased=True,\n",
    "                df=pd.DataFrame(),\n",
    "                note=\"Cannot link data because trait information is not available.\"\n",
    "            )\n",
    "except Exception as e:\n",
    "    print(f\"Error in data processing: {e}\")\n",
    "    \n",
    "    # Log the error and mark the dataset as unusable\n",
    "    validate_and_save_cohort_info(\n",
    "        is_final=True,\n",
    "        cohort=cohort,\n",
    "        info_path=json_path,\n",
    "        is_gene_available=False,  # Consider gene data unavailable if we had an error\n",
    "        is_trait_available=is_trait_available,\n",
    "        is_biased=True,  # Consider it biased as we can't use it\n",
    "        df=pd.DataFrame(),  # Empty dataframe for metadata\n",
    "        note=f\"Error during normalization or linking: {str(e)}\"\n",
    "    )"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.16"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}