File size: 51,312 Bytes
d1894e4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "b2a98720",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:24:51.416770Z",
     "iopub.status.busy": "2025-03-25T05:24:51.416545Z",
     "iopub.status.idle": "2025-03-25T05:24:51.587478Z",
     "shell.execute_reply": "2025-03-25T05:24:51.587123Z"
    }
   },
   "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 = \"Glucocorticoid_Sensitivity\"\n",
    "cohort = \"GSE32962\"\n",
    "\n",
    "# Input paths\n",
    "in_trait_dir = \"../../input/GEO/Glucocorticoid_Sensitivity\"\n",
    "in_cohort_dir = \"../../input/GEO/Glucocorticoid_Sensitivity/GSE32962\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/Glucocorticoid_Sensitivity/GSE32962.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/Glucocorticoid_Sensitivity/gene_data/GSE32962.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/Glucocorticoid_Sensitivity/clinical_data/GSE32962.csv\"\n",
    "json_path = \"../../output/preprocess/Glucocorticoid_Sensitivity/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c5dc5a64",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "7a17104e",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:24:51.588735Z",
     "iopub.status.busy": "2025-03-25T05:24:51.588590Z",
     "iopub.status.idle": "2025-03-25T05:24:51.775317Z",
     "shell.execute_reply": "2025-03-25T05:24:51.774949Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Background Information:\n",
      "!Series_title\t\"In vitro prednisolone resistance signature in MLL-rearranged infant ALL\"\n",
      "!Series_summary\t\"Acute Lymphoblastic Leukemia (ALL) in infants (<1 year of age) is characterized by a high incidence of MLL translocations which is associated with a poor prognosis. Contributing to this poor prognosis is cellular drug resistance, especially to glucocorticoids like prednisolone. Although in vitro prednisolone resistance mechanisms have been proposed in pediatric ALL, it has never been studied in MLL-rearranged infant ALL, which are highly resistant to glucocorticoids in vitro and in vivo.\"\n",
      "!Series_overall_design\t\"We analyzed primary MLL-rearranged infant ALL expression profiles, which were either in vitro prednisolone-resistant or prednisolone-sensitive, in order to study in vitro prednisolone resistance.\"\n",
      "Sample Characteristics Dictionary:\n",
      "{0: ['disease state: Precursor B-cell acute lymphoblastic leukemia (ALL)'], 1: ['cell type: Primary infant ALL cells at diagnosis (untreated) (>90% blasts)'], 2: ['genotype: MLL-rearranged'], 3: ['age: < 1 year of age'], 4: ['prednisolone sensitivity: resistant', 'prednisolone sensitivity: sensitive']}\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": "85b3a805",
   "metadata": {},
   "source": [
    "### Step 2: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "f0d8b8be",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:24:51.776845Z",
     "iopub.status.busy": "2025-03-25T05:24:51.776610Z",
     "iopub.status.idle": "2025-03-25T05:24:51.788029Z",
     "shell.execute_reply": "2025-03-25T05:24:51.787710Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Clinical Data Preview:\n",
      "{'GSM816393': [1.0, 0.5], 'GSM816394': [1.0, 0.5], 'GSM816395': [1.0, 0.5], 'GSM816396': [1.0, 0.5], 'GSM816397': [1.0, 0.5], 'GSM816398': [1.0, 0.5], 'GSM816399': [1.0, 0.5], 'GSM816400': [1.0, 0.5], 'GSM816401': [1.0, 0.5], 'GSM816402': [1.0, 0.5], 'GSM816403': [1.0, 0.5], 'GSM816404': [1.0, 0.5], 'GSM816405': [1.0, 0.5], 'GSM816406': [1.0, 0.5], 'GSM816407': [1.0, 0.5], 'GSM816408': [1.0, 0.5], 'GSM816409': [1.0, 0.5], 'GSM816410': [1.0, 0.5], 'GSM816411': [1.0, 0.5], 'GSM816412': [1.0, 0.5], 'GSM816413': [1.0, 0.5], 'GSM816414': [1.0, 0.5], 'GSM816415': [1.0, 0.5], 'GSM816416': [1.0, 0.5], 'GSM816417': [0.0, 0.5], 'GSM816418': [0.0, 0.5], 'GSM816419': [0.0, 0.5], 'GSM816420': [0.0, 0.5], 'GSM816421': [0.0, 0.5], 'GSM816422': [0.0, 0.5], 'GSM816423': [0.0, 0.5], 'GSM816424': [0.0, 0.5], 'GSM816425': [0.0, 0.5], 'GSM816426': [0.0, 0.5], 'GSM816427': [0.0, 0.5], 'GSM816428': [0.0, 0.5], 'GSM816429': [0.0, 0.5], 'GSM816430': [0.0, 0.5], 'GSM816431': [0.0, 0.5], 'GSM816432': [0.0, 0.5], 'GSM816433': [0.0, 0.5], 'GSM816434': [0.0, 0.5], 'GSM816435': [0.0, 0.5]}\n",
      "Clinical data saved to ../../output/preprocess/Glucocorticoid_Sensitivity/clinical_data/GSE32962.csv\n"
     ]
    }
   ],
   "source": [
    "import pandas as pd\n",
    "import os\n",
    "import json\n",
    "from typing import Callable, Optional, Dict, Any\n",
    "\n",
    "# 1. Gene Expression Data Availability\n",
    "# Based on background information mentioning ALL expression profiles\n",
    "# This indicates gene expression data should be available\n",
    "is_gene_available = True\n",
    "\n",
    "# 2. Variable Availability and Data Type Conversion\n",
    "# 2.1 Data Availability\n",
    "# From sample characteristics, identifying keys for trait, age, and gender\n",
    "trait_row = 4  # prednisolone sensitivity\n",
    "age_row = 3    # age\n",
    "gender_row = None  # gender information is not available\n",
    "\n",
    "# 2.2 Data Type Conversion\n",
    "def convert_trait(value):\n",
    "    \"\"\"Convert prednisolone sensitivity to binary value.\"\"\"\n",
    "    if not isinstance(value, str):\n",
    "        return None\n",
    "    \n",
    "    # Extract value after colon if present\n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip()\n",
    "    \n",
    "    value = value.lower()\n",
    "    if 'resistant' in value:\n",
    "        return 1  # resistant\n",
    "    elif 'sensitive' in value:\n",
    "        return 0  # sensitive\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "def convert_age(value):\n",
    "    \"\"\"Convert age information to a standardized format.\"\"\"\n",
    "    if not isinstance(value, str):\n",
    "        return None\n",
    "    \n",
    "    # Extract value after colon if present\n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip()\n",
    "    \n",
    "    # All patients are < 1 year of age, so we can't get specific ages\n",
    "    # Will return constant value since all are infants\n",
    "    if '< 1 year' in value.lower():\n",
    "        return 0.5  # Approximate midpoint for infants under 1 year\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "# 3. Save Metadata - Initial Filtering\n",
    "# Check if trait information is available (based on trait_row not being None)\n",
    "is_trait_available = trait_row is not None\n",
    "validate_and_save_cohort_info(\n",
    "    is_final=False,\n",
    "    cohort=cohort,\n",
    "    info_path=json_path,\n",
    "    is_gene_available=is_gene_available,\n",
    "    is_trait_available=is_trait_available\n",
    ")\n",
    "\n",
    "# 4. Clinical Feature Extraction\n",
    "if trait_row is not None:\n",
    "    # Create output directory if it doesn't exist\n",
    "    os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
    "    \n",
    "    # Assuming clinical_data is available as a variable from a previous step\n",
    "    # Let's try to access it directly first, rather than loading from a file\n",
    "    try:\n",
    "        # Try to access clinical_data from the environment\n",
    "        if 'clinical_data' in globals():\n",
    "            clinical_df = clinical_data\n",
    "        else:\n",
    "            # If not available directly, try loading from predefined paths\n",
    "            try:\n",
    "                clinical_df = pd.read_csv(os.path.join(in_cohort_dir, \"clinical_data.txt\"), sep='\\t')\n",
    "            except FileNotFoundError:\n",
    "                # Look for other potential files that might contain the clinical data\n",
    "                potential_files = [f for f in os.listdir(in_cohort_dir) if os.path.isfile(os.path.join(in_cohort_dir, f))]\n",
    "                \n",
    "                if 'clinical.csv' in potential_files:\n",
    "                    clinical_df = pd.read_csv(os.path.join(in_cohort_dir, 'clinical.csv'))\n",
    "                elif 'characteristics.csv' in potential_files:\n",
    "                    clinical_df = pd.read_csv(os.path.join(in_cohort_dir, 'characteristics.csv'))\n",
    "                else:\n",
    "                    # If we can't find the clinical data, we may need to skip this step\n",
    "                    print(f\"Could not find clinical data files in {in_cohort_dir}\")\n",
    "                    print(f\"Available files: {potential_files}\")\n",
    "                    raise FileNotFoundError(\"Clinical data not found. Cannot proceed with clinical feature extraction.\")\n",
    "        \n",
    "        # Extract clinical features using the library function\n",
    "        selected_clinical_df = geo_select_clinical_features(\n",
    "            clinical_df=clinical_df,\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=None\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\n",
    "        selected_clinical_df.to_csv(out_clinical_data_file, index=False)\n",
    "        print(f\"Clinical data saved to {out_clinical_data_file}\")\n",
    "    except Exception as e:\n",
    "        print(f\"Error during clinical data processing: {str(e)}\")\n",
    "        print(\"Skipping clinical feature extraction step.\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "af17b1fe",
   "metadata": {},
   "source": [
    "### Step 3: Gene Data Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "a691392f",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:24:51.789329Z",
     "iopub.status.busy": "2025-03-25T05:24:51.789216Z",
     "iopub.status.idle": "2025-03-25T05:24:52.064061Z",
     "shell.execute_reply": "2025-03-25T05:24:52.063726Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Found data marker at line 64\n",
      "Header line: \"ID_REF\"\t\"GSM816393\"\t\"GSM816394\"\t\"GSM816395\"\t\"GSM816396\"\t\"GSM816397\"\t\"GSM816398\"\t\"GSM816399\"\t\"GSM816400\"\t\"GSM816401\"\t\"GSM816402\"\t\"GSM816403\"\t\"GSM816404\"\t\"GSM816405\"\t\"GSM816406\"\t\"GSM816407\"\t\"GSM816408\"\t\"GSM816409\"\t\"GSM816410\"\t\"GSM816411\"\t\"GSM816412\"\t\"GSM816413\"\t\"GSM816414\"\t\"GSM816415\"\t\"GSM816416\"\t\"GSM816417\"\t\"GSM816418\"\t\"GSM816419\"\t\"GSM816420\"\t\"GSM816421\"\t\"GSM816422\"\t\"GSM816423\"\t\"GSM816424\"\t\"GSM816425\"\t\"GSM816426\"\t\"GSM816427\"\t\"GSM816428\"\t\"GSM816429\"\t\"GSM816430\"\t\"GSM816431\"\t\"GSM816432\"\t\"GSM816433\"\t\"GSM816434\"\t\"GSM816435\"\n",
      "First data line: \"1007_s_at\"\t3.907563631\t3.318962591\t3.98536714\t4.271082363\t2.662877522\t4.922713597\t5.212086782\t3.542450029\t5.171343838\t4.097394296\t4.474937028\t4.427429853\t4.155954785\t3.839779638\t4.479720696\t3.371124677\t4.038207496\t4.219455083\t3.892608822\t4.45604985\t4.402967007\t3.704188659\t3.89026041\t4.076764483\t4.167769501\t3.908383635\t4.230898849\t4.00237022\t4.325269426\t3.644105352\t4.879649423\t5.40470506\t4.495447925\t4.594496346\t5.19170564\t4.793711304\t4.587338357\t4.639496754\t5.590971478\t4.499214918\t5.771727852\t5.431383575\t5.558481219\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Index(['1007_s_at', '1053_at', '117_at', '121_at', '1255_g_at', '1294_at',\n",
      "       '1316_at', '1320_at', '1405_i_at', '1431_at', '1438_at', '1487_at',\n",
      "       '1494_f_at', '1552256_a_at', '1552257_a_at', '1552258_at', '1552261_at',\n",
      "       '1552263_at', '1552264_a_at', '1552266_at'],\n",
      "      dtype='object', name='ID')\n"
     ]
    }
   ],
   "source": [
    "# 1. Get the file paths for the SOFT file and matrix file\n",
    "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
    "\n",
    "# 2. First, let's examine the structure of the matrix file to understand its format\n",
    "import gzip\n",
    "\n",
    "# Peek at the first few lines of the file to understand its structure\n",
    "with gzip.open(matrix_file, 'rt') as file:\n",
    "    # Read first 100 lines to find the header structure\n",
    "    for i, line in enumerate(file):\n",
    "        if '!series_matrix_table_begin' in line:\n",
    "            print(f\"Found data marker at line {i}\")\n",
    "            # Read the next line which should be the header\n",
    "            header_line = next(file)\n",
    "            print(f\"Header line: {header_line.strip()}\")\n",
    "            # And the first data line\n",
    "            first_data_line = next(file)\n",
    "            print(f\"First data line: {first_data_line.strip()}\")\n",
    "            break\n",
    "        if i > 100:  # Limit search to first 100 lines\n",
    "            print(\"Matrix table marker not found in first 100 lines\")\n",
    "            break\n",
    "\n",
    "# 3. Now try to get the genetic data with better error handling\n",
    "try:\n",
    "    gene_data = get_genetic_data(matrix_file)\n",
    "    print(gene_data.index[:20])\n",
    "except KeyError as e:\n",
    "    print(f\"KeyError: {e}\")\n",
    "    \n",
    "    # Alternative approach: manually extract the data\n",
    "    print(\"\\nTrying alternative approach to read the gene data:\")\n",
    "    with gzip.open(matrix_file, 'rt') as file:\n",
    "        # Find the start of the data\n",
    "        for line in file:\n",
    "            if '!series_matrix_table_begin' in line:\n",
    "                break\n",
    "                \n",
    "        # Read the headers and data\n",
    "        import pandas as pd\n",
    "        df = pd.read_csv(file, sep='\\t', index_col=0)\n",
    "        print(f\"Column names: {df.columns[:5]}\")\n",
    "        print(f\"First 20 row IDs: {df.index[:20]}\")\n",
    "        gene_data = df\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a38ef274",
   "metadata": {},
   "source": [
    "### Step 4: Gene Identifier Review"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "14b0ed1c",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:24:52.065556Z",
     "iopub.status.busy": "2025-03-25T05:24:52.065433Z",
     "iopub.status.idle": "2025-03-25T05:24:52.067363Z",
     "shell.execute_reply": "2025-03-25T05:24:52.067067Z"
    }
   },
   "outputs": [],
   "source": [
    "# Looking at the gene identifiers like \"1007_s_at\", \"1053_at\", \"117_at\", etc.\n",
    "# These appear to be Affymetrix probe IDs from a microarray platform,\n",
    "# not standard human gene symbols like BRCA1, TP53, etc.\n",
    "# Therefore, these identifiers need to be mapped to standard gene symbols.\n",
    "\n",
    "requires_gene_mapping = True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "068a32d9",
   "metadata": {},
   "source": [
    "### Step 5: Gene Annotation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "b1565cc4",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:24:52.068572Z",
     "iopub.status.busy": "2025-03-25T05:24:52.068465Z",
     "iopub.status.idle": "2025-03-25T05:24:52.978439Z",
     "shell.execute_reply": "2025-03-25T05:24:52.978002Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Examining SOFT file structure:\n",
      "Line 0: ^DATABASE = GeoMiame\n",
      "Line 1: !Database_name = Gene Expression Omnibus (GEO)\n",
      "Line 2: !Database_institute = NCBI NLM NIH\n",
      "Line 3: !Database_web_link = http://www.ncbi.nlm.nih.gov/geo\n",
      "Line 4: !Database_email = [email protected]\n",
      "Line 5: ^SERIES = GSE32962\n",
      "Line 6: !Series_title = In vitro prednisolone resistance signature in MLL-rearranged infant ALL\n",
      "Line 7: !Series_geo_accession = GSE32962\n",
      "Line 8: !Series_status = Public on Oct 13 2011\n",
      "Line 9: !Series_submission_date = Oct 13 2011\n",
      "Line 10: !Series_last_update_date = Mar 25 2019\n",
      "Line 11: !Series_pubmed_id = 22282267\n",
      "Line 12: !Series_summary = Acute Lymphoblastic Leukemia (ALL) in infants (<1 year of age) is characterized by a high incidence of MLL translocations which is associated with a poor prognosis. Contributing to this poor prognosis is cellular drug resistance, especially to glucocorticoids like prednisolone. Although in vitro prednisolone resistance mechanisms have been proposed in pediatric ALL, it has never been studied in MLL-rearranged infant ALL, which are highly resistant to glucocorticoids in vitro and in vivo.\n",
      "Line 13: !Series_overall_design = We analyzed primary MLL-rearranged infant ALL expression profiles, which were either in vitro prednisolone-resistant or prednisolone-sensitive, in order to study in vitro prednisolone resistance.\n",
      "Line 14: !Series_type = Expression profiling by array\n",
      "Line 15: !Series_contributor = J,A,Spijkers-Hagelstein\n",
      "Line 16: !Series_contributor = R,W,Stam\n",
      "Line 17: !Series_sample_id = GSM816393\n",
      "Line 18: !Series_sample_id = GSM816394\n",
      "Line 19: !Series_sample_id = GSM816395\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "Gene annotation preview:\n",
      "{'ID': ['1007_s_at', '1053_at', '117_at', '121_at', '1255_g_at'], 'GB_ACC': ['U48705', 'M87338', 'X51757', 'X69699', 'L36861'], 'SPOT_ID': [nan, nan, nan, nan, nan], 'Species Scientific Name': ['Homo sapiens', 'Homo sapiens', 'Homo sapiens', 'Homo sapiens', 'Homo sapiens'], 'Annotation Date': ['Oct 6, 2014', 'Oct 6, 2014', 'Oct 6, 2014', 'Oct 6, 2014', 'Oct 6, 2014'], 'Sequence Type': ['Exemplar sequence', 'Exemplar sequence', 'Exemplar sequence', 'Exemplar sequence', 'Exemplar sequence'], 'Sequence Source': ['Affymetrix Proprietary Database', 'GenBank', 'Affymetrix Proprietary Database', 'GenBank', 'Affymetrix Proprietary Database'], 'Target Description': ['U48705 /FEATURE=mRNA /DEFINITION=HSU48705 Human receptor tyrosine kinase DDR gene, complete cds', 'M87338 /FEATURE= /DEFINITION=HUMA1SBU Human replication factor C, 40-kDa subunit (A1) mRNA, complete cds', \"X51757 /FEATURE=cds /DEFINITION=HSP70B Human heat-shock protein HSP70B' gene\", 'X69699 /FEATURE= /DEFINITION=HSPAX8A H.sapiens Pax8 mRNA', 'L36861 /FEATURE=expanded_cds /DEFINITION=HUMGCAPB Homo sapiens guanylate cyclase activating protein (GCAP) gene exons 1-4, complete cds'], 'Representative Public ID': ['U48705', 'M87338', 'X51757', 'X69699', 'L36861'], 'Gene Title': ['discoidin domain receptor tyrosine kinase 1 /// microRNA 4640', 'replication factor C (activator 1) 2, 40kDa', \"heat shock 70kDa protein 6 (HSP70B')\", 'paired box 8', 'guanylate cyclase activator 1A (retina)'], 'Gene Symbol': ['DDR1 /// MIR4640', 'RFC2', 'HSPA6', 'PAX8', 'GUCA1A'], 'ENTREZ_GENE_ID': ['780 /// 100616237', '5982', '3310', '7849', '2978'], 'RefSeq Transcript ID': ['NM_001202521 /// NM_001202522 /// NM_001202523 /// NM_001954 /// NM_013993 /// NM_013994 /// NR_039783 /// XM_005249385 /// XM_005249386 /// XM_005249387 /// XM_005249389 /// XM_005272873 /// XM_005272874 /// XM_005272875 /// XM_005272877 /// XM_005275027 /// XM_005275028 /// XM_005275030 /// XM_005275031 /// XM_005275162 /// XM_005275163 /// XM_005275164 /// XM_005275166 /// XM_005275457 /// XM_005275458 /// XM_005275459 /// XM_005275461 /// XM_006715185 /// XM_006715186 /// XM_006715187 /// XM_006715188 /// XM_006715189 /// XM_006715190 /// XM_006725501 /// XM_006725502 /// XM_006725503 /// XM_006725504 /// XM_006725505 /// XM_006725506 /// XM_006725714 /// XM_006725715 /// XM_006725716 /// XM_006725717 /// XM_006725718 /// XM_006725719 /// XM_006725720 /// XM_006725721 /// XM_006725722 /// XM_006725827 /// XM_006725828 /// XM_006725829 /// XM_006725830 /// XM_006725831 /// XM_006725832 /// XM_006726017 /// XM_006726018 /// XM_006726019 /// XM_006726020 /// XM_006726021 /// XM_006726022 /// XR_427836 /// XR_430858 /// XR_430938 /// XR_430974 /// XR_431015', 'NM_001278791 /// NM_001278792 /// NM_001278793 /// NM_002914 /// NM_181471 /// XM_006716080', 'NM_002155', 'NM_003466 /// NM_013951 /// NM_013952 /// NM_013953 /// NM_013992', 'NM_000409 /// XM_006715073'], 'Gene Ontology Biological Process': ['0001558 // regulation of cell growth // inferred from electronic annotation /// 0001952 // regulation of cell-matrix adhesion // inferred from electronic annotation /// 0006468 // protein phosphorylation // inferred from electronic annotation /// 0007155 // cell adhesion // traceable author statement /// 0007169 // transmembrane receptor protein tyrosine kinase signaling pathway // inferred from electronic annotation /// 0007565 // female pregnancy // inferred from electronic annotation /// 0007566 // embryo implantation // inferred from electronic annotation /// 0007595 // lactation // inferred from electronic annotation /// 0008285 // negative regulation of cell proliferation // inferred from electronic annotation /// 0010715 // regulation of extracellular matrix disassembly // inferred from mutant phenotype /// 0014909 // smooth muscle cell migration // inferred from mutant phenotype /// 0016310 // phosphorylation // inferred from electronic annotation /// 0018108 // peptidyl-tyrosine phosphorylation // inferred from electronic annotation /// 0030198 // extracellular matrix organization // traceable author statement /// 0038063 // collagen-activated tyrosine kinase receptor signaling pathway // inferred from direct assay /// 0038063 // collagen-activated tyrosine kinase receptor signaling pathway // inferred from mutant phenotype /// 0038083 // peptidyl-tyrosine autophosphorylation // inferred from direct assay /// 0043583 // ear development // inferred from electronic annotation /// 0044319 // wound healing, spreading of cells // inferred from mutant phenotype /// 0046777 // protein autophosphorylation // inferred from direct assay /// 0060444 // branching involved in mammary gland duct morphogenesis // inferred from electronic annotation /// 0060749 // mammary gland alveolus development // inferred from electronic annotation /// 0061302 // smooth muscle cell-matrix adhesion // inferred from mutant phenotype', '0000278 // mitotic cell cycle // traceable author statement /// 0000722 // telomere maintenance via recombination // traceable author statement /// 0000723 // telomere maintenance // traceable author statement /// 0006260 // DNA replication // traceable author statement /// 0006271 // DNA strand elongation involved in DNA replication // traceable author statement /// 0006281 // DNA repair // traceable author statement /// 0006283 // transcription-coupled nucleotide-excision repair // traceable author statement /// 0006289 // nucleotide-excision repair // traceable author statement /// 0006297 // nucleotide-excision repair, DNA gap filling // traceable author statement /// 0015979 // photosynthesis // inferred from electronic annotation /// 0015995 // chlorophyll biosynthetic process // inferred from electronic annotation /// 0032201 // telomere maintenance via semi-conservative replication // traceable author statement', '0000902 // cell morphogenesis // inferred from electronic annotation /// 0006200 // ATP catabolic process // inferred from direct assay /// 0006950 // response to stress // inferred from electronic annotation /// 0006986 // response to unfolded protein // traceable author statement /// 0034605 // cellular response to heat // inferred from direct assay /// 0042026 // protein refolding // inferred from direct assay /// 0070370 // cellular heat acclimation // inferred from mutant phenotype', '0001655 // urogenital system development // inferred from sequence or structural similarity /// 0001656 // metanephros development // inferred from electronic annotation /// 0001658 // branching involved in ureteric bud morphogenesis // inferred from expression pattern /// 0001822 // kidney development // inferred from expression pattern /// 0001823 // mesonephros development // inferred from sequence or structural similarity /// 0003337 // mesenchymal to epithelial transition involved in metanephros morphogenesis // inferred from expression pattern /// 0006351 // transcription, DNA-templated // inferred from direct assay /// 0006355 // regulation of transcription, DNA-templated // inferred from electronic annotation /// 0007275 // multicellular organismal development // inferred from electronic annotation /// 0007417 // central nervous system development // inferred from expression pattern /// 0009653 // anatomical structure morphogenesis // traceable author statement /// 0030154 // cell differentiation // inferred from electronic annotation /// 0030878 // thyroid gland development // inferred from expression pattern /// 0030878 // thyroid gland development // inferred from mutant phenotype /// 0038194 // thyroid-stimulating hormone signaling pathway // traceable author statement /// 0039003 // pronephric field specification // inferred from sequence or structural similarity /// 0042472 // inner ear morphogenesis // inferred from sequence or structural similarity /// 0042981 // regulation of apoptotic process // inferred from sequence or structural similarity /// 0045893 // positive regulation of transcription, DNA-templated // inferred from direct assay /// 0045893 // positive regulation of transcription, DNA-templated // inferred from sequence or structural similarity /// 0045944 // positive regulation of transcription from RNA polymerase II promoter // inferred from direct assay /// 0048793 // pronephros development // inferred from sequence or structural similarity /// 0071371 // cellular response to gonadotropin stimulus // inferred from direct assay /// 0071599 // otic vesicle development // inferred from expression pattern /// 0072050 // S-shaped body morphogenesis // inferred from electronic annotation /// 0072073 // kidney epithelium development // inferred from electronic annotation /// 0072108 // positive regulation of mesenchymal to epithelial transition involved in metanephros morphogenesis // inferred from sequence or structural similarity /// 0072164 // mesonephric tubule development // inferred from electronic annotation /// 0072207 // metanephric epithelium development // inferred from expression pattern /// 0072221 // metanephric distal convoluted tubule development // inferred from sequence or structural similarity /// 0072278 // metanephric comma-shaped body morphogenesis // inferred from expression pattern /// 0072284 // metanephric S-shaped body morphogenesis // inferred from expression pattern /// 0072289 // metanephric nephron tubule formation // inferred from sequence or structural similarity /// 0072305 // negative regulation of mesenchymal cell apoptotic process involved in metanephric nephron morphogenesis // inferred from sequence or structural similarity /// 0072307 // regulation of metanephric nephron tubule epithelial cell differentiation // inferred from sequence or structural similarity /// 0090190 // positive regulation of branching involved in ureteric bud morphogenesis // inferred from sequence or structural similarity /// 1900212 // negative regulation of mesenchymal cell apoptotic process involved in metanephros development // inferred from sequence or structural similarity /// 1900215 // negative regulation of apoptotic process involved in metanephric collecting duct development // inferred from sequence or structural similarity /// 1900218 // negative regulation of apoptotic process involved in metanephric nephron tubule development // inferred from sequence or structural similarity /// 2000594 // positive regulation of metanephric DCT cell differentiation // inferred from sequence or structural similarity /// 2000611 // positive regulation of thyroid hormone generation // inferred from mutant phenotype /// 2000612 // regulation of thyroid-stimulating hormone secretion // inferred from mutant phenotype', '0007165 // signal transduction // non-traceable author statement /// 0007601 // visual perception // inferred from electronic annotation /// 0007602 // phototransduction // inferred from electronic annotation /// 0007603 // phototransduction, visible light // traceable author statement /// 0016056 // rhodopsin mediated signaling pathway // traceable author statement /// 0022400 // regulation of rhodopsin mediated signaling pathway // traceable author statement /// 0030828 // positive regulation of cGMP biosynthetic process // inferred from electronic annotation /// 0031282 // regulation of guanylate cyclase activity // inferred from electronic annotation /// 0031284 // positive regulation of guanylate cyclase activity // inferred from electronic annotation /// 0050896 // response to stimulus // inferred from electronic annotation'], 'Gene Ontology Cellular Component': ['0005576 // extracellular region // inferred from electronic annotation /// 0005615 // extracellular space // inferred from direct assay /// 0005886 // plasma membrane // traceable author statement /// 0005887 // integral component of plasma membrane // traceable author statement /// 0016020 // membrane // inferred from electronic annotation /// 0016021 // integral component of membrane // inferred from electronic annotation /// 0043235 // receptor complex // inferred from direct assay /// 0070062 // extracellular vesicular exosome // inferred from direct assay', '0005634 // nucleus // inferred from electronic annotation /// 0005654 // nucleoplasm // traceable author statement /// 0005663 // DNA replication factor C complex // inferred from direct assay', '0005737 // cytoplasm // inferred from direct assay /// 0005814 // centriole // inferred from direct assay /// 0005829 // cytosol // inferred from direct assay /// 0008180 // COP9 signalosome // inferred from direct assay /// 0070062 // extracellular vesicular exosome // inferred from direct assay /// 0072562 // blood microparticle // inferred from direct assay', '0005634 // nucleus // inferred from direct assay /// 0005654 // nucleoplasm // inferred from sequence or structural similarity /// 0005730 // nucleolus // inferred from direct assay', '0001750 // photoreceptor outer segment // inferred from electronic annotation /// 0001917 // photoreceptor inner segment // inferred from electronic annotation /// 0005578 // proteinaceous extracellular matrix // inferred from electronic annotation /// 0005886 // plasma membrane // inferred from direct assay /// 0016020 // membrane // inferred from electronic annotation /// 0097381 // photoreceptor disc membrane // traceable author statement'], 'Gene Ontology Molecular Function': ['0000166 // nucleotide binding // inferred from electronic annotation /// 0004672 // protein kinase activity // inferred from electronic annotation /// 0004713 // protein tyrosine kinase activity // inferred from electronic annotation /// 0004714 // transmembrane receptor protein tyrosine kinase activity // traceable author statement /// 0005515 // protein binding // inferred from physical interaction /// 0005518 // collagen binding // inferred from direct assay /// 0005518 // collagen binding // inferred from mutant phenotype /// 0005524 // ATP binding // inferred from electronic annotation /// 0016301 // kinase activity // inferred from electronic annotation /// 0016740 // transferase activity // inferred from electronic annotation /// 0016772 // transferase activity, transferring phosphorus-containing groups // inferred from electronic annotation /// 0038062 // protein tyrosine kinase collagen receptor activity // inferred from direct assay /// 0046872 // metal ion binding // inferred from electronic annotation', '0000166 // nucleotide binding // inferred from electronic annotation /// 0003677 // DNA binding // inferred from electronic annotation /// 0005515 // protein binding // inferred from physical interaction /// 0005524 // ATP binding // inferred from electronic annotation /// 0016851 // magnesium chelatase activity // inferred from electronic annotation /// 0017111 // nucleoside-triphosphatase activity // inferred from electronic annotation', '0000166 // nucleotide binding // inferred from electronic annotation /// 0005524 // ATP binding // inferred from electronic annotation /// 0019899 // enzyme binding // inferred from physical interaction /// 0031072 // heat shock protein binding // inferred from physical interaction /// 0042623 // ATPase activity, coupled // inferred from direct assay /// 0051082 // unfolded protein binding // inferred from direct assay', '0000979 // RNA polymerase II core promoter sequence-specific DNA binding // inferred from direct assay /// 0003677 // DNA binding // inferred from direct assay /// 0003677 // DNA binding // inferred from mutant phenotype /// 0003700 // sequence-specific DNA binding transcription factor activity // inferred from direct assay /// 0004996 // thyroid-stimulating hormone receptor activity // traceable author statement /// 0005515 // protein binding // inferred from physical interaction /// 0044212 // transcription regulatory region DNA binding // inferred from direct assay', '0005509 // calcium ion binding // inferred from electronic annotation /// 0008048 // calcium sensitive guanylate cyclase activator activity // inferred from electronic annotation /// 0030249 // guanylate cyclase regulator activity // inferred from electronic annotation /// 0046872 // metal ion binding // inferred from electronic annotation']}\n"
     ]
    }
   ],
   "source": [
    "# 1. Let's first examine the structure of the SOFT file before trying to parse it\n",
    "import gzip\n",
    "\n",
    "# Look at the first few lines of the SOFT file to understand its structure\n",
    "print(\"Examining SOFT file structure:\")\n",
    "try:\n",
    "    with gzip.open(soft_file, 'rt') as file:\n",
    "        # Read first 20 lines to understand the file structure\n",
    "        for i, line in enumerate(file):\n",
    "            if i < 20:\n",
    "                print(f\"Line {i}: {line.strip()}\")\n",
    "            else:\n",
    "                break\n",
    "except Exception as e:\n",
    "    print(f\"Error reading SOFT file: {e}\")\n",
    "\n",
    "# 2. Now let's try a more robust approach to extract the gene annotation\n",
    "# Instead of using the library function which failed, we'll implement a custom approach\n",
    "try:\n",
    "    # First, look for the platform section which contains gene annotation\n",
    "    platform_data = []\n",
    "    with gzip.open(soft_file, 'rt') as file:\n",
    "        in_platform_section = False\n",
    "        for line in file:\n",
    "            if line.startswith('^PLATFORM'):\n",
    "                in_platform_section = True\n",
    "                continue\n",
    "            if in_platform_section and line.startswith('!platform_table_begin'):\n",
    "                # Next line should be the header\n",
    "                header = next(file).strip()\n",
    "                platform_data.append(header)\n",
    "                # Read until the end of the platform table\n",
    "                for table_line in file:\n",
    "                    if table_line.startswith('!platform_table_end'):\n",
    "                        break\n",
    "                    platform_data.append(table_line.strip())\n",
    "                break\n",
    "    \n",
    "    # If we found platform data, convert it to a DataFrame\n",
    "    if platform_data:\n",
    "        import pandas as pd\n",
    "        import io\n",
    "        platform_text = '\\n'.join(platform_data)\n",
    "        gene_annotation = pd.read_csv(io.StringIO(platform_text), delimiter='\\t', \n",
    "                                      low_memory=False, on_bad_lines='skip')\n",
    "        print(\"\\nGene annotation preview:\")\n",
    "        print(preview_df(gene_annotation))\n",
    "    else:\n",
    "        print(\"Could not find platform table in SOFT file\")\n",
    "        \n",
    "        # Try an alternative approach - extract mapping from other sections\n",
    "        with gzip.open(soft_file, 'rt') as file:\n",
    "            for line in file:\n",
    "                if 'ANNOTATION information' in line or 'annotation information' in line:\n",
    "                    print(f\"Found annotation information: {line.strip()}\")\n",
    "                if line.startswith('!Platform_title') or line.startswith('!platform_title'):\n",
    "                    print(f\"Platform title: {line.strip()}\")\n",
    "            \n",
    "except Exception as e:\n",
    "    print(f\"Error processing gene annotation: {e}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6ee538ef",
   "metadata": {},
   "source": [
    "### Step 6: Gene Identifier Mapping"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "8c6ffe20",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:24:52.980261Z",
     "iopub.status.busy": "2025-03-25T05:24:52.980115Z",
     "iopub.status.idle": "2025-03-25T05:24:53.749122Z",
     "shell.execute_reply": "2025-03-25T05:24:53.748584Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene mapping preview:\n",
      "          ID              Gene\n",
      "0  1007_s_at  DDR1 /// MIR4640\n",
      "1    1053_at              RFC2\n",
      "2     117_at             HSPA6\n",
      "3     121_at              PAX8\n",
      "4  1255_g_at            GUCA1A\n",
      "\n",
      "Gene data after mapping:\n",
      "Shape: (21253, 43)\n",
      "First few gene symbols:\n",
      "Index(['A1BG', 'A1BG-AS1', 'A1CF', 'A2M', 'A2M-AS1', 'A2ML1', 'A2MP1',\n",
      "       'A4GALT', 'A4GNT', 'AA06'],\n",
      "      dtype='object', name='Gene')\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene expression data saved to ../../output/preprocess/Glucocorticoid_Sensitivity/gene_data/GSE32962.csv\n"
     ]
    }
   ],
   "source": [
    "# 1. Identify the relevant columns in gene annotation that match the gene IDs and gene symbols\n",
    "probe_id_column = 'ID'  # Observed from gene annotation data - matches the index of gene_data\n",
    "gene_symbol_column = 'Gene Symbol'  # Column containing gene symbols\n",
    "\n",
    "# 2. Extract the mapping between probe IDs and gene symbols\n",
    "gene_mapping = get_gene_mapping(gene_annotation, probe_id_column, gene_symbol_column)\n",
    "\n",
    "# Preview the mapping to ensure it's correct\n",
    "print(\"Gene mapping preview:\")\n",
    "print(gene_mapping.head())\n",
    "\n",
    "# 3. Apply the mapping to convert probe-level expression to gene-level expression\n",
    "gene_data = apply_gene_mapping(gene_data, gene_mapping)\n",
    "\n",
    "# Check the first few rows and shape of the resulting gene expression data\n",
    "print(\"\\nGene data after mapping:\")\n",
    "print(f\"Shape: {gene_data.shape}\")\n",
    "print(\"First few gene symbols:\")\n",
    "print(gene_data.index[:10])\n",
    "\n",
    "# Create output directory if it doesn't exist\n",
    "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
    "\n",
    "# Save the processed gene data to CSV\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": "0522e28c",
   "metadata": {},
   "source": [
    "### Step 7: Data Normalization and Linking"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "af3df55c",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:24:53.750667Z",
     "iopub.status.busy": "2025-03-25T05:24:53.750538Z",
     "iopub.status.idle": "2025-03-25T05:25:03.964614Z",
     "shell.execute_reply": "2025-03-25T05:25:03.963866Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene data shape after normalization: (19823, 43)\n",
      "Sample gene symbols after normalization: ['A1BG', 'A1BG-AS1', 'A1CF', 'A2M', 'A2M-AS1', 'A2ML1', 'A2MP1', 'A4GALT', 'A4GNT', 'AA06']\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene data saved to ../../output/preprocess/Glucocorticoid_Sensitivity/gene_data/GSE32962.csv\n",
      "Clinical data shape: (2, 43)\n",
      "Clinical data preview:\n",
      "   GSM816393  GSM816394  GSM816395  GSM816396  GSM816397  GSM816398  \\\n",
      "0        1.0        1.0        1.0        1.0        1.0        1.0   \n",
      "1        0.5        0.5        0.5        0.5        0.5        0.5   \n",
      "\n",
      "   GSM816399  GSM816400  GSM816401  GSM816402  ...  GSM816426  GSM816427  \\\n",
      "0        1.0        1.0        1.0        1.0  ...        0.0        0.0   \n",
      "1        0.5        0.5        0.5        0.5  ...        0.5        0.5   \n",
      "\n",
      "   GSM816428  GSM816429  GSM816430  GSM816431  GSM816432  GSM816433  \\\n",
      "0        0.0        0.0        0.0        0.0        0.0        0.0   \n",
      "1        0.5        0.5        0.5        0.5        0.5        0.5   \n",
      "\n",
      "   GSM816434  GSM816435  \n",
      "0        0.0        0.0  \n",
      "1        0.5        0.5  \n",
      "\n",
      "[2 rows x 43 columns]\n",
      "\n",
      "Linked data shape: (43, 19825)\n",
      "Linked data preview (first 5 rows, first 10 columns):\n",
      "           Glucocorticoid_Sensitivity  Age      A1BG  A1BG-AS1      A1CF  \\\n",
      "Sample_ID                                                                  \n",
      "GSM816393                         1.0  0.5  5.001876  2.810375  5.783136   \n",
      "GSM816394                         1.0  0.5  4.196047  2.902940  5.866804   \n",
      "GSM816395                         1.0  0.5  5.150384  3.526135  5.903096   \n",
      "GSM816396                         1.0  0.5  5.065505  3.518386  6.267063   \n",
      "GSM816397                         1.0  0.5  5.383749  3.816337  5.422859   \n",
      "\n",
      "                A2M   A2M-AS1     A2ML1     A2MP1    A4GALT  \n",
      "Sample_ID                                                    \n",
      "GSM816393  5.709695  1.222944  6.378610  3.741055  3.391859  \n",
      "GSM816394  5.843247  1.738531  5.712951  3.494124  2.431028  \n",
      "GSM816395  4.649645  1.573531  6.861088  1.314516  3.262087  \n",
      "GSM816396  6.238998  2.227465  4.495667  2.616780  2.694314  \n",
      "GSM816397  5.703648  1.951251  5.719359  1.781286  1.965361  \n",
      "\n",
      "Missing values before handling:\n",
      "  Trait (Glucocorticoid_Sensitivity) missing: 0 out of 43\n",
      "  Genes with >20% missing: 0\n",
      "  Samples with >5% missing genes: 0\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Data shape after handling missing values: (43, 19825)\n",
      "For the feature 'Glucocorticoid_Sensitivity', the least common label is '0.0' with 19 occurrences. This represents 44.19% of the dataset.\n",
      "The distribution of the feature 'Glucocorticoid_Sensitivity' in this dataset is fine.\n",
      "\n",
      "Quartiles for 'Age':\n",
      "  25%: 0.5\n",
      "  50% (Median): 0.5\n",
      "  75%: 0.5\n",
      "Min: 0.5\n",
      "Max: 0.5\n",
      "The distribution of the feature 'Age' in this dataset is severely biased.\n",
      "\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Linked data saved to ../../output/preprocess/Glucocorticoid_Sensitivity/GSE32962.csv\n"
     ]
    }
   ],
   "source": [
    "# 1. Normalize gene symbols in the obtained gene expression data\n",
    "normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n",
    "print(f\"Gene data shape after normalization: {normalized_gene_data.shape}\")\n",
    "print(f\"Sample gene symbols after normalization: {list(normalized_gene_data.index[:10])}\")\n",
    "\n",
    "# Save the normalized gene data\n",
    "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
    "normalized_gene_data.to_csv(out_gene_data_file)\n",
    "print(f\"Gene data saved to {out_gene_data_file}\")\n",
    "\n",
    "# 2. Load the previously saved clinical data\n",
    "clinical_data = pd.read_csv(out_clinical_data_file)\n",
    "print(f\"Clinical data shape: {clinical_data.shape}\")\n",
    "print(\"Clinical data preview:\")\n",
    "print(clinical_data.head())\n",
    "\n",
    "# 3. Link clinical and genetic data\n",
    "# First convert clinical data to proper format with trait as column name\n",
    "clinical_df_t = clinical_data.T.reset_index()\n",
    "clinical_df_t.columns = ['Sample_ID', trait, 'Age']  # Set proper column names\n",
    "\n",
    "# Convert gene expression data to have samples as rows\n",
    "gene_data_t = normalized_gene_data.T.reset_index()\n",
    "gene_data_t = gene_data_t.rename(columns={'index': 'Sample_ID'})\n",
    "\n",
    "# Merge the two dataframes on Sample_ID\n",
    "linked_data = pd.merge(clinical_df_t, gene_data_t, on='Sample_ID')\n",
    "linked_data = linked_data.set_index('Sample_ID')\n",
    "\n",
    "print(f\"\\nLinked data shape: {linked_data.shape}\")\n",
    "print(\"Linked data preview (first 5 rows, first 10 columns):\")\n",
    "if linked_data.shape[1] >= 10:\n",
    "    print(linked_data.iloc[:5, :10])\n",
    "else:\n",
    "    print(linked_data.head())\n",
    "\n",
    "# 4. Handle missing values\n",
    "if linked_data.shape[0] > 0:\n",
    "    print(\"\\nMissing values before handling:\")\n",
    "    print(f\"  Trait ({trait}) missing: {linked_data[trait].isna().sum()} out of {len(linked_data)}\")\n",
    "    \n",
    "    gene_cols = [col for col in linked_data.columns if col not in [trait, 'Age', 'Gender']]\n",
    "    if gene_cols:\n",
    "        missing_genes_pct = linked_data[gene_cols].isna().mean()\n",
    "        genes_with_high_missing = sum(missing_genes_pct > 0.2)\n",
    "        print(f\"  Genes with >20% missing: {genes_with_high_missing}\")\n",
    "        \n",
    "        missing_per_sample = linked_data[gene_cols].isna().mean(axis=1)\n",
    "        samples_with_high_missing = sum(missing_per_sample > 0.05)\n",
    "        print(f\"  Samples with >5% missing genes: {samples_with_high_missing}\")\n",
    "\n",
    "    # Handle missing values\n",
    "    cleaned_data = handle_missing_values(linked_data, trait)\n",
    "    print(f\"Data shape after handling missing values: {cleaned_data.shape}\")\n",
    "\n",
    "    # 5. Evaluate bias in trait and demographic features\n",
    "    trait_biased, cleaned_data = judge_and_remove_biased_features(cleaned_data, trait)\n",
    "else:\n",
    "    print(\"No samples in linked data, skipping missing value handling and bias evaluation\")\n",
    "    cleaned_data = linked_data\n",
    "    trait_biased = True  # Mark as biased if we have no data\n",
    "\n",
    "# 6. Final validation and save\n",
    "note = \"Dataset contains gene expression data from glucocorticoid sensitivity studies. \"\n",
    "if linked_data.shape[0] > 0:\n",
    "    if 'Age' in cleaned_data.columns:\n",
    "        note += \"Age data is available but constant across all samples (all patients are infants under 1 year). \"\n",
    "else:\n",
    "    note += \"ERROR: No samples remained after linking clinical and gene data.\"\n",
    "\n",
    "is_gene_available = len(normalized_gene_data) > 0\n",
    "is_trait_available = True\n",
    "\n",
    "# Check if the cleaned data is empty\n",
    "if cleaned_data.shape[0] == 0:\n",
    "    note += \" WARNING: Dataset has 0 samples after preprocessing.\"\n",
    "    \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=trait_biased, \n",
    "    df=cleaned_data,\n",
    "    note=note\n",
    ")\n",
    "\n",
    "# 7. Save if usable\n",
    "if is_usable and len(cleaned_data) > 0:\n",
    "    os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n",
    "    cleaned_data.to_csv(out_data_file)\n",
    "    print(f\"Linked data saved to {out_data_file}\")\n",
    "else:\n",
    "    print(\"Data was determined to be unusable or empty and was 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
}