File size: 35,574 Bytes
92d2f89
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "107b8644",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T07:05:40.011432Z",
     "iopub.status.busy": "2025-03-25T07:05:40.011200Z",
     "iopub.status.idle": "2025-03-25T07:05:40.180428Z",
     "shell.execute_reply": "2025-03-25T07:05:40.180079Z"
    }
   },
   "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 = \"Cardiovascular_Disease\"\n",
    "cohort = \"GSE182600\"\n",
    "\n",
    "# Input paths\n",
    "in_trait_dir = \"../../input/GEO/Cardiovascular_Disease\"\n",
    "in_cohort_dir = \"../../input/GEO/Cardiovascular_Disease/GSE182600\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/Cardiovascular_Disease/GSE182600.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/Cardiovascular_Disease/gene_data/GSE182600.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/Cardiovascular_Disease/clinical_data/GSE182600.csv\"\n",
    "json_path = \"../../output/preprocess/Cardiovascular_Disease/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a55e6232",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "950689ab",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T07:05:40.181866Z",
     "iopub.status.busy": "2025-03-25T07:05:40.181720Z",
     "iopub.status.idle": "2025-03-25T07:05:40.366619Z",
     "shell.execute_reply": "2025-03-25T07:05:40.366264Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Background Information:\n",
      "!Series_title\t\"Gene Expression of Cardiogenic Shock Patients under Extracorporeal Membrane Oxygenation\"\n",
      "!Series_summary\t\"Prognosis for cardiogenic shock patients under ECMO was our study goal. Success defined as survived more than 7 days after ECMO installation and failure died or had multiple organ failure in 7 days. Total 34 cases were enrolled, 17 success and 17 failure.\"\n",
      "!Series_summary\t\"Peripheral blood mononuclear cells collected at ECMO installation 0hr, 2hr and removal were used analyzed.\"\n",
      "!Series_overall_design\t\"Analysis of the cardiogenic shock patients at extracorporeal membrane oxygenation treatment by genome-wide gene expression. Transcriptomic profiling between successful and failure groups were analyzed.\"\n",
      "Sample Characteristics Dictionary:\n",
      "{0: ['disease state: Acute myocarditis', 'disease state: Acute myocardial infarction', 'disease state: Dilated cardiomyopathy, DCMP', 'disease state: Congestive heart failure', 'disease state: Dilated cardiomyopathy', 'disease state: Arrhythmia', 'disease state: Aortic dissection'], 1: ['age: 33.4', 'age: 51.2', 'age: 51.9', 'age: 47.8', 'age: 41.5', 'age: 67.3', 'age: 52.8', 'age: 16.1', 'age: 78.9', 'age: 53.2', 'age: 70.9', 'age: 59.9', 'age: 21.9', 'age: 45.2', 'age: 52.4', 'age: 32.3', 'age: 55.8', 'age: 47', 'age: 57.3', 'age: 31.7', 'age: 49.3', 'age: 66.1', 'age: 55.9', 'age: 49.1', 'age: 63', 'age: 21', 'age: 53.6', 'age: 50.1', 'age: 37.4', 'age: 71.5'], 2: ['gender: F', 'gender: M'], 3: ['outcome: Success', 'outcome: Failure', 'outcome: failure'], 4: ['cell type: PBMC'], 5: ['time: 0hr', 'time: 2hr', 'time: Removal']}\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": "73100bcd",
   "metadata": {},
   "source": [
    "### Step 2: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "8c027350",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T07:05:40.367843Z",
     "iopub.status.busy": "2025-03-25T07:05:40.367734Z",
     "iopub.status.idle": "2025-03-25T07:05:40.377936Z",
     "shell.execute_reply": "2025-03-25T07:05:40.377634Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Preview of extracted clinical features:\n",
      "{'Cardiovascular_Disease': [0.0, 1.0, 1.0, nan, nan], 'Age': [33.4, 51.2, 51.9, 47.8, 41.5], 'Gender': [0.0, 1.0, nan, nan, nan]}\n",
      "Clinical data saved to: ../../output/preprocess/Cardiovascular_Disease/clinical_data/GSE182600.csv\n"
     ]
    }
   ],
   "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "import os\n",
    "import json\n",
    "from typing import Callable, Optional, Dict, Any\n",
    "\n",
    "# 1. Gene Expression Data Availability\n",
    "# Based on the background info, this dataset likely contains gene expression data from PBMCs\n",
    "is_gene_available = True\n",
    "\n",
    "# 2. Variable Availability and Data Type Conversion\n",
    "# 2.1 Data Availability\n",
    "\n",
    "# Trait: Cardiovascular disease outcome, available at key 3\n",
    "trait_row = 3\n",
    "\n",
    "# Age: Available at key 1\n",
    "age_row = 1\n",
    "\n",
    "# Gender: Available at key 2\n",
    "gender_row = 2\n",
    "\n",
    "# 2.2 Data Type Conversion\n",
    "\n",
    "def convert_trait(value):\n",
    "    \"\"\"Convert trait values to binary (0 for success, 1 for failure)\"\"\"\n",
    "    if value is None:\n",
    "        return None\n",
    "    \n",
    "    # Extract value after colon if it exists\n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip()\n",
    "    \n",
    "    # Convert to binary\n",
    "    if value.lower() == 'success':\n",
    "        return 0\n",
    "    elif value.lower() in ['failure', 'fail']:\n",
    "        return 1\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "def convert_age(value):\n",
    "    \"\"\"Convert age values to continuous numeric values\"\"\"\n",
    "    if value is None:\n",
    "        return None\n",
    "    \n",
    "    # Extract value after colon if it exists\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_gender(value):\n",
    "    \"\"\"Convert gender values to binary (0 for female, 1 for male)\"\"\"\n",
    "    if value is None:\n",
    "        return None\n",
    "    \n",
    "    # Extract value after colon if it exists\n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip()\n",
    "    \n",
    "    # Convert to binary\n",
    "    if value.upper() == 'F':\n",
    "        return 0\n",
    "    elif value.upper() == 'M':\n",
    "        return 1\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "# 3. Save Metadata\n",
    "# Determine trait data availability\n",
    "is_trait_available = trait_row is not None\n",
    "\n",
    "# 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",
    "if trait_row is not None:\n",
    "    # Create a DataFrame from the sample characteristics dictionary\n",
    "    # First, we need to create a function to get feature data since we're not using the normal workflow\n",
    "    def get_feature_data(clinical_dict, row_idx, feature_name, convert_func):\n",
    "        if row_idx is None or row_idx not in clinical_dict:\n",
    "            return pd.DataFrame()\n",
    "        \n",
    "        raw_values = clinical_dict[row_idx]\n",
    "        processed_values = [convert_func(val) for val in raw_values]\n",
    "        \n",
    "        # Create a dataframe with sample IDs as columns and feature as rows\n",
    "        feature_df = pd.DataFrame([processed_values], columns=[f\"Sample_{i+1}\" for i in range(len(processed_values))])\n",
    "        feature_df.index = [feature_name]\n",
    "        \n",
    "        return feature_df\n",
    "    \n",
    "    # Sample characteristics dictionary from the previous step output\n",
    "    sample_chars_dict = {\n",
    "        0: ['disease state: Acute myocarditis', 'disease state: Acute myocardial infarction', 'disease state: Dilated cardiomyopathy, DCMP', 'disease state: Congestive heart failure', 'disease state: Dilated cardiomyopathy', 'disease state: Arrhythmia', 'disease state: Aortic dissection'],\n",
    "        1: ['age: 33.4', 'age: 51.2', 'age: 51.9', 'age: 47.8', 'age: 41.5', 'age: 67.3', 'age: 52.8', 'age: 16.1', 'age: 78.9', 'age: 53.2', 'age: 70.9', 'age: 59.9', 'age: 21.9', 'age: 45.2', 'age: 52.4', 'age: 32.3', 'age: 55.8', 'age: 47', 'age: 57.3', 'age: 31.7', 'age: 49.3', 'age: 66.1', 'age: 55.9', 'age: 49.1', 'age: 63', 'age: 21', 'age: 53.6', 'age: 50.1', 'age: 37.4', 'age: 71.5'],\n",
    "        2: ['gender: F', 'gender: M'],\n",
    "        3: ['outcome: Success', 'outcome: Failure', 'outcome: failure'],\n",
    "        4: ['cell type: PBMC'],\n",
    "        5: ['time: 0hr', 'time: 2hr', 'time: Removal']\n",
    "    }\n",
    "    \n",
    "    # Create feature DataFrames\n",
    "    feature_list = []\n",
    "    trait_data = get_feature_data(sample_chars_dict, trait_row, trait, convert_trait)\n",
    "    feature_list.append(trait_data)\n",
    "    \n",
    "    if age_row is not None:\n",
    "        age_data = get_feature_data(sample_chars_dict, age_row, 'Age', convert_age)\n",
    "        feature_list.append(age_data)\n",
    "    \n",
    "    if gender_row is not None:\n",
    "        gender_data = get_feature_data(sample_chars_dict, gender_row, 'Gender', convert_gender)\n",
    "        feature_list.append(gender_data)\n",
    "    \n",
    "    # Combine all features\n",
    "    selected_clinical_df = pd.concat(feature_list, axis=0)\n",
    "    \n",
    "    # Transpose the DataFrame to have samples as rows and features as columns\n",
    "    selected_clinical_df = selected_clinical_df.transpose()\n",
    "    \n",
    "    # Preview the result\n",
    "    print(\"Preview of extracted clinical features:\")\n",
    "    preview = preview_df(selected_clinical_df)\n",
    "    print(preview)\n",
    "    \n",
    "    # Save 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=True)\n",
    "    print(f\"Clinical data saved to: {out_clinical_data_file}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5af853f3",
   "metadata": {},
   "source": [
    "### Step 3: Gene Data Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "4211b7a4",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T07:05:40.379081Z",
     "iopub.status.busy": "2025-03-25T07:05:40.378966Z",
     "iopub.status.idle": "2025-03-25T07:05:40.716395Z",
     "shell.execute_reply": "2025-03-25T07:05:40.716003Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Matrix file found: ../../input/GEO/Cardiovascular_Disease/GSE182600/GSE182600_series_matrix.txt.gz\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene data shape: (29363, 78)\n",
      "First 20 gene/probe identifiers:\n",
      "Index(['ILMN_1343291', 'ILMN_1651209', 'ILMN_1651228', 'ILMN_1651229',\n",
      "       'ILMN_1651235', 'ILMN_1651236', 'ILMN_1651237', 'ILMN_1651238',\n",
      "       'ILMN_1651254', 'ILMN_1651260', 'ILMN_1651262', 'ILMN_1651268',\n",
      "       'ILMN_1651278', 'ILMN_1651282', 'ILMN_1651285', 'ILMN_1651286',\n",
      "       'ILMN_1651292', 'ILMN_1651303', 'ILMN_1651309', 'ILMN_1651315'],\n",
      "      dtype='object', name='ID')\n"
     ]
    }
   ],
   "source": [
    "# 1. Get the SOFT and matrix file paths again \n",
    "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
    "print(f\"Matrix file found: {matrix_file}\")\n",
    "\n",
    "# 2. Use the get_genetic_data function from the library to get the gene_data\n",
    "try:\n",
    "    gene_data = get_genetic_data(matrix_file)\n",
    "    print(f\"Gene data shape: {gene_data.shape}\")\n",
    "    \n",
    "    # 3. Print the first 20 row IDs (gene or probe identifiers)\n",
    "    print(\"First 20 gene/probe identifiers:\")\n",
    "    print(gene_data.index[:20])\n",
    "except Exception as e:\n",
    "    print(f\"Error extracting gene data: {e}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fa109453",
   "metadata": {},
   "source": [
    "### Step 4: Gene Identifier Review"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "d4c866b4",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T07:05:40.717746Z",
     "iopub.status.busy": "2025-03-25T07:05:40.717624Z",
     "iopub.status.idle": "2025-03-25T07:05:40.719630Z",
     "shell.execute_reply": "2025-03-25T07:05:40.719339Z"
    }
   },
   "outputs": [],
   "source": [
    "# Looking at the gene identifiers, I can see they are ILMN_* format\n",
    "# These are Illumina probe IDs (BeadArray technology), not human gene symbols\n",
    "# They will need to be mapped to standard gene symbols for analysis\n",
    "\n",
    "requires_gene_mapping = True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "62f41cf3",
   "metadata": {},
   "source": [
    "### Step 5: Gene Annotation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "1d132180",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T07:05:40.720805Z",
     "iopub.status.busy": "2025-03-25T07:05:40.720700Z",
     "iopub.status.idle": "2025-03-25T07:05:45.411148Z",
     "shell.execute_reply": "2025-03-25T07:05:45.410749Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "Gene annotation preview:\n",
      "Columns in gene annotation: ['ID', 'Transcript', 'Species', 'Source', 'Search_Key', 'ILMN_Gene', 'Source_Reference_ID', 'RefSeq_ID', 'Entrez_Gene_ID', 'GI', 'Accession', 'Symbol', 'Protein_Product', '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_3166687', 'ILMN_3165566', 'ILMN_3164811', 'ILMN_3165363', 'ILMN_3166511'], 'Transcript': ['ILMN_333737', 'ILMN_333646', 'ILMN_333584', 'ILMN_333628', 'ILMN_333719'], 'Species': ['ILMN Controls', 'ILMN Controls', 'ILMN Controls', 'ILMN Controls', 'ILMN Controls'], 'Source': ['ILMN_Controls', 'ILMN_Controls', 'ILMN_Controls', 'ILMN_Controls', 'ILMN_Controls'], 'Search_Key': ['ERCC-00162', 'ERCC-00071', 'ERCC-00009', 'ERCC-00053', 'ERCC-00144'], 'ILMN_Gene': ['ERCC-00162', 'ERCC-00071', 'ERCC-00009', 'ERCC-00053', 'ERCC-00144'], 'Source_Reference_ID': ['ERCC-00162', 'ERCC-00071', 'ERCC-00009', 'ERCC-00053', 'ERCC-00144'], 'RefSeq_ID': [nan, nan, nan, nan, nan], 'Entrez_Gene_ID': [nan, nan, nan, nan, nan], 'GI': [nan, nan, nan, nan, nan], 'Accession': ['DQ516750', 'DQ883654', 'DQ668364', 'DQ516785', 'DQ854995'], 'Symbol': ['ERCC-00162', 'ERCC-00071', 'ERCC-00009', 'ERCC-00053', 'ERCC-00144'], 'Protein_Product': [nan, nan, nan, nan, nan], 'Array_Address_Id': [5270161.0, 4260594.0, 7610424.0, 5260356.0, 2030196.0], 'Probe_Type': ['S', 'S', 'S', 'S', 'S'], 'Probe_Start': [12.0, 224.0, 868.0, 873.0, 130.0], 'SEQUENCE': ['CCCATGTGTCCAATTCTGAATATCTTTCCAGCTAAGTGCTTCTGCCCACC', 'GGATTAACTGCTGTGGTGTGTCATACTCGGCTACCTCCTGGTTTGGCGTC', 'GACCACGCCTTGTAATCGTATGACACGCGCTTGACACGACTGAATCCAGC', 'CTGCAATGCCATTAACAACCTTAGCACGGTATTTCCAGTAGCTGGTGAGC', 'CGTGCAGACAGGGATCGTAAGGCGATCCAGCCGGTATACCTTAGTCACAT'], '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': ['Methanocaldococcus jannaschii spike-in control MJ-500-33 genomic sequence', 'Synthetic construct clone NISTag13 external RNA control sequence', 'Synthetic construct clone TagJ microarray control', 'Methanocaldococcus jannaschii spike-in control MJ-1000-68 genomic sequence', 'Synthetic construct clone AG006.1100 external RNA control sequence'], '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': ['DQ516750', 'DQ883654', 'DQ668364', 'DQ516785', 'DQ854995']}\n",
      "\n",
      "Searching for platform information in SOFT file:\n",
      "Platform ID not found in first 100 lines\n",
      "\n",
      "Searching for gene symbol information in SOFT file:\n",
      "Found references to gene symbols:\n",
      "#ILMN_Gene = Internal gene symbol\n",
      "#Symbol = Gene symbol from the source database\n",
      "#Synonyms = Gene symbol synonyms from Refseq\n",
      "ID\tTranscript\tSpecies\tSource\tSearch_Key\tILMN_Gene\tSource_Reference_ID\tRefSeq_ID\tEntrez_Gene_ID\tGI\tAccession\tSymbol\tProtein_Product\tArray_Address_Id\tProbe_Type\tProbe_Start\tSEQUENCE\tChromosome\tProbe_Chr_Orientation\tProbe_Coordinates\tCytoband\tDefinition\tOntology_Component\tOntology_Process\tOntology_Function\tSynonyms\tObsolete_Probe_Id\tGB_ACC\n",
      "ILMN_1713086\tILMN_139166\tHomo sapiens\tRefSeq\tNM_000990.2\tRPL27A\tNM_000990.2\tNM_000990.2\t6157\t14141189\tNM_000990.2\tRPL27A\tNP_000981.1\t4920193\tS\t27\tCATCCAGACTGAGGAAGACCCGGAAACTTAGGGGCCACGTGAGCCACGGC\t11\t+\t8661326-8661375\t11p15.4b\tHomo sapiens ribosomal protein L27a (RPL27A), mRNA.\tThe living contents of a cell; the matter contained within (but not including) the plasma membrane, usually taken to exclude large vacuoles and masses of secretory or ingested material. In eukaryotes it includes the nucleus and cytoplasm [goid 5622] [evidence IEA]; That part of the cytoplasm that does not contain membranous or particulate subcellular components [goid 5829] [pmid 14567916] [evidence EXP]; An intracellular organelle, about 200 A in diameter, consisting of RNA and protein. It is the site of protein biosynthesis resulting from translation of messenger RNA (mRNA). It consists of two subunits, one large and one small, each containing only protein and RNA. Both the ribosome and its subunits are characterized by their sedimentation coefficients, expressed in Svedberg units (symbol: S). Hence, the prokaryotic ribosome (70S) comprises a large (50S) subunit and a small (30S) subunit, while the eukaryotic ribosome (80S) comprises a large (60S) subunit and a small (40S) subunit. Two sites on the ribosomal large subunit are involved in translation, namely the aminoacyl site (A site) and peptidyl site (P site). Ribosomes from prokaryotes, eukaryotes, mitochondria, and chloroplasts have characteristically distinct ribosomal proteins [goid 5840] [evidence IEA]; The large subunit of the ribosome that is found in the cytosol of the cell. The cytosol is that part of the cytoplasm that does not contain membranous or particulate subcellular components [goid 22625] [pmid 7772601] [evidence TAS]\tThe successive addition of amino acid residues to a nascent polypeptide chain during protein biosynthesis [goid 6414] [pmid 15189156] [evidence EXP]\tInteracting selectively with an RNA molecule or a portion thereof [goid 3723] [pmid 7772601] [evidence TAS]; The action of a molecule that contributes to the structural integrity of the ribosome [goid 3735] [pmid 7772601] [evidence TAS]\tMGC87238\tMGC87238\tNM_000990.2\n",
      "\n",
      "Checking for additional annotation files in the directory:\n",
      "[]\n"
     ]
    }
   ],
   "source": [
    "# 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.\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=5))\n",
    "\n",
    "# Let's look for platform information in the SOFT file to understand the annotation better\n",
    "print(\"\\nSearching for platform information in SOFT file:\")\n",
    "with gzip.open(soft_file, 'rt') as f:\n",
    "    for i, line in enumerate(f):\n",
    "        if '!Series_platform_id' in line:\n",
    "            print(line.strip())\n",
    "            break\n",
    "        if i > 100:  # Limit search to first 100 lines\n",
    "            print(\"Platform ID not found in first 100 lines\")\n",
    "            break\n",
    "\n",
    "# Check if the SOFT file includes any reference to gene symbols\n",
    "print(\"\\nSearching for gene symbol information in SOFT file:\")\n",
    "with gzip.open(soft_file, 'rt') as f:\n",
    "    gene_symbol_lines = []\n",
    "    for i, line in enumerate(f):\n",
    "        if 'GENE_SYMBOL' in line or 'gene_symbol' in line.lower() or 'symbol' in line.lower():\n",
    "            gene_symbol_lines.append(line.strip())\n",
    "        if i > 1000 and len(gene_symbol_lines) > 0:  # Limit search but ensure we found something\n",
    "            break\n",
    "    \n",
    "    if gene_symbol_lines:\n",
    "        print(\"Found references to gene symbols:\")\n",
    "        for line in gene_symbol_lines[:5]:  # Show just first 5 matches\n",
    "            print(line)\n",
    "    else:\n",
    "        print(\"No explicit gene symbol references found in first 1000 lines\")\n",
    "\n",
    "# Look for alternative annotation files or references in the directory\n",
    "print(\"\\nChecking for additional annotation files in the directory:\")\n",
    "all_files = os.listdir(in_cohort_dir)\n",
    "print([f for f in all_files if 'annotation' in f.lower() or 'platform' in f.lower() or 'gpl' in f.lower()])\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7197d9ce",
   "metadata": {},
   "source": [
    "### Step 6: Gene Identifier Mapping"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "0b04f770",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T07:05:45.412543Z",
     "iopub.status.busy": "2025-03-25T07:05:45.412416Z",
     "iopub.status.idle": "2025-03-25T07:05:46.841560Z",
     "shell.execute_reply": "2025-03-25T07:05:46.841162Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "Identifying mapping columns:\n",
      "Probe ID column: 'ID'\n",
      "Gene Symbol column: 'Symbol'\n",
      "\n",
      "Preview of gene mapping data:\n",
      "{'ID': ['ILMN_3166687', 'ILMN_3165566', 'ILMN_3164811', 'ILMN_3165363', 'ILMN_3166511'], 'Gene': ['ERCC-00162', 'ERCC-00071', 'ERCC-00009', 'ERCC-00053', 'ERCC-00144']}\n",
      "Gene mapping shape: (29377, 2)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "Preview of resulting gene expression data:\n",
      "Gene data shape after mapping: (20206, 78)\n",
      "First 10 gene symbols: ['A1BG', 'A1CF', 'A26C3', 'A2BP1', 'A2LD1', 'A2M', 'A2ML1', 'A3GALT2', 'A4GALT', 'A4GNT']\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "Gene expression data saved to: ../../output/preprocess/Cardiovascular_Disease/gene_data/GSE182600.csv\n"
     ]
    }
   ],
   "source": [
    "# 1. Identify which columns to use for gene mapping\n",
    "# From the preview, we can see that 'ID' contains the ILMN_* identifiers matching gene_data's index\n",
    "# 'Symbol' contains the gene symbols we want to map to\n",
    "print(\"\\nIdentifying mapping columns:\")\n",
    "print(f\"Probe ID column: 'ID'\")\n",
    "print(f\"Gene Symbol column: 'Symbol'\")\n",
    "\n",
    "# 2. Create a gene mapping dataframe using the get_gene_mapping function\n",
    "gene_mapping = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='Symbol')\n",
    "\n",
    "# Preview the mapping data\n",
    "print(\"\\nPreview of gene mapping data:\")\n",
    "print(preview_df(gene_mapping))\n",
    "print(f\"Gene mapping shape: {gene_mapping.shape}\")\n",
    "\n",
    "# 3. Apply the gene mapping to convert probe-level measurements to gene expression data\n",
    "gene_data = apply_gene_mapping(gene_data, gene_mapping)\n",
    "\n",
    "# Preview the results\n",
    "print(\"\\nPreview of resulting gene expression data:\")\n",
    "print(f\"Gene data shape after mapping: {gene_data.shape}\")\n",
    "print(f\"First 10 gene symbols: {gene_data.index[:10].tolist()}\")\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\"\\nGene expression data saved to: {out_gene_data_file}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "aa603511",
   "metadata": {},
   "source": [
    "### Step 7: Data Normalization and Linking"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "4004cfe4",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T07:05:46.842991Z",
     "iopub.status.busy": "2025-03-25T07:05:46.842876Z",
     "iopub.status.idle": "2025-03-25T07:05:59.283816Z",
     "shell.execute_reply": "2025-03-25T07:05:59.283359Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene data shape after normalization: (19445, 78)\n",
      "First 10 normalized gene symbols: ['A1BG', 'A1BG-AS1', 'A1CF', 'A2M', 'A2ML1', 'A3GALT2', 'A4GALT', 'A4GNT', 'AAA1', 'AAAS']\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Normalized gene data saved to: ../../output/preprocess/Cardiovascular_Disease/gene_data/GSE182600.csv\n",
      "Clinical features saved to: ../../output/preprocess/Cardiovascular_Disease/clinical_data/GSE182600.csv\n",
      "Clinical features preview (transposed):\n",
      "{'Cardiovascular_Disease': [0.0, 0.0, 1.0, 0.0, 1.0], 'Age': [33.4, 51.2, 51.9, 47.8, 41.5], 'Gender': [0.0, 1.0, 0.0, 1.0, 0.0]}\n",
      "Linked data shape: (78, 19448)\n",
      "Linked data preview (first 5 rows, 5 columns):\n",
      "            Cardiovascular_Disease   Age  Gender        A1BG     A1BG-AS1\n",
      "GSM5532093                     0.0  33.4     0.0  123.145500  1284.286536\n",
      "GSM5532094                     0.0  51.2     1.0  134.323626  2123.843378\n",
      "GSM5532095                     1.0  51.9     0.0  100.294706  1088.857429\n",
      "GSM5532096                     0.0  47.8     1.0  130.315854  1074.517347\n",
      "GSM5532097                     1.0  41.5     0.0  106.890941  1070.809003\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Linked data shape after handling missing values: (78, 19448)\n",
      "For the feature 'Cardiovascular_Disease', the least common label is '1.0' with 31 occurrences. This represents 39.74% of the dataset.\n",
      "The distribution of the feature 'Cardiovascular_Disease' in this dataset is fine.\n",
      "\n",
      "Quartiles for 'Age':\n",
      "  25%: 47.0\n",
      "  50% (Median): 52.15\n",
      "  75%: 56.35\n",
      "Min: 16.1\n",
      "Max: 78.9\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 24 occurrences. This represents 30.77% of the dataset.\n",
      "The distribution of the feature 'Gender' in this dataset is fine.\n",
      "\n",
      "A new JSON file was created at: ../../output/preprocess/Cardiovascular_Disease/cohort_info.json\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Linked data saved to ../../output/preprocess/Cardiovascular_Disease/GSE182600.csv\n"
     ]
    }
   ],
   "source": [
    "# 1. Normalize gene symbols in the gene expression data\n",
    "gene_data_normalized = normalize_gene_symbols_in_index(gene_data)\n",
    "print(f\"Gene data shape after normalization: {gene_data_normalized.shape}\")\n",
    "print(f\"First 10 normalized gene symbols: {gene_data_normalized.index[:10].tolist()}\")\n",
    "\n",
    "# Save the normalized gene data\n",
    "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
    "gene_data_normalized.to_csv(out_gene_data_file)\n",
    "print(f\"Normalized gene data saved to: {out_gene_data_file}\")\n",
    "\n",
    "# 2. Re-extract the clinical data directly from the source\n",
    "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
    "background_info, clinical_data = get_background_and_clinical_data(matrix_file)\n",
    "\n",
    "# Define conversion functions based on previous analysis\n",
    "def convert_trait(value):\n",
    "    \"\"\"Convert trait values to binary (0 for success, 1 for failure)\"\"\"\n",
    "    if value is None or pd.isna(value):\n",
    "        return None\n",
    "    \n",
    "    # Extract value after colon if it exists\n",
    "    if isinstance(value, str) and ':' in value:\n",
    "        value = value.split(':', 1)[1].strip()\n",
    "    \n",
    "    # Convert to binary\n",
    "    if value.lower() == 'success':\n",
    "        return 0\n",
    "    elif value.lower() in ['failure', 'fail']:\n",
    "        return 1\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "def convert_age(value):\n",
    "    \"\"\"Convert age values to continuous numeric values\"\"\"\n",
    "    if value is None or pd.isna(value):\n",
    "        return None\n",
    "    \n",
    "    # Extract value after colon if it exists\n",
    "    if isinstance(value, str) and ':' 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_gender(value):\n",
    "    \"\"\"Convert gender values to binary (0 for female, 1 for male)\"\"\"\n",
    "    if value is None or pd.isna(value):\n",
    "        return None\n",
    "    \n",
    "    # Extract value after colon if it exists\n",
    "    if isinstance(value, str) and ':' in value:\n",
    "        value = value.split(':', 1)[1].strip()\n",
    "    \n",
    "    # Convert to binary\n",
    "    if value.upper() == 'F':\n",
    "        return 0\n",
    "    elif value.upper() == 'M':\n",
    "        return 1\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "# Use the correct row indices from previous analysis\n",
    "trait_row = 3  # outcome\n",
    "age_row = 1    # age\n",
    "gender_row = 2 # gender\n",
    "\n",
    "# Extract clinical features\n",
    "clinical_features = geo_select_clinical_features(\n",
    "    clinical_data,\n",
    "    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 - make sure to transpose it so samples are rows, not columns\n",
    "clinical_features_t = clinical_features.T  # Transpose for proper format\n",
    "clinical_features_t.to_csv(out_clinical_data_file)\n",
    "print(f\"Clinical features saved to: {out_clinical_data_file}\")\n",
    "print(\"Clinical features preview (transposed):\")\n",
    "print(preview_df(clinical_features_t))\n",
    "\n",
    "# 3. Link clinical and genetic data - use the transposed clinical data\n",
    "linked_data = pd.merge(\n",
    "    clinical_features_t, \n",
    "    gene_data_normalized.T,  # Transpose gene data so genes are columns\n",
    "    left_index=True, \n",
    "    right_index=True,\n",
    "    how='inner'\n",
    ")\n",
    "\n",
    "print(f\"Linked data shape: {linked_data.shape}\")\n",
    "print(\"Linked data preview (first 5 rows, 5 columns):\")\n",
    "preview_cols = min(5, linked_data.shape[1])\n",
    "print(linked_data.iloc[:5, :preview_cols])\n",
    "\n",
    "# 4. Handle missing values\n",
    "linked_data_clean = handle_missing_values(linked_data, trait)\n",
    "print(f\"Linked data shape after handling missing values: {linked_data_clean.shape}\")\n",
    "\n",
    "# 5. Check for bias in the dataset\n",
    "is_biased, linked_data_clean = judge_and_remove_biased_features(linked_data_clean, trait)\n",
    "\n",
    "# 6. Conduct final quality validation\n",
    "note = \"Dataset contains gene expression data from PBMCs of cardiogenic shock patients under ECMO treatment, comparing successful and failed outcomes.\"\n",
    "is_usable = validate_and_save_cohort_info(\n",
    "    is_final=True,\n",
    "    cohort=cohort,\n",
    "    info_path=json_path,\n",
    "    is_gene_available=True,\n",
    "    is_trait_available=True,\n",
    "    is_biased=is_biased,\n",
    "    df=linked_data_clean,\n",
    "    note=note\n",
    ")\n",
    "\n",
    "# 7. 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_clean.to_csv(out_data_file, index=True)\n",
    "    print(f\"Linked data saved to {out_data_file}\")\n",
    "else:\n",
    "    print(\"Dataset deemed not usable for associative studies. Linked data not saved.\")"
   ]
  }
 ],
 "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
}