File size: 30,090 Bytes
53eb596
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "d7c20b37",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T07:09:22.181719Z",
     "iopub.status.busy": "2025-03-25T07:09:22.181618Z",
     "iopub.status.idle": "2025-03-25T07:09:22.344878Z",
     "shell.execute_reply": "2025-03-25T07:09:22.344565Z"
    }
   },
   "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 = \"Intellectual_Disability\"\n",
    "cohort = \"GSE158385\"\n",
    "\n",
    "# Input paths\n",
    "in_trait_dir = \"../../input/GEO/Intellectual_Disability\"\n",
    "in_cohort_dir = \"../../input/GEO/Intellectual_Disability/GSE158385\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/Intellectual_Disability/GSE158385.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/Intellectual_Disability/gene_data/GSE158385.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/Intellectual_Disability/clinical_data/GSE158385.csv\"\n",
    "json_path = \"../../output/preprocess/Intellectual_Disability/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b66bda59",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "1531d515",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T07:09:22.346308Z",
     "iopub.status.busy": "2025-03-25T07:09:22.346167Z",
     "iopub.status.idle": "2025-03-25T07:09:22.399218Z",
     "shell.execute_reply": "2025-03-25T07:09:22.398923Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Background Information:\n",
      "!Series_title\t\"Apigenin as a Candidate Prenatal Treatment for Trisomy 21: Effects in Human Amniocytes and the Ts1Cje Mouse Model\"\n",
      "!Series_summary\t\"This SuperSeries is composed of the SubSeries listed below.\"\n",
      "!Series_overall_design\t\"Refer to individual Series\"\n",
      "Sample Characteristics Dictionary:\n",
      "{0: ['tissue: forebrain'], 1: ['developmental stage: E15'], 2: ['genotype: WT', 'genotype: Ts1Cje'], 3: ['treatment: Powder', 'treatment: Apigenin']}\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": "155ba7cf",
   "metadata": {},
   "source": [
    "### Step 2: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "37d56a9d",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T07:09:22.400266Z",
     "iopub.status.busy": "2025-03-25T07:09:22.400160Z",
     "iopub.status.idle": "2025-03-25T07:09:22.407907Z",
     "shell.execute_reply": "2025-03-25T07:09:22.407650Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Preview of selected clinical data:\n",
      "{'GSM4798553': [nan], 'GSM4798554': [nan], 'GSM4798555': [nan], 'GSM4798556': [nan], 'GSM4798557': [nan], 'GSM4798558': [nan], 'GSM4798559': [nan], 'GSM4798560': [nan], 'GSM4798561': [nan], 'GSM4798562': [nan], 'GSM4798563': [nan], 'GSM4798564': [nan], 'GSM4798565': [nan], 'GSM4798566': [nan], 'GSM4798567': [nan], 'GSM4798568': [nan], 'GSM4798569': [nan], 'GSM4798570': [nan], 'GSM4798571': [nan], 'GSM4798572': [nan]}\n",
      "Clinical data saved to ../../output/preprocess/Intellectual_Disability/clinical_data/GSE158385.csv\n"
     ]
    }
   ],
   "source": [
    "import pandas as pd\n",
    "from typing import Optional, Callable\n",
    "import os\n",
    "import json\n",
    "\n",
    "# Check if gene expression data is available\n",
    "# From the background information, this appears to be related to trisomy 21 and gene expression\n",
    "is_gene_available = True\n",
    "\n",
    "# Define the row indices for trait, age, and gender\n",
    "# trait_row: Karyotype information (row 2) can be used to determine intellectual disability (trisomy 21)\n",
    "trait_row = 2  # karyotype information\n",
    "age_row = None  # No age information available\n",
    "gender_row = None  # Gender can be inferred from karyotype, but it's not a separate variable for analysis\n",
    "\n",
    "# Conversion functions\n",
    "def convert_trait(value: str) -> Optional[int]:\n",
    "    \"\"\"Convert karyotype information to binary trait value (1 for T21, 0 for normal)\"\"\"\n",
    "    if not value or \":\" not in value:\n",
    "        return None\n",
    "    value = value.split(\":\", 1)[1].strip()\n",
    "    if \"T21\" in value:  # Trisomy 21 indicates intellectual disability\n",
    "        return 1\n",
    "    elif \"2N\" in value:  # Normal karyotype\n",
    "        return 0\n",
    "    return None\n",
    "\n",
    "def convert_age(value: str) -> Optional[float]:\n",
    "    \"\"\"Convert age value to float\"\"\"\n",
    "    # Not used but defined for completeness\n",
    "    if not value or \":\" not in value:\n",
    "        return None\n",
    "    value = value.split(\":\", 1)[1].strip()\n",
    "    try:\n",
    "        return float(value)\n",
    "    except:\n",
    "        return None\n",
    "\n",
    "def convert_gender(value: str) -> Optional[int]:\n",
    "    \"\"\"Convert gender value to binary (0 for female, 1 for male)\"\"\"\n",
    "    # Not used but defined for completeness\n",
    "    if not value or \":\" not in value:\n",
    "        return None\n",
    "    value = value.split(\":\", 1)[1].strip()\n",
    "    if \"female\" in value.lower() or \"f\" == value.lower():\n",
    "        return 0\n",
    "    elif \"male\" in value.lower() or \"m\" == value.lower():\n",
    "        return 1\n",
    "    return None\n",
    "\n",
    "# Check trait availability\n",
    "is_trait_available = trait_row is not None\n",
    "\n",
    "# Save metadata using the validation function\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",
    "# Extract clinical features if trait data is available\n",
    "# Note: We'll assume the clinical_data is already available as a variable\n",
    "# from a previous step, rather than loading from a file\n",
    "if trait_row is not None and 'clinical_data' in locals():\n",
    "    try:\n",
    "        # Use the geo_select_clinical_features function to extract 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 selected clinical data\n",
    "        print(\"Preview of selected clinical data:\")\n",
    "        print(preview_df(selected_clinical_df))\n",
    "        \n",
    "        # Create the output directory if it doesn't exist\n",
    "        os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
    "        \n",
    "        # Save the clinical data to a CSV file\n",
    "        selected_clinical_df.to_csv(out_clinical_data_file, index=False)\n",
    "        print(f\"Clinical data saved to {out_clinical_data_file}\")\n",
    "    except Exception as e:\n",
    "        print(f\"Error processing clinical data: {e}\")\n",
    "else:\n",
    "    if trait_row is not None:\n",
    "        print(\"Clinical data not available in memory. Skipping clinical feature extraction.\")\n",
    "    else:\n",
    "        print(\"No trait data available. Skipping clinical feature extraction.\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d3282f6e",
   "metadata": {},
   "source": [
    "### Step 3: Gene Data Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "1b96ef2d",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T07:09:22.408904Z",
     "iopub.status.busy": "2025-03-25T07:09:22.408802Z",
     "iopub.status.idle": "2025-03-25T07:09:22.466551Z",
     "shell.execute_reply": "2025-03-25T07:09:22.466248Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Extracting gene data from matrix file:\n",
      "Successfully extracted gene data with 21225 rows\n",
      "First 20 gene IDs:\n",
      "Index(['100008567_at', '100009600_at', '100009609_at', '100009614_at',\n",
      "       '100012_at', '100017_at', '100019_at', '100033459_at', '100034251_at',\n",
      "       '100034748_at', '100036520_at', '100036521_at', '100036523_at',\n",
      "       '100036537_at', '100036768_at', '100037258_at', '100037260_at',\n",
      "       '100037262_at', '100037278_at', '100037396_at'],\n",
      "      dtype='object', name='ID')\n",
      "\n",
      "Gene expression data available: True\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. Extract gene expression data from the matrix file\n",
    "try:\n",
    "    print(\"Extracting gene data from matrix file:\")\n",
    "    gene_data = get_genetic_data(matrix_file)\n",
    "    if gene_data.empty:\n",
    "        print(\"Extracted gene expression data is empty\")\n",
    "        is_gene_available = False\n",
    "    else:\n",
    "        print(f\"Successfully extracted gene data with {len(gene_data.index)} rows\")\n",
    "        print(\"First 20 gene IDs:\")\n",
    "        print(gene_data.index[:20])\n",
    "        is_gene_available = True\n",
    "except Exception as e:\n",
    "    print(f\"Error extracting gene data: {e}\")\n",
    "    print(\"This dataset appears to have an empty or malformed gene expression matrix\")\n",
    "    is_gene_available = False\n",
    "\n",
    "print(f\"\\nGene expression data available: {is_gene_available}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "12237d86",
   "metadata": {},
   "source": [
    "### Step 4: Gene Identifier Review"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "43ca195f",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T07:09:22.467721Z",
     "iopub.status.busy": "2025-03-25T07:09:22.467614Z",
     "iopub.status.idle": "2025-03-25T07:09:22.469358Z",
     "shell.execute_reply": "2025-03-25T07:09:22.469095Z"
    }
   },
   "outputs": [],
   "source": [
    "# Based on my biomedical knowledge, these identifiers (TC01000001.hg.1, etc.) are not standard human gene symbols\n",
    "# They appear to be Affymetrix transcript cluster IDs from a human gene array\n",
    "# Standard human gene symbols would be like BRCA1, TP53, etc.\n",
    "# These IDs need to be mapped to standard gene symbols\n",
    "\n",
    "requires_gene_mapping = True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cfdf62a1",
   "metadata": {},
   "source": [
    "### Step 5: Gene Annotation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "407315bf",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T07:09:22.470375Z",
     "iopub.status.busy": "2025-03-25T07:09:22.470276Z",
     "iopub.status.idle": "2025-03-25T07:09:25.433365Z",
     "shell.execute_reply": "2025-03-25T07:09:25.432988Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Extracting gene annotation data from SOFT file...\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Successfully extracted gene annotation data with 1647953 rows\n",
      "\n",
      "Gene annotation preview (first few rows):\n",
      "{'ID': ['100008567_at', '100009600_at', '100009609_at', '100009614_at', '100012_at'], 'ENTREZ_GENE_ID': ['100008567', '100009600', '100009609', '100009614', '100012'], 'Description': ['predicted gene 14964', 'zinc finger, GATA-like protein 1', 'vomeronasal 2, receptor 65', 'keratin associated protein LOC100009614', 'oogenesin 3']}\n",
      "\n",
      "Column names in gene annotation data:\n",
      "['ID', 'ENTREZ_GENE_ID', 'Description']\n"
     ]
    }
   ],
   "source": [
    "# 1. Extract gene annotation data from the SOFT file\n",
    "print(\"Extracting gene annotation data from SOFT file...\")\n",
    "try:\n",
    "    # Use the library function to extract gene annotation\n",
    "    gene_annotation = get_gene_annotation(soft_file)\n",
    "    print(f\"Successfully extracted gene annotation data with {len(gene_annotation.index)} rows\")\n",
    "    \n",
    "    # Preview the annotation DataFrame\n",
    "    print(\"\\nGene annotation preview (first few rows):\")\n",
    "    print(preview_df(gene_annotation))\n",
    "    \n",
    "    # Show column names to help identify which columns we need for mapping\n",
    "    print(\"\\nColumn names in gene annotation data:\")\n",
    "    print(gene_annotation.columns.tolist())\n",
    "    \n",
    "    # Check for relevant mapping columns\n",
    "    if 'GB_ACC' in gene_annotation.columns:\n",
    "        print(\"\\nThe dataset contains GenBank accessions (GB_ACC) that could be used for gene mapping.\")\n",
    "        # Count non-null values in GB_ACC column\n",
    "        non_null_count = gene_annotation['GB_ACC'].count()\n",
    "        print(f\"Number of rows with GenBank accessions: {non_null_count} out of {len(gene_annotation)}\")\n",
    "    \n",
    "    if 'SPOT_ID' in gene_annotation.columns:\n",
    "        print(\"\\nThe dataset contains genomic regions (SPOT_ID) that could be used for location-based gene mapping.\")\n",
    "        print(\"Example SPOT_ID format:\", gene_annotation['SPOT_ID'].iloc[0])\n",
    "    \n",
    "except Exception as e:\n",
    "    print(f\"Error processing gene annotation data: {e}\")\n",
    "    is_gene_available = False\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5c593ed3",
   "metadata": {},
   "source": [
    "### Step 6: Gene Identifier Mapping"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "a5b2974c",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T07:09:25.434765Z",
     "iopub.status.busy": "2025-03-25T07:09:25.434638Z",
     "iopub.status.idle": "2025-03-25T07:09:26.413409Z",
     "shell.execute_reply": "2025-03-25T07:09:26.413080Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Analyzing gene identifiers for mapping...\n",
      "\n",
      "Creating gene mapping dataframe...\n",
      "Created mapping dataframe with 1647953 rows\n",
      "Sample mapping entries:\n",
      "             ID       Gene\n",
      "0  100008567_at  100008567\n",
      "1  100009600_at  100009600\n",
      "2  100009609_at  100009609\n",
      "3  100009614_at  100009614\n",
      "4     100012_at     100012\n",
      "\n",
      "Applying gene mapping to expression data...\n",
      "Overlap between expression data and mapping: 21225 probes out of 21225\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Successfully mapped to 0 genes\n",
      "First few gene symbols:\n",
      "Index([], dtype='object', name='Gene')\n",
      "\n",
      "Normalizing gene symbols...\n",
      "After normalization: 0 genes\n",
      "Gene expression data saved to ../../output/preprocess/Intellectual_Disability/gene_data/GSE158385.csv\n"
     ]
    }
   ],
   "source": [
    "# 1. Examine the gene identifiers to determine mapping\n",
    "print(\"Analyzing gene identifiers for mapping...\")\n",
    "\n",
    "# From the previous output, we have gene annotation with ID, ENTREZ_GENE_ID, and Description\n",
    "# We'll use the ENTREZ_GENE_ID for mapping since it contains gene identifiers\n",
    "\n",
    "# Create mapping dataframe using ID and ENTREZ_GENE_ID\n",
    "print(\"\\nCreating gene mapping dataframe...\")\n",
    "mapping_df = pd.DataFrame({\n",
    "    'ID': gene_annotation['ID'],\n",
    "    'Gene': gene_annotation['ENTREZ_GENE_ID']\n",
    "})\n",
    "\n",
    "# Keep only rows with valid gene mappings\n",
    "mapping_df = mapping_df.dropna(subset=['Gene'])\n",
    "mapping_df = mapping_df[mapping_df['Gene'] != '---']  # Remove any placeholder values\n",
    "print(f\"Created mapping dataframe with {len(mapping_df)} rows\")\n",
    "print(\"Sample mapping entries:\")\n",
    "print(mapping_df.head())\n",
    "\n",
    "# 2. Apply gene mapping to convert probe-level measurements to gene expression data\n",
    "try:\n",
    "    print(\"\\nApplying gene mapping to expression data...\")\n",
    "    # First, check the overlap between gene expression data IDs and mapping IDs\n",
    "    overlap_count = sum(gene_data.index.isin(mapping_df['ID']))\n",
    "    print(f\"Overlap between expression data and mapping: {overlap_count} probes out of {len(gene_data.index)}\")\n",
    "    \n",
    "    if overlap_count > 0:\n",
    "        # Apply gene mapping to convert probe-level measurements to gene expression data\n",
    "        gene_data = apply_gene_mapping(gene_data, mapping_df)\n",
    "        print(f\"Successfully mapped to {len(gene_data.index)} genes\")\n",
    "        print(\"First few gene symbols:\")\n",
    "        print(gene_data.index[:5])\n",
    "        \n",
    "        # Optional: Normalize gene symbols to standard forms\n",
    "        try:\n",
    "            print(\"\\nNormalizing gene symbols...\")\n",
    "            gene_data = normalize_gene_symbols_in_index(gene_data)\n",
    "            print(f\"After normalization: {len(gene_data.index)} genes\")\n",
    "        except Exception as e:\n",
    "            print(f\"Error normalizing gene symbols: {e}\")\n",
    "            # Continue with unnormalized symbols\n",
    "    else:\n",
    "        print(\"No overlap found between expression data IDs and mapping IDs.\")\n",
    "        print(\"Using probe IDs directly as gene proxies.\")\n",
    "        # Rename index to Gene for consistency in downstream processing\n",
    "        gene_data.index.name = 'Gene'\n",
    "    \n",
    "    # 3. Save the gene expression data\n",
    "    os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
    "    gene_data.to_csv(out_gene_data_file)\n",
    "    print(f\"Gene expression data saved to {out_gene_data_file}\")\n",
    "    \n",
    "except Exception as e:\n",
    "    print(f\"Error applying gene mapping: {e}\")\n",
    "    is_gene_available = False\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "690ec6b7",
   "metadata": {},
   "source": [
    "### Step 7: Data Normalization and Linking"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "2602f583",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T07:09:26.414798Z",
     "iopub.status.busy": "2025-03-25T07:09:26.414690Z",
     "iopub.status.idle": "2025-03-25T07:09:26.731964Z",
     "shell.execute_reply": "2025-03-25T07:09:26.731633Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "Handling gene data...\n",
      "No valid gene symbols after mapping. Using original probe data as gene proxies...\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene data saved to: ../../output/preprocess/Intellectual_Disability/gene_data/GSE158385.csv with 21225 features\n",
      "\n",
      "Loading clinical data and linking with genetic data...\n",
      "Loaded clinical data with shape: (1, 19)\n",
      "Clinical data columns: Index(['GSM4798554', 'GSM4798555', 'GSM4798556', 'GSM4798557', 'GSM4798558',\n",
      "       'GSM4798559', 'GSM4798560', 'GSM4798561', 'GSM4798562', 'GSM4798563',\n",
      "       'GSM4798564', 'GSM4798565', 'GSM4798566', 'GSM4798567', 'GSM4798568',\n",
      "       'GSM4798569', 'GSM4798570', 'GSM4798571', 'GSM4798572'],\n",
      "      dtype='object')\n",
      "Clinical data index: Index([nan], dtype='float64', name='GSM4798553')\n",
      "Updated clinical data index: Index(['Intellectual_Disability'], dtype='object')\n",
      "First few clinical sample IDs: ['GSM4798554', 'GSM4798555', 'GSM4798556', 'GSM4798557', 'GSM4798558']\n",
      "First few genetic sample IDs: ['GSM4798553', 'GSM4798554', 'GSM4798555', 'GSM4798556', 'GSM4798557']\n",
      "Found 19 common samples between clinical and genetic data\n",
      "Linked data shape: (19, 21226)\n",
      "Linked data columns: Index(['Intellectual_Disability', '100008567_at', '100009600_at',\n",
      "       '100009609_at', '100009614_at', '100012_at', '100017_at', '100019_at',\n",
      "       '100033459_at', '100034251_at'],\n",
      "      dtype='object')\n",
      "\n",
      "Handling missing values...\n",
      "After handling missing values, data shape: (0, 1)\n",
      "\n",
      "Checking for bias in features...\n",
      "Quartiles for 'Intellectual_Disability':\n",
      "  25%: nan\n",
      "  50% (Median): nan\n",
      "  75%: nan\n",
      "Min: nan\n",
      "Max: nan\n",
      "The distribution of the feature 'Intellectual_Disability' in this dataset is fine.\n",
      "\n",
      "\n",
      "Performing final validation...\n",
      "Abnormality detected in the cohort: GSE158385. Preprocessing failed.\n",
      "Dataset not usable for Intellectual_Disability association studies. Data not saved.\n"
     ]
    }
   ],
   "source": [
    "# 1. Use the original gene expression data with probe IDs since normalization gave 0 genes\n",
    "print(\"\\nHandling gene data...\")\n",
    "try:\n",
    "    # Load original gene data from previous step if it exists\n",
    "    if 'gene_data' not in locals() or len(gene_data.index) == 0:\n",
    "        print(\"No valid gene symbols after mapping. Using original probe data as gene proxies...\")\n",
    "        # Get original gene expression data again\n",
    "        gene_data = get_genetic_data(matrix_file)\n",
    "        # Rename index to Gene for consistency\n",
    "        gene_data.index.name = 'Gene'\n",
    "    \n",
    "    # Save the 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 data saved to: {out_gene_data_file} with {len(gene_data.index)} features\")\n",
    "    is_gene_available = len(gene_data.index) > 0\n",
    "except Exception as e:\n",
    "    print(f\"Error handling gene data: {e}\")\n",
    "    is_gene_available = False\n",
    "\n",
    "# 2. Load the clinical data and link with genetic data\n",
    "print(\"\\nLoading clinical data and linking with genetic data...\")\n",
    "try:\n",
    "    # Load the clinical data\n",
    "    clinical_df = pd.read_csv(out_clinical_data_file)\n",
    "    \n",
    "    # If clinical_df doesn't have an index column, set the first column as index\n",
    "    if not clinical_df.index.name and len(clinical_df.columns) > 1:\n",
    "        clinical_df = clinical_df.set_index(clinical_df.columns[0])\n",
    "    \n",
    "    print(f\"Loaded clinical data with shape: {clinical_df.shape}\")\n",
    "    print(f\"Clinical data columns: {clinical_df.columns}\")\n",
    "    print(f\"Clinical data index: {clinical_df.index}\")\n",
    "    \n",
    "    # Set the appropriate name for the trait in clinical data\n",
    "    # Since we're working with one trait row from earlier steps\n",
    "    clinical_df.index = [trait]\n",
    "    print(f\"Updated clinical data index: {clinical_df.index}\")\n",
    "    \n",
    "    # Ensure we have gene data\n",
    "    if is_gene_available and not gene_data.empty:\n",
    "        # Print sample IDs from both datasets for debugging\n",
    "        print(\"First few clinical sample IDs:\", list(clinical_df.columns)[:5])\n",
    "        print(\"First few genetic sample IDs:\", list(gene_data.columns)[:5])\n",
    "        \n",
    "        # Check and align sample IDs if needed\n",
    "        common_samples = set(clinical_df.columns).intersection(set(gene_data.columns))\n",
    "        if len(common_samples) > 0:\n",
    "            print(f\"Found {len(common_samples)} common samples between clinical and genetic data\")\n",
    "            # Keep only common samples\n",
    "            clinical_subset = clinical_df[list(common_samples)]\n",
    "            gene_data_subset = gene_data[list(common_samples)]\n",
    "            \n",
    "            # Link clinical and genetic data\n",
    "            linked_data = pd.concat([clinical_subset, gene_data_subset], axis=0).T\n",
    "            is_trait_available = True\n",
    "            print(f\"Linked data shape: {linked_data.shape}\")\n",
    "            print(f\"Linked data columns: {linked_data.columns[:10]}\")  # Print first 10 columns\n",
    "            \n",
    "            # 3. Handle missing values systematically\n",
    "            print(\"\\nHandling missing values...\")\n",
    "            try:\n",
    "                # Make sure the trait column exists in the linked data\n",
    "                if trait not in linked_data.columns:\n",
    "                    print(f\"Warning: {trait} column not found in linked data. Available columns: {linked_data.columns[:5]}\")\n",
    "                    # If the first column is our trait data, rename it\n",
    "                    linked_data.rename(columns={linked_data.columns[0]: trait}, inplace=True)\n",
    "                    print(f\"Renamed first column to {trait}\")\n",
    "                \n",
    "                linked_data = handle_missing_values(linked_data, trait)\n",
    "                print(f\"After handling missing values, data shape: {linked_data.shape}\")\n",
    "                \n",
    "                # 4. Determine whether the trait and demographic features are biased\n",
    "                print(\"\\nChecking for bias in features...\")\n",
    "                is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n",
    "            except Exception as e:\n",
    "                print(f\"Error handling missing values: {e}\")\n",
    "                linked_data = pd.DataFrame()\n",
    "                is_trait_available = False\n",
    "                is_biased = True\n",
    "        else:\n",
    "            print(\"No common samples found between clinical and genetic data\")\n",
    "            linked_data = pd.DataFrame()\n",
    "            is_trait_available = False\n",
    "            is_biased = True\n",
    "    else:\n",
    "        print(\"No valid gene expression data available\")\n",
    "        linked_data = pd.DataFrame()\n",
    "        is_trait_available = False\n",
    "        is_biased = True\n",
    "        \n",
    "except Exception as e:\n",
    "    print(f\"Error in linking clinical and genetic data: {e}\")\n",
    "    linked_data = pd.DataFrame()\n",
    "    is_trait_available = False\n",
    "    is_biased = True\n",
    "\n",
    "# 5. Final quality validation\n",
    "print(\"\\nPerforming final validation...\")\n",
    "note = \"Dataset is about trisomy 21 (Down syndrome) which is associated with intellectual disability\"\n",
    "\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",
    "# 6. Save linked data if usable\n",
    "if is_usable:\n",
    "    # Create directory if it doesn't exist\n",
    "    os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n",
    "    \n",
    "    # Save linked data\n",
    "    linked_data.to_csv(out_data_file)\n",
    "    print(f\"Linked data saved to {out_data_file}\")\n",
    "else:\n",
    "    print(f\"Dataset not usable for {trait} association studies. Data 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
}