File size: 44,921 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
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "5c87ce87",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:24:37.823564Z",
     "iopub.status.busy": "2025-03-25T05:24:37.823235Z",
     "iopub.status.idle": "2025-03-25T05:24:37.990591Z",
     "shell.execute_reply": "2025-03-25T05:24:37.990240Z"
    }
   },
   "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 = \"GSE15820\"\n",
    "\n",
    "# Input paths\n",
    "in_trait_dir = \"../../input/GEO/Glucocorticoid_Sensitivity\"\n",
    "in_cohort_dir = \"../../input/GEO/Glucocorticoid_Sensitivity/GSE15820\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/Glucocorticoid_Sensitivity/GSE15820.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/Glucocorticoid_Sensitivity/gene_data/GSE15820.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/Glucocorticoid_Sensitivity/clinical_data/GSE15820.csv\"\n",
    "json_path = \"../../output/preprocess/Glucocorticoid_Sensitivity/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "db1af3cf",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "9f86c5a1",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:24:37.991982Z",
     "iopub.status.busy": "2025-03-25T05:24:37.991845Z",
     "iopub.status.idle": "2025-03-25T05:24:38.470249Z",
     "shell.execute_reply": "2025-03-25T05:24:38.469875Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Background Information:\n",
      "!Series_title\t\"ZBTB16, a glucocorticoid response gene in acute lymphoblastic leukemia, interferes with glucocorticoid-induced apoptosis\"\n",
      "!Series_summary\t\"Glucocorticoids (GCs) cause apoptosis in lymphoid lineage cells and are therefore widely used in the therapy of lymphoid malignancies. The molecular mechanisms of the anti-leukemic GC effects are, however, poorly understood. We have previously defined a list of GC-regulated candidate genes by Affymetrix-based whole genome comparative expression profiling in children with acute lymphoblastic leukemia (ALL) during systemic GC monotherapy and in experimental systems of GC-induced apoptosis. ZBTB16, a Zink finger and BOZ-domain containing transcriptional repressor, was one of the most promising candidates derived from this screen. To investigate its possible role in GC-induced apoptosis and cell cycle arrest, we performed conditional over-expression experiments in CCRF-CEM childhood ALL cells. Transgenic ZBTB16 alone had no detectable effect on survival, however, it reduced sensitivity to GC-induced apoptosis. This protective effect was not seen when apoptosis was induced by antibodies against Fas/CD95 or 3 different chemotherapeutics. To address the molecular mechanism underlying this protective effect, we performed whole genome expression profiling in cells with conditional ZBTB16 expression. Surprisingly, ZBTB16 induction did not significantly alter the expression profile, however, it interfered with the regulation of several GC response genes. One of them, BCL2L11/Bim, has previously been shown to be responsible for cell death induction in CCRF-CEM cells. Thus, ZBTB16´s protective effect can be attributed to interference with transcriptional regulation of apoptotic genes, at least in the investigated model system.\"\n",
      "!Series_overall_design\t\"To determine ZBTB16 response genes, C7H2-2C8-ZBTB16#19 and #58 cells (expressing ZBTB16 in a doxycycline-dependent manner) were cultured in duplicates in the absence (treatment “none”) or presence of 400ng/ml doxycycline (treatment “Dox”) for 2h, 6h or 24h. Total RNA was prepared and 1.5 µg RNA subjected to expression profiling on Exon 1.0 microarrays (total of 24 arrays). To assess the effect of ZBTB16 on the GC response, the above cell lines were cultured for 24h in the absence (treatment “Dex”) or presence (treatment “DexDox”) of 200ng/ml doxycycline and subsequently exposed to 10-8M dexamethasone for 6h and 24h and expression-profiled as above resulting in a total of 15 arrays (one of the four 6h replicates (0997_001_58pp6S2_E01_MB_110708.CEL) had to be removed from the following analysis because it didn´t pass quality control).\"\n",
      "Sample Characteristics Dictionary:\n",
      "{0: ['cell ine: C7H2-2C8-ZBTB16#19', 'cell ine: C7H2-2C8-ZBTB16#58'], 1: ['treatment: none', 'treatment: Dox', 'treatment: Dex', 'treatment: DexDox'], 2: ['time [h]: 2', 'time [h]: 6', 'time [h]: 24'], 3: ['experiment nr: III', 'experiment nr: II', 'experiment nr: I'], 4: ['clone nr: 19', 'clone nr: 58']}\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": "4839f08c",
   "metadata": {},
   "source": [
    "### Step 2: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "699c119f",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:24:38.471551Z",
     "iopub.status.busy": "2025-03-25T05:24:38.471444Z",
     "iopub.status.idle": "2025-03-25T05:24:38.476826Z",
     "shell.execute_reply": "2025-03-25T05:24:38.476551Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Clinical data file not found. Skipping clinical feature extraction.\n"
     ]
    }
   ],
   "source": [
    "import pandas as pd\n",
    "import os\n",
    "import json\n",
    "from typing import Optional, Callable, Dict, Any\n",
    "\n",
    "# 1. Gene Expression Data Availability\n",
    "# Based on the background information, this appears to be gene expression data\n",
    "# from Affymetrix Exon 1.0 microarrays studying ZBTB16 and glucocorticoid response\n",
    "is_gene_available = True\n",
    "\n",
    "# 2. Variable Availability and Data Type Conversion\n",
    "# Looking at the sample characteristics dictionary\n",
    "# 2.1 Data Availability\n",
    "\n",
    "# For trait (Glucocorticoid Sensitivity):\n",
    "# The \"treatment\" in row 1 indicates treatment conditions including \"Dex\" (dexamethasone, a glucocorticoid)\n",
    "# We can use this to determine glucocorticoid sensitivity\n",
    "trait_row = 1\n",
    "\n",
    "# For age: Not available in the sample characteristics\n",
    "age_row = None\n",
    "\n",
    "# For gender: Not available - these appear to be cell lines, not individual patients\n",
    "gender_row = None\n",
    "\n",
    "# 2.2 Data Type Conversion Functions\n",
    "\n",
    "def convert_trait(value: str) -> int:\n",
    "    \"\"\"Convert treatment information to glucocorticoid sensitivity binary indicator.\n",
    "    \n",
    "    The \"Dex\" and \"DexDox\" treatments indicate exposure to dexamethasone (a glucocorticoid)\n",
    "    which can be used as our trait indicator.\n",
    "    \"\"\"\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",
    "    # Determine treatment type\n",
    "    if value == \"Dex\" or value == \"DexDox\":\n",
    "        return 1  # Exposed to glucocorticoid\n",
    "    elif value == \"none\" or value == \"Dox\":\n",
    "        return 0  # Not exposed to glucocorticoid\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "def convert_age(value: str) -> Optional[float]:\n",
    "    \"\"\"Convert age information to float.\"\"\"\n",
    "    # Age data is not available\n",
    "    return None\n",
    "\n",
    "def convert_gender(value: str) -> Optional[int]:\n",
    "    \"\"\"Convert gender information to binary (0=female, 1=male).\"\"\"\n",
    "    # Gender data is not available\n",
    "    return None\n",
    "\n",
    "# 3. Save Metadata\n",
    "# Determine trait data availability\n",
    "is_trait_available = trait_row is not None\n",
    "\n",
    "# Validate and save cohort info\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",
    "# Only execute if trait_row is not None\n",
    "if trait_row is not None:\n",
    "    # Assuming clinical_data is available from previous steps\n",
    "    try:\n",
    "        # Load clinical data if it exists\n",
    "        clinical_data = pd.read_csv(os.path.join(in_cohort_dir, \"clinical_data.csv\"))\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",
    "        print(\"Preview of selected clinical features:\")\n",
    "        print(preview_df(selected_clinical_df))\n",
    "        \n",
    "        # Create directory if it doesn't exist\n",
    "        os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
    "        \n",
    "        # Save 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",
    "        \n",
    "    except FileNotFoundError:\n",
    "        print(\"Clinical data file not found. Skipping clinical feature extraction.\")\n",
    "    except Exception as e:\n",
    "        print(f\"Error during clinical feature extraction: {e}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "deb141fe",
   "metadata": {},
   "source": [
    "### Step 3: Gene Data Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "f6d92f2e",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:24:38.477913Z",
     "iopub.status.busy": "2025-03-25T05:24:38.477814Z",
     "iopub.status.idle": "2025-03-25T05:24:39.234105Z",
     "shell.execute_reply": "2025-03-25T05:24:39.233768Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Found data marker at line 69\n",
      "Header line: \"ID_REF\"\t\"GSM397450\"\t\"GSM397451\"\t\"GSM397452\"\t\"GSM397453\"\t\"GSM397454\"\t\"GSM397455\"\t\"GSM397456\"\t\"GSM397457\"\t\"GSM397458\"\t\"GSM397459\"\t\"GSM397460\"\t\"GSM397461\"\t\"GSM397462\"\t\"GSM397463\"\t\"GSM397464\"\t\"GSM397465\"\t\"GSM397466\"\t\"GSM397467\"\t\"GSM397468\"\t\"GSM397469\"\t\"GSM397470\"\t\"GSM397471\"\t\"GSM397472\"\t\"GSM397473\"\t\"GSM397474\"\t\"GSM397475\"\t\"GSM397476\"\t\"GSM397477\"\t\"GSM397478\"\t\"GSM397479\"\t\"GSM397480\"\t\"GSM397481\"\t\"GSM397482\"\t\"GSM397483\"\t\"GSM397484\"\t\"GSM397485\"\t\"GSM397486\"\t\"GSM397487\"\t\"GSM397488\"\t\"GSM397489\"\n",
      "First data line: \"52_36nbg_gc10\"\t1.36755972312661\t1.36703559676413\t1.35410230935632\t1.38059015791809\t1.42740938904254\t1.43124503160126\t1.41567377618281\t1.40124792419307\t1.35540529604859\t1.35799836513495\t1.38758634012505\t1.36094675480995\t1.35763165856656\t1.39344264875760\t1.36455661100291\t1.36552628300498\t1.36612594197734\t1.38366057436023\t1.40126778404146\t1.42285685315322\t1.33998005284175\t1.35451231570066\t1.32936586717567\t1.36449159029923\t1.36183473620910\t1.33019716685760\t1.41270901846183\t1.38224690964737\t1.3589714743535\t1.35338678279769\t1.36415166085043\t1.37797792254353\t1.36775135164149\t1.37647544213206\t1.3589271084623\t1.35838075985707\t1.35197707674852\t1.35591139709054\t1.35304570060391\t1.36392613290556\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Index(['52_36nbg_gc10', '52_36nbg_gc11', '52_36nbg_gc12', '52_36nbg_gc13',\n",
      "       '52_36nbg_gc14', '52_36nbg_gc15', '52_36nbg_gc16', '52_36nbg_gc17',\n",
      "       '52_36nbg_gc18', '52_36nbg_gc19', '52_36nbg_gc20', '52_36nbg_gc21',\n",
      "       '52_36nbg_gc22', '52_36nbg_gc23', '52_36nbg_gc24', '52_36nbg_gc25',\n",
      "       '52_36nbg_gc3', '52_36nbg_gc4', '52_36nbg_gc5', '52_36nbg_gc6'],\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": "9e19df36",
   "metadata": {},
   "source": [
    "### Step 4: Gene Identifier Review"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "e2d358c5",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:24:39.235366Z",
     "iopub.status.busy": "2025-03-25T05:24:39.235257Z",
     "iopub.status.idle": "2025-03-25T05:24:39.237115Z",
     "shell.execute_reply": "2025-03-25T05:24:39.236850Z"
    }
   },
   "outputs": [],
   "source": [
    "# Looking at the gene identifiers in the dataset: '52_36nbg_gc10', '52_36nbg_gc11', etc.\n",
    "# These are not standard human gene symbols, which are typically like BRCA1, TP53, etc.\n",
    "# These appear to be probe IDs or custom identifiers that will need to be mapped to gene symbols.\n",
    "\n",
    "requires_gene_mapping = True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bfaf887c",
   "metadata": {},
   "source": [
    "### Step 5: Gene Annotation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "6a7bef97",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:24:39.238225Z",
     "iopub.status.busy": "2025-03-25T05:24:39.238129Z",
     "iopub.status.idle": "2025-03-25T05:24:40.393406Z",
     "shell.execute_reply": "2025-03-25T05:24:40.392978Z"
    }
   },
   "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 = GSE15820\n",
      "Line 6: !Series_title = ZBTB16, a glucocorticoid response gene in acute lymphoblastic leukemia, interferes with glucocorticoid-induced apoptosis\n",
      "Line 7: !Series_geo_accession = GSE15820\n",
      "Line 8: !Series_status = Public on May 07 2010\n",
      "Line 9: !Series_submission_date = Apr 24 2009\n",
      "Line 10: !Series_last_update_date = Jun 26 2012\n",
      "Line 11: !Series_pubmed_id = 20435142\n",
      "Line 12: !Series_summary = Glucocorticoids (GCs) cause apoptosis in lymphoid lineage cells and are therefore widely used in the therapy of lymphoid malignancies. The molecular mechanisms of the anti-leukemic GC effects are, however, poorly understood. We have previously defined a list of GC-regulated candidate genes by Affymetrix-based whole genome comparative expression profiling in children with acute lymphoblastic leukemia (ALL) during systemic GC monotherapy and in experimental systems of GC-induced apoptosis. ZBTB16, a Zink finger and BOZ-domain containing transcriptional repressor, was one of the most promising candidates derived from this screen. To investigate its possible role in GC-induced apoptosis and cell cycle arrest, we performed conditional over-expression experiments in CCRF-CEM childhood ALL cells. Transgenic ZBTB16 alone had no detectable effect on survival, however, it reduced sensitivity to GC-induced apoptosis. This protective effect was not seen when apoptosis was induced by antibodies against Fas/CD95 or 3 different chemotherapeutics. To address the molecular mechanism underlying this protective effect, we performed whole genome expression profiling in cells with conditional ZBTB16 expression. Surprisingly, ZBTB16 induction did not significantly alter the expression profile, however, it interfered with the regulation of several GC response genes. One of them, BCL2L11/Bim, has previously been shown to be responsible for cell death induction in CCRF-CEM cells. Thus, ZBTB16´s protective effect can be attributed to interference with transcriptional regulation of apoptotic genes, at least in the investigated model system.\n",
      "Line 13: !Series_overall_design = To determine ZBTB16 response genes, C7H2-2C8-ZBTB16#19 and #58 cells (expressing ZBTB16 in a doxycycline-dependent manner) were cultured in duplicates in the absence (treatment “none”) or presence of 400ng/ml doxycycline (treatment “Dox”) for 2h, 6h or 24h. Total RNA was prepared and 1.5 µg RNA subjected to expression profiling on Exon 1.0 microarrays (total of 24 arrays). To assess the effect of ZBTB16 on the GC response, the above cell lines were cultured for 24h in the absence (treatment “Dex”) or presence (treatment “DexDox”) of 200ng/ml doxycycline and subsequently exposed to 10-8M dexamethasone for 6h and 24h and expression-profiled as above resulting in a total of 15 arrays (one of the four 6h replicates (0997_001_58pp6S2_E01_MB_110708.CEL) had to be removed from the following analysis because it didn´t pass quality control).\n",
      "Line 14: !Series_type = Expression profiling by array\n",
      "Line 15: !Series_contributor = Muhammad,,Wasim\n",
      "Line 16: !Series_contributor = Muhammad,,Mansha\n",
      "Line 17: !Series_contributor = Michela,,Carlet\n",
      "Line 18: !Series_contributor = Christian,,Ploner\n",
      "Line 19: !Series_contributor = Alexander,,Trockenbacher\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "Gene annotation preview:\n",
      "{'ID': ['52_36nENST00000343609', '52_36nTRAN00000088867', '52_36nENST00000361444', '52_36nENST00000401567', '52_36nENST00000332556'], 'transcript_id': ['ENST00000343609', 'TRAN00000088867', 'ENST00000361444;ENST00000335791;TRAN00000088866', 'ENST00000401567', 'ENST00000332556'], 'gene_id': ['ENSG00000136840', 'ENSG00000136840', 'ENSG00000136840', 'ENSG00000218830', 'ENSG00000185896'], 'nr_probes': [45, 25, 49, 8, 50], 'probes': ['1000013;1821570;3542467;5826253;2703268;372673;939345;3829429;3465732;4704754;2926002;4384017;3619759;4707366;4988334;3744432;1489412;3923300;3488760;5449937;5498240;1104695;4952605;1066297;2631422;2795348;3778075;3701190;2556339;4473678;1271165;3013026;5982170;5971292;455529;1263516;1532691;2502837;6540389;6204608;3314611;3836325;3053558;2448962;4057529', '1000013;1821570;5492779;4126240;29898;866976;3542467;2703268;372673;939345;3465732;4704754;2926002;3619759;4707366;3923300;4952605;2631422;3701190;4473678;1271165;5982170;5971292;2502837;4057529', '1000013;1821570;5492779;4126240;29898;866976;3542467;5826253;2703268;372673;939345;3829429;3465732;4704754;2926002;4384017;3619759;4707366;4988334;3744432;1489412;3923300;3488760;5449937;5498240;1104695;4952605;1066297;2631422;2795348;3778075;3701190;2556339;4473678;1271165;3013026;5982170;5971292;455529;1263516;1532691;2502837;6540389;6204608;3314611;3836325;3053558;2448962;4057529', '1000038;3183931;5216729;4868450;4804549;4085423;4284782;2080417', '1000058;3365945;3749277;4988641;5761327;85887;403374;2617651;65288;5383310;3202013;3691402;4054688;1074813;6430176;4123373;6107467;1901462;452232;189358;2372175;1962913;5311082;2579237;5048074;1241376;3462843;4482269;3414403;3471163;4880780;3298746;547167;429389;5812919;6309474;4093105;55840;5193353;4315785;4130628;3652963;1986178;1725325;798011;6104549;6378967;5100924;1213422;2902552'], 'indices': ['1000013;1821570;3542467;5826253;2703268;372673;939345;3829429;3465732;4704754;2926002;4384017;3619759;4707366;4988334;3744432;1489412;3923300;3488760;5449937;5498240;1104695;4952605;1066297;2631422;2795348;3778075;3701190;2556339;4473678;1271165;3013026;5982170;5971292;455529;1263516;1532691;2502837;6540389;6204608;3314611;3836325;3053558;2448962;4057529', '1000013;1821570;5492779;4126240;29898;866976;3542467;2703268;372673;939345;3465732;4704754;2926002;3619759;4707366;3923300;4952605;2631422;3701190;4473678;1271165;5982170;5971292;2502837;4057529', '1000013;1821570;5492779;4126240;29898;866976;3542467;5826253;2703268;372673;939345;3829429;3465732;4704754;2926002;4384017;3619759;4707366;4988334;3744432;1489412;3923300;3488760;5449937;5498240;1104695;4952605;1066297;2631422;2795348;3778075;3701190;2556339;4473678;1271165;3013026;5982170;5971292;455529;1263516;1532691;2502837;6540389;6204608;3314611;3836325;3053558;2448962;4057529', '1000038;3183931;5216729;4868450;4804549;4085423;4284782;2080417', '1000058;3365945;3749277;4988641;5761327;85887;403374;2617651;65288;5383310;3202013;3691402;4054688;1074813;6430176;4123373;6107467;1901462;452232;189358;2372175;1962913;5311082;2579237;5048074;1241376;3462843;4482269;3414403;3471163;4880780;3298746;547167;429389;5812919;6309474;4093105;55840;5193353;4315785;4130628;3652963;1986178;1725325;798011;6104549;6378967;5100924;1213422;2902552'], 'symbol': ['ST6GALNAC4', 'ST6GALNAC4', 'ST6GALNAC4', nan, 'LAMP1'], 'entrezgene': ['27090', '27090', '27090', nan, '3916'], 'mirbase': [nan, nan, nan, nan, nan], 'SPOT_ID': ['ENST00000343609', 'TRAN00000088867', 'ENST00000361444;ENST00000335791;TRAN00000088866', 'ENST00000401567', 'ENST00000332556']}\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": "e82b3f69",
   "metadata": {},
   "source": [
    "### Step 6: Gene Identifier Mapping"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "ee1ceec2",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:24:40.394724Z",
     "iopub.status.busy": "2025-03-25T05:24:40.394611Z",
     "iopub.status.idle": "2025-03-25T05:24:41.396513Z",
     "shell.execute_reply": "2025-03-25T05:24:41.396184Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Sample gene expression IDs: ['52_36nbg_gc13', '52_36nbg_gc10', '52_36nbg_gc11', '52_36nbg_gc14', '52_36nbg_gc12']\n",
      "Sample annotation IDs: ['52_36nENST00000401567', '52_36nENST00000361444', '52_36nENST00000332556', '52_36nTRAN00000088867', '52_36nENST00000343609']\n",
      "Gene mapping created with 118098 rows\n",
      "Sample mapping entries:\n",
      "                      ID        Gene\n",
      "0  52_36nENST00000343609  ST6GALNAC4\n",
      "1  52_36nTRAN00000088867  ST6GALNAC4\n",
      "2  52_36nENST00000361444  ST6GALNAC4\n",
      "4  52_36nENST00000332556       LAMP1\n",
      "5  52_36nTRAN00000107877       LAMP1\n",
      "Number of common IDs between expression data and mapping: 118098\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene expression data created with 18151 genes and 40 samples\n",
      "Sample gene expression data:\n",
      "       GSM397450  GSM397451  GSM397452  GSM397453  GSM397454  GSM397455  \\\n",
      "Gene                                                                      \n",
      "A1BG    8.510088   8.778496   8.191638   9.090064   9.387474   9.093869   \n",
      "A1CF   19.023268  20.432171  20.078757  21.372999  21.347969  23.153673   \n",
      "A26A1   5.568398   5.678820   5.527850   5.642854   5.836115   5.679008   \n",
      "A2LD1  13.905637  13.912146  12.940048  15.369641  16.542266  14.013720   \n",
      "A2M    27.717106  27.142966  26.976324  28.835185  29.746781  31.796226   \n",
      "\n",
      "       GSM397456  GSM397457  GSM397458  GSM397459  ...  GSM397480  GSM397481  \\\n",
      "Gene                                               ...                         \n",
      "A1BG    9.241304   8.718551   9.075634   8.368584  ...   8.267192   8.349470   \n",
      "A1CF   20.842212  21.226769  20.845009  19.277951  ...  21.011489  20.391923   \n",
      "A26A1   5.793950   6.203565   5.674946   5.659406  ...   5.209453   5.572318   \n",
      "A2LD1  15.661127  15.476094  14.129344  14.675561  ...  15.465957  13.519326   \n",
      "A2M    29.980280  30.078266  30.294065  28.925444  ...  28.225792  28.148947   \n",
      "\n",
      "       GSM397482  GSM397483  GSM397484  GSM397485  GSM397486  GSM397487  \\\n",
      "Gene                                                                      \n",
      "A1BG    8.609079   9.027214   8.319996   7.920551   8.703216   8.777528   \n",
      "A1CF   20.668052  21.937723  20.234471  20.378771  20.239224  20.802530   \n",
      "A26A1   5.457108   5.591031   5.429368   5.171567   5.252621   5.766174   \n",
      "A2LD1  14.446946  15.645423  13.834515  13.525970  13.790216  13.304547   \n",
      "A2M    27.549746  28.882444  26.205307  26.390324  27.615895  27.230797   \n",
      "\n",
      "       GSM397488  GSM397489  \n",
      "Gene                         \n",
      "A1BG    8.230826   8.060867  \n",
      "A1CF   21.018104  21.105185  \n",
      "A26A1   5.570421   5.471707  \n",
      "A2LD1  14.055442  13.762268  \n",
      "A2M    28.624573  28.681745  \n",
      "\n",
      "[5 rows x 40 columns]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene expression data saved to ../../output/preprocess/Glucocorticoid_Sensitivity/gene_data/GSE15820.csv\n"
     ]
    }
   ],
   "source": [
    "# 1. Determine the right columns for probe IDs and gene symbols from the gene annotation data\n",
    "# Looking at the preview, we can see:\n",
    "# - 'ID' column contains identifiers like '52_36nENST00000343609' which match the format of the gene expression data\n",
    "# - 'symbol' column contains gene symbols like 'ST6GALNAC4', 'LAMP1'\n",
    "\n",
    "# Let's extract these two columns for our mapping\n",
    "prob_col = 'ID'\n",
    "gene_col = 'symbol'\n",
    "\n",
    "# First, let's check if the gene expression data's identifiers match the annotation IDs\n",
    "gene_expression_ids = set(gene_data.index.tolist()[:5])  # Take a small sample\n",
    "annotation_ids = set(gene_annotation[prob_col].tolist()[:5])\n",
    "\n",
    "print(f\"Sample gene expression IDs: {list(gene_expression_ids)[:5]}\")\n",
    "print(f\"Sample annotation IDs: {list(annotation_ids)[:5]}\")\n",
    "\n",
    "# 2. Create the gene mapping dataframe\n",
    "try:\n",
    "    mapping_df = get_gene_mapping(gene_annotation, prob_col, gene_col)\n",
    "    print(f\"Gene mapping created with {len(mapping_df)} rows\")\n",
    "    print(\"Sample mapping entries:\")\n",
    "    print(mapping_df.head())\n",
    "except Exception as e:\n",
    "    print(f\"Error creating gene mapping: {e}\")\n",
    "    \n",
    "    # Manual approach if library function fails\n",
    "    mapping_df = gene_annotation[[prob_col, gene_col]].copy()\n",
    "    mapping_df = mapping_df.dropna(subset=[gene_col])\n",
    "    mapping_df = mapping_df.rename(columns={gene_col: 'Gene'})\n",
    "    mapping_df = mapping_df.astype({prob_col: 'str'})\n",
    "    print(f\"Gene mapping created manually with {len(mapping_df)} rows\")\n",
    "    print(\"Sample mapping entries:\")\n",
    "    print(mapping_df.head())\n",
    "\n",
    "# 3. Apply the gene mapping to convert probe expression to gene expression\n",
    "try:\n",
    "    # Check if our IDs in gene_data match those in the mapping\n",
    "    common_ids = set(gene_data.index).intersection(set(mapping_df[prob_col]))\n",
    "    print(f\"Number of common IDs between expression data and mapping: {len(common_ids)}\")\n",
    "    \n",
    "    # Apply the mapping to get gene expression data\n",
    "    gene_data = apply_gene_mapping(gene_data, mapping_df)\n",
    "    print(f\"Gene expression data created with {gene_data.shape[0]} genes and {gene_data.shape[1]} samples\")\n",
    "    print(\"Sample gene expression data:\")\n",
    "    print(gene_data.head())\n",
    "    \n",
    "    # Save the gene expression data\n",
    "    os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
    "    gene_data.to_csv(out_gene_data_file)\n",
    "    print(f\"Gene expression data saved to {out_gene_data_file}\")\n",
    "    \n",
    "except Exception as e:\n",
    "    print(f\"Error applying gene mapping: {e}\")\n",
    "    \n",
    "    # Print more diagnostic information\n",
    "    print(\"\\nDiagnostic information:\")\n",
    "    print(f\"gene_data index type: {type(gene_data.index[0])}\")\n",
    "    if 'ID' in mapping_df.columns:\n",
    "        print(f\"mapping_df ID column type: {type(mapping_df['ID'].iloc[0])}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d7ab8d3c",
   "metadata": {},
   "source": [
    "### Step 7: Data Normalization and Linking"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "3c81ac1e",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:24:41.397814Z",
     "iopub.status.busy": "2025-03-25T05:24:41.397694Z",
     "iopub.status.idle": "2025-03-25T05:24:50.446856Z",
     "shell.execute_reply": "2025-03-25T05:24:50.446445Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene data shape after normalization: (18042, 40)\n",
      "Sample gene symbols after normalization: ['A1BG', 'A1CF', 'A2M', 'A2ML1', 'A3GALT2', 'A4GALT', 'A4GNT', 'AAAS', 'AACS', 'AADAC']\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene data saved to ../../output/preprocess/Glucocorticoid_Sensitivity/gene_data/GSE15820.csv\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Selected clinical features:\n",
      "                            GSM397450  GSM397451  GSM397452  GSM397453  \\\n",
      "Glucocorticoid_Sensitivity        0.0        0.0        0.0        0.0   \n",
      "\n",
      "                            GSM397454  GSM397455  GSM397456  GSM397457  \\\n",
      "Glucocorticoid_Sensitivity        0.0        0.0        0.0        0.0   \n",
      "\n",
      "                            GSM397458  GSM397459  ...  GSM397480  GSM397481  \\\n",
      "Glucocorticoid_Sensitivity        0.0        0.0  ...        1.0        1.0   \n",
      "\n",
      "                            GSM397482  GSM397483  GSM397484  GSM397485  \\\n",
      "Glucocorticoid_Sensitivity        1.0        0.0        1.0        1.0   \n",
      "\n",
      "                            GSM397486  GSM397487  GSM397488  GSM397489  \n",
      "Glucocorticoid_Sensitivity        1.0        1.0        1.0        1.0  \n",
      "\n",
      "[1 rows x 40 columns]\n",
      "Clinical data saved to ../../output/preprocess/Glucocorticoid_Sensitivity/clinical_data/GSE15820.csv\n",
      "Linked data shape: (40, 18043)\n",
      "Linked data columns preview:\n",
      "['Glucocorticoid_Sensitivity', 'A1BG', 'A1CF', 'A2M', 'A2ML1', 'A3GALT2', 'A4GALT', 'A4GNT', 'AAAS', 'AACS']\n",
      "\n",
      "Missing values before handling:\n",
      "  Trait (Glucocorticoid_Sensitivity) missing: 0 out of 40\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: (40, 18043)\n",
      "For the feature 'Glucocorticoid_Sensitivity', the least common label is '1.0' with 15 occurrences. This represents 37.50% of the dataset.\n",
      "The distribution of the feature 'Glucocorticoid_Sensitivity' in this dataset is fine.\n",
      "\n",
      "A new JSON file was created at: ../../output/preprocess/Glucocorticoid_Sensitivity/cohort_info.json\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Linked data saved to ../../output/preprocess/Glucocorticoid_Sensitivity/GSE15820.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. Since we didn't successfully save clinical data in previous steps, let's extract it again\n",
    "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
    "background_info, clinical_df = get_background_and_clinical_data(matrix_file)\n",
    "\n",
    "# Define conversion functions (from Step 2)\n",
    "def convert_trait(value: str) -> int:\n",
    "    \"\"\"Convert treatment information to glucocorticoid sensitivity binary indicator.\"\"\"\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",
    "    # Determine treatment type\n",
    "    if value == \"Dex\" or value == \"DexDox\":\n",
    "        return 1  # Exposed to glucocorticoid\n",
    "    elif value == \"none\" or value == \"Dox\":\n",
    "        return 0  # Not exposed to glucocorticoid\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "def convert_age(value: str) -> Optional[float]:\n",
    "    \"\"\"Convert age information to float.\"\"\"\n",
    "    # Age data is not available\n",
    "    return None\n",
    "\n",
    "def convert_gender(value: str) -> Optional[int]:\n",
    "    \"\"\"Convert gender information to binary (0=female, 1=male).\"\"\"\n",
    "    # Gender data is not available\n",
    "    return None\n",
    "\n",
    "# Extract clinical features with the identified row indices\n",
    "trait_row = 1  # From Step 2\n",
    "age_row = None  # From Step 2\n",
    "gender_row = None  # From Step 2\n",
    "\n",
    "# Extract clinical features\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=convert_gender\n",
    ")\n",
    "\n",
    "print(\"Selected clinical features:\")\n",
    "print(selected_clinical_df)\n",
    "\n",
    "# Save clinical data for future reference\n",
    "os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
    "selected_clinical_df.to_csv(out_clinical_data_file)\n",
    "print(f\"Clinical data saved to {out_clinical_data_file}\")\n",
    "\n",
    "# 3. Link clinical and genetic data\n",
    "linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)\n",
    "print(f\"Linked data shape: {linked_data.shape}\")\n",
    "print(\"Linked data columns preview:\")\n",
    "print(list(linked_data.columns[:10]))  # Show first 10 column names\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 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",
    "    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",
    "if 'Age' in cleaned_data.columns:\n",
    "    note += \"Age data is available. \"\n",
    "if 'Gender' in cleaned_data.columns:\n",
    "    note += \"Gender data is available. \"\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
}