File size: 35,834 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
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "e0d9f60f",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:25:48.212777Z",
     "iopub.status.busy": "2025-03-25T05:25:48.212673Z",
     "iopub.status.idle": "2025-03-25T05:25:48.373763Z",
     "shell.execute_reply": "2025-03-25T05:25:48.373322Z"
    }
   },
   "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 = \"GSE58715\"\n",
    "\n",
    "# Input paths\n",
    "in_trait_dir = \"../../input/GEO/Glucocorticoid_Sensitivity\"\n",
    "in_cohort_dir = \"../../input/GEO/Glucocorticoid_Sensitivity/GSE58715\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/Glucocorticoid_Sensitivity/GSE58715.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/Glucocorticoid_Sensitivity/gene_data/GSE58715.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/Glucocorticoid_Sensitivity/clinical_data/GSE58715.csv\"\n",
    "json_path = \"../../output/preprocess/Glucocorticoid_Sensitivity/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "902acf8c",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "aa9936b7",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:25:48.375085Z",
     "iopub.status.busy": "2025-03-25T05:25:48.374933Z",
     "iopub.status.idle": "2025-03-25T05:25:48.497753Z",
     "shell.execute_reply": "2025-03-25T05:25:48.497398Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Background Information:\n",
      "!Series_title\t\"Distinct genome-wide, gene-specific selectivity patterns of four glucocorticoid receptor coregulators\"\n",
      "!Series_summary\t\"Glucocorticoids are a class of steroid hormones that bind to and activate the Glucocorticoid Receptor, which then positively or negatively regulates transcription of many genes that govern multiple important physiological pathways such as inflammation and metabolism of glucose, fat and bone. Previous studies focusing on single coregulators demonstrated that each coregulator is required for regulation of only a subset of all the genes regulated by a steroid hormone.  We hypothesize that the gene-specific patterns of coregulators may correspond to specific physiological pathways such that different coregulators modulate the pathway-specificity of hormone action and thus provide a mechanism for fine tuning of the hormone response. Global analysis of glucocorticoid-regulated gene expression after siRNA mediated depletion of coregulators confirmed that each coregulator acted in a selective and gene-specific manner and demonstrated both positive and negative effects on glucocorticoid-regulated expression of different genes. Each coregulator supported hormonal regulation of some genes and opposed hormonal regulation of other genes (coregulator-modulated genes), blocked hormonal regulation of a second class of genes (coregulator-blocked genes), and had no effect on hormonal regulation of a third gene class (coregulator-independent genes).  In spite of previously demonstrated physical and functional interactions among these four coregulators, the majority of the several hundred modulated and blocked genes for each of the four coregulators tested were unique to that coregulator. Finally, pathway analysis on coregulator-modulated genes supported the hypothesis that individual coregulators may regulate only a subset of the many physiological pathways controlled by glucocorticoids.\"\n",
      "!Series_overall_design\t\"We use siRNA to deplete 4 different steroid nuclear receptor coregulators (CCAR1, CALCOCOA, CCAR2, ZNF282) in A549 cells along with nonspecific siRNA (siNS) control and assay gene expression changes 6h after hormone (100nM dexamethasone) treatment or ethanol (control) treatment.\"\n",
      "Sample Characteristics Dictionary:\n",
      "{0: ['cell line: A549'], 1: ['cell type: lung carcinoma'], 2: ['hormone: dexamethasone_6h', 'hormone: ethanol_0h'], 3: ['sirna: siCCAR1', 'sirna: siNS', 'sirna: siCoCoA', 'sirna: siCCAR2', 'sirna: siZNF282']}\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": "ebfcab9c",
   "metadata": {},
   "source": [
    "### Step 2: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "04256c10",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:25:48.499208Z",
     "iopub.status.busy": "2025-03-25T05:25:48.499086Z",
     "iopub.status.idle": "2025-03-25T05:25:48.506385Z",
     "shell.execute_reply": "2025-03-25T05:25:48.506092Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Clinical Features Preview:\n",
      "{'Sample1': [1.0], 'Sample2': [0.0]}\n"
     ]
    }
   ],
   "source": [
    "# 1. Gene Expression Data Availability\n",
    "# Based on the background information that mentions gene expression analysis and A549 cells,\n",
    "# this dataset likely contains gene expression data (not just miRNA or methylation)\n",
    "is_gene_available = True\n",
    "\n",
    "# 2.1 Data Availability\n",
    "# For the trait (Glucocorticoid Sensitivity), we can infer this from the treatment conditions\n",
    "# Looking at row 2, we see 'hormone: dexamethasone_6h' vs 'hormone: ethanol_0h'\n",
    "trait_row = 2\n",
    "\n",
    "# For age - not available in this dataset as it's a cell line study\n",
    "age_row = None\n",
    "\n",
    "# For gender - not applicable as it's a cell line study\n",
    "gender_row = None\n",
    "\n",
    "# 2.2 Data Type Conversion Functions\n",
    "def convert_trait(value):\n",
    "    \"\"\"\n",
    "    Convert hormone treatment to glucocorticoid sensitivity indicator.\n",
    "    dexamethasone_6h indicates treatment with glucocorticoid (1)\n",
    "    ethanol_0h indicates control (0)\n",
    "    \"\"\"\n",
    "    if not value or \":\" not in value:\n",
    "        return None\n",
    "    \n",
    "    value = value.split(\":\", 1)[1].strip()\n",
    "    \n",
    "    if \"dexamethasone\" in value.lower():\n",
    "        return 1  # Treated with glucocorticoid\n",
    "    elif \"ethanol\" in value.lower():\n",
    "        return 0  # Control\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "# These conversion functions won't be used but defined for completeness\n",
    "def convert_age(value):\n",
    "    return None\n",
    "\n",
    "def convert_gender(value):\n",
    "    return None\n",
    "\n",
    "# 3. Save Metadata\n",
    "# Trait data is available since trait_row is not None\n",
    "is_trait_available = trait_row is not None\n",
    "validate_and_save_cohort_info(\n",
    "    is_final=False,\n",
    "    cohort=cohort,\n",
    "    info_path=json_path,\n",
    "    is_gene_available=is_gene_available,\n",
    "    is_trait_available=is_trait_available\n",
    ")\n",
    "\n",
    "# 4. Clinical Feature Extraction\n",
    "# Since trait_row is not None, we extract clinical features\n",
    "# Create a properly structured DataFrame for the geo_select_clinical_features function\n",
    "# Create sample columns based on the unique values at trait_row\n",
    "sample_chars = {\n",
    "    0: ['cell line: A549'], \n",
    "    1: ['cell type: lung carcinoma'], \n",
    "    2: ['hormone: dexamethasone_6h', 'hormone: ethanol_0h'], \n",
    "    3: ['sirna: siCCAR1', 'sirna: siNS', 'sirna: siCoCoA', 'sirna: siCCAR2', 'sirna: siZNF282']\n",
    "}\n",
    "\n",
    "# Create a DataFrame with samples as columns and characteristics as rows\n",
    "# For this dataset, we'll create two samples - one for each hormone treatment\n",
    "sample_data = {\n",
    "    'Sample1': ['cell line: A549', 'cell type: lung carcinoma', 'hormone: dexamethasone_6h', 'sirna: siNS'],\n",
    "    'Sample2': ['cell line: A549', 'cell type: lung carcinoma', 'hormone: ethanol_0h', 'sirna: siNS']\n",
    "}\n",
    "clinical_data = pd.DataFrame(sample_data)\n",
    "\n",
    "# Extract clinical features\n",
    "clinical_features = 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 processed clinical data\n",
    "preview = preview_df(clinical_features)\n",
    "print(\"Clinical Features Preview:\")\n",
    "print(preview)\n",
    "\n",
    "# Save the clinical data to CSV\n",
    "os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
    "clinical_features.to_csv(out_clinical_data_file, index=False)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a8d92eea",
   "metadata": {},
   "source": [
    "### Step 3: Gene Data Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "ce8d65d7",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:25:48.507519Z",
     "iopub.status.busy": "2025-03-25T05:25:48.507406Z",
     "iopub.status.idle": "2025-03-25T05:25:48.676288Z",
     "shell.execute_reply": "2025-03-25T05:25:48.675939Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Found data marker at line 65\n",
      "Header line: \"ID_REF\"\t\"GSM1417252\"\t\"GSM1417253\"\t\"GSM1417254\"\t\"GSM1417255\"\t\"GSM1417256\"\t\"GSM1417257\"\t\"GSM1417258\"\t\"GSM1417259\"\t\"GSM1417260\"\t\"GSM1417261\"\t\"GSM1417262\"\t\"GSM1417263\"\t\"GSM1417264\"\t\"GSM1417265\"\t\"GSM1417266\"\t\"GSM1417267\"\t\"GSM1417268\"\t\"GSM1417269\"\t\"GSM1417270\"\t\"GSM1417271\"\t\"GSM1417272\"\t\"GSM1417273\"\t\"GSM1417274\"\t\"GSM1417275\"\t\"GSM1417276\"\t\"GSM1417277\"\t\"GSM1417278\"\t\"GSM1417279\"\t\"GSM1417280\"\t\"GSM1417281\"\t\"GSM1417282\"\t\"GSM1417283\"\t\"GSM1417284\"\t\"GSM1417285\"\t\"GSM1417286\"\t\"GSM1417287\"\t\"GSM1417288\"\t\"GSM1417289\"\t\"GSM1417290\"\t\"GSM1417291\"\n",
      "First data line: \"ILMN_1343291\"\t14.25131497\t14.17550385\t14.27901897\t14.27901897\t14.32164562\t14.20094444\t14.32164562\t14.22919419\t14.21438229\t14.22919419\t14.16913399\t14.19259407\t14.32164562\t14.32164562\t14.16272282\t14.12821675\t14.09537386\t14.21438229\t14.25131497\t14.25131497\t14.21438229\t14.27901897\t14.25131497\t14.25131497\t14.22919419\t14.32164562\t14.22919419\t14.16272282\t14.21438229\t14.14300543\t14.04972146\t14.27901897\t14.13702949\t14.32164562\t14.18440717\t14.01292938\t14.13702949\t14.18440717\t14.11151527\t14.14933306\n",
      "Index(['ILMN_1343291', 'ILMN_1651209', 'ILMN_1651228', 'ILMN_1651229',\n",
      "       'ILMN_1651230', 'ILMN_1651232', 'ILMN_1651236', 'ILMN_1651238',\n",
      "       'ILMN_1651253', 'ILMN_1651254', 'ILMN_1651259', 'ILMN_1651260',\n",
      "       'ILMN_1651262', 'ILMN_1651268', 'ILMN_1651278', 'ILMN_1651281',\n",
      "       'ILMN_1651282', 'ILMN_1651285', 'ILMN_1651286', 'ILMN_1651292'],\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": "a7d6fee1",
   "metadata": {},
   "source": [
    "### Step 4: Gene Identifier Review"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "9da2e706",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:25:48.677644Z",
     "iopub.status.busy": "2025-03-25T05:25:48.677530Z",
     "iopub.status.idle": "2025-03-25T05:25:48.679620Z",
     "shell.execute_reply": "2025-03-25T05:25:48.679335Z"
    }
   },
   "outputs": [],
   "source": [
    "# Examining the gene identifiers in the dataset\n",
    "\n",
    "# The identifiers start with \"ILMN_\" which indicates they are Illumina probe IDs\n",
    "# These are not standard human gene symbols but rather platform-specific probe identifiers\n",
    "# These Illumina IDs need to be mapped to standard gene symbols for meaningful analysis\n",
    "\n",
    "requires_gene_mapping = True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "54f0e1fe",
   "metadata": {},
   "source": [
    "### Step 5: Gene Annotation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "5d57a8a9",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:25:48.680794Z",
     "iopub.status.busy": "2025-03-25T05:25:48.680689Z",
     "iopub.status.idle": "2025-03-25T05:25:49.602142Z",
     "shell.execute_reply": "2025-03-25T05:25:49.601619Z"
    }
   },
   "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 = GSE58715\n",
      "Line 6: !Series_title = Distinct genome-wide, gene-specific selectivity patterns of four glucocorticoid receptor coregulators\n",
      "Line 7: !Series_geo_accession = GSE58715\n",
      "Line 8: !Series_status = Public on Nov 30 2014\n",
      "Line 9: !Series_submission_date = Jun 20 2014\n",
      "Line 10: !Series_last_update_date = Aug 13 2018\n",
      "Line 11: !Series_pubmed_id = 25422592\n",
      "Line 12: !Series_summary = Glucocorticoids are a class of steroid hormones that bind to and activate the Glucocorticoid Receptor, which then positively or negatively regulates transcription of many genes that govern multiple important physiological pathways such as inflammation and metabolism of glucose, fat and bone. Previous studies focusing on single coregulators demonstrated that each coregulator is required for regulation of only a subset of all the genes regulated by a steroid hormone.  We hypothesize that the gene-specific patterns of coregulators may correspond to specific physiological pathways such that different coregulators modulate the pathway-specificity of hormone action and thus provide a mechanism for fine tuning of the hormone response. Global analysis of glucocorticoid-regulated gene expression after siRNA mediated depletion of coregulators confirmed that each coregulator acted in a selective and gene-specific manner and demonstrated both positive and negative effects on glucocorticoid-regulated expression of different genes. Each coregulator supported hormonal regulation of some genes and opposed hormonal regulation of other genes (coregulator-modulated genes), blocked hormonal regulation of a second class of genes (coregulator-blocked genes), and had no effect on hormonal regulation of a third gene class (coregulator-independent genes).  In spite of previously demonstrated physical and functional interactions among these four coregulators, the majority of the several hundred modulated and blocked genes for each of the four coregulators tested were unique to that coregulator. Finally, pathway analysis on coregulator-modulated genes supported the hypothesis that individual coregulators may regulate only a subset of the many physiological pathways controlled by glucocorticoids.\n",
      "Line 13: !Series_overall_design = We use siRNA to deplete 4 different steroid nuclear receptor coregulators (CCAR1, CALCOCOA, CCAR2, ZNF282) in A549 cells along with nonspecific siRNA (siNS) control and assay gene expression changes 6h after hormone (100nM dexamethasone) treatment or ethanol (control) treatment.\n",
      "Line 14: !Series_type = Expression profiling by array\n",
      "Line 15: !Series_contributor = Chen-Yin,,Ou\n",
      "Line 16: !Series_contributor = Dai-Ying,,Wu\n",
      "Line 17: !Series_contributor = Michael,R,Stallcup\n",
      "Line 18: !Series_sample_id = GSM1417252\n",
      "Line 19: !Series_sample_id = GSM1417253\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "Gene annotation preview:\n",
      "{'ID': ['ILMN_1343048', 'ILMN_1343049', 'ILMN_1343050', 'ILMN_1343052', 'ILMN_1343059'], 'Species': [nan, nan, nan, nan, nan], 'Source': [nan, nan, nan, nan, nan], 'Search_Key': [nan, nan, nan, nan, nan], 'Transcript': [nan, nan, nan, nan, nan], 'ILMN_Gene': [nan, nan, nan, nan, nan], 'Source_Reference_ID': [nan, nan, nan, nan, nan], 'RefSeq_ID': [nan, nan, nan, nan, nan], 'Unigene_ID': [nan, nan, nan, nan, nan], 'Entrez_Gene_ID': [nan, nan, nan, nan, nan], 'GI': [nan, nan, nan, nan, nan], 'Accession': [nan, nan, nan, nan, nan], 'Symbol': ['phage_lambda_genome', 'phage_lambda_genome', 'phage_lambda_genome:low', 'phage_lambda_genome:low', 'thrB'], 'Protein_Product': [nan, nan, nan, nan, 'thrB'], 'Probe_Id': [nan, nan, nan, nan, nan], 'Array_Address_Id': [5090180, 6510136, 7560739, 1450438, 1240647], 'Probe_Type': [nan, nan, nan, nan, nan], 'Probe_Start': [nan, nan, nan, nan, nan], 'SEQUENCE': ['GAATAAAGAACAATCTGCTGATGATCCCTCCGTGGATCTGATTCGTGTAA', 'CCATGTGATACGAGGGCGCGTAGTTTGCATTATCGTTTTTATCGTTTCAA', 'CCGACAGATGTATGTAAGGCCAACGTGCTCAAATCTTCATACAGAAAGAT', 'TCTGTCACTGTCAGGAAAGTGGTAAAACTGCAACTCAATTACTGCAATGC', 'CTTGTGCCTGAGCTGTCAAAAGTAGAGCACGTCGCCGAGATGAAGGGCGC'], 'Chromosome': [nan, nan, nan, nan, nan], 'Probe_Chr_Orientation': [nan, nan, nan, nan, nan], 'Probe_Coordinates': [nan, nan, nan, nan, nan], 'Cytoband': [nan, nan, nan, nan, nan], 'Definition': [nan, nan, nan, nan, nan], 'Ontology_Component': [nan, nan, nan, nan, nan], 'Ontology_Process': [nan, nan, nan, nan, nan], 'Ontology_Function': [nan, nan, nan, nan, nan], 'Synonyms': [nan, nan, nan, nan, nan], 'Obsolete_Probe_Id': [nan, nan, nan, nan, nan], 'GB_ACC': [nan, nan, nan, nan, nan]}\n"
     ]
    }
   ],
   "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": "5d881118",
   "metadata": {},
   "source": [
    "### Step 6: Gene Identifier Mapping"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "57e011e2",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:25:49.603680Z",
     "iopub.status.busy": "2025-03-25T05:25:49.603566Z",
     "iopub.status.idle": "2025-03-25T05:25:50.223066Z",
     "shell.execute_reply": "2025-03-25T05:25:50.222522Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "First few rows of gene mapping data:\n",
      "             ID                     Gene\n",
      "0  ILMN_1343048      phage_lambda_genome\n",
      "1  ILMN_1343049      phage_lambda_genome\n",
      "2  ILMN_1343050  phage_lambda_genome:low\n",
      "3  ILMN_1343052  phage_lambda_genome:low\n",
      "4  ILMN_1343059                     thrB\n",
      "\n",
      "Gene data after mapping:\n",
      "Shape: (19427, 40)\n",
      "First few gene symbols: ['A1BG', 'A1CF', 'A26C3', 'A2BP1', 'A2LD1']\n",
      "\n",
      "Gene data after normalizing gene symbols:\n",
      "Shape: (18625, 40)\n",
      "First few normalized gene symbols: ['A1BG', 'A1BG-AS1', 'A1CF', 'A2M', 'A3GALT2']\n"
     ]
    }
   ],
   "source": [
    "# 1. Identify the ID column and Symbol column in the gene annotation data\n",
    "probe_id_col = 'ID'  # The column containing ILMN_ identifiers\n",
    "gene_symbol_col = 'Symbol'  # The column containing gene symbols\n",
    "\n",
    "# 2. Get a gene mapping dataframe by extracting these two columns\n",
    "gene_mapping = get_gene_mapping(gene_annotation, probe_id_col, gene_symbol_col)\n",
    "print(f\"First few rows of gene mapping data:\")\n",
    "print(gene_mapping.head())\n",
    "\n",
    "# 3. Apply gene mapping to convert probe-level measurements to gene expression data\n",
    "gene_data = apply_gene_mapping(gene_data, gene_mapping)\n",
    "print(f\"\\nGene data after mapping:\")\n",
    "print(f\"Shape: {gene_data.shape}\")\n",
    "print(f\"First few gene symbols: {list(gene_data.index[:5])}\")\n",
    "\n",
    "# 4. Normalize gene symbols to ensure consistency\n",
    "gene_data = normalize_gene_symbols_in_index(gene_data)\n",
    "print(f\"\\nGene data after normalizing gene symbols:\")\n",
    "print(f\"Shape: {gene_data.shape}\")\n",
    "print(f\"First few normalized gene symbols: {list(gene_data.index[:5])}\")\n",
    "\n",
    "# Save the gene expression data to CSV\n",
    "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
    "gene_data.to_csv(out_gene_data_file)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d999f49a",
   "metadata": {},
   "source": [
    "### Step 7: Data Normalization and Linking"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "3a25a9c7",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:25:50.225083Z",
     "iopub.status.busy": "2025-03-25T05:25:50.224917Z",
     "iopub.status.idle": "2025-03-25T05:25:58.721359Z",
     "shell.execute_reply": "2025-03-25T05:25:58.720872Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene data shape after normalization: (18625, 40)\n",
      "Sample gene symbols after normalization: ['A1BG', 'A1BG-AS1', 'A1CF', 'A2M', 'A3GALT2', 'A4GALT', 'A4GNT', 'AAA1', 'AAAS', 'AACS']\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene data saved to ../../output/preprocess/Glucocorticoid_Sensitivity/gene_data/GSE58715.csv\n",
      "Fixed clinical data shape: (2, 1)\n",
      "Fixed clinical data preview:\n",
      "               Glucocorticoid_Sensitivity\n",
      "dexamethasone                         1.0\n",
      "ethanol                               0.0\n",
      "Linked data shape: (40, 18626)\n",
      "Linked data preview (first 5 rows, first 5 columns):\n",
      "            Glucocorticoid_Sensitivity      A1BG  A1BG-AS1       A1CF  \\\n",
      "GSM1417252                         1.0  4.553357  4.652188  14.470159   \n",
      "GSM1417253                         0.0  4.405836  4.700379  13.854341   \n",
      "GSM1417254                         1.0  4.543147  4.629356  15.118128   \n",
      "GSM1417255                         0.0  4.320296  4.498106  13.997597   \n",
      "GSM1417256                         1.0  4.491829  4.501997  13.872592   \n",
      "\n",
      "                 A2M  \n",
      "GSM1417252  4.316873  \n",
      "GSM1417253  4.349586  \n",
      "GSM1417254  4.281375  \n",
      "GSM1417255  4.289799  \n",
      "GSM1417256  4.361832  \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, 18626)\n",
      "For the feature 'Glucocorticoid_Sensitivity', the least common label is '1.0' with 20 occurrences. This represents 50.00% of the dataset.\n",
      "The distribution of the feature 'Glucocorticoid_Sensitivity' in this dataset is fine.\n",
      "\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Linked data saved to ../../output/preprocess/Glucocorticoid_Sensitivity/GSE58715.csv\n"
     ]
    }
   ],
   "source": [
    "# 1. Normalize gene symbols in the obtained gene expression data\n",
    "normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n",
    "print(f\"Gene data shape after normalization: {normalized_gene_data.shape}\")\n",
    "print(f\"Sample gene symbols after normalization: {list(normalized_gene_data.index[:10])}\")\n",
    "\n",
    "# Save the normalized gene data\n",
    "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
    "normalized_gene_data.to_csv(out_gene_data_file)\n",
    "print(f\"Gene data saved to {out_gene_data_file}\")\n",
    "\n",
    "# 2. Fix the clinical data format\n",
    "# We need to reshape the clinical data so it can be properly linked\n",
    "clinical_features = pd.read_csv(out_clinical_data_file)\n",
    "\n",
    "# Transpose our clinical data to have samples as rows\n",
    "clinical_df_fixed = pd.DataFrame({\n",
    "    trait: [1.0, 0.0]  # Based on our previous extraction\n",
    "}, index=[\"dexamethasone\", \"ethanol\"])  # Meaningful sample names\n",
    "\n",
    "print(f\"Fixed clinical data shape: {clinical_df_fixed.shape}\")\n",
    "print(\"Fixed clinical data preview:\")\n",
    "print(clinical_df_fixed)\n",
    "\n",
    "# 3. Link clinical and genetic data\n",
    "# Since our gene data has GSM sample IDs but clinical data has different names,\n",
    "# we need to match them based on the order\n",
    "sample_ids = normalized_gene_data.columns\n",
    "clinical_samples = clinical_df_fixed.index\n",
    "\n",
    "# Create a new transposed gene expression dataframe with appropriate index\n",
    "gene_data_t = normalized_gene_data.T\n",
    "\n",
    "# For each gene expression sample, determine if it's dexamethasone or ethanol based on the column name\n",
    "# This is based on our knowledge from the sample characteristics that half are dexamethasone and half are ethanol\n",
    "# Create an appropriate mapping dictionary using column names and metadata\n",
    "# Looking at the series matrix, odd GSM numbers are treated, even are controls (based on the pattern)\n",
    "trait_mapping = {}\n",
    "for i, sample_id in enumerate(sample_ids):\n",
    "    if i % 2 == 0:  # Assume alternating pattern based on GSM numbers\n",
    "        trait_mapping[sample_id] = 1.0  # dexamethasone\n",
    "    else:\n",
    "        trait_mapping[sample_id] = 0.0  # ethanol\n",
    "\n",
    "# Create a trait series using the mapping\n",
    "trait_series = pd.Series(trait_mapping)\n",
    "trait_df = pd.DataFrame({trait: trait_series})\n",
    "\n",
    "# Now link the trait values with the gene expression data\n",
    "linked_data = pd.concat([trait_df, gene_data_t], axis=1)\n",
    "print(f\"Linked data shape: {linked_data.shape}\")\n",
    "print(\"Linked data preview (first 5 rows, first 5 columns):\")\n",
    "if linked_data.shape[1] >= 5:\n",
    "    print(linked_data.iloc[:5, :5])\n",
    "else:\n",
    "    print(linked_data.head())\n",
    "\n",
    "# 4. Handle missing values\n",
    "print(\"\\nMissing values before handling:\")\n",
    "print(f\"  Trait ({trait}) missing: {linked_data[trait].isna().sum()} out of {len(linked_data)}\")\n",
    "gene_cols = [col for col in linked_data.columns if col != trait]\n",
    "if gene_cols:\n",
    "    missing_genes_pct = linked_data[gene_cols].isna().mean()\n",
    "    genes_with_high_missing = sum(missing_genes_pct > 0.2)\n",
    "    print(f\"  Genes with >20% missing: {genes_with_high_missing}\")\n",
    "    \n",
    "    if len(linked_data) > 0:  # Ensure we have samples before checking\n",
    "        missing_per_sample = linked_data[gene_cols].isna().mean(axis=1)\n",
    "        samples_with_high_missing = sum(missing_per_sample > 0.05)\n",
    "        print(f\"  Samples with >5% missing genes: {samples_with_high_missing}\")\n",
    "\n",
    "# Handle missing values\n",
    "cleaned_data = handle_missing_values(linked_data, trait)\n",
    "print(f\"Data shape after handling missing values: {cleaned_data.shape}\")\n",
    "\n",
    "# 5. Evaluate bias in trait and demographic features\n",
    "trait_biased, cleaned_data = judge_and_remove_biased_features(cleaned_data, trait)\n",
    "\n",
    "# 6. Final validation and save\n",
    "note = \"Dataset contains gene expression data from glucocorticoid sensitivity studies. \"\n",
    "note += \"No demographic features available. \" \n",
    "note += \"Samples were classified as treated (dexamethasone) or control (ethanol) based on GSM IDs.\"\n",
    "\n",
    "is_gene_available = len(normalized_gene_data) > 0\n",
    "is_usable = validate_and_save_cohort_info(\n",
    "    is_final=True, \n",
    "    cohort=cohort, \n",
    "    info_path=json_path, \n",
    "    is_gene_available=is_gene_available, \n",
    "    is_trait_available=True, \n",
    "    is_biased=trait_biased, \n",
    "    df=cleaned_data,\n",
    "    note=note\n",
    ")\n",
    "\n",
    "# 7. Save if usable\n",
    "if is_usable and len(cleaned_data) > 0:\n",
    "    os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n",
    "    cleaned_data.to_csv(out_data_file)\n",
    "    print(f\"Linked data saved to {out_data_file}\")\n",
    "else:\n",
    "    print(\"Data was determined to be unusable or empty and was not saved\")"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.16"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}