File size: 44,239 Bytes
3923fb8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "93e2cd0e",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:21:56.424114Z",
     "iopub.status.busy": "2025-03-25T05:21:56.423490Z",
     "iopub.status.idle": "2025-03-25T05:21:56.624005Z",
     "shell.execute_reply": "2025-03-25T05:21:56.623554Z"
    }
   },
   "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 = \"Glioblastoma\"\n",
    "cohort = \"GSE175700\"\n",
    "\n",
    "# Input paths\n",
    "in_trait_dir = \"../../input/GEO/Glioblastoma\"\n",
    "in_cohort_dir = \"../../input/GEO/Glioblastoma/GSE175700\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/Glioblastoma/GSE175700.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/Glioblastoma/gene_data/GSE175700.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/Glioblastoma/clinical_data/GSE175700.csv\"\n",
    "json_path = \"../../output/preprocess/Glioblastoma/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d7e6a5c0",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "745a18a1",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:21:56.625505Z",
     "iopub.status.busy": "2025-03-25T05:21:56.625350Z",
     "iopub.status.idle": "2025-03-25T05:21:56.924441Z",
     "shell.execute_reply": "2025-03-25T05:21:56.924023Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Background Information:\n",
      "!Series_title\t\"Identification of indoleamine 2, 3-dioxygenase 1 (IDO1) regulated genes in human glioblastoma cell line U87\"\n",
      "!Series_summary\t\"Transcriptome analysis of U87 cells under different treatments to identify IDO1-regulated genes\"\n",
      "!Series_summary\t\"Indoleamine 2, 3-dioxygenase 1 (IDO1) is a tryptophan (Trp) catabolic enzyme that converts Trp into downstream kynurinine (Kyn). Many studies have indicated that IDO1 is a critical suppressive immune checkpoint molecule invovled in various types of cancer. Canonically, the underlying mechanism of IDO1 immunosuppressive role is related with its enzyme activity, that is the depletion of Trp and accumulation of Kyn lead to increased tumor infiltrating suppressive regulatory T cells. Recent studies, however, challenged this hypothesis and imply that tumor cell-derived IDO1 can mediate immunosuppression independent of its enzyme activity. In this study, we aim to identify genes that are regulated by IDO1 in human glioblastoma cells, a gene expression regulatory function of IDO1 that is indepent of its enzyme activity.\"\n",
      "!Series_overall_design\t\"U87 cells were either non-treated or treated with 20 nM human IDO1-specific siRNA for 16-18 hours, followed by human IFN-g (100 ng/ml) treatment for another 24 hours. Human IDO1 overexpressing U87 (O/E) cells were either non-treated or treated with 20 nM human IDO1-siRNA for 24 hours. At the end of experiment, total RNAs were extracted from the following 6 groups: 1) U87 NT; 2) U87 + IFNg; 3) U87 + siRNA; 4) U87 + siRNA + IFNg; 5) IDO1-O/E U87 NT; 6) IDO1-O/E U87 + siRNA and subject to microarray analysis. Each treatment group has two replicates. Experiment was repeated 3 times. Totally 36 samples were analyzed.\"\n",
      "Sample Characteristics Dictionary:\n",
      "{0: ['tissue: brain'], 1: ['Sex: male']}\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": "d33bb0c5",
   "metadata": {},
   "source": [
    "### Step 2: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "c7109983",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:21:56.925835Z",
     "iopub.status.busy": "2025-03-25T05:21:56.925720Z",
     "iopub.status.idle": "2025-03-25T05:21:56.931200Z",
     "shell.execute_reply": "2025-03-25T05:21:56.930842Z"
    }
   },
   "outputs": [],
   "source": [
    "# 1. Gene Expression Data Availability\n",
    "# Based on the background information, this is a microarray study of gene expression\n",
    "# in U87 glioblastoma cells under different treatment conditions\n",
    "is_gene_available = True\n",
    "\n",
    "# 2. Variable Availability and Data Type Conversion\n",
    "# Looking at the sample characteristics dictionary\n",
    "\n",
    "# 2.1 Data Availability\n",
    "# From the sample characteristics dictionary and background information:\n",
    "# For trait (Glioblastoma): The dataset consists of U87 glioblastoma cells\n",
    "# Everyone in the dataset has glioblastoma (cell line), so trait is constant\n",
    "trait_row = None  # Trait data is not useful for association study since it's constant\n",
    "\n",
    "# For age: No age information provided\n",
    "age_row = None\n",
    "\n",
    "# For gender: There's 'Sex: male' at index 1\n",
    "gender_row = 1\n",
    "\n",
    "# 2.2 Data Type Conversion functions\n",
    "def convert_trait(value):\n",
    "    # Not used since trait_row is None, but defining for completeness\n",
    "    if value and \":\" in value:\n",
    "        trait_value = value.split(\":\", 1)[1].strip().lower()\n",
    "        if \"glioblastoma\" in trait_value:\n",
    "            return 1\n",
    "        else:\n",
    "            return 0\n",
    "    return None\n",
    "\n",
    "def convert_age(value):\n",
    "    # Not used since age_row is None, but defining for completeness\n",
    "    if value and \":\" in value:\n",
    "        age_value = value.split(\":\", 1)[1].strip()\n",
    "        try:\n",
    "            return float(age_value)\n",
    "        except ValueError:\n",
    "            return None\n",
    "    return None\n",
    "\n",
    "def convert_gender(value):\n",
    "    if value and \":\" in value:\n",
    "        gender_value = value.split(\":\", 1)[1].strip().lower()\n",
    "        if \"female\" in gender_value:\n",
    "            return 0\n",
    "        elif \"male\" in gender_value:\n",
    "            return 1\n",
    "        else:\n",
    "            return None\n",
    "    return None\n",
    "\n",
    "# 3. Save Metadata\n",
    "# Determine trait data availability (if trait_row is not None)\n",
    "is_trait_available = trait_row is not None\n",
    "\n",
    "# Use the validate_and_save_cohort_info function for initial filtering\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 (if trait_row is not None)\n",
    "# In this case, trait_row is None, so we skip this step\n",
    "# But let's still include the code for completeness with a condition\n",
    "\n",
    "if trait_row is not None:\n",
    "    # Define the sample characteristics dictionary\n",
    "    sample_characteristics = {0: ['tissue: brain'], 1: ['Sex: male']}\n",
    "    \n",
    "    # Define the dataframe for clinical data\n",
    "    clinical_data = pd.DataFrame(list(sample_characteristics.values()), \n",
    "                                index=sample_characteristics.keys(),\n",
    "                                columns=[\"characteristics\"])\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 output\n",
    "    preview = preview_df(selected_clinical_df)\n",
    "    print(\"Clinical data preview:\", preview)\n",
    "    \n",
    "    # Save the clinical data\n",
    "    os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
    "    selected_clinical_df.to_csv(out_clinical_data_file)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "954c15db",
   "metadata": {},
   "source": [
    "### Step 3: Gene Data Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "64efdc12",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:21:56.932328Z",
     "iopub.status.busy": "2025-03-25T05:21:56.932220Z",
     "iopub.status.idle": "2025-03-25T05:21:57.344446Z",
     "shell.execute_reply": "2025-03-25T05:21:57.343972Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Found data marker at line 69\n",
      "Header line: \"ID_REF\"\t\"GSM5344433\"\t\"GSM5344434\"\t\"GSM5344435\"\t\"GSM5344436\"\t\"GSM5344437\"\t\"GSM5344438\"\t\"GSM5344439\"\t\"GSM5344440\"\t\"GSM5344441\"\t\"GSM5344442\"\t\"GSM5344443\"\t\"GSM5344444\"\t\"GSM5344445\"\t\"GSM5344446\"\t\"GSM5344447\"\t\"GSM5344448\"\t\"GSM5344449\"\t\"GSM5344450\"\t\"GSM5344451\"\t\"GSM5344452\"\t\"GSM5344453\"\t\"GSM5344454\"\t\"GSM5344455\"\t\"GSM5344456\"\t\"GSM5344457\"\t\"GSM5344458\"\t\"GSM5344459\"\t\"GSM5344460\"\t\"GSM5344461\"\t\"GSM5344462\"\t\"GSM5344463\"\t\"GSM5344464\"\t\"GSM5344465\"\t\"GSM5344466\"\t\"GSM5344467\"\t\"GSM5344468\"\n",
      "First data line: \"AFFX-BkGr-GC03_st\"\t8.7173\t9.07515\t8.58114\t7.23554\t8.72152\t8.81188\t9.45325\t8.28566\t10.5923\t8.7657\t8.08258\t8.94281\t9.22912\t9.4206\t10.2476\t9.18288\t8.11761\t8.5086\t7.88719\t9.10813\t8.64127\t9.05306\t8.84052\t7.82312\t9.88867\t9.80206\t10.9257\t9.94282\t9.51898\t8.61312\t9.44908\t9.06246\t8.82998\t9.3153\t9.54165\t9.37893\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Index(['AFFX-BkGr-GC03_st', 'AFFX-BkGr-GC04_st', 'AFFX-BkGr-GC05_st',\n",
      "       'AFFX-BkGr-GC06_st', 'AFFX-BkGr-GC07_st', 'AFFX-BkGr-GC08_st',\n",
      "       'AFFX-BkGr-GC09_st', 'AFFX-BkGr-GC10_st', 'AFFX-BkGr-GC11_st',\n",
      "       'AFFX-BkGr-GC12_st', 'AFFX-BkGr-GC13_st', 'AFFX-BkGr-GC14_st',\n",
      "       'AFFX-BkGr-GC15_st', 'AFFX-BkGr-GC16_st', 'AFFX-BkGr-GC17_st',\n",
      "       'AFFX-BkGr-GC18_st', 'AFFX-BkGr-GC19_st', 'AFFX-BkGr-GC20_st',\n",
      "       'AFFX-BkGr-GC21_st', 'AFFX-BkGr-GC22_st'],\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": "3267a01d",
   "metadata": {},
   "source": [
    "### Step 4: Gene Identifier Review"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "b786db22",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:21:57.345903Z",
     "iopub.status.busy": "2025-03-25T05:21:57.345785Z",
     "iopub.status.idle": "2025-03-25T05:21:57.347833Z",
     "shell.execute_reply": "2025-03-25T05:21:57.347487Z"
    }
   },
   "outputs": [],
   "source": [
    "# Looking at the gene identifiers in the gene expression data\n",
    "# The identifiers like 'AFFX-BkGr-GC03_st' are Affymetrix probe IDs, not human gene symbols\n",
    "# These are microarray probe identifiers that need to be mapped to gene symbols\n",
    "# The \"_st\" suffix indicates these are from an Affymetrix GeneChip ST (Sense Target) array\n",
    "\n",
    "requires_gene_mapping = True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6f987d2b",
   "metadata": {},
   "source": [
    "### Step 5: Gene Annotation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "a3c2a092",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:21:57.348934Z",
     "iopub.status.busy": "2025-03-25T05:21:57.348828Z",
     "iopub.status.idle": "2025-03-25T05:22:08.393027Z",
     "shell.execute_reply": "2025-03-25T05:22:08.392540Z"
    }
   },
   "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 = GSE175700\n",
      "Line 6: !Series_title = Identification of indoleamine 2, 3-dioxygenase 1 (IDO1) regulated genes in human glioblastoma cell line U87\n",
      "Line 7: !Series_geo_accession = GSE175700\n",
      "Line 8: !Series_status = Public on Dec 10 2021\n",
      "Line 9: !Series_submission_date = May 27 2021\n",
      "Line 10: !Series_last_update_date = Dec 11 2021\n",
      "Line 11: !Series_pubmed_id = 34479957\n",
      "Line 12: !Series_summary = Transcriptome analysis of U87 cells under different treatments to identify IDO1-regulated genes\n",
      "Line 13: !Series_summary = Indoleamine 2, 3-dioxygenase 1 (IDO1) is a tryptophan (Trp) catabolic enzyme that converts Trp into downstream kynurinine (Kyn). Many studies have indicated that IDO1 is a critical suppressive immune checkpoint molecule invovled in various types of cancer. Canonically, the underlying mechanism of IDO1 immunosuppressive role is related with its enzyme activity, that is the depletion of Trp and accumulation of Kyn lead to increased tumor infiltrating suppressive regulatory T cells. Recent studies, however, challenged this hypothesis and imply that tumor cell-derived IDO1 can mediate immunosuppression independent of its enzyme activity. In this study, we aim to identify genes that are regulated by IDO1 in human glioblastoma cells, a gene expression regulatory function of IDO1 that is indepent of its enzyme activity.\n",
      "Line 14: !Series_overall_design = U87 cells were either non-treated or treated with 20 nM human IDO1-specific siRNA for 16-18 hours, followed by human IFN-g (100 ng/ml) treatment for another 24 hours. Human IDO1 overexpressing U87 (O/E) cells were either non-treated or treated with 20 nM human IDO1-siRNA for 24 hours. At the end of experiment, total RNAs were extracted from the following 6 groups: 1) U87 NT; 2) U87 + IFNg; 3) U87 + siRNA; 4) U87 + siRNA + IFNg; 5) IDO1-O/E U87 NT; 6) IDO1-O/E U87 + siRNA and subject to microarray analysis. Each treatment group has two replicates. Experiment was repeated 3 times. Totally 36 samples were analyzed.\n",
      "Line 15: !Series_type = Expression profiling by array\n",
      "Line 16: !Series_contributor = Derek,,Wainwright\n",
      "Line 17: !Series_contributor = Matthew,,Genet\n",
      "Line 18: !Series_contributor = Brenda,,Nguyen\n",
      "Line 19: !Series_contributor = Lijie,,Zhai\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "Gene annotation preview:\n",
      "{'ID': ['TC0100006432.hg.1', 'TC0100006433.hg.1', 'TC0100006434.hg.1', 'TC0100006435.hg.1', 'TC0100006436.hg.1'], 'probeset_id': ['TC0100006432.hg.1', 'TC0100006433.hg.1', 'TC0100006434.hg.1', 'TC0100006435.hg.1', 'TC0100006436.hg.1'], 'seqname': ['chr1', 'chr1', 'chr1', 'chr1', 'chr1'], 'strand': ['+', '+', '+', '+', '+'], 'start': ['11869', '28046', '29554', '52473', '62948'], 'stop': ['14412', '29178', '31109', '53312', '63887'], 'total_probes': [10, 6, 10, 10, 10], 'gene_assignment': ['NR_046018 // DDX11L1 // DEAD/H (Asp-Glu-Ala-Asp/His) box helicase 11 like 1 // 1p36.33 // 100287102 /// OTTHUMT00000002844 // DDX11L1 // DEAD/H (Asp-Glu-Ala-Asp/His) box helicase 11 like 1 // 1p36.33 // 100287102 /// OTTHUMT00000362751 // DDX11L1 // DEAD/H (Asp-Glu-Ala-Asp/His) box helicase 11 like 1 // 1p36.33 // 100287102', 'spopoybu.aAug10-unspliced // spopoybu // Transcript Identified by AceView // --- // ---', 'NR_036267 // MIR1302-10 // microRNA 1302-10 // --- // 100422834 /// ENST00000607096 // MIR1302-2 // microRNA 1302-2 // --- // 100302278', 'OTTHUMT00000471235 // OR4G4P // olfactory receptor, family 4, subfamily G, member 4 pseudogene // 1p36.33 // 79504', 'ENST00000492842 // OR4G2P // olfactory receptor, family 4, subfamily G, member 2 pseudogene // 15q26 // 26680 /// OTTHUMT00000003224 // OR4G11P // olfactory receptor, family 4, subfamily G, member 11 pseudogene // 1p36.33 // 403263'], 'mrna_assignment': ['NR_046018 // RefSeq // Homo sapiens DEAD/H (Asp-Glu-Ala-Asp/His) box helicase 11 like 1 (DDX11L1), non-coding RNA. // chr1 // 100 // 100 // 0 // --- // 0 /// OTTHUMT00000002844 // Havana transcript // DEAD/H (Asp-Glu-Ala-Asp/His) box helicase 11 like 1[gene_biotype:transcribed_unprocessed_pseudogene transcript_biotype:transcribed_unprocessed_pseudogene] // chr1 // 100 // 100 // 0 // --- // 0 /// OTTHUMT00000362751 // Havana transcript // DEAD/H (Asp-Glu-Ala-Asp/His) box helicase 11 like 1[gene_biotype:transcribed_unprocessed_pseudogene transcript_biotype:processed_transcript] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000450305 // ENSEMBL // DEAD/H (Asp-Glu-Ala-Asp/His) box helicase 11 like 1 [gene_biotype:transcribed_unprocessed_pseudogene transcript_biotype:transcribed_unprocessed_pseudogene] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000456328 // ENSEMBL // DEAD/H (Asp-Glu-Ala-Asp/His) box helicase 11 like 1 [gene_biotype:transcribed_unprocessed_pseudogene transcript_biotype:processed_transcript] // chr1 // 100 // 100 // 0 // --- // 0 /// NONHSAT000001 // lncRNAWiki // Non-coding transcript identified by NONCODE // chr1 // 100 // 100 // 0 // --- // 0 /// NONHSAT000001 // NONCODE // Non-coding transcript identified by NONCODE: Linc // chr1 // 100 // 100 // 0 // --- // 0 /// NONHSAT000002 // lncRNAWiki // Non-coding transcript identified by NONCODE // chr1 // 100 // 100 // 0 // --- // 0 /// NONHSAT000002 // NONCODE // Non-coding transcript identified by NONCODE: Linc // chr1 // 100 // 100 // 0 // --- // 0 /// NONHSAT000003 // lncRNAWiki // Non-coding transcript identified by NONCODE // chr1 // 100 // 100 // 0 // --- // 0 /// NONHSAT000003 // NONCODE // Non-coding transcript identified by NONCODE: Linc // chr1 // 100 // 100 // 0 // --- // 0 /// NONHSAT000004 // lncRNAWiki // Non-coding transcript identified by NONCODE // chr1 // 100 // 100 // 0 // --- // 0 /// NONHSAT000004 // NONCODE // Non-coding transcript identified by NONCODE: Linc // chr1 // 100 // 100 // 0 // --- // 0', 'spopoybu.aAug10-unspliced // Ace View // Transcript Identified by AceView // chr1 // 100 // 100 // 0 // --- // 0', 'NR_036267 // RefSeq // Homo sapiens microRNA 1302-10 (MIR1302-10), microRNA. // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000607096 // ENSEMBL // microRNA 1302-2 [gene_biotype:miRNA transcript_biotype:miRNA] // chr1 // 100 // 100 // 0 // --- // 0 /// NR_036051_3 // RefSeq // Homo sapiens microRNA 1302-2 (MIR1302-2), microRNA. // chr1 // 100 // 100 // 0 // --- // 0 /// NR_036266_3 // RefSeq // Homo sapiens microRNA 1302-9 (MIR1302-9), microRNA. // chr1 // 100 // 100 // 0 // --- // 0 /// NR_036268_4 // RefSeq // Homo sapiens microRNA 1302-11 (MIR1302-11), microRNA. // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000469289 // ENSEMBL // havana:known chromosome:GRCh38:1:30267:31109:1 gene:ENSG00000243485 gene_biotype:lincRNA transcript_biotype:lincRNA // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000473358 // ENSEMBL // havana:known chromosome:GRCh38:1:29554:31097:1 gene:ENSG00000243485 gene_biotype:lincRNA transcript_biotype:lincRNA // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000469289.1 // lncRNAWiki // microRNA 1302-11 [Source:HGNC Symbol;Acc:HGNC:38246] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000473358.1 // lncRNAWiki // microRNA 1302-11 [Source:HGNC Symbol;Acc:HGNC:38246] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000607096.1 // lncRNAWiki // microRNA 1302-11 [Source:HGNC Symbol;Acc:38246] // chr1 // 100 // 100 // 0 // --- // 0 /// OTTHUMT00000002840 // Havana transcript // novel transcript // chr1 // 100 // 100 // 0 // --- // 0 /// OTTHUMT00000002841 // Havana transcript // novel transcript // chr1 // 100 // 100 // 0 // --- // 0 /// uc031tlb.1 // UCSC Genes // microRNA 1302-2 [Source:HGNC Symbol;Acc:HGNC:35294] // chr1 // 100 // 100 // 0 // --- // 0 /// uc057aty.1 // UCSC Genes // N/A // chr1 // 100 // 100 // 0 // --- // 0 /// uc057atz.1 // UCSC Genes // N/A // chr1 // 100 // 100 // 0 // --- // 0 /// HG491497.1:1..712:ncRNA // RNACentral // long non-coding RNA OTTHUMT00000002840.1 (RP11-34P13.3 gene // chr1 // 100 // 100 // 0 // --- // 0 /// HG491498.1:1..535:ncRNA // RNACentral // long non-coding RNA OTTHUMT00000002841.2 (RP11-34P13.3 gene // chr1 // 100 // 100 // 0 // --- // 0 /// LM610125.1:1..138:precursor_RNA // RNACentral // microRNA hsa-mir-1302-9 precursor // chr1 // 100 // 100 // 0 // --- // 0 /// NONHSAT000011 // NONCODE // Non-coding transcript identified by NONCODE: Linc // chr1 // 100 // 100 // 0 // --- // 0 /// NONHSAT000012 // NONCODE // Non-coding transcript identified by NONCODE: Linc // chr1 // 100 // 100 // 0 // --- // 0 /// NR_036051.1:1..138:precursor_RNA // RNACentral // microRNA hsa-mir-1302-9 precursor // chr1 // 100 // 100 // 0 // --- // 0', 'OTTHUMT00000471235 // Havana transcript // lfactory receptor, family 4, subfamily G, member 4 pseudogene[gene_biotype:unprocessed_pseudogene transcript_biotype:unprocessed_pseudogene] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000606857 // ENSEMBL // olfactory receptor, family 4, subfamily G, member 4 pseudogene [gene_biotype:unprocessed_pseudogene transcript_biotype:unprocessed_pseudogene] // chr1 // 100 // 100 // 0 // --- // 0', 'ENST00000492842 // ENSEMBL // olfactory receptor, family 4, subfamily G, member 11 pseudogene [gene_biotype:unprocessed_pseudogene transcript_biotype:unprocessed_pseudogene] // chr1 // 100 // 100 // 0 // --- // 0 /// OTTHUMT00000003224 // Havana transcript // olfactory receptor, family 4, subfamily G, member 11 pseudogene[gene_biotype:unprocessed_pseudogene transcript_biotype:unprocessed_pseudogene] // chr1 // 100 // 100 // 0 // --- // 0 /// NONHSAT000016 // lncRNAWiki // Non-coding transcript identified by NONCODE // chr1 // 100 // 100 // 0 // --- // 0 /// NONHSAT000016 // NONCODE // Non-coding transcript identified by NONCODE: Linc // chr1 // 100 // 100 // 0 // --- // 0'], 'swissprot': ['NR_046018 // B7ZGX0 /// NR_046018 // B7ZGX2 /// NR_046018 // B7ZGX7 /// NR_046018 // B7ZGX8 /// OTTHUMT00000002844 // B7ZGX0 /// OTTHUMT00000002844 // B7ZGX2 /// OTTHUMT00000002844 // B7ZGX7 /// OTTHUMT00000002844 // B7ZGX8 /// OTTHUMT00000362751 // B7ZGX0 /// OTTHUMT00000362751 // B7ZGX2 /// OTTHUMT00000362751 // B7ZGX7 /// OTTHUMT00000362751 // B7ZGX8 /// ENST00000450305 // B7ZGX0 /// ENST00000450305 // B7ZGX2 /// ENST00000450305 // B7ZGX7 /// ENST00000450305 // B7ZGX8 /// ENST00000450305 // B4E2Z4 /// ENST00000450305 // B7ZGW9 /// ENST00000450305 // Q6ZU42 /// ENST00000450305 // B7ZGX3 /// ENST00000450305 // B5WYT6 /// ENST00000456328 // B7ZGX0 /// ENST00000456328 // B7ZGX2 /// ENST00000456328 // B7ZGX7 /// ENST00000456328 // B7ZGX8 /// ENST00000456328 // B4E2Z4 /// ENST00000456328 // B7ZGW9 /// ENST00000456328 // Q6ZU42 /// ENST00000456328 // B7ZGX3 /// ENST00000456328 // B5WYT6', '---', '---', '---', '---'], 'unigene': ['NR_046018 // Hs.714157 // testis| normal| adult /// OTTHUMT00000002844 // Hs.714157 // testis| normal| adult /// OTTHUMT00000362751 // Hs.714157 // testis| normal| adult /// ENST00000450305 // Hs.719844 // brain| testis| normal /// ENST00000450305 // Hs.714157 // testis| normal| adult /// ENST00000450305 // Hs.740212 // --- /// ENST00000450305 // Hs.712940 // bladder| bone marrow| brain| embryonic tissue| intestine| mammary gland| muscle| pharynx| placenta| prostate| skin| spleen| stomach| testis| thymus| breast (mammary gland) tumor| gastrointestinal tumor| glioma| non-neoplasia| normal| prostate cancer| skin tumor| soft tissue/muscle tissue tumor|embryoid body| adult /// ENST00000456328 // Hs.719844 // brain| testis| normal /// ENST00000456328 // Hs.714157 // testis| normal| adult /// ENST00000456328 // Hs.740212 // --- /// ENST00000456328 // Hs.712940 // bladder| bone marrow| brain| embryonic tissue| intestine| mammary gland| muscle| pharynx| placenta| prostate| skin| spleen| stomach| testis| thymus| breast (mammary gland) tumor| gastrointestinal tumor| glioma| non-neoplasia| normal| prostate cancer| skin tumor| soft tissue/muscle tissue tumor|embryoid body| adult', '---', '---', '---', '---'], 'GO_biological_process': ['ENST00000450305 // GO:0006139 // nucleobase-containing compound metabolic process // inferred from electronic annotation  /// ENST00000456328 // GO:0006139 // nucleobase-containing compound metabolic process // inferred from electronic annotation', '---', '---', '---', '---'], 'GO_cellular_component': ['---', '---', '---', '---', '---'], 'GO_molecular_function': ['ENST00000450305 // GO:0003676 // nucleic acid binding // inferred from electronic annotation  /// ENST00000450305 // GO:0005524 // ATP binding // inferred from electronic annotation  /// ENST00000450305 // GO:0008026 // ATP-dependent helicase activity // inferred from electronic annotation  /// ENST00000450305 // GO:0016818 // hydrolase activity, acting on acid anhydrides, in phosphorus-containing anhydrides // inferred from electronic annotation  /// ENST00000456328 // GO:0003676 // nucleic acid binding // inferred from electronic annotation  /// ENST00000456328 // GO:0005524 // ATP binding // inferred from electronic annotation  /// ENST00000456328 // GO:0008026 // ATP-dependent helicase activity // inferred from electronic annotation  /// ENST00000456328 // GO:0016818 // hydrolase activity, acting on acid anhydrides, in phosphorus-containing anhydrides // inferred from electronic annotation', '---', '---', '---', '---'], 'pathway': ['---', '---', '---', '---', '---'], 'protein_domains': ['---', '---', '---', '---', '---'], 'category': ['main', 'main', 'main', 'main', 'main'], 'locus type': ['Multiple_Complex', 'Coding', 'Multiple_Complex', 'Pseudogene', 'Multiple_Complex'], 'SPOT_ID': ['NR_046018 // RefSeq', 'spopoybu.aAug10-unspliced // Ace View', 'NR_036267 // RefSeq', 'OTTHUMT00000471235 // Havana transcript', 'ENST00000492842 // ENSEMBL']}\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": "b23fd413",
   "metadata": {},
   "source": [
    "### Step 6: Gene Identifier Mapping"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "2038e9f9",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:22:08.394376Z",
     "iopub.status.busy": "2025-03-25T05:22:08.394266Z",
     "iopub.status.idle": "2025-03-25T05:22:10.426787Z",
     "shell.execute_reply": "2025-03-25T05:22:10.426302Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene expression data after mapping:\n",
      "Shape: (73312, 36)\n",
      "First 5 gene symbols: ['A-', 'A-52', 'A-E', 'A-I', 'A-II']\n",
      "Sample of gene expression values:\n",
      "      GSM5344433  GSM5344434  GSM5344435  GSM5344436  GSM5344437\n",
      "Gene                                                            \n",
      "A-     33.056562   33.313759   33.639137   33.114868   33.792869\n",
      "A-52   19.138190   18.546140   19.292170   19.040045   19.265255\n",
      "A-E     0.769540    0.632636    0.748591    0.716990    0.893139\n",
      "A-I     3.273666    3.064109    3.105160    3.134560    3.060834\n",
      "A-II    1.306777    1.430533    1.328100    1.298530    1.352080\n",
      "\n",
      "After normalizing gene symbols:\n",
      "Shape: (34003, 36)\n",
      "First 5 gene symbols: ['A1BG', 'A1BG-AS1', 'A1CF', 'A2M', 'A2M-AS1']\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene expression data saved to ../../output/preprocess/Glioblastoma/gene_data/GSE175700.csv\n"
     ]
    }
   ],
   "source": [
    "# 1. Identify which columns in gene_annotation contain probe IDs and gene symbols\n",
    "# From examining the gene_annotation dataframe:\n",
    "# 'ID' column contains the probe IDs that match the gene expression data\n",
    "# 'gene_assignment' column contains gene symbol information, but needs to be processed\n",
    "\n",
    "# 2. Create a gene mapping dataframe with probe IDs and gene symbols\n",
    "# First, let's extract the columns and rename gene_assignment to 'Gene' as required by apply_gene_mapping\n",
    "mapping_data = gene_annotation[['ID', 'gene_assignment']].copy()\n",
    "mapping_data = mapping_data.rename(columns={'gene_assignment': 'Gene'})\n",
    "\n",
    "# 3. Apply the mapping to convert probe-level measurements to gene expression\n",
    "# Use the apply_gene_mapping function, which will:\n",
    "# - Extract human gene symbols from the gene_assignment text\n",
    "# - Handle the many-to-many mapping between probes and genes\n",
    "# - Split probe values proportionally when a probe maps to multiple genes\n",
    "# - Sum all probe contributions for each gene\n",
    "gene_data = apply_gene_mapping(gene_data, mapping_data)\n",
    "\n",
    "# Add validation to check if the mapping was successful\n",
    "if gene_data.empty:\n",
    "    print(\"Warning: No genes were successfully mapped. Check the gene annotation format.\")\n",
    "else:\n",
    "    # Preview the results\n",
    "    print(\"Gene expression data after mapping:\")\n",
    "    print(f\"Shape: {gene_data.shape}\")\n",
    "    print(f\"First 5 gene symbols: {list(gene_data.index[:5])}\")\n",
    "    print(\"Sample of gene expression values:\")\n",
    "    print(gene_data.iloc[:5, :5])\n",
    "\n",
    "    # Normalize gene symbols in the index to handle synonyms and aggregate rows with same symbol\n",
    "    gene_data = normalize_gene_symbols_in_index(gene_data)\n",
    "    print(\"\\nAfter normalizing gene symbols:\")\n",
    "    print(f\"Shape: {gene_data.shape}\")\n",
    "    print(f\"First 5 gene symbols: {list(gene_data.index[:5])}\")\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"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d48796b6",
   "metadata": {},
   "source": [
    "### Step 7: Data Normalization and Linking"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "632e63c4",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:22:10.428159Z",
     "iopub.status.busy": "2025-03-25T05:22:10.428035Z",
     "iopub.status.idle": "2025-03-25T05:22:24.117604Z",
     "shell.execute_reply": "2025-03-25T05:22:24.117197Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Loaded gene data shape: (34003, 36)\n",
      "Normalized gene data shape: (34003, 36)\n",
      "Sample gene symbols after normalization: ['A1BG', 'A1BG-AS1', 'A1CF', 'A2M', 'A2M-AS1', 'A2ML1', 'A2ML1-AS1', 'A2ML1-AS2', 'A2MP1', 'A3GALT2']\n",
      "\n",
      "Creating mock clinical data - this is a cell line experiment with no clinical variation\n",
      "Mock clinical data shape: (36, 1)\n",
      "Mock clinical data preview:\n",
      "            Glioblastoma\n",
      "GSM5344433             1\n",
      "GSM5344434             1\n",
      "GSM5344435             1\n",
      "GSM5344436             1\n",
      "GSM5344437             1\n",
      "Linked data shape: (36, 34004)\n",
      "Linked data preview (first 5 rows, first 5 columns):\n",
      "            Glioblastoma      A1BG  A1BG-AS1      A1CF       A2M\n",
      "GSM5344433             1  3.306317  2.422265  0.951533  4.913935\n",
      "GSM5344434             1  3.350438  2.392850  0.988175  4.899650\n",
      "GSM5344435             1  3.103491  2.201615  0.952673  4.918110\n",
      "GSM5344436             1  3.343382  2.464650  0.902613  4.953450\n",
      "GSM5344437             1  3.484879  2.545615  1.205907  5.221790\n",
      "\n",
      "Missing values before handling:\n",
      "  Trait (Glioblastoma) missing: 0 out of 36\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: (36, 34004)\n",
      "\n",
      "Evaluating trait bias:\n",
      "All samples in this dataset are glioblastoma cell lines under different experimental conditions.\n",
      "Since there is no variation in the trait, this dataset is biased and not suitable for associational studies.\n",
      "This dataset is not usable for trait-gene association studies as it lacks trait variation.\n"
     ]
    }
   ],
   "source": [
    "# 1. Load the gene expression data saved in step 6\n",
    "gene_data = pd.read_csv(out_gene_data_file, index_col=0)\n",
    "print(f\"Loaded gene data shape: {gene_data.shape}\")\n",
    "\n",
    "# Normalize gene symbols using NCBI Gene database (already done in step 6, so we don't need to do it again)\n",
    "# We'll use the normalized gene data directly from the previous step\n",
    "normalized_gene_data = gene_data\n",
    "print(f\"Normalized gene data shape: {normalized_gene_data.shape}\")\n",
    "print(f\"Sample gene symbols after normalization: {list(normalized_gene_data.index[:10])}\")\n",
    "\n",
    "# 2. Create mock clinical data since this dataset doesn't have real clinical features\n",
    "# Based on the background information, this is a cell line study with no clinical variation\n",
    "print(\"\\nCreating mock clinical data - this is a cell line experiment with no clinical variation\")\n",
    "# Create a clinical DataFrame with just the trait column (all samples have glioblastoma)\n",
    "sample_ids = normalized_gene_data.columns\n",
    "mock_clinical_data = pd.DataFrame(\n",
    "    {trait: [1] * len(sample_ids)},  # All samples are glioblastoma cell lines\n",
    "    index=sample_ids\n",
    ")\n",
    "print(f\"Mock clinical data shape: {mock_clinical_data.shape}\")\n",
    "print(\"Mock clinical data preview:\")\n",
    "print(mock_clinical_data.head())\n",
    "\n",
    "# Save the mock clinical data\n",
    "os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
    "mock_clinical_data.to_csv(out_clinical_data_file)\n",
    "\n",
    "# 3. Link clinical and genetic data\n",
    "linked_data = pd.concat([mock_clinical_data, normalized_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",
    "    print(f\"  Genes with >20% missing: {sum(linked_data[gene_cols].isna().mean() > 0.2)}\")\n",
    "    print(f\"  Samples with >5% missing genes: {sum(linked_data[gene_cols].isna().mean(axis=1) > 0.05)}\")\n",
    "\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",
    "is_trait_biased = True  # Set to True since all samples have the same trait value (all are glioblastoma)\n",
    "print(\"\\nEvaluating trait bias:\")\n",
    "print(f\"All samples in this dataset are glioblastoma cell lines under different experimental conditions.\")\n",
    "print(f\"Since there is no variation in the trait, this dataset is biased and not suitable for associational studies.\")\n",
    "\n",
    "# 6. Final validation and save\n",
    "is_usable = validate_and_save_cohort_info(\n",
    "    is_final=True, \n",
    "    cohort=cohort, \n",
    "    info_path=json_path, \n",
    "    is_gene_available=len(normalized_gene_data) > 0, \n",
    "    is_trait_available=True,  # The trait is available, but lacks variation\n",
    "    is_biased=is_trait_biased, \n",
    "    df=cleaned_data,\n",
    "    note=\"Dataset contains gene expression from glioblastoma cell line U87 under different treatments, but lacks trait variation.\"\n",
    ")\n",
    "\n",
    "# 7. Since this is a cell line experiment without clinical variation,\n",
    "# we won't save the linked data as it's not suitable for trait-gene association studies\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(\"This dataset is not usable for trait-gene association studies as it lacks trait variation.\")"
   ]
  }
 ],
 "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
}