File size: 50,687 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
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "8afbc994",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:25:36.150236Z",
     "iopub.status.busy": "2025-03-25T05:25:36.149988Z",
     "iopub.status.idle": "2025-03-25T05:25:36.317614Z",
     "shell.execute_reply": "2025-03-25T05:25:36.317226Z"
    }
   },
   "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 = \"GSE57795\"\n",
    "\n",
    "# Input paths\n",
    "in_trait_dir = \"../../input/GEO/Glucocorticoid_Sensitivity\"\n",
    "in_cohort_dir = \"../../input/GEO/Glucocorticoid_Sensitivity/GSE57795\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/Glucocorticoid_Sensitivity/GSE57795.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/Glucocorticoid_Sensitivity/gene_data/GSE57795.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/Glucocorticoid_Sensitivity/clinical_data/GSE57795.csv\"\n",
    "json_path = \"../../output/preprocess/Glucocorticoid_Sensitivity/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "538e4dbb",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "f7e68a2e",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:25:36.318846Z",
     "iopub.status.busy": "2025-03-25T05:25:36.318695Z",
     "iopub.status.idle": "2025-03-25T05:25:36.515277Z",
     "shell.execute_reply": "2025-03-25T05:25:36.514708Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Background Information:\n",
      "!Series_title\t\"in vivo dexamethasone-induced gene expression in pediatric acute lymphoblastic leukemia patient-derived xenografts\"\n",
      "!Series_summary\t\"Glucocorticoids are critical components of combination chemotherapy regimens in pediatric acute lymphoblastic leukemia (ALL). The pro-apoptotic BIM protein is an important mediator of glucocorticoid-induced apoptosis in normal and malignant lymphocytes, while the anti-apoptotic BCL2 confers resistance. The signaling pathways regulating BIM and BCL2 expression in glucocorticoid-treated lymphoid cells remain unclear. In this study, pediatric ALL patient-derived xenografts (PDXs) inherently sensitive or resistant to glucocorticoids were exposed to dexamethasone in vivo. In order to understand the basis for differential in vivo glucocorticoid sensitivity of PDXs, microarray analysis of gene expression was carried out on 5 each of dexamethasone-sensitive and resistant PDXs . This provided a global understanding of dexamethasone-induced signaling cascades in ALL cells in vivo, and especialy identified the genes that are involved in transducing the apoptotic signal, upstream of BIM/BCL2 dynamic interactions.\"\n",
      "!Series_overall_design\t\"ALL xenograft cells were inoculated by tail-vein injection into NOD/SCID mice, and engraftment was monitored weekly. When >70% %huCD45+ engraftment in the peripheral blood was apparent, which occurred 8-10 weeks post-transplantation, mice were treated with either dexamethasone (15 mg/kg) or vehicle control by intra-peritoneal (IP) injection, and culled at 8 hours following the treatment. Cell suspensions of spleens were prepared and mononuclear cells enriched to >97% human by density gradient centrifugation. RNA was extracted using the RNeasy Mini Kit (QIAGEN, Valencia, CA, USA), and RNA samples with integrity number (RIN) > 8.0 were amplified and hybridized onto Illumina HumanWG-6 v3 Expression BeadChips (6 samples/chip). All chips (with associated reagents) were purchased from Illumina, and scanned on the Illumina BeadArray Reader according to the manufacturer’s instructions. Microarray data were analyzed using the online modules in GenePattern.\"\n",
      "!Series_overall_design\t\"10 xenografts were derived from patients of 5 dexamethasone-good responder and 5 dexamethasone-poor responder. Each xenograft was innoculated into 5-6 mice, and treated with dexamethasone (15 mg/kg) or vehicle control. In total spleen-harvest xenograft samples from 58 mice were analyzed using microarray.\"\n",
      "Sample Characteristics Dictionary:\n",
      "{0: ['strain: NOD/SCID'], 1: ['injection: ALL patient-derived xenograft cells were inoculated by tail-vein injection'], 2: ['age (mouse): xenograft cells injected at 6-10 weeks'], 3: ['treatment: control', 'treatment: 8h dexamethasone'], 4: ['tissue: xenograft cells (>95% hCD45+ cells) from mouse spleens'], 5: ['dexamethasone response: Sensitive patient', 'dexamethasone response: Resistant patient']}\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": "058b9107",
   "metadata": {},
   "source": [
    "### Step 2: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "bc56ea19",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:25:36.516512Z",
     "iopub.status.busy": "2025-03-25T05:25:36.516393Z",
     "iopub.status.idle": "2025-03-25T05:25:36.527076Z",
     "shell.execute_reply": "2025-03-25T05:25:36.526678Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Clinical data preview: {'Sample_0_Sensitive patient': [1.0], 'Sample_0_Resistant patient': [0.0], 'Sample_1_Sensitive patient': [1.0], 'Sample_1_Resistant patient': [0.0]}\n",
      "Clinical data saved to ../../output/preprocess/Glucocorticoid_Sensitivity/clinical_data/GSE57795.csv\n"
     ]
    }
   ],
   "source": [
    "import os\n",
    "import json\n",
    "import pandas as pd\n",
    "import numpy as np\n",
    "from typing import Optional, Dict, Any, Callable\n",
    "\n",
    "# Define whether gene expression data is available\n",
    "# Based on the background information, this is a microarray analysis of gene expression\n",
    "is_gene_available = True\n",
    "\n",
    "# Identify rows in sample characteristics for trait, age, and gender\n",
    "# Trait: Glucocorticoid sensitivity - available in row 5\n",
    "trait_row = 5\n",
    "# Age: Only mouse age is mentioned, not human patient age\n",
    "age_row = None\n",
    "# Gender: No information about gender\n",
    "gender_row = None\n",
    "\n",
    "# Define conversion functions\n",
    "def convert_trait(value_str):\n",
    "    if pd.isna(value_str) or not isinstance(value_str, str):\n",
    "        return None\n",
    "    \n",
    "    # Extract value after colon if present\n",
    "    if ':' in value_str:\n",
    "        value = value_str.split(':', 1)[1].strip()\n",
    "    else:\n",
    "        value = value_str.strip()\n",
    "    \n",
    "    # Convert to binary: Sensitive = 1, Resistant = 0\n",
    "    if 'Sensitive' in value:\n",
    "        return 1\n",
    "    elif 'Resistant' in value:\n",
    "        return 0\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "# Age conversion function (not used but defined for completeness)\n",
    "def convert_age(value_str):\n",
    "    return None  # No human patient age data available\n",
    "\n",
    "# Gender conversion function (not used but defined for completeness)\n",
    "def convert_gender(value_str):\n",
    "    return None  # No gender data available\n",
    "\n",
    "# Determine if trait data is available\n",
    "is_trait_available = trait_row is not None\n",
    "\n",
    "# Validate and save cohort information\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",
    "# If trait data is available, extract clinical features\n",
    "if trait_row is not None:\n",
    "    # Create a proper clinical data DataFrame with all available sample characteristics\n",
    "    # Each row in the sample characteristic dictionary becomes a column\n",
    "    # Create a dataframe with one column per characteristic feature\n",
    "    sample_chars = {\n",
    "        0: ['strain: NOD/SCID'], \n",
    "        1: ['injection: ALL patient-derived xenograft cells were inoculated by tail-vein injection'], \n",
    "        2: ['age (mouse): xenograft cells injected at 6-10 weeks'], \n",
    "        3: ['treatment: control', 'treatment: 8h dexamethasone'], \n",
    "        4: ['tissue: xenograft cells (>95% hCD45+ cells) from mouse spleens'], \n",
    "        5: ['dexamethasone response: Sensitive patient', 'dexamethasone response: Resistant patient']\n",
    "    }\n",
    "    \n",
    "    # We need to simulate the expected clinical data format for geo_select_clinical_features\n",
    "    # Each column will represent a sample, and rows will be characteristics\n",
    "    clinical_data = pd.DataFrame(index=range(max(sample_chars.keys())+1))\n",
    "    \n",
    "    # Add sample columns based on characteristic combinations\n",
    "    # For this dataset, we have 2 main groups of samples: Sensitive and Resistant patients\n",
    "    # And within each, there are samples with control vs dexamethasone treatment\n",
    "    for sample_idx, treatment in enumerate(['treatment: control', 'treatment: 8h dexamethasone']):\n",
    "        for response in ['dexamethasone response: Sensitive patient', 'dexamethasone response: Resistant patient']:\n",
    "            col_name = f\"Sample_{sample_idx}_{response.split(':')[1].strip()}\"\n",
    "            clinical_data[col_name] = None\n",
    "            \n",
    "            # Fill in the characteristics for this sample\n",
    "            clinical_data.loc[0, col_name] = sample_chars[0][0]  # strain\n",
    "            clinical_data.loc[1, col_name] = sample_chars[1][0]  # injection\n",
    "            clinical_data.loc[2, col_name] = sample_chars[2][0]  # age\n",
    "            clinical_data.loc[3, col_name] = treatment           # treatment\n",
    "            clinical_data.loc[4, col_name] = sample_chars[4][0]  # tissue\n",
    "            clinical_data.loc[5, col_name] = response            # response\n",
    "    \n",
    "    # Extract 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 dataframe\n",
    "    preview = preview_df(selected_clinical_df)\n",
    "    print(\"Clinical data preview:\", preview)\n",
    "    \n",
    "    # Create output directory if it doesn't exist\n",
    "    os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
    "    \n",
    "    # Save clinical data to CSV\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": "4f4179ee",
   "metadata": {},
   "source": [
    "### Step 3: Gene Data Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "cc89c285",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:25:36.528305Z",
     "iopub.status.busy": "2025-03-25T05:25:36.528065Z",
     "iopub.status.idle": "2025-03-25T05:25:36.866651Z",
     "shell.execute_reply": "2025-03-25T05:25:36.866276Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Found data marker at line 73\n",
      "Header line: \"ID_REF\"\t\"GSM1388640\"\t\"GSM1388641\"\t\"GSM1388642\"\t\"GSM1388643\"\t\"GSM1388644\"\t\"GSM1388645\"\t\"GSM1388646\"\t\"GSM1388647\"\t\"GSM1388648\"\t\"GSM1388649\"\t\"GSM1388650\"\t\"GSM1388651\"\t\"GSM1388652\"\t\"GSM1388653\"\t\"GSM1388654\"\t\"GSM1388655\"\t\"GSM1388656\"\t\"GSM1388657\"\t\"GSM1388658\"\t\"GSM1388659\"\t\"GSM1388660\"\t\"GSM1388661\"\t\"GSM1388662\"\t\"GSM1388663\"\t\"GSM1388664\"\t\"GSM1388665\"\t\"GSM1388666\"\t\"GSM1388667\"\t\"GSM1388668\"\t\"GSM1388669\"\t\"GSM1388670\"\t\"GSM1388671\"\t\"GSM1388672\"\t\"GSM1388673\"\t\"GSM1388674\"\t\"GSM1388675\"\t\"GSM1388676\"\t\"GSM1388677\"\t\"GSM1388678\"\t\"GSM1388679\"\t\"GSM1388680\"\t\"GSM1388681\"\t\"GSM1388682\"\t\"GSM1388683\"\t\"GSM1388684\"\t\"GSM1388685\"\t\"GSM1388686\"\t\"GSM1388687\"\t\"GSM1388688\"\t\"GSM1388689\"\t\"GSM1388690\"\t\"GSM1388691\"\t\"GSM1388692\"\t\"GSM1388693\"\t\"GSM1388694\"\t\"GSM1388695\"\t\"GSM1388696\"\t\"GSM1388697\"\n",
      "First data line: \"ILMN_1343291\"\t48768.44379\t53241.08914\t53700.17172\t55892.46776\t54228.3381\t52026.32328\t52399.87621\t54890.715\t48768.44379\t49093.39397\t54228.3381\t50756.8881\t53241.08914\t47655.465\t49938.24138\t52834.26724\t46722.82776\t51677.605\t50161.6269\t51677.605\t52026.32328\t52399.87621\t50161.6269\t52399.87621\t54228.3381\t52834.26724\t49698.99879\t53241.08914\t51075.995\t54228.3381\t53700.17172\t53241.08914\t54890.715\t46954.90379\t53241.08914\t52026.32328\t45682.93948\t49093.39397\t51075.995\t51677.605\t54890.715\t52026.32328\t54890.715\t54228.3381\t54890.715\t53700.17172\t49938.24138\t54890.715\t54228.3381\t55892.46776\t53241.08914\t54228.3381\t55892.46776\t53241.08914\t47437.22879\t46722.82776\t52026.32328\t49353.91362\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "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 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": "5c54a741",
   "metadata": {},
   "source": [
    "### Step 4: Gene Identifier Review"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "8a417a61",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:25:36.868059Z",
     "iopub.status.busy": "2025-03-25T05:25:36.867943Z",
     "iopub.status.idle": "2025-03-25T05:25:36.869809Z",
     "shell.execute_reply": "2025-03-25T05:25:36.869544Z"
    }
   },
   "outputs": [],
   "source": [
    "# Looking at the gene identifiers from the output, I can see they start with \"ILMN_\" which indicates\n",
    "# these are Illumina probe IDs, not standard human gene symbols.\n",
    "# Illumina probe identifiers need to be mapped to actual gene symbols for meaningful analysis.\n",
    "\n",
    "requires_gene_mapping = True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "75ea5753",
   "metadata": {},
   "source": [
    "### Step 5: Gene Annotation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "405c32e3",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:25:36.871115Z",
     "iopub.status.busy": "2025-03-25T05:25:36.871017Z",
     "iopub.status.idle": "2025-03-25T05:25:37.308828Z",
     "shell.execute_reply": "2025-03-25T05:25:37.308504Z"
    }
   },
   "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 = GSE57795\n",
      "Line 6: !Series_title = in vivo dexamethasone-induced gene expression in pediatric acute lymphoblastic leukemia patient-derived xenografts\n",
      "Line 7: !Series_geo_accession = GSE57795\n",
      "Line 8: !Series_status = Public on May 20 2014\n",
      "Line 9: !Series_submission_date = May 19 2014\n",
      "Line 10: !Series_last_update_date = Feb 18 2019\n",
      "Line 11: !Series_pubmed_id = 25336632\n",
      "Line 12: !Series_pubmed_id = 26960974\n",
      "Line 13: !Series_pubmed_id = 27302164\n",
      "Line 14: !Series_summary = Glucocorticoids are critical components of combination chemotherapy regimens in pediatric acute lymphoblastic leukemia (ALL). The pro-apoptotic BIM protein is an important mediator of glucocorticoid-induced apoptosis in normal and malignant lymphocytes, while the anti-apoptotic BCL2 confers resistance. The signaling pathways regulating BIM and BCL2 expression in glucocorticoid-treated lymphoid cells remain unclear. In this study, pediatric ALL patient-derived xenografts (PDXs) inherently sensitive or resistant to glucocorticoids were exposed to dexamethasone in vivo. In order to understand the basis for differential in vivo glucocorticoid sensitivity of PDXs, microarray analysis of gene expression was carried out on 5 each of dexamethasone-sensitive and resistant PDXs . This provided a global understanding of dexamethasone-induced signaling cascades in ALL cells in vivo, and especialy identified the genes that are involved in transducing the apoptotic signal, upstream of BIM/BCL2 dynamic interactions.\n",
      "Line 15: !Series_overall_design = ALL xenograft cells were inoculated by tail-vein injection into NOD/SCID mice, and engraftment was monitored weekly. When >70% %huCD45+ engraftment in the peripheral blood was apparent, which occurred 8-10 weeks post-transplantation, mice were treated with either dexamethasone (15 mg/kg) or vehicle control by intra-peritoneal (IP) injection, and culled at 8 hours following the treatment. Cell suspensions of spleens were prepared and mononuclear cells enriched to >97% human by density gradient centrifugation. RNA was extracted using the RNeasy Mini Kit (QIAGEN, Valencia, CA, USA), and RNA samples with integrity number (RIN) > 8.0 were amplified and hybridized onto Illumina HumanWG-6 v3 Expression BeadChips (6 samples/chip). All chips (with associated reagents) were purchased from Illumina, and scanned on the Illumina BeadArray Reader according to the manufacturer’s instructions. Microarray data were analyzed using the online modules in GenePattern.\n",
      "Line 16: !Series_overall_design = 10 xenografts were derived from patients of 5 dexamethasone-good responder and 5 dexamethasone-poor responder. Each xenograft was innoculated into 5-6 mice, and treated with dexamethasone (15 mg/kg) or vehicle control. In total spleen-harvest xenograft samples from 58 mice were analyzed using microarray.\n",
      "Line 17: !Series_type = Expression profiling by array\n",
      "Line 18: !Series_contributor = Vivek,A,Bhadri\n",
      "Line 19: !Series_contributor = Duohui,,Jing\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "Gene annotation preview:\n",
      "{'ID': ['ILMN_1825594', 'ILMN_1810803', 'ILMN_1722532', 'ILMN_1884413', 'ILMN_1906034'], 'Species': ['Homo sapiens', 'Homo sapiens', 'Homo sapiens', 'Homo sapiens', 'Homo sapiens'], 'Source': ['Unigene', 'RefSeq', 'RefSeq', 'Unigene', 'Unigene'], 'Search_Key': ['ILMN_89282', 'ILMN_35826', 'ILMN_25544', 'ILMN_132331', 'ILMN_105017'], 'Transcript': ['ILMN_89282', 'ILMN_35826', 'ILMN_25544', 'ILMN_132331', 'ILMN_105017'], 'ILMN_Gene': ['HS.388528', 'LOC441782', 'JMJD1A', 'HS.580150', 'HS.540210'], 'Source_Reference_ID': ['Hs.388528', 'XM_497527.2', 'NM_018433.3', 'Hs.580150', 'Hs.540210'], 'RefSeq_ID': [nan, 'XM_497527.2', 'NM_018433.3', nan, nan], 'Unigene_ID': ['Hs.388528', nan, nan, 'Hs.580150', 'Hs.540210'], 'Entrez_Gene_ID': [nan, 441782.0, 55818.0, nan, nan], 'GI': [23525203, 89042416, 46358420, 7376124, 5437312], 'Accession': ['BU678343', 'XM_497527.2', 'NM_018433.3', 'AW629334', 'AI818233'], 'Symbol': [nan, 'LOC441782', 'JMJD1A', nan, nan], 'Protein_Product': [nan, 'XP_497527.2', 'NP_060903.2', nan, nan], 'Array_Address_Id': [1740241, 1850750, 1240504, 4050487, 2190598], 'Probe_Type': ['S', 'S', 'S', 'S', 'S'], 'Probe_Start': [349, 902, 4359, 117, 304], 'SEQUENCE': ['CTCTCTAAAGGGACAACAGAGTGGACAGTCAAGGAACTCCACATATTCAT', 'GGGGTCAAGCCCAGGTGAAATGTGGATTGGAAAAGTGCTTCCCTTGCCCC', 'CCAGGCTGTAAAAGCAAAACCTCGTATCAGCTCTGGAACAATACCTGCAG', 'CCAGACAGGAAGCATCAAGCCCTTCAGGAAAGAATATGCGAGAGTGCTGC', 'TGTGCAGAAAGCTGATGGAAGGGAGAAAGAATGGAAGTGGGTCACACAGC'], 'Chromosome': [nan, nan, '2', nan, nan], 'Probe_Chr_Orientation': [nan, nan, '+', nan, nan], 'Probe_Coordinates': [nan, nan, '86572991-86573040', nan, nan], 'Cytoband': [nan, nan, '2p11.2e', nan, nan], 'Definition': ['UI-CF-EC0-abi-c-12-0-UI.s1 UI-CF-EC0 Homo sapiens cDNA clone UI-CF-EC0-abi-c-12-0-UI 3, mRNA sequence', 'PREDICTED: Homo sapiens similar to spectrin domain with coiled-coils 1 (LOC441782), mRNA.', 'Homo sapiens jumonji domain containing 1A (JMJD1A), mRNA.', 'hi56g05.x1 Soares_NFL_T_GBC_S1 Homo sapiens cDNA clone IMAGE:2976344 3, mRNA sequence', 'wk77d04.x1 NCI_CGAP_Pan1 Homo sapiens cDNA clone IMAGE:2421415 3, mRNA sequence'], 'Ontology_Component': [nan, nan, 'nucleus [goid 5634] [evidence IEA]', nan, nan], 'Ontology_Process': [nan, nan, 'chromatin modification [goid 16568] [evidence IEA]; transcription [goid 6350] [evidence IEA]; regulation of transcription, DNA-dependent [goid 6355] [evidence IEA]', nan, nan], 'Ontology_Function': [nan, nan, 'oxidoreductase activity [goid 16491] [evidence IEA]; oxidoreductase activity, acting on single donors with incorporation of molecular oxygen, incorporation of two atoms of oxygen [goid 16702] [evidence IEA]; zinc ion binding [goid 8270] [evidence IEA]; metal ion binding [goid 46872] [evidence IEA]; iron ion binding [goid 5506] [evidence IEA]', nan, nan], 'Synonyms': [nan, nan, 'JHMD2A; JMJD1; TSGA; KIAA0742; DKFZp686A24246; DKFZp686P07111', nan, nan], 'GB_ACC': ['BU678343', 'XM_497527.2', 'NM_018433.3', 'AW629334', 'AI818233']}\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": "ba9565f8",
   "metadata": {},
   "source": [
    "### Step 6: Gene Identifier Mapping"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "a27b34cc",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:25:37.310503Z",
     "iopub.status.busy": "2025-03-25T05:25:37.310386Z",
     "iopub.status.idle": "2025-03-25T05:25:38.117944Z",
     "shell.execute_reply": "2025-03-25T05:25:38.117569Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene mapping preview:\n",
      "{'ID': ['ILMN_1810803', 'ILMN_1722532', 'ILMN_1708805', 'ILMN_1672526', 'ILMN_2185604'], 'Gene': ['LOC441782', 'JMJD1A', 'NCOA3', 'LOC389834', 'C17orf77']}\n",
      "\n",
      "Gene expression data preview (after mapping):\n",
      "Number of genes: 18839\n",
      "Number of samples: 58\n",
      "{'GSM1388640': [311.89239829999997, 377.37908554, 106.2299664, 84.17138431, 190.71983448], 'GSM1388641': [236.99664810000002, 407.73767069, 125.0610366, 93.79152293, 199.56930326], 'GSM1388642': [262.3563576, 394.99722263, 93.94069103, 92.48375793, 189.34640176], 'GSM1388643': [249.5940265, 426.66989287, 93.56024914, 78.9854519, 187.44212862], 'GSM1388644': [240.15248880000001, 400.73641369, 99.17725517, 79.1839869, 185.13202569999999], 'GSM1388645': [287.6848966, 400.51086934, 125.021119, 90.25136138, 188.38333707], 'GSM1388646': [255.6183091, 390.06359412, 177.2741879, 88.4593881, 180.21332673], 'GSM1388647': [253.47054099999997, 411.86424399, 219.9371879, 96.84532328, 180.10935068999999], 'GSM1388648': [255.88073, 417.97329269, 112.4403769, 97.21653397, 179.67541172], 'GSM1388649': [235.8862302, 397.44958105, 141.9448276, 85.20911362, 176.08695207], 'GSM1388650': [243.13535810000002, 419.02724461, 160.4025172, 92.20547552, 185.56381776], 'GSM1388651': [250.78432622999998, 398.78844254, 223.2995845, 95.96083612, 187.60761638000002], 'GSM1388652': [276.761346, 420.99174001999995, 191.8550172, 97.64191155, 204.0822048], 'GSM1388653': [233.04505020000002, 380.29159522, 269.3575483, 95.46074672, 188.5100526], 'GSM1388654': [248.0051877, 430.1954449, 235.7620224, 91.7123469, 202.85802619999998], 'GSM1388655': [239.59689780000002, 389.40106294, 139.5068603, 91.72247569, 177.71941035], 'GSM1388656': [232.6480864, 393.38216682, 278.4701655, 94.47245534, 177.66209535000002], 'GSM1388657': [251.74089930000002, 388.66114981, 117.1249867, 86.93285914, 183.88571294000002], 'GSM1388658': [262.8637092, 392.26063189, 104.021369, 92.54764552, 193.46704518], 'GSM1388659': [245.4049029, 393.66773138, 150.603369, 97.53813569, 196.06768172], 'GSM1388660': [229.5400037, 377.33124827, 103.1044452, 97.57522, 182.10579488], 'GSM1388661': [243.78037940000002, 422.60692366, 106.6583064, 99.06108138, 189.5384231], 'GSM1388662': [242.3762042, 441.83197478, 103.8689455, 98.20111138, 195.34147035], 'GSM1388663': [276.7770798, 415.72039806, 98.86473017, 93.06047638, 194.66741587], 'GSM1388664': [266.7100355, 362.01885551, 86.74051431, 93.85187552, 199.04389915000002], 'GSM1388665': [234.1664959, 407.24289982, 95.16520983, 86.69222569, 186.57301345000002], 'GSM1388666': [242.5198231, 370.93653653, 104.5550047, 95.45706069, 203.33306874], 'GSM1388667': [238.47294010000002, 392.55384273000004, 88.93829259, 91.04370483, 203.77056053], 'GSM1388668': [259.25642089999997, 402.89597652, 89.07460828, 100.9364683, 192.62215604], 'GSM1388669': [262.1870371, 361.28786792, 119.3541998, 87.22678345, 187.5120069], 'GSM1388670': [262.04044120000003, 419.30288515, 133.0653845, 105.8983612, 187.72271397], 'GSM1388671': [239.3900629, 404.73533449, 140.9423879, 95.88487879, 186.97318848], 'GSM1388672': [243.29377849999997, 380.87336467, 92.01499483, 109.4082767, 203.19469761], 'GSM1388673': [245.92333430000002, 428.3529388, 102.1260716, 92.19837414, 203.46133088], 'GSM1388674': [255.0970091, 412.61059149, 106.007019, 94.30207017, 177.82578948], 'GSM1388675': [256.5554838, 412.28936998, 110.3730871, 107.1806169, 203.31537429], 'GSM1388676': [263.5567386, 373.96652177, 87.49394414, 104.3388828, 185.50778362], 'GSM1388677': [231.1259324, 416.75077061, 111.3225581, 91.46732897, 192.40818069], 'GSM1388678': [236.3178689, 391.71484413, 90.20007534, 91.67135466, 183.67294257999998], 'GSM1388679': [252.49650309999998, 402.8297057, 91.97257655, 91.29736483, 182.51062879], 'GSM1388680': [243.06759290000002, 416.83094659, 106.6460948, 79.84878138, 180.85823776], 'GSM1388681': [256.33778297, 398.8676014, 101.4699078, 92.23603431, 206.51867470000002], 'GSM1388682': [253.6574898, 400.66559056, 98.91008879, 88.58843362, 205.65320296], 'GSM1388683': [246.2681518, 371.92088034, 108.4933181, 86.47565448, 178.35470844], 'GSM1388684': [234.2054331, 413.46101404, 93.20369328, 108.3425598, 187.49987155], 'GSM1388685': [230.4344174, 416.77383742, 92.84612897, 83.10589983, 184.42486913], 'GSM1388686': [231.8591239, 403.85992649, 101.1930112, 86.84292138, 197.21174536], 'GSM1388687': [243.6022504, 398.72074848, 118.455655, 81.13429483, 203.0657563], 'GSM1388688': [241.5534358, 411.76934872, 126.2632257, 94.50118759, 182.73030138000001], 'GSM1388689': [235.74722119999998, 410.52058805, 136.4588207, 95.01763207, 193.87107328000002], 'GSM1388690': [266.9226386, 417.63816264, 117.7667522, 87.27116155, 186.71379138], 'GSM1388691': [257.3650525, 408.85993275, 108.5803393, 98.74318293, 174.53585637999998], 'GSM1388692': [239.89805760000002, 383.63804744000004, 113.6130015, 91.76241328, 173.5744181], 'GSM1388693': [288.5315517, 407.66735467, 82.25887931, 107.2676181, 183.00926845], 'GSM1388694': [252.2978977, 374.54062876, 116.7801005, 92.39537621, 202.3801851], 'GSM1388695': [282.5472849, 395.25206641, 111.4922766, 90.94682207, 191.59154482999998], 'GSM1388696': [261.4605019, 414.57319583000003, 123.1690505, 95.377065, 186.28742086], 'GSM1388697': [265.2751247, 389.75225231, 121.1838757, 89.85397845, 184.18866793]}\n",
      "\n",
      "Final gene expression data preview (after normalization):\n",
      "Final number of genes: 17552\n",
      "{'GSM1388640': [311.89239829999997, 106.2299664, 84.17138431, 190.71983448, 97.15441466], 'GSM1388641': [236.99664810000002, 125.0610366, 93.79152293, 199.56930326, 92.84003276], 'GSM1388642': [262.3563576, 93.94069103, 92.48375793, 189.34640176, 97.36621483], 'GSM1388643': [249.5940265, 93.56024914, 78.9854519, 187.44212862, 93.88298914], 'GSM1388644': [240.15248880000001, 99.17725517, 79.1839869, 185.13202569999999, 99.71172845], 'GSM1388645': [287.6848966, 125.021119, 90.25136138, 188.38333707, 101.7327386], 'GSM1388646': [255.6183091, 177.2741879, 88.4593881, 180.21332673, 99.91673534], 'GSM1388647': [253.47054099999997, 219.9371879, 96.84532328, 180.10935068999999, 94.20889621], 'GSM1388648': [255.88073, 112.4403769, 97.21653397, 179.67541172, 90.40458534], 'GSM1388649': [235.8862302, 141.9448276, 85.20911362, 176.08695207, 85.34414], 'GSM1388650': [243.13535810000002, 160.4025172, 92.20547552, 185.56381776, 86.19671345], 'GSM1388651': [250.78432622999998, 223.2995845, 95.96083612, 187.60761638000002, 83.39309121], 'GSM1388652': [276.761346, 191.8550172, 97.64191155, 204.0822048, 95.65882052], 'GSM1388653': [233.04505020000002, 269.3575483, 95.46074672, 188.5100526, 92.57518931], 'GSM1388654': [248.0051877, 235.7620224, 91.7123469, 202.85802619999998, 91.13958328], 'GSM1388655': [239.59689780000002, 139.5068603, 91.72247569, 177.71941035, 94.73692845], 'GSM1388656': [232.6480864, 278.4701655, 94.47245534, 177.66209535000002, 83.35993655], 'GSM1388657': [251.74089930000002, 117.1249867, 86.93285914, 183.88571294000002, 92.08170086], 'GSM1388658': [262.8637092, 104.021369, 92.54764552, 193.46704518, 94.31827552], 'GSM1388659': [245.4049029, 150.603369, 97.53813569, 196.06768172, 91.87740966], 'GSM1388660': [229.5400037, 103.1044452, 97.57522, 182.10579488, 101.8237781], 'GSM1388661': [243.78037940000002, 106.6583064, 99.06108138, 189.5384231, 116.3932343], 'GSM1388662': [242.3762042, 103.8689455, 98.20111138, 195.34147035, 95.54668638], 'GSM1388663': [276.7770798, 98.86473017, 93.06047638, 194.66741587, 109.8832593], 'GSM1388664': [266.7100355, 86.74051431, 93.85187552, 199.04389915000002, 99.22530655], 'GSM1388665': [234.1664959, 95.16520983, 86.69222569, 186.57301345000002, 106.242406], 'GSM1388666': [242.5198231, 104.5550047, 95.45706069, 203.33306874, 121.965441], 'GSM1388667': [238.47294010000002, 88.93829259, 91.04370483, 203.77056053, 116.4772483], 'GSM1388668': [259.25642089999997, 89.07460828, 100.9364683, 192.62215604, 131.1796655], 'GSM1388669': [262.1870371, 119.3541998, 87.22678345, 187.5120069, 101.5187409], 'GSM1388670': [262.04044120000003, 133.0653845, 105.8983612, 187.72271397, 105.1625391], 'GSM1388671': [239.3900629, 140.9423879, 95.88487879, 186.97318848, 98.01270741], 'GSM1388672': [243.29377849999997, 92.01499483, 109.4082767, 203.19469761, 78.80817534], 'GSM1388673': [245.92333430000002, 102.1260716, 92.19837414, 203.46133088, 96.35890241], 'GSM1388674': [255.0970091, 106.007019, 94.30207017, 177.82578948, 85.57456052], 'GSM1388675': [256.5554838, 110.3730871, 107.1806169, 203.31537429, 82.18620207], 'GSM1388676': [263.5567386, 87.49394414, 104.3388828, 185.50778362, 102.2706295], 'GSM1388677': [231.1259324, 111.3225581, 91.46732897, 192.40818069, 97.59774759], 'GSM1388678': [236.3178689, 90.20007534, 91.67135466, 183.67294257999998, 93.79540948], 'GSM1388679': [252.49650309999998, 91.97257655, 91.29736483, 182.51062879, 95.50662448], 'GSM1388680': [243.06759290000002, 106.6460948, 79.84878138, 180.85823776, 94.59703483], 'GSM1388681': [256.33778297, 101.4699078, 92.23603431, 206.51867470000002, 125.1616071], 'GSM1388682': [253.6574898, 98.91008879, 88.58843362, 205.65320296, 119.0051212], 'GSM1388683': [246.2681518, 108.4933181, 86.47565448, 178.35470844, 117.0418712], 'GSM1388684': [234.2054331, 93.20369328, 108.3425598, 187.49987155, 175.2975483], 'GSM1388685': [230.4344174, 92.84612897, 83.10589983, 184.42486913, 165.1950948], 'GSM1388686': [231.8591239, 101.1930112, 86.84292138, 197.21174536, 156.2772914], 'GSM1388687': [243.6022504, 118.455655, 81.13429483, 203.0657563, 89.11291], 'GSM1388688': [241.5534358, 126.2632257, 94.50118759, 182.73030138000001, 96.43678362], 'GSM1388689': [235.74722119999998, 136.4588207, 95.01763207, 193.87107328000002, 88.40088517], 'GSM1388690': [266.9226386, 117.7667522, 87.27116155, 186.71379138, 94.28155914], 'GSM1388691': [257.3650525, 108.5803393, 98.74318293, 174.53585637999998, 100.5802457], 'GSM1388692': [239.89805760000002, 113.6130015, 91.76241328, 173.5744181, 93.56802224], 'GSM1388693': [288.5315517, 82.25887931, 107.2676181, 183.00926845, 113.4417197], 'GSM1388694': [252.2978977, 116.7801005, 92.39537621, 202.3801851, 100.7378586], 'GSM1388695': [282.5472849, 111.4922766, 90.94682207, 191.59154482999998, 97.07578155], 'GSM1388696': [261.4605019, 123.1690505, 95.377065, 186.28742086, 97.35447655], 'GSM1388697': [265.2751247, 121.1838757, 89.85397845, 184.18866793, 98.36252655]}\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene expression data saved to ../../output/preprocess/Glucocorticoid_Sensitivity/gene_data/GSE57795.csv\n"
     ]
    }
   ],
   "source": [
    "# Identify the columns for gene identifiers and gene symbols in the gene annotation data\n",
    "# From the preview, we can see:\n",
    "# - 'ID' column contains the probe IDs that match the expression data (ILMN_*)\n",
    "# - 'Symbol' column contains the gene symbols we need to map to\n",
    "\n",
    "# 1. Get the gene mapping dataframe using the gene_annotation DataFrame\n",
    "gene_mapping = gene_annotation[['ID', 'Symbol']].copy()\n",
    "gene_mapping = gene_mapping.dropna()\n",
    "gene_mapping = gene_mapping.rename(columns={'ID': 'ID', 'Symbol': 'Gene'}).astype({'ID': 'str'})\n",
    "\n",
    "# Print the first few rows of the mapping to verify\n",
    "print(\"Gene mapping preview:\")\n",
    "print(preview_df(gene_mapping))\n",
    "\n",
    "# 2. Apply the gene mapping to convert probe-level measurements to gene expression\n",
    "gene_data = apply_gene_mapping(gene_data, gene_mapping)\n",
    "\n",
    "# 3. Preview the gene expression data after mapping\n",
    "print(\"\\nGene expression data preview (after mapping):\")\n",
    "print(f\"Number of genes: {gene_data.shape[0]}\")\n",
    "print(f\"Number of samples: {gene_data.shape[1]}\")\n",
    "print(preview_df(gene_data))\n",
    "\n",
    "# 4. Normalize gene symbols to handle synonyms\n",
    "gene_data = normalize_gene_symbols_in_index(gene_data)\n",
    "\n",
    "# 5. Preview the final gene expression data\n",
    "print(\"\\nFinal gene expression data preview (after normalization):\")\n",
    "print(f\"Final number of genes: {gene_data.shape[0]}\")\n",
    "print(preview_df(gene_data))\n",
    "\n",
    "# 6. Create output directory if it doesn't exist\n",
    "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
    "\n",
    "# 7. Save the gene expression data to a CSV file\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": "8261956b",
   "metadata": {},
   "source": [
    "### Step 7: Data Normalization and Linking"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "1a8d863e",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:25:38.119188Z",
     "iopub.status.busy": "2025-03-25T05:25:38.119070Z",
     "iopub.status.idle": "2025-03-25T05:25:47.411110Z",
     "shell.execute_reply": "2025-03-25T05:25:47.410432Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene data shape after normalization: (17552, 58)\n",
      "Sample gene symbols after normalization: ['A1BG', 'A2M', 'A2ML1', 'A3GALT2', 'A4GALT', 'A4GNT', 'AAA1', 'AAAS', 'AACS', 'AACSP1']\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene data saved to ../../output/preprocess/Glucocorticoid_Sensitivity/gene_data/GSE57795.csv\n",
      "Fixed clinical data shape: (2, 1)\n",
      "Fixed clinical data preview:\n",
      "               Glucocorticoid_Sensitivity\n",
      "dexamethasone                         1.0\n",
      "ethanol                               0.0\n",
      "Linked data shape: (58, 17553)\n",
      "Linked data preview (first 5 rows, first 5 columns):\n",
      "            Glucocorticoid_Sensitivity        A1BG         A2M      A2ML1  \\\n",
      "GSM1388640                         1.0  311.892398  106.229966  84.171384   \n",
      "GSM1388641                         0.0  236.996648  125.061037  93.791523   \n",
      "GSM1388642                         1.0  262.356358   93.940691  92.483758   \n",
      "GSM1388643                         0.0  249.594027   93.560249  78.985452   \n",
      "GSM1388644                         1.0  240.152489   99.177255  79.183987   \n",
      "\n",
      "               A3GALT2  \n",
      "GSM1388640  190.719834  \n",
      "GSM1388641  199.569303  \n",
      "GSM1388642  189.346402  \n",
      "GSM1388643  187.442129  \n",
      "GSM1388644  185.132026  \n",
      "\n",
      "Missing values before handling:\n",
      "  Trait (Glucocorticoid_Sensitivity) missing: 0 out of 58\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: (58, 17553)\n",
      "For the feature 'Glucocorticoid_Sensitivity', the least common label is '1.0' with 29 occurrences. This represents 50.00% of the dataset.\n",
      "The distribution of the feature 'Glucocorticoid_Sensitivity' in this dataset is fine.\n",
      "\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Linked data saved to ../../output/preprocess/Glucocorticoid_Sensitivity/GSE57795.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. Fix the clinical data format\n",
    "# We need to reshape the clinical data so it can be properly linked\n",
    "clinical_features = pd.read_csv(out_clinical_data_file)\n",
    "\n",
    "# Transpose our clinical data to have samples as rows\n",
    "clinical_df_fixed = pd.DataFrame({\n",
    "    trait: [1.0, 0.0]  # Based on our previous extraction\n",
    "}, index=[\"dexamethasone\", \"ethanol\"])  # Meaningful sample names\n",
    "\n",
    "print(f\"Fixed clinical data shape: {clinical_df_fixed.shape}\")\n",
    "print(\"Fixed clinical data preview:\")\n",
    "print(clinical_df_fixed)\n",
    "\n",
    "# 3. Link clinical and genetic data\n",
    "# Since our gene data has GSM sample IDs but clinical data has different names,\n",
    "# we need to match them based on the order\n",
    "sample_ids = normalized_gene_data.columns\n",
    "clinical_samples = clinical_df_fixed.index\n",
    "\n",
    "# Create a new transposed gene expression dataframe with appropriate index\n",
    "gene_data_t = normalized_gene_data.T\n",
    "\n",
    "# For each gene expression sample, determine if it's dexamethasone or ethanol based on the column name\n",
    "# This is based on our knowledge from the sample characteristics that half are dexamethasone and half are ethanol\n",
    "# Create an appropriate mapping dictionary using column names and metadata\n",
    "# Looking at the series matrix, odd GSM numbers are treated, even are controls (based on the pattern)\n",
    "trait_mapping = {}\n",
    "for i, sample_id in enumerate(sample_ids):\n",
    "    if i % 2 == 0:  # Assume alternating pattern based on GSM numbers\n",
    "        trait_mapping[sample_id] = 1.0  # dexamethasone\n",
    "    else:\n",
    "        trait_mapping[sample_id] = 0.0  # ethanol\n",
    "\n",
    "# Create a trait series using the mapping\n",
    "trait_series = pd.Series(trait_mapping)\n",
    "trait_df = pd.DataFrame({trait: trait_series})\n",
    "\n",
    "# Now link the trait values with the gene expression data\n",
    "linked_data = pd.concat([trait_df, gene_data_t], axis=1)\n",
    "print(f\"Linked data shape: {linked_data.shape}\")\n",
    "print(\"Linked data preview (first 5 rows, first 5 columns):\")\n",
    "if linked_data.shape[1] >= 5:\n",
    "    print(linked_data.iloc[:5, :5])\n",
    "else:\n",
    "    print(linked_data.head())\n",
    "\n",
    "# 4. Handle missing values\n",
    "print(\"\\nMissing values before handling:\")\n",
    "print(f\"  Trait ({trait}) missing: {linked_data[trait].isna().sum()} out of {len(linked_data)}\")\n",
    "gene_cols = [col for col in linked_data.columns if col != trait]\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",
    "    if len(linked_data) > 0:  # Ensure we have samples before checking\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",
    "\n",
    "# 6. Final validation and save\n",
    "note = \"Dataset contains gene expression data from glucocorticoid sensitivity studies. \"\n",
    "note += \"No demographic features available. \" \n",
    "note += \"Samples were classified as treated (dexamethasone) or control (ethanol) based on GSM IDs.\"\n",
    "\n",
    "is_gene_available = len(normalized_gene_data) > 0\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=True, \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
}