File size: 31,496 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
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "88c09c10",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:09:28.102100Z",
     "iopub.status.busy": "2025-03-25T05:09:28.101915Z",
     "iopub.status.idle": "2025-03-25T05:09:28.285425Z",
     "shell.execute_reply": "2025-03-25T05:09:28.285090Z"
    }
   },
   "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 = \"Epilepsy\"\n",
    "cohort = \"GSE63808\"\n",
    "\n",
    "# Input paths\n",
    "in_trait_dir = \"../../input/GEO/Epilepsy\"\n",
    "in_cohort_dir = \"../../input/GEO/Epilepsy/GSE63808\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/Epilepsy/GSE63808.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/Epilepsy/gene_data/GSE63808.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/Epilepsy/clinical_data/GSE63808.csv\"\n",
    "json_path = \"../../output/preprocess/Epilepsy/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bb9c5e30",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "a5d3c922",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:09:28.286801Z",
     "iopub.status.busy": "2025-03-25T05:09:28.286659Z",
     "iopub.status.idle": "2025-03-25T05:09:28.570636Z",
     "shell.execute_reply": "2025-03-25T05:09:28.570319Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Background Information:\n",
      "!Series_title\t\"chronic temporal lobe epilepsy: biopsy hippocampus\"\n",
      "!Series_summary\t\"Analysis of biopsy hippocampal tissue of patients with pharmacoresistant temporal lobe epilepsy (TLE) undergoing neurosurgical removal of the epileptogenic focus for seizure control. Chronic TLE goes along with focal hyperexcitability. Results provide insight into molecular mechanisms that may play a role in seizure propensity\"\n",
      "!Series_overall_design\t\"129 human hippocampus samples\"\n",
      "Sample Characteristics Dictionary:\n",
      "{0: ['tissue: hippocampal formation'], 1: ['phenotype: epilepsy']}\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": "220f4b67",
   "metadata": {},
   "source": [
    "### Step 2: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "23eb002a",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:09:28.571823Z",
     "iopub.status.busy": "2025-03-25T05:09:28.571710Z",
     "iopub.status.idle": "2025-03-25T05:09:28.577668Z",
     "shell.execute_reply": "2025-03-25T05:09:28.577394Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "False"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import pandas as pd\n",
    "import os\n",
    "import json\n",
    "from typing import Callable, Optional, Dict, Any\n",
    "\n",
    "# 1. Gene Expression Data Availability\n",
    "# Based on the background information, the dataset is about human hippocampus gene expression\n",
    "# in epilepsy patients, which suggests gene expression data is available.\n",
    "is_gene_available = True\n",
    "\n",
    "# 2. Variable Availability and Data Type Conversion\n",
    "# 2.1 Data Availability\n",
    "# From the sample characteristics dictionary:\n",
    "# Key 1 corresponds to 'phenotype: epilepsy' which is our trait\n",
    "trait_row = 1\n",
    "# Age is not available in the sample characteristics\n",
    "age_row = None\n",
    "# Gender is not available in the sample characteristics\n",
    "gender_row = None\n",
    "\n",
    "# 2.2 Data Type Conversion Functions\n",
    "def convert_trait(value):\n",
    "    \"\"\"Convert trait value to binary (1 for epilepsy, 0 for control)\"\"\"\n",
    "    if value is None:\n",
    "        return None\n",
    "    # Extract the value after colon if present\n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip().lower()\n",
    "    else:\n",
    "        value = value.strip().lower()\n",
    "    \n",
    "    # Based on the sample characteristics, all samples have epilepsy\n",
    "    # This is a constant feature which isn't useful for association studies\n",
    "    if 'epilepsy' in value:\n",
    "        return 1\n",
    "    # For completeness, though not present in this dataset\n",
    "    elif 'control' in value or 'normal' in value or 'healthy' in value:\n",
    "        return 0\n",
    "    return None\n",
    "\n",
    "def convert_age(value):\n",
    "    \"\"\"Convert age value to continuous\"\"\"\n",
    "    # Not applicable as age data is not available\n",
    "    return None\n",
    "\n",
    "def convert_gender(value):\n",
    "    \"\"\"Convert gender value to binary (0 for female, 1 for male)\"\"\"\n",
    "    # Not applicable as gender data is not available\n",
    "    return None\n",
    "\n",
    "# 3. Save Metadata\n",
    "# Since all samples have the same trait value (all are epilepsy cases),\n",
    "# this is a constant feature and not useful for association studies\n",
    "is_trait_available = False\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",
    "# Skipping this step since trait data is not variable (constant feature)\n",
    "# and the required clinical_data.csv file doesn't exist in the specified path\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ed365d91",
   "metadata": {},
   "source": [
    "### Step 3: Gene Data Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "c73fddcf",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:09:28.578779Z",
     "iopub.status.busy": "2025-03-25T05:09:28.578675Z",
     "iopub.status.idle": "2025-03-25T05:09:29.223992Z",
     "shell.execute_reply": "2025-03-25T05:09:29.223625Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "SOFT file: ../../input/GEO/Epilepsy/GSE63808/GSE63808_family.soft.gz\n",
      "Matrix file: ../../input/GEO/Epilepsy/GSE63808/GSE63808_series_matrix.txt.gz\n",
      "Found the matrix table marker in the file.\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene data shape: (48803, 129)\n",
      "First 20 gene/probe identifiers:\n",
      "['ILMN_1343291', 'ILMN_1343295', 'ILMN_1651199', 'ILMN_1651209', 'ILMN_1651210', 'ILMN_1651221', 'ILMN_1651228', 'ILMN_1651229', 'ILMN_1651230', 'ILMN_1651232', 'ILMN_1651235', 'ILMN_1651236', 'ILMN_1651237', 'ILMN_1651238', 'ILMN_1651249', 'ILMN_1651253', 'ILMN_1651254', 'ILMN_1651259', 'ILMN_1651260', 'ILMN_1651262']\n"
     ]
    }
   ],
   "source": [
    "# 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",
    "print(f\"SOFT file: {soft_file}\")\n",
    "print(f\"Matrix file: {matrix_file}\")\n",
    "\n",
    "# Set gene availability flag\n",
    "is_gene_available = True  # Initially assume gene data is available\n",
    "\n",
    "# First check if the matrix file contains the expected marker\n",
    "found_marker = False\n",
    "try:\n",
    "    with gzip.open(matrix_file, 'rt') as file:\n",
    "        for line in file:\n",
    "            if \"!series_matrix_table_begin\" in line:\n",
    "                found_marker = True\n",
    "                break\n",
    "    \n",
    "    if found_marker:\n",
    "        print(\"Found the matrix table marker in the file.\")\n",
    "    else:\n",
    "        print(\"Warning: Could not find '!series_matrix_table_begin' marker in the file.\")\n",
    "        \n",
    "    # Try to extract gene data from the matrix file\n",
    "    gene_data = get_genetic_data(matrix_file)\n",
    "    \n",
    "    if gene_data.shape[0] == 0:\n",
    "        print(\"Warning: Extracted gene data has 0 rows.\")\n",
    "        is_gene_available = False\n",
    "    else:\n",
    "        print(f\"Gene data shape: {gene_data.shape}\")\n",
    "        # Print the first 20 gene/probe identifiers\n",
    "        print(\"First 20 gene/probe identifiers:\")\n",
    "        print(gene_data.index[:20].tolist())\n",
    "        \n",
    "except Exception as e:\n",
    "    print(f\"Error extracting gene data: {e}\")\n",
    "    is_gene_available = False\n",
    "    \n",
    "    # Try to diagnose the file format\n",
    "    print(\"Examining file content to diagnose the issue:\")\n",
    "    try:\n",
    "        with gzip.open(matrix_file, 'rt') as file:\n",
    "            for i, line in enumerate(file):\n",
    "                if i < 10:  # Print first 10 lines to diagnose\n",
    "                    print(f\"Line {i}: {line.strip()[:100]}...\")  # Print first 100 chars of each line\n",
    "                else:\n",
    "                    break\n",
    "    except Exception as e2:\n",
    "        print(f\"Error examining file: {e2}\")\n",
    "\n",
    "if not is_gene_available:\n",
    "    print(\"Gene expression data could not be successfully extracted from this dataset.\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fed50090",
   "metadata": {},
   "source": [
    "### Step 4: Gene Identifier Review"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "9317d6cd",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:09:29.225253Z",
     "iopub.status.busy": "2025-03-25T05:09:29.225148Z",
     "iopub.status.idle": "2025-03-25T05:09:29.226965Z",
     "shell.execute_reply": "2025-03-25T05:09:29.226700Z"
    }
   },
   "outputs": [],
   "source": [
    "# Analyze the gene identifiers from the output\n",
    "# The identifiers starting with \"ILMN_\" are Illumina microarray probe IDs\n",
    "# These are not human gene symbols and need to be mapped to gene symbols\n",
    "\n",
    "requires_gene_mapping = True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3c1d2f4a",
   "metadata": {},
   "source": [
    "### Step 5: Gene Annotation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "2af1eef2",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:09:29.227982Z",
     "iopub.status.busy": "2025-03-25T05:09:29.227882Z",
     "iopub.status.idle": "2025-03-25T05:09:40.800523Z",
     "shell.execute_reply": "2025-03-25T05:09:40.800204Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "Gene annotation preview:\n",
      "Columns in gene annotation: ['ID', 'nuID', 'Species', 'Source', 'Search_Key', 'Transcript', 'ILMN_Gene', 'Source_Reference_ID', 'RefSeq_ID', 'Unigene_ID', 'Entrez_Gene_ID', 'GI', 'Accession', 'Symbol', 'Protein_Product', 'Array_Address_Id', 'Probe_Type', 'Probe_Start', 'SEQUENCE', 'Chromosome', 'Probe_Chr_Orientation', 'Probe_Coordinates', 'Cytoband', 'Definition', 'Ontology_Component', 'Ontology_Process', 'Ontology_Function', 'Synonyms', 'Obsolete_Probe_Id', 'GB_ACC']\n",
      "{'ID': ['ILMN_1725881', 'ILMN_1910180', 'ILMN_1804174', 'ILMN_1796063', 'ILMN_1811966'], 'nuID': ['rp13_p1x6D80lNLk3c', 'NEX0oqCV8.er4HVfU4', 'KyqQynMZxJcruyylEU', 'xXl7eXuF7sbPEp.KFI', '9ckqJrioiaej9_ajeQ'], 'Species': ['Homo sapiens', 'Homo sapiens', 'Homo sapiens', 'Homo sapiens', 'Homo sapiens'], 'Source': ['RefSeq', 'Unigene', 'RefSeq', 'RefSeq', 'RefSeq'], 'Search_Key': ['ILMN_44919', 'ILMN_127219', 'ILMN_139282', 'ILMN_5006', 'ILMN_38756'], 'Transcript': ['ILMN_44919', 'ILMN_127219', 'ILMN_139282', 'ILMN_5006', 'ILMN_38756'], 'ILMN_Gene': ['LOC23117', 'HS.575038', 'FCGR2B', 'TRIM44', 'LOC653895'], 'Source_Reference_ID': ['XM_933824.1', 'Hs.575038', 'XM_938851.1', 'NM_017583.3', 'XM_936379.1'], 'RefSeq_ID': ['XM_933824.1', nan, 'XM_938851.1', 'NM_017583.3', 'XM_936379.1'], 'Unigene_ID': [nan, 'Hs.575038', nan, nan, nan], 'Entrez_Gene_ID': [23117.0, nan, 2213.0, 54765.0, 653895.0], 'GI': [89040007.0, 10437021.0, 88952550.0, 29029528.0, 89033487.0], 'Accession': ['XM_933824.1', 'AK024680', 'XM_938851.1', 'NM_017583.3', 'XM_936379.1'], 'Symbol': ['LOC23117', nan, 'FCGR2B', 'TRIM44', 'LOC653895'], 'Protein_Product': ['XP_938917.1', nan, 'XP_943944.1', 'NP_060053.2', 'XP_941472.1'], 'Array_Address_Id': [1710221.0, 5900364.0, 2480717.0, 1300239.0, 4480719.0], 'Probe_Type': ['I', 'S', 'I', 'S', 'S'], 'Probe_Start': [122.0, 1409.0, 1643.0, 2901.0, 25.0], 'SEQUENCE': ['GGCTCCTCTTTGGGCTCCTACTGGAATTTATCAGCCATCAGTGCATCTCT', 'ACACCTTCAGGAGGGAAGCCCTTATTTCTGGGTTGAACTCCCCTTCCATG', 'TAGGGGCAATAGGCTATACGCTACAGCCTAGGTGTGTAGTAGGCCACACC', 'CCTGCCTGTCTGCCTGTGACCTGTGTACGTATTACAGGCTTTAGGACCAG', 'CTAGCAGGGAGCGGTGAGGGAGAGCGGCTGGATTTCTTGCGGGATCTGCA'], 'Chromosome': ['16', nan, nan, '11', nan], 'Probe_Chr_Orientation': ['-', nan, nan, '+', nan], 'Probe_Coordinates': ['21766363-21766363:21769901-21769949', nan, nan, '35786070-35786119', nan], 'Cytoband': ['16p12.2a', nan, '1q23.3b', '11p13a', '10q11.23b'], 'Definition': ['PREDICTED: Homo sapiens KIAA0220-like protein, transcript variant 11 (LOC23117), mRNA.', 'Homo sapiens cDNA: FLJ21027 fis, clone CAE07110', 'PREDICTED: Homo sapiens Fc fragment of IgG, low affinity IIb, receptor (CD32) (FCGR2B), mRNA.', 'Homo sapiens tripartite motif-containing 44 (TRIM44), mRNA.', 'PREDICTED: Homo sapiens similar to protein geranylgeranyltransferase type I, beta subunit (LOC653895), mRNA.'], 'Ontology_Component': [nan, nan, nan, 'intracellular [goid 5622] [evidence IEA]', nan], 'Ontology_Process': [nan, nan, nan, nan, nan], 'Ontology_Function': [nan, nan, nan, 'zinc ion binding [goid 8270] [evidence IEA]; metal ion binding [goid 46872] [evidence IEA]', nan], 'Synonyms': [nan, nan, nan, 'MGC3490; MC7; HSA249128; DIPB', nan], 'Obsolete_Probe_Id': [nan, nan, nan, 'MGC3490; MC7; HSA249128; DIPB', nan], 'GB_ACC': ['XM_933824.1', 'AK024680', 'XM_938851.1', 'NM_017583.3', 'XM_936379.1']}\n",
      "\n",
      "Sample of Description column (first 5 rows):\n"
     ]
    }
   ],
   "source": [
    "# 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.\n",
    "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
    "gene_annotation = get_gene_annotation(soft_file)\n",
    "\n",
    "# 2. Analyze the gene annotation dataframe to identify which columns contain the gene identifiers and gene symbols\n",
    "print(\"\\nGene annotation preview:\")\n",
    "print(f\"Columns in gene annotation: {gene_annotation.columns.tolist()}\")\n",
    "print(preview_df(gene_annotation, n=5))\n",
    "\n",
    "# Based on the preview, 'ID' appears to be the probe ID and 'Description' contains gene names\n",
    "# Display more samples from the Description column to better understand the format\n",
    "print(\"\\nSample of Description column (first 5 rows):\")\n",
    "if 'Description' in gene_annotation.columns:\n",
    "    for i in range(min(5, len(gene_annotation))):\n",
    "        print(f\"Row {i}: {gene_annotation['Description'].iloc[i]}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "912e4e61",
   "metadata": {},
   "source": [
    "### Step 6: Gene Identifier Mapping"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "3fe64fea",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:09:40.801984Z",
     "iopub.status.busy": "2025-03-25T05:09:40.801864Z",
     "iopub.status.idle": "2025-03-25T05:09:43.081043Z",
     "shell.execute_reply": "2025-03-25T05:09:43.080544Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene mapping dataframe shape: (36157, 2)\n",
      "Preview of gene_mapping dataframe:\n",
      "{'ID': ['ILMN_1725881', 'ILMN_1804174', 'ILMN_1796063', 'ILMN_1811966', 'ILMN_1668162'], 'Gene': ['LOC23117', 'FCGR2B', 'TRIM44', 'LOC653895', 'DGAT2L3']}\n",
      "\n",
      "Applying gene mapping to convert probes to gene symbols...\n",
      "After mapping: gene_data shape: (19120, 129)\n",
      "First few genes in the expression data:\n",
      "['A1BG', 'A1CF', 'A26A1', 'A26B1', 'A26C1B', 'A26C3', 'A2BP1', 'A2M', 'A2ML1', 'A3GALT2']\n",
      "Number of unique genes: 19120\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene expression data saved to: ../../output/preprocess/Epilepsy/gene_data/GSE63808.csv\n"
     ]
    }
   ],
   "source": [
    "# 1. Identify the columns needed for mapping\n",
    "# 'ID' column in gene_annotation contains the probe identifiers (ILMN_*)\n",
    "# 'Symbol' column contains the gene symbols we need to map to\n",
    "prob_col = 'ID'\n",
    "gene_col = 'Symbol'\n",
    "\n",
    "# 2. Get the gene mapping dataframe\n",
    "gene_mapping = get_gene_mapping(gene_annotation, prob_col, gene_col)\n",
    "print(f\"Gene mapping dataframe shape: {gene_mapping.shape}\")\n",
    "print(\"Preview of gene_mapping dataframe:\")\n",
    "print(preview_df(gene_mapping, n=5))\n",
    "\n",
    "# 3. Convert probe-level measurements to gene expression data\n",
    "print(\"\\nApplying gene mapping to convert probes to gene symbols...\")\n",
    "gene_data = apply_gene_mapping(gene_data, gene_mapping)\n",
    "print(f\"After mapping: gene_data shape: {gene_data.shape}\")\n",
    "print(\"First few genes in the expression data:\")\n",
    "print(gene_data.index[:10].tolist())\n",
    "\n",
    "# Check the number of unique genes after mapping\n",
    "print(f\"Number of unique genes: {len(gene_data)}\")\n",
    "\n",
    "# Save the processed gene 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": "258d7812",
   "metadata": {},
   "source": [
    "### Step 7: Data Normalization and Linking"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "df826f3d",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:09:43.082478Z",
     "iopub.status.busy": "2025-03-25T05:09:43.082347Z",
     "iopub.status.idle": "2025-03-25T05:09:50.739091Z",
     "shell.execute_reply": "2025-03-25T05:09:50.738692Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene data shape before normalization: (19120, 129)\n",
      "Gene data shape after normalization: (18326, 129)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Normalized gene data saved to ../../output/preprocess/Epilepsy/gene_data/GSE63808.csv\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Extracted clinical data shape: (1, 129)\n",
      "Preview of clinical data (first 5 samples):\n",
      "          GSM1565578  GSM1565579  GSM1565580  GSM1565581  GSM1565582\n",
      "Epilepsy         1.0         1.0         1.0         1.0         1.0\n",
      "Clinical data saved to ../../output/preprocess/Epilepsy/clinical_data/GSE63808.csv\n",
      "Gene data columns (first 5): ['GSM1565578', 'GSM1565579', 'GSM1565580', 'GSM1565581', 'GSM1565582']\n",
      "Clinical data columns (first 5): ['GSM1565578', 'GSM1565579', 'GSM1565580', 'GSM1565581', 'GSM1565582']\n",
      "Found 129 common samples between gene and clinical data\n",
      "Initial linked data shape: (129, 18327)\n",
      "Preview of linked data (first 5 rows, first 5 columns):\n",
      "            Epilepsy        A1BG        A1CF         A2M       A2ML1\n",
      "GSM1565578       1.0  171.960000  264.260000  431.243333   90.660000\n",
      "GSM1565579       1.0  170.456667  261.040000  326.450000  101.096667\n",
      "GSM1565580       1.0  175.460000  260.106667  331.516667  106.350000\n",
      "GSM1565581       1.0  176.813333  254.776667  665.113333   89.360000\n",
      "GSM1565582       1.0  178.753333  254.280000  326.263333   95.166667\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Linked data shape after handling missing values: (129, 18327)\n",
      "Quartiles for 'Epilepsy':\n",
      "  25%: 1.0\n",
      "  50% (Median): 1.0\n",
      "  75%: 1.0\n",
      "Min: 1.0\n",
      "Max: 1.0\n",
      "The distribution of the feature 'Epilepsy' in this dataset is severely biased.\n",
      "\n",
      "Data not usable for the trait study - not saving final linked data.\n"
     ]
    }
   ],
   "source": [
    "# 1. Normalize gene symbols in the gene expression data\n",
    "try:\n",
    "    # Make sure the directory exists\n",
    "    os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
    "    \n",
    "    # Use the gene_data variable from the previous step (don't try to load it from file)\n",
    "    print(f\"Gene data shape before normalization: {gene_data.shape}\")\n",
    "    \n",
    "    # Apply normalization to gene symbols\n",
    "    normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n",
    "    print(f\"Gene data shape after normalization: {normalized_gene_data.shape}\")\n",
    "    \n",
    "    # Save the normalized gene data\n",
    "    normalized_gene_data.to_csv(out_gene_data_file)\n",
    "    print(f\"Normalized gene data saved to {out_gene_data_file}\")\n",
    "    \n",
    "    # Use the normalized data for further processing\n",
    "    gene_data = normalized_gene_data\n",
    "    is_gene_available = True\n",
    "except Exception as e:\n",
    "    print(f\"Error normalizing gene data: {e}\")\n",
    "    is_gene_available = False\n",
    "\n",
    "# 2. Load clinical data - respecting the analysis from Step 2\n",
    "# From Step 2, we determined:\n",
    "# trait_row = None  # No Epilepsy data available\n",
    "# age_row = None\n",
    "# gender_row = None\n",
    "is_trait_available = trait_row is not None\n",
    "\n",
    "# Skip clinical feature extraction when trait_row is None\n",
    "if is_trait_available:\n",
    "    try:\n",
    "        # Load the clinical data from file\n",
    "        soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
    "        background_info, clinical_data = get_background_and_clinical_data(matrix_file)\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",
    "            gender_row=gender_row,\n",
    "            convert_gender=convert_gender,\n",
    "            age_row=age_row,\n",
    "            convert_age=convert_age\n",
    "        )\n",
    "        \n",
    "        print(f\"Extracted clinical data shape: {clinical_features.shape}\")\n",
    "        print(\"Preview of clinical data (first 5 samples):\")\n",
    "        print(clinical_features.iloc[:, :5])\n",
    "        \n",
    "        # Save the properly extracted clinical data\n",
    "        os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
    "        clinical_features.to_csv(out_clinical_data_file)\n",
    "        print(f\"Clinical data saved to {out_clinical_data_file}\")\n",
    "    except Exception as e:\n",
    "        print(f\"Error extracting clinical data: {e}\")\n",
    "        is_trait_available = False\n",
    "else:\n",
    "    print(\"No trait data (Epilepsy) available in this dataset based on previous analysis.\")\n",
    "\n",
    "# 3. Link clinical and genetic data if both are available\n",
    "if is_trait_available and is_gene_available:\n",
    "    try:\n",
    "        # Debug the column names to ensure they match\n",
    "        print(f\"Gene data columns (first 5): {gene_data.columns[:5].tolist()}\")\n",
    "        print(f\"Clinical data columns (first 5): {clinical_features.columns[:5].tolist()}\")\n",
    "        \n",
    "        # Check for common sample IDs\n",
    "        common_samples = set(gene_data.columns).intersection(clinical_features.columns)\n",
    "        print(f\"Found {len(common_samples)} common samples between gene and clinical data\")\n",
    "        \n",
    "        if len(common_samples) > 0:\n",
    "            # Link the clinical and genetic data\n",
    "            linked_data = geo_link_clinical_genetic_data(clinical_features, gene_data)\n",
    "            print(f\"Initial linked data shape: {linked_data.shape}\")\n",
    "            \n",
    "            # Debug the trait values before handling missing values\n",
    "            print(\"Preview of linked data (first 5 rows, first 5 columns):\")\n",
    "            print(linked_data.iloc[:5, :5])\n",
    "            \n",
    "            # Handle missing values\n",
    "            linked_data = handle_missing_values(linked_data, trait)\n",
    "            print(f\"Linked data shape after handling missing values: {linked_data.shape}\")\n",
    "            \n",
    "            if linked_data.shape[0] > 0:\n",
    "                # Check for bias in trait and demographic features\n",
    "                is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n",
    "                \n",
    "                # Validate the data quality and save cohort info\n",
    "                note = \"Dataset contains gene expression data from GBM cell cultures, but no epilepsy phenotype information.\"\n",
    "                is_usable = validate_and_save_cohort_info(\n",
    "                    is_final=True,\n",
    "                    cohort=cohort,\n",
    "                    info_path=json_path,\n",
    "                    is_gene_available=is_gene_available,\n",
    "                    is_trait_available=is_trait_available,\n",
    "                    is_biased=is_biased,\n",
    "                    df=linked_data,\n",
    "                    note=note\n",
    "                )\n",
    "                \n",
    "                # Save the linked data if it's usable\n",
    "                if is_usable:\n",
    "                    os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n",
    "                    linked_data.to_csv(out_data_file)\n",
    "                    print(f\"Linked data saved to {out_data_file}\")\n",
    "                else:\n",
    "                    print(\"Data not usable for the trait study - not saving final linked data.\")\n",
    "            else:\n",
    "                print(\"After handling missing values, no samples remain.\")\n",
    "                validate_and_save_cohort_info(\n",
    "                    is_final=True,\n",
    "                    cohort=cohort,\n",
    "                    info_path=json_path,\n",
    "                    is_gene_available=is_gene_available,\n",
    "                    is_trait_available=is_trait_available,\n",
    "                    is_biased=True,\n",
    "                    df=pd.DataFrame(),\n",
    "                    note=\"No valid samples after handling missing values.\"\n",
    "                )\n",
    "        else:\n",
    "            print(\"No common samples found between gene expression and clinical data.\")\n",
    "            validate_and_save_cohort_info(\n",
    "                is_final=True,\n",
    "                cohort=cohort,\n",
    "                info_path=json_path,\n",
    "                is_gene_available=is_gene_available,\n",
    "                is_trait_available=is_trait_available,\n",
    "                is_biased=True,\n",
    "                df=pd.DataFrame(),\n",
    "                note=\"No common samples between gene expression and clinical data.\"\n",
    "            )\n",
    "    except Exception as e:\n",
    "        print(f\"Error linking or processing data: {e}\")\n",
    "        validate_and_save_cohort_info(\n",
    "            is_final=True,\n",
    "            cohort=cohort,\n",
    "            info_path=json_path,\n",
    "            is_gene_available=is_gene_available,\n",
    "            is_trait_available=is_trait_available,\n",
    "            is_biased=True,  # Assume biased if there's an error\n",
    "            df=pd.DataFrame(),  # Empty dataframe for metadata\n",
    "            note=f\"Error in data processing: {str(e)}\"\n",
    "        )\n",
    "else:\n",
    "    # Create an empty DataFrame for metadata purposes\n",
    "    empty_df = pd.DataFrame()\n",
    "    \n",
    "    # We can't proceed with linking if either trait or gene data is missing\n",
    "    print(\"Cannot proceed with data linking due to missing trait or gene data.\")\n",
    "    validate_and_save_cohort_info(\n",
    "        is_final=True,\n",
    "        cohort=cohort,\n",
    "        info_path=json_path,\n",
    "        is_gene_available=is_gene_available,\n",
    "        is_trait_available=is_trait_available,\n",
    "        is_biased=True,  # Data is unusable if we're missing components\n",
    "        df=empty_df,  # Empty dataframe for metadata\n",
    "        note=\"Missing essential data components for linking: dataset contains gene expression data from GBM cell cultures, but no epilepsy phenotype information.\"\n",
    "    )"
   ]
  }
 ],
 "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
}