File size: 37,047 Bytes
736e4a0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "2f7717e3",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:55:03.345212Z",
     "iopub.status.busy": "2025-03-25T06:55:03.344978Z",
     "iopub.status.idle": "2025-03-25T06:55:03.515957Z",
     "shell.execute_reply": "2025-03-25T06:55:03.515497Z"
    }
   },
   "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 = \"Bipolar_disorder\"\n",
    "cohort = \"GSE45484\"\n",
    "\n",
    "# Input paths\n",
    "in_trait_dir = \"../../input/GEO/Bipolar_disorder\"\n",
    "in_cohort_dir = \"../../input/GEO/Bipolar_disorder/GSE45484\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/Bipolar_disorder/GSE45484.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/Bipolar_disorder/gene_data/GSE45484.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/Bipolar_disorder/clinical_data/GSE45484.csv\"\n",
    "json_path = \"../../output/preprocess/Bipolar_disorder/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "956aebd4",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "60868666",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:55:03.517485Z",
     "iopub.status.busy": "2025-03-25T06:55:03.517333Z",
     "iopub.status.idle": "2025-03-25T06:55:03.751405Z",
     "shell.execute_reply": "2025-03-25T06:55:03.750905Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Background Information:\n",
      "!Series_title\t\"Gene-expression differences in peripheral blood between lithium responders and non-responders in the “Lithium Treatment -Moderate dose Use Study” (LiTMUS)\"\n",
      "!Series_summary\t\"Analysis of gene-expression changes in treatment responders vs non-responders to two different treatments among subjectrs participating in LiTMUS.\"\n",
      "!Series_summary\t\"Results provide information on pathways that may be involved in the clinical response to Lithium in patients with bipolar disorder.\"\n",
      "!Series_overall_design\t\"Total RNA isolated from PAXgene blood RNA tubes from 60 subjects with bipolar disorder, randomized to 2 treatment groups (OPT, Li+OPT) at 2 time-points (baseline, 1 month after treatment)\"\n",
      "Sample Characteristics Dictionary:\n",
      "{0: ['treatment group: OPT', 'treatment group: Li+OPT'], 1: ['time point: baseline', 'time point: 1 month'], 2: ['responder: NO', 'responder: YES'], 3: ['sex: M', 'sex: F'], 4: ['age: 46', 'age: 44', 'age: 59', 'age: 32', 'age: 45', 'age: 25', 'age: 26', 'age: 43', 'age: 24', 'age: 38', 'age: 47', 'age: 37', 'age: 57', 'age: 23', 'age: 30', 'age: 51', 'age: 35', 'age: 64', 'age: 53', 'age: 61', 'age: 39', 'age: 36', 'age: 18', 'age: 20', 'age: 27', 'age: 49', 'age: 29', 'age: 40', 'age: 41', 'age: 31']}\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": "7ba38fa7",
   "metadata": {},
   "source": [
    "### Step 2: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "06628229",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:55:03.752948Z",
     "iopub.status.busy": "2025-03-25T06:55:03.752831Z",
     "iopub.status.idle": "2025-03-25T06:55:03.769937Z",
     "shell.execute_reply": "2025-03-25T06:55:03.769497Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Clinical Data Preview:\n",
      "{'GSM1105438': [0.0, 46.0, 1.0], 'GSM1105439': [0.0, 44.0, 0.0], 'GSM1105440': [0.0, 46.0, 1.0], 'GSM1105441': [0.0, 44.0, 0.0], 'GSM1105442': [0.0, 59.0, 1.0], 'GSM1105443': [0.0, 32.0, 0.0], 'GSM1105444': [0.0, 59.0, 1.0], 'GSM1105445': [0.0, 32.0, 0.0], 'GSM1105446': [0.0, 45.0, 0.0], 'GSM1105447': [0.0, 25.0, 0.0], 'GSM1105448': [0.0, 45.0, 0.0], 'GSM1105449': [0.0, 25.0, 0.0], 'GSM1105450': [1.0, 25.0, 0.0], 'GSM1105451': [1.0, 26.0, 0.0], 'GSM1105452': [1.0, 25.0, 0.0], 'GSM1105453': [1.0, 26.0, 0.0], 'GSM1105454': [1.0, 43.0, 1.0], 'GSM1105455': [0.0, 24.0, 0.0], 'GSM1105456': [1.0, 43.0, 1.0], 'GSM1105457': [0.0, 24.0, 0.0], 'GSM1105458': [0.0, 43.0, 1.0], 'GSM1105459': [0.0, 43.0, 0.0], 'GSM1105460': [0.0, 43.0, 1.0], 'GSM1105461': [0.0, 43.0, 0.0], 'GSM1105462': [0.0, 38.0, 0.0], 'GSM1105463': [0.0, 47.0, 1.0], 'GSM1105464': [0.0, 38.0, 0.0], 'GSM1105465': [0.0, 47.0, 1.0], 'GSM1105466': [1.0, 37.0, 1.0], 'GSM1105467': [0.0, 57.0, 0.0], 'GSM1105468': [1.0, 37.0, 1.0], 'GSM1105469': [0.0, 57.0, 0.0], 'GSM1105470': [0.0, 23.0, 0.0], 'GSM1105471': [0.0, 57.0, 0.0], 'GSM1105472': [0.0, 23.0, 0.0], 'GSM1105473': [0.0, 57.0, 0.0], 'GSM1105474': [0.0, 30.0, 0.0], 'GSM1105475': [0.0, 37.0, 0.0], 'GSM1105476': [0.0, 30.0, 0.0], 'GSM1105477': [0.0, 37.0, 0.0], 'GSM1105478': [1.0, 51.0, 1.0], 'GSM1105479': [1.0, 35.0, 0.0], 'GSM1105480': [1.0, 51.0, 1.0], 'GSM1105481': [1.0, 35.0, 0.0], 'GSM1105482': [0.0, 64.0, 0.0], 'GSM1105483': [0.0, 45.0, 0.0], 'GSM1105484': [0.0, 64.0, 0.0], 'GSM1105485': [0.0, 45.0, 0.0], 'GSM1105486': [0.0, 53.0, 0.0], 'GSM1105487': [0.0, 57.0, 1.0], 'GSM1105488': [0.0, 53.0, 0.0], 'GSM1105489': [0.0, 57.0, 1.0], 'GSM1105490': [0.0, 25.0, 0.0], 'GSM1105491': [0.0, 61.0, 0.0], 'GSM1105492': [0.0, 25.0, 0.0], 'GSM1105493': [0.0, 61.0, 0.0], 'GSM1105494': [0.0, 44.0, 1.0], 'GSM1105495': [0.0, 39.0, 1.0], 'GSM1105496': [0.0, 44.0, 1.0], 'GSM1105497': [0.0, 39.0, 1.0], 'GSM1105498': [0.0, 26.0, 0.0], 'GSM1105499': [0.0, 45.0, 0.0], 'GSM1105500': [0.0, 26.0, 0.0], 'GSM1105501': [0.0, 45.0, 0.0], 'GSM1105502': [1.0, 53.0, 0.0], 'GSM1105503': [0.0, 51.0, 0.0], 'GSM1105504': [1.0, 53.0, 0.0], 'GSM1105505': [0.0, 51.0, 0.0], 'GSM1105506': [0.0, 36.0, 1.0], 'GSM1105507': [0.0, 45.0, 0.0], 'GSM1105508': [0.0, 36.0, 1.0], 'GSM1105509': [0.0, 45.0, 0.0], 'GSM1105510': [1.0, 38.0, 0.0], 'GSM1105511': [0.0, 18.0, 0.0], 'GSM1105512': [1.0, 38.0, 0.0], 'GSM1105513': [0.0, 18.0, 0.0], 'GSM1105514': [0.0, 20.0, 0.0], 'GSM1105515': [1.0, 27.0, 1.0], 'GSM1105516': [0.0, 20.0, 0.0], 'GSM1105517': [1.0, 27.0, 1.0], 'GSM1105518': [0.0, 49.0, 0.0], 'GSM1105519': [0.0, 43.0, 0.0], 'GSM1105520': [0.0, 49.0, 0.0], 'GSM1105521': [0.0, 43.0, 0.0], 'GSM1105522': [0.0, 29.0, 1.0], 'GSM1105523': [1.0, 20.0, 0.0], 'GSM1105524': [0.0, 29.0, 1.0], 'GSM1105525': [1.0, 20.0, 0.0], 'GSM1105526': [0.0, 32.0, 0.0], 'GSM1105527': [0.0, 40.0, 1.0], 'GSM1105528': [0.0, 32.0, 0.0], 'GSM1105529': [0.0, 40.0, 1.0], 'GSM1105530': [1.0, 59.0, 0.0], 'GSM1105531': [0.0, 41.0, 0.0], 'GSM1105532': [1.0, 59.0, 0.0], 'GSM1105533': [0.0, 41.0, 0.0], 'GSM1105534': [0.0, 20.0, 0.0], 'GSM1105535': [0.0, 31.0, 1.0], 'GSM1105536': [0.0, 20.0, 0.0], 'GSM1105537': [0.0, 31.0, 1.0], 'GSM1105538': [0.0, 29.0, 1.0], 'GSM1105539': [1.0, 49.0, 0.0], 'GSM1105540': [0.0, 29.0, 1.0], 'GSM1105541': [1.0, 49.0, 0.0], 'GSM1105542': [0.0, 52.0, 0.0], 'GSM1105543': [0.0, 22.0, 1.0], 'GSM1105544': [0.0, 52.0, 0.0], 'GSM1105545': [0.0, 22.0, 1.0], 'GSM1105546': [0.0, 52.0, 0.0], 'GSM1105547': [0.0, 39.0, 0.0], 'GSM1105548': [0.0, 52.0, 0.0], 'GSM1105549': [0.0, 39.0, 0.0], 'GSM1105550': [1.0, 27.0, 0.0], 'GSM1105551': [0.0, 57.0, 1.0], 'GSM1105552': [1.0, 27.0, 0.0], 'GSM1105553': [0.0, 57.0, 1.0], 'GSM1105554': [0.0, 27.0, 0.0], 'GSM1105555': [0.0, 36.0, 0.0], 'GSM1105556': [0.0, 27.0, 0.0], 'GSM1105557': [0.0, 36.0, 0.0]}\n",
      "Clinical data saved to ../../output/preprocess/Bipolar_disorder/clinical_data/GSE45484.csv\n"
     ]
    }
   ],
   "source": [
    "# 1. Gene Expression Data Availability\n",
    "is_gene_available = True  # Based on the series title and summary, this dataset contains gene expression data\n",
    "\n",
    "# 2. Variable Availability and Data Type Conversion\n",
    "# 2.1 Data Availability\n",
    "trait_row = 2  # 'responder: NO', 'responder: YES' - this represents bipolar disorder response to treatment\n",
    "age_row = 4    # Contains age information with multiple values\n",
    "gender_row = 3  # Contains sex information 'M' and 'F'\n",
    "\n",
    "# 2.2 Data Type Conversion\n",
    "def convert_trait(value):\n",
    "    if value is None:\n",
    "        return None\n",
    "    \n",
    "    # Extract the value after the colon\n",
    "    if \":\" in value:\n",
    "        value = value.split(\":\", 1)[1].strip()\n",
    "    \n",
    "    # Convert to binary: YES=1 (responder), NO=0 (non-responder)\n",
    "    if value.upper() == \"YES\":\n",
    "        return 1\n",
    "    elif value.upper() == \"NO\":\n",
    "        return 0\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "def convert_age(value):\n",
    "    if value is None:\n",
    "        return None\n",
    "    \n",
    "    # Extract the value after the colon\n",
    "    if \":\" in value:\n",
    "        value = value.split(\":\", 1)[1].strip()\n",
    "    \n",
    "    # Convert to integer\n",
    "    try:\n",
    "        return int(value)\n",
    "    except:\n",
    "        return None\n",
    "\n",
    "def convert_gender(value):\n",
    "    if value is None:\n",
    "        return None\n",
    "    \n",
    "    # Extract the value after the colon\n",
    "    if \":\" in value:\n",
    "        value = value.split(\":\", 1)[1].strip()\n",
    "    \n",
    "    # Convert to binary: F=0, M=1\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",
    "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 (only if trait_row is not None)\n",
    "if trait_row is not None:\n",
    "    # Get the clinical features\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,\n",
    "        gender_row=gender_row,\n",
    "        convert_gender=convert_gender\n",
    "    )\n",
    "    \n",
    "    # Preview the resulting dataframe\n",
    "    preview = preview_df(selected_clinical_df)\n",
    "    print(\"Clinical Data Preview:\")\n",
    "    print(preview)\n",
    "    \n",
    "    # Save the clinical data to CSV\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",
    "    print(f\"Clinical data saved to {out_clinical_data_file}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f73cabab",
   "metadata": {},
   "source": [
    "### Step 3: Gene Data Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "84b16b22",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:55:03.771268Z",
     "iopub.status.busy": "2025-03-25T06:55:03.771157Z",
     "iopub.status.idle": "2025-03-25T06:55:04.214033Z",
     "shell.execute_reply": "2025-03-25T06:55:04.213490Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Matrix file found: ../../input/GEO/Bipolar_disorder/GSE45484/GSE45484_series_matrix.txt.gz\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene data shape: (47323, 120)\n",
      "First 20 gene/probe identifiers:\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"
     ]
    }
   ],
   "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": "fc03f25d",
   "metadata": {},
   "source": [
    "### Step 4: Gene Identifier Review"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "890f78ee",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:55:04.215429Z",
     "iopub.status.busy": "2025-03-25T06:55:04.215312Z",
     "iopub.status.idle": "2025-03-25T06:55:04.217694Z",
     "shell.execute_reply": "2025-03-25T06:55:04.217289Z"
    }
   },
   "outputs": [],
   "source": [
    "# These identifiers start with \"ILMN_\" which indicates they are Illumina BeadArray probe IDs\n",
    "# They are not human gene symbols and require mapping to standard gene symbols\n",
    "# Illumina probe IDs are specific to the microarray platform and need to be converted\n",
    "\n",
    "requires_gene_mapping = True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "130078fa",
   "metadata": {},
   "source": [
    "### Step 5: Gene Annotation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "7fb58729",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:55:04.219139Z",
     "iopub.status.busy": "2025-03-25T06:55:04.218988Z",
     "iopub.status.idle": "2025-03-25T06:55:15.103374Z",
     "shell.execute_reply": "2025-03-25T06:55:15.102727Z"
    }
   },
   "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', '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.0, 6510136.0, 7560739.0, 1450438.0, 1240647.0], '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",
      "\n",
      "First row as dictionary:\n",
      "ID: ILMN_1343048\n",
      "Species: nan\n",
      "Source: nan\n",
      "Search_Key: nan\n",
      "Transcript: nan\n",
      "ILMN_Gene: nan\n",
      "Source_Reference_ID: nan\n",
      "RefSeq_ID: nan\n",
      "Unigene_ID: nan\n",
      "Entrez_Gene_ID: nan\n",
      "GI: nan\n",
      "Accession: nan\n",
      "Symbol: phage_lambda_genome\n",
      "Protein_Product: nan\n",
      "Probe_Id: nan\n",
      "Array_Address_Id: 5090180.0\n",
      "Probe_Type: nan\n",
      "Probe_Start: nan\n",
      "SEQUENCE: GAATAAAGAACAATCTGCTGATGATCCCTCCGTGGATCTGATTCGTGTAA\n",
      "Chromosome: nan\n",
      "Probe_Chr_Orientation: nan\n",
      "Probe_Coordinates: nan\n",
      "Cytoband: nan\n",
      "Definition: nan\n",
      "Ontology_Component: nan\n",
      "Ontology_Process: nan\n",
      "Ontology_Function: nan\n",
      "Synonyms: nan\n",
      "Obsolete_Probe_Id: nan\n",
      "GB_ACC: nan\n",
      "\n",
      "Comparing gene data IDs with annotation IDs:\n",
      "First 5 gene data IDs: ['ILMN_1343291', 'ILMN_1343295', 'ILMN_1651199', 'ILMN_1651209', 'ILMN_1651210']\n",
      "First 5 annotation IDs: ['ILMN_1343048', 'ILMN_1343049', 'ILMN_1343050', 'ILMN_1343052', 'ILMN_1343059']\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "Exact ID match between gene data and annotation:\n",
      "Matching IDs: 47323 out of 47323 (100.00%)\n",
      "\n",
      "Potential columns for gene symbols: ['ILMN_Gene', 'Unigene_ID', 'Entrez_Gene_ID', 'Symbol']\n",
      "Column 'ILMN_Gene': 47323 non-null values (0.83%)\n",
      "Column 'Unigene_ID': 3270 non-null values (0.06%)\n",
      "Column 'Entrez_Gene_ID': 43960 non-null values (0.77%)\n",
      "Column 'Symbol': 44837 non-null values (0.78%)\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",
    "# Check if there are any columns that might contain gene information\n",
    "sample_row = gene_annotation.iloc[0].to_dict()\n",
    "print(\"\\nFirst row as dictionary:\")\n",
    "for col, value in sample_row.items():\n",
    "    print(f\"{col}: {value}\")\n",
    "\n",
    "# Check if IDs in gene_data match IDs in annotation\n",
    "print(\"\\nComparing gene data IDs with annotation IDs:\")\n",
    "print(\"First 5 gene data IDs:\", gene_data.index[:5].tolist())\n",
    "print(\"First 5 annotation IDs:\", gene_annotation['ID'].head().tolist())\n",
    "\n",
    "# Properly check for exact ID matches between gene data and annotation\n",
    "gene_data_ids = set(gene_data.index)\n",
    "annotation_ids = set(gene_annotation['ID'].astype(str))\n",
    "matching_ids = gene_data_ids.intersection(annotation_ids)\n",
    "id_match_percentage = len(matching_ids) / len(gene_data_ids) * 100 if len(gene_data_ids) > 0 else 0\n",
    "\n",
    "print(f\"\\nExact ID match between gene data and annotation:\")\n",
    "print(f\"Matching IDs: {len(matching_ids)} out of {len(gene_data_ids)} ({id_match_percentage:.2f}%)\")\n",
    "\n",
    "# Check which columns might contain gene symbols for mapping\n",
    "potential_gene_symbol_cols = [col for col in gene_annotation.columns \n",
    "                             if any(term in col.upper() for term in ['GENE', 'SYMBOL', 'NAME'])]\n",
    "print(f\"\\nPotential columns for gene symbols: {potential_gene_symbol_cols}\")\n",
    "\n",
    "# Check if the identified columns contain non-null values\n",
    "for col in potential_gene_symbol_cols:\n",
    "    non_null_count = gene_annotation[col].notnull().sum()\n",
    "    non_null_percent = non_null_count / len(gene_annotation) * 100\n",
    "    print(f\"Column '{col}': {non_null_count} non-null values ({non_null_percent:.2f}%)\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b55ba1e5",
   "metadata": {},
   "source": [
    "### Step 6: Gene Identifier Mapping"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "7c96ec2d",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:55:15.105242Z",
     "iopub.status.busy": "2025-03-25T06:55:15.105120Z",
     "iopub.status.idle": "2025-03-25T06:55:16.904289Z",
     "shell.execute_reply": "2025-03-25T06:55:16.903634Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Created mapping dataframe with shape: (44837, 2)\n",
      "Sample of mapping data:\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",
      "Created gene expression dataframe with shape: (21464, 120)\n",
      "First 5 genes and their expression values:\n",
      "       GSM1105438  GSM1105439  GSM1105440  GSM1105441  GSM1105442  GSM1105443  \\\n",
      "Gene                                                                            \n",
      "A1BG     14.03088    13.93148    13.81406    13.83391    13.78051    13.96313   \n",
      "A1CF     20.32521    20.63063    20.66692    20.54370    20.64116    20.71162   \n",
      "A26C3    20.39159    20.30175    20.52752    20.41063    20.47654    20.56898   \n",
      "A2BP1    27.15309    27.27428    26.94768    27.12319    27.09179    26.95093   \n",
      "A2LD1     7.32095     7.29238     7.47339     7.21109     7.26801     7.35792   \n",
      "\n",
      "       GSM1105444  GSM1105445  GSM1105446  GSM1105447  ...  GSM1105548  \\\n",
      "Gene                                                   ...               \n",
      "A1BG     13.99187    13.98965    13.65448    13.59944  ...    13.92483   \n",
      "A1CF     20.58564    20.50426    20.82332    20.55633  ...    20.55526   \n",
      "A26C3    20.29670    20.46836    20.55004    20.29735  ...    20.27635   \n",
      "A2BP1    27.35133    26.94886    27.07386    27.20497  ...    26.93445   \n",
      "A2LD1     7.45566     7.36758     6.93695     7.21794  ...     7.33647   \n",
      "\n",
      "       GSM1105549  GSM1105550  GSM1105551  GSM1105552  GSM1105553  GSM1105554  \\\n",
      "Gene                                                                            \n",
      "A1BG     13.72544    13.94040    13.70261    13.91181    13.70411    13.73513   \n",
      "A1CF     20.64901    20.55603    20.36035    20.75112    20.61628    20.46376   \n",
      "A26C3    20.61305    20.40383    20.40375    20.54260    20.47298    20.35977   \n",
      "A2BP1    27.09989    27.18521    27.42922    26.94529    26.91467    26.90594   \n",
      "A2LD1     7.09422     7.19649     7.22026     7.35474     7.58675     7.12003   \n",
      "\n",
      "       GSM1105555  GSM1105556  GSM1105557  \n",
      "Gene                                       \n",
      "A1BG     13.70526    13.75100    13.80716  \n",
      "A1CF     21.03313    20.70163    20.67360  \n",
      "A26C3    20.67486    20.61405    20.41787  \n",
      "A2BP1    27.04305    27.16635    27.29938  \n",
      "A2LD1     7.30742     7.14190     7.48781  \n",
      "\n",
      "[5 rows x 120 columns]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene expression data saved to ../../output/preprocess/Bipolar_disorder/gene_data/GSE45484.csv\n"
     ]
    }
   ],
   "source": [
    "# 1. Determine which columns to use for probe IDs and gene symbols\n",
    "# Based on previous step output, we need:\n",
    "# - The 'ID' column (contains probe IDs like ILMN_1343048) that matches gene_data index\n",
    "# - The 'Symbol' column (contains gene symbols) has 78% non-null values\n",
    "\n",
    "# 2. Get gene mapping dataframe\n",
    "mapping_df = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='Symbol')\n",
    "print(f\"Created mapping dataframe with shape: {mapping_df.shape}\")\n",
    "print(f\"Sample of mapping data:\")\n",
    "print(mapping_df.head())\n",
    "\n",
    "# 3. Apply gene mapping to convert probe-level measurements to gene-level expression\n",
    "gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)\n",
    "print(f\"Created gene expression dataframe with shape: {gene_data.shape}\")\n",
    "print(f\"First 5 genes and their expression values:\")\n",
    "print(gene_data.head())\n",
    "\n",
    "# Save the processed 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"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c2dd9ec2",
   "metadata": {},
   "source": [
    "### Step 7: Data Normalization and Linking"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "08577309",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:55:16.906242Z",
     "iopub.status.busy": "2025-03-25T06:55:16.906075Z",
     "iopub.status.idle": "2025-03-25T06:55:33.696705Z",
     "shell.execute_reply": "2025-03-25T06:55:33.696328Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene data shape after normalization: (20259, 120)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Normalized gene expression data saved to ../../output/preprocess/Bipolar_disorder/gene_data/GSE45484.csv\n",
      "Loaded clinical data shape: (3, 120)\n",
      "Selected clinical data shape: (3, 120)\n",
      "Clinical data preview:\n",
      "{'GSM1105438': [0.0, 46.0, 1.0], 'GSM1105439': [0.0, 44.0, 0.0], 'GSM1105440': [0.0, 46.0, 1.0], 'GSM1105441': [0.0, 44.0, 0.0], 'GSM1105442': [0.0, 59.0, 1.0], 'GSM1105443': [0.0, 32.0, 0.0], 'GSM1105444': [0.0, 59.0, 1.0], 'GSM1105445': [0.0, 32.0, 0.0], 'GSM1105446': [0.0, 45.0, 0.0], 'GSM1105447': [0.0, 25.0, 0.0], 'GSM1105448': [0.0, 45.0, 0.0], 'GSM1105449': [0.0, 25.0, 0.0], 'GSM1105450': [1.0, 25.0, 0.0], 'GSM1105451': [1.0, 26.0, 0.0], 'GSM1105452': [1.0, 25.0, 0.0], 'GSM1105453': [1.0, 26.0, 0.0], 'GSM1105454': [1.0, 43.0, 1.0], 'GSM1105455': [0.0, 24.0, 0.0], 'GSM1105456': [1.0, 43.0, 1.0], 'GSM1105457': [0.0, 24.0, 0.0], 'GSM1105458': [0.0, 43.0, 1.0], 'GSM1105459': [0.0, 43.0, 0.0], 'GSM1105460': [0.0, 43.0, 1.0], 'GSM1105461': [0.0, 43.0, 0.0], 'GSM1105462': [0.0, 38.0, 0.0], 'GSM1105463': [0.0, 47.0, 1.0], 'GSM1105464': [0.0, 38.0, 0.0], 'GSM1105465': [0.0, 47.0, 1.0], 'GSM1105466': [1.0, 37.0, 1.0], 'GSM1105467': [0.0, 57.0, 0.0], 'GSM1105468': [1.0, 37.0, 1.0], 'GSM1105469': [0.0, 57.0, 0.0], 'GSM1105470': [0.0, 23.0, 0.0], 'GSM1105471': [0.0, 57.0, 0.0], 'GSM1105472': [0.0, 23.0, 0.0], 'GSM1105473': [0.0, 57.0, 0.0], 'GSM1105474': [0.0, 30.0, 0.0], 'GSM1105475': [0.0, 37.0, 0.0], 'GSM1105476': [0.0, 30.0, 0.0], 'GSM1105477': [0.0, 37.0, 0.0], 'GSM1105478': [1.0, 51.0, 1.0], 'GSM1105479': [1.0, 35.0, 0.0], 'GSM1105480': [1.0, 51.0, 1.0], 'GSM1105481': [1.0, 35.0, 0.0], 'GSM1105482': [0.0, 64.0, 0.0], 'GSM1105483': [0.0, 45.0, 0.0], 'GSM1105484': [0.0, 64.0, 0.0], 'GSM1105485': [0.0, 45.0, 0.0], 'GSM1105486': [0.0, 53.0, 0.0], 'GSM1105487': [0.0, 57.0, 1.0], 'GSM1105488': [0.0, 53.0, 0.0], 'GSM1105489': [0.0, 57.0, 1.0], 'GSM1105490': [0.0, 25.0, 0.0], 'GSM1105491': [0.0, 61.0, 0.0], 'GSM1105492': [0.0, 25.0, 0.0], 'GSM1105493': [0.0, 61.0, 0.0], 'GSM1105494': [0.0, 44.0, 1.0], 'GSM1105495': [0.0, 39.0, 1.0], 'GSM1105496': [0.0, 44.0, 1.0], 'GSM1105497': [0.0, 39.0, 1.0], 'GSM1105498': [0.0, 26.0, 0.0], 'GSM1105499': [0.0, 45.0, 0.0], 'GSM1105500': [0.0, 26.0, 0.0], 'GSM1105501': [0.0, 45.0, 0.0], 'GSM1105502': [1.0, 53.0, 0.0], 'GSM1105503': [0.0, 51.0, 0.0], 'GSM1105504': [1.0, 53.0, 0.0], 'GSM1105505': [0.0, 51.0, 0.0], 'GSM1105506': [0.0, 36.0, 1.0], 'GSM1105507': [0.0, 45.0, 0.0], 'GSM1105508': [0.0, 36.0, 1.0], 'GSM1105509': [0.0, 45.0, 0.0], 'GSM1105510': [1.0, 38.0, 0.0], 'GSM1105511': [0.0, 18.0, 0.0], 'GSM1105512': [1.0, 38.0, 0.0], 'GSM1105513': [0.0, 18.0, 0.0], 'GSM1105514': [0.0, 20.0, 0.0], 'GSM1105515': [1.0, 27.0, 1.0], 'GSM1105516': [0.0, 20.0, 0.0], 'GSM1105517': [1.0, 27.0, 1.0], 'GSM1105518': [0.0, 49.0, 0.0], 'GSM1105519': [0.0, 43.0, 0.0], 'GSM1105520': [0.0, 49.0, 0.0], 'GSM1105521': [0.0, 43.0, 0.0], 'GSM1105522': [0.0, 29.0, 1.0], 'GSM1105523': [1.0, 20.0, 0.0], 'GSM1105524': [0.0, 29.0, 1.0], 'GSM1105525': [1.0, 20.0, 0.0], 'GSM1105526': [0.0, 32.0, 0.0], 'GSM1105527': [0.0, 40.0, 1.0], 'GSM1105528': [0.0, 32.0, 0.0], 'GSM1105529': [0.0, 40.0, 1.0], 'GSM1105530': [1.0, 59.0, 0.0], 'GSM1105531': [0.0, 41.0, 0.0], 'GSM1105532': [1.0, 59.0, 0.0], 'GSM1105533': [0.0, 41.0, 0.0], 'GSM1105534': [0.0, 20.0, 0.0], 'GSM1105535': [0.0, 31.0, 1.0], 'GSM1105536': [0.0, 20.0, 0.0], 'GSM1105537': [0.0, 31.0, 1.0], 'GSM1105538': [0.0, 29.0, 1.0], 'GSM1105539': [1.0, 49.0, 0.0], 'GSM1105540': [0.0, 29.0, 1.0], 'GSM1105541': [1.0, 49.0, 0.0], 'GSM1105542': [0.0, 52.0, 0.0], 'GSM1105543': [0.0, 22.0, 1.0], 'GSM1105544': [0.0, 52.0, 0.0], 'GSM1105545': [0.0, 22.0, 1.0], 'GSM1105546': [0.0, 52.0, 0.0], 'GSM1105547': [0.0, 39.0, 0.0], 'GSM1105548': [0.0, 52.0, 0.0], 'GSM1105549': [0.0, 39.0, 0.0], 'GSM1105550': [1.0, 27.0, 0.0], 'GSM1105551': [0.0, 57.0, 1.0], 'GSM1105552': [1.0, 27.0, 0.0], 'GSM1105553': [0.0, 57.0, 1.0], 'GSM1105554': [0.0, 27.0, 0.0], 'GSM1105555': [0.0, 36.0, 0.0], 'GSM1105556': [0.0, 27.0, 0.0], 'GSM1105557': [0.0, 36.0, 0.0]}\n",
      "Linked data shape: (120, 20262)\n",
      "Linked data preview (first 5 rows, 5 columns):\n",
      "            Bipolar_disorder   Age  Gender      A1BG  A1BG-AS1\n",
      "GSM1105438               0.0  46.0     1.0  14.03088   6.76428\n",
      "GSM1105439               0.0  44.0     0.0  13.93148   6.87647\n",
      "GSM1105440               0.0  46.0     1.0  13.81406   6.81161\n",
      "GSM1105441               0.0  44.0     0.0  13.83391   6.87946\n",
      "GSM1105442               0.0  59.0     1.0  13.78051   6.86722\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Data shape after handling missing values: (120, 20262)\n",
      "For the feature 'Bipolar_disorder', the least common label is '1.0' with 26 occurrences. This represents 21.67% of the dataset.\n",
      "The distribution of the feature 'Bipolar_disorder' in this dataset is fine.\n",
      "\n",
      "Quartiles for 'Age':\n",
      "  25%: 28.5\n",
      "  50% (Median): 39.5\n",
      "  75%: 49.0\n",
      "Min: 18.0\n",
      "Max: 64.0\n",
      "The distribution of the feature 'Age' in this dataset is fine.\n",
      "\n",
      "For the feature 'Gender', the least common label is '1.0' with 36 occurrences. This represents 30.00% of the dataset.\n",
      "The distribution of the feature 'Gender' in this dataset is fine.\n",
      "\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Linked data saved to ../../output/preprocess/Bipolar_disorder/GSE45484.csv\n"
     ]
    }
   ],
   "source": [
    "# 1. Normalize gene symbols in the gene expression data\n",
    "gene_data = normalize_gene_symbols_in_index(gene_data)\n",
    "print(f\"Gene data shape after normalization: {gene_data.shape}\")\n",
    "\n",
    "# Save the normalized gene data to file\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\"Normalized gene expression data saved to {out_gene_data_file}\")\n",
    "\n",
    "# 2. Link the clinical and genetic data\n",
    "# Read the saved clinical data file\n",
    "clinical_df = pd.read_csv(out_clinical_data_file)\n",
    "print(f\"Loaded clinical data shape: {clinical_df.shape}\")\n",
    "\n",
    "# Load proper clinical data with the correct conversion functions from Step 2\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,  # Using the previously defined function from Step 2\n",
    "    age_row=age_row,\n",
    "    convert_age=convert_age,      # Using the previously defined function from Step 2\n",
    "    gender_row=gender_row,\n",
    "    convert_gender=convert_gender # Using the previously defined function from Step 2\n",
    ")\n",
    "\n",
    "print(f\"Selected clinical data shape: {selected_clinical_df.shape}\")\n",
    "print(\"Clinical data preview:\")\n",
    "print(preview_df(selected_clinical_df))\n",
    "\n",
    "# Link clinical and genetic data\n",
    "linked_data = geo_link_clinical_genetic_data(selected_clinical_df, gene_data)\n",
    "print(f\"Linked data shape: {linked_data.shape}\")\n",
    "print(\"Linked data preview (first 5 rows, 5 columns):\")\n",
    "print(linked_data.iloc[:5, :5] if not linked_data.empty else \"Linked data is empty\")\n",
    "\n",
    "# 3. Handle missing values\n",
    "linked_data = handle_missing_values(linked_data, trait)\n",
    "print(f\"Data shape after handling missing values: {linked_data.shape}\")\n",
    "\n",
    "# 4. Check for bias in features\n",
    "is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n",
    "\n",
    "# 5. Validate and save cohort information\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,\n",
    "    note=\"Dataset contains gene expression data from blood samples of bipolar disorder patients, analyzing response to lithium treatment.\"\n",
    ")\n",
    "\n",
    "# 6. Save the linked data if 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 is not usable for analysis. No linked data file 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
}