File size: 25,985 Bytes
736e4a0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "56b10ce3",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T07:11:35.071914Z",
     "iopub.status.busy": "2025-03-25T07:11:35.071808Z",
     "iopub.status.idle": "2025-03-25T07:11:35.235244Z",
     "shell.execute_reply": "2025-03-25T07:11:35.234882Z"
    }
   },
   "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 = \"GSE98697\"\n",
    "\n",
    "# Input paths\n",
    "in_trait_dir = \"../../input/GEO/Intellectual_Disability\"\n",
    "in_cohort_dir = \"../../input/GEO/Intellectual_Disability/GSE98697\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/Intellectual_Disability/GSE98697.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/Intellectual_Disability/gene_data/GSE98697.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/Intellectual_Disability/clinical_data/GSE98697.csv\"\n",
    "json_path = \"../../output/preprocess/Intellectual_Disability/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "913e2593",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "3aa7bec2",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T07:11:35.236688Z",
     "iopub.status.busy": "2025-03-25T07:11:35.236550Z",
     "iopub.status.idle": "2025-03-25T07:11:35.440720Z",
     "shell.execute_reply": "2025-03-25T07:11:35.440364Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Background Information:\n",
      "!Series_title\t\"Coding and noncoding gene expression of 48 pediatric AML samples\"\n",
      "!Series_summary\t\"Long non-coding RNAs (lncRNAs) and miRNAs have emerged as crucial regulators of gene expression and cell fate decisions. Here we present an integrated analysis of the ncRNA-transcriptome of purified human hematopoietic stem cells (HSCs) and their differentiated progenies, including granulocytes, monocytes, T-cells, NK-cells, B-cells, megakaryocytes and erythroid precursors, which we correlated with the ncRNA expression profile of 48 pediatric AML samples to establish a core lncRNA stem cell signature in AML.Linear (PCA) and nonlinear (t-SNE) dimensionality reduction of 46 pediatric AML samples including Down syndrome AMKL, core-binding factor AMLs (inv[16] or t[8;21]) and MLL-rearranged leukemias mapped most samples to a space between HSCs and differentiated cells together with the myeloid progenitors. A subset of AML-samples mapped closely to healthy HSCs, including most of the DS-AMKLs and MLL-AMLs. Following the incorporation of acute myeloid leukemia (AML) samples into the landscape, we further uncover prognostically relevant ncRNA stem cell signatures shared between AML blasts and healthy hematopoietic stem cells.\"\n",
      "!Series_overall_design\t\"AML blasts from 48 pediatric AML samples were FACS-purified and total RNA was subjected to Microarray Analysis on the Arraystar Human LncRNA microarray V2.0 (Agilent-033010) platform\"\n",
      "Sample Characteristics Dictionary:\n",
      "{0: ['cell type: AML blasts'], 1: ['facs sorting gate: CD117- CD34+/- CD41+', 'facs sorting gate: CD117- CD34- CD41+', 'facs sorting gate: CD117+ CD34+ CD41- AND CD117- CD34- CD41+', 'facs sorting gate: CD117- CD34+ CD41+', 'facs sorting gate: CD117high+ CD33+ CD34-', 'facs sorting gate: CD117- CD33+ CD34-', 'facs sorting gate: CD117+/ - CD33+ CD34+', 'facs sorting gate: CD117+ CD33+ CD34+', 'facs sorting gate: CD117+ CD33+ CD34+/-', 'facs sorting gate: CD117+ CD33- CD34+', 'facs sorting gate: CD117- CD33- CD34+', 'facs sorting gate: CD117- CD33+ CD34+', 'facs sorting gate: CD117+ CD33+/- CD34+', 'facs sorting gate: CD117+ CD33- CD34-', 'facs sorting gate: CD117+ CD33- CD34+/-', 'facs sorting gate: CD117+/- CD33+ CD34-', 'facs sorting gate: CD117+  CD33- CD34-', 'facs sorting gate: CD117+  CD33+ CD34-', 'facs sorting gate: CD117+ CD33+ CD34-', 'facs sorting gate: CD117+7- CD33+ CD34-'], 2: ['aml subtype: Down-syndrome acute megakaryoblastic leukemia', 'aml subtype: acute megakaryoblastic leukemia', 'aml subtype: AML inv(16) M4eo', 'aml subtype: AML t(15;17) acute promyelocytic leukemia', 'aml subtype: AML t(8;21) M2', 'aml subtype: AML t(10;11) M5']}\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": "0820f588",
   "metadata": {},
   "source": [
    "### Step 2: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "93b6dfea",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T07:11:35.442207Z",
     "iopub.status.busy": "2025-03-25T07:11:35.442086Z",
     "iopub.status.idle": "2025-03-25T07:11:35.464643Z",
     "shell.execute_reply": "2025-03-25T07:11:35.464375Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "False"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import pandas as pd\n",
    "from typing import Dict, Any, Callable, Optional\n",
    "import os\n",
    "import json\n",
    "\n",
    "# 1. Gene Expression Data Availability\n",
    "# Based on the background information, this dataset contains microarray data of coding and noncoding gene expression\n",
    "# The \"Series_overall_design\" mentions \"Microarray Analysis on the Arraystar Human LncRNA microarray\" platform\n",
    "is_gene_available = True\n",
    "\n",
    "# 2. Variable Availability and Data Type Conversion\n",
    "# 2.1 Data Availability\n",
    "\n",
    "# For trait: Looking at the sample characteristics, row 2 contains AML subtypes\n",
    "# This is not intellectual disability data, but AML (Acute Myeloid Leukemia) data\n",
    "# Therefore, the intellectual disability trait is not available in this dataset\n",
    "trait_row = None  # No intellectual disability data\n",
    "\n",
    "# For age: There's no specific age mentioned in the sample characteristics\n",
    "age_row = None\n",
    "\n",
    "# For gender: There's no gender information in the sample characteristics\n",
    "gender_row = None\n",
    "\n",
    "# 2.2 Data Type Conversion Functions\n",
    "# Define conversion functions even though they might not be used in this dataset\n",
    "\n",
    "def convert_trait(value: str) -> Optional[int]:\n",
    "    \"\"\"Convert trait value to binary (0 or 1).\"\"\"\n",
    "    if value is None or pd.isna(value):\n",
    "        return None\n",
    "    \n",
    "    # Extract value after colon if present\n",
    "    if \":\" in value:\n",
    "        value = value.split(\":\", 1)[1].strip()\n",
    "    \n",
    "    # Since this dataset doesn't have intellectual disability data, \n",
    "    # we would return None for all values\n",
    "    return None\n",
    "\n",
    "def convert_age(value: str) -> Optional[float]:\n",
    "    \"\"\"Convert age value to continuous (float).\"\"\"\n",
    "    if value is None or pd.isna(value):\n",
    "        return None\n",
    "    \n",
    "    # Extract value after colon if present\n",
    "    if \":\" in value:\n",
    "        value = value.split(\":\", 1)[1].strip()\n",
    "    \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",
    "    if value is None or pd.isna(value):\n",
    "        return None\n",
    "    \n",
    "    # Extract value after colon if present\n",
    "    if \":\" in value:\n",
    "        value = value.split(\":\", 1)[1].strip().lower()\n",
    "    \n",
    "    if \"female\" in value or \"f\" == value:\n",
    "        return 0\n",
    "    elif \"male\" in value or \"m\" == value:\n",
    "        return 1\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "# 3. Save Metadata\n",
    "# Check if trait data is available (trait_row is not None)\n",
    "is_trait_available = trait_row is not None\n",
    "\n",
    "# Validate and save cohort information for initial filtering\n",
    "validate_and_save_cohort_info(\n",
    "    is_final=False,\n",
    "    cohort=cohort,\n",
    "    info_path=json_path,\n",
    "    is_gene_available=is_gene_available,\n",
    "    is_trait_available=is_trait_available\n",
    ")\n",
    "\n",
    "# 4. Clinical Feature Extraction\n",
    "# Since trait_row is None, we skip this step\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "83993654",
   "metadata": {},
   "source": [
    "### Step 3: Gene Data Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "afec298d",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T07:11:35.465990Z",
     "iopub.status.busy": "2025-03-25T07:11:35.465887Z",
     "iopub.status.idle": "2025-03-25T07:11:35.737548Z",
     "shell.execute_reply": "2025-03-25T07:11:35.737163Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Extracting gene data from matrix file:\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Successfully extracted gene data with 62738 rows\n",
      "First 20 gene IDs:\n",
      "Index(['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13',\n",
      "       '14', '15', '16', '17', '18', '19', '20'],\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": "495ec315",
   "metadata": {},
   "source": [
    "### Step 4: Gene Identifier Review"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "57f7ce43",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T07:11:35.739413Z",
     "iopub.status.busy": "2025-03-25T07:11:35.739290Z",
     "iopub.status.idle": "2025-03-25T07:11:35.741248Z",
     "shell.execute_reply": "2025-03-25T07:11:35.740957Z"
    }
   },
   "outputs": [],
   "source": [
    "# Examining the gene identifiers from the previous output\n",
    "# The identifiers appear to be simple numeric values (1, 2, 3, etc.)\n",
    "# These are not standard human gene symbols which typically look like:\n",
    "# BRCA1, TP53, APOE, etc.\n",
    "\n",
    "# These numeric identifiers will need to be mapped to standard gene symbols\n",
    "# for meaningful analysis and interpretation\n",
    "\n",
    "requires_gene_mapping = True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "35f15361",
   "metadata": {},
   "source": [
    "### Step 5: Gene Annotation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "ead402c5",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T07:11:35.742906Z",
     "iopub.status.busy": "2025-03-25T07:11:35.742797Z",
     "iopub.status.idle": "2025-03-25T07:11:39.272775Z",
     "shell.execute_reply": "2025-03-25T07:11:39.272383Z"
    }
   },
   "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 3074210 rows\n",
      "\n",
      "Gene annotation preview (first few rows):\n",
      "{'ID': ['1', '2', '3', '4', '5'], 'NAME': ['GE_BrightCorner', 'DarkCorner', 'DarkCorner', 'ASHG19A3A019218', 'ASHG19A3A052390'], 'ORF': [nan, nan, nan, 'DOPEY2', 'SCAMP2'], 'FINAL_SYMBOL': [nan, nan, nan, 'DOPEY2', 'SCAMP2'], 'FINAL_SOURCE': [nan, nan, nan, 'Gencode.V23', 'Gencode.V23'], 'FINAL_TYPE': [nan, nan, nan, 'coding', 'coding'], 'Ensembl.Symbol': [nan, nan, nan, 'DOPEY2', 'SCAMP2'], 'Ensembl.Gene': [nan, nan, nan, 'ENSG00000142197.12', 'ENSG00000140497.16'], 'Ensembl.Type': [nan, nan, nan, 'protein_coding', 'protein_coding'], 'chrom': [nan, nan, nan, 'chr21', 'chr15'], 'txEnd': [nan, nan, nan, 37666571.0, 75165670.0], 'txStart': [nan, nan, nan, 37536838.0, 75137196.0], 'SPOT_ID': ['CONTROL', 'CONTROL', 'CONTROL', 'ASHG19A3A019218', 'ASHG19A3A052390']}\n",
      "\n",
      "Column names in gene annotation data:\n",
      "['ID', 'NAME', 'ORF', 'FINAL_SYMBOL', 'FINAL_SOURCE', 'FINAL_TYPE', 'Ensembl.Symbol', 'Ensembl.Gene', 'Ensembl.Type', 'chrom', 'txEnd', 'txStart', 'SPOT_ID']\n",
      "\n",
      "The dataset contains genomic regions (SPOT_ID) that could be used for location-based gene mapping.\n",
      "Example SPOT_ID format: CONTROL\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": "7fe3e245",
   "metadata": {},
   "source": [
    "### Step 6: Gene Identifier Mapping"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "24174b5d",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T07:11:39.274584Z",
     "iopub.status.busy": "2025-03-25T07:11:39.274433Z",
     "iopub.status.idle": "2025-03-25T07:11:40.330217Z",
     "shell.execute_reply": "2025-03-25T07:11:40.329818Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Creating gene mapping from ID to gene symbols...\n",
      "Created mapping with 61332 entries\n",
      "Sample of mapping data:\n",
      "  ID             Gene\n",
      "3  4           DOPEY2\n",
      "4  5           SCAMP2\n",
      "5  6           uc.387\n",
      "6  7  lincRNA-SPATS2L\n",
      "7  8             VIL1\n",
      "\n",
      "Converting probe measurements to gene expression data...\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Successfully mapped probes to 37220 genes\n",
      "First few genes in the mapped data:\n",
      "Index(['A1BG', 'A1BG-AS1', 'A1CF', 'A2M', 'A2M-AS1', 'A2ML1', 'A3GALT2',\n",
      "       'A4GALT', 'A4GNT', 'AA155639'],\n",
      "      dtype='object', name='Gene')\n",
      "\n",
      "Normalizing gene symbols...\n",
      "After normalization: 24360 genes\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Saved processed gene data to ../../output/preprocess/Intellectual_Disability/gene_data/GSE98697.csv\n"
     ]
    }
   ],
   "source": [
    "# 1. Identify which columns to use for mapping\n",
    "# Based on the annotation preview, we need to map:\n",
    "# - 'ID' column from gene_annotation (numeric identifiers like '1', '2', '3') to the gene expression data index\n",
    "# - 'FINAL_SYMBOL' column contains gene symbols (like 'DOPEY2', 'SCAMP2')\n",
    "\n",
    "print(\"Creating gene mapping from ID to gene symbols...\")\n",
    "\n",
    "# 2. Create gene mapping dataframe\n",
    "mapping_data = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='FINAL_SYMBOL')\n",
    "\n",
    "# Print some information about the mapping\n",
    "print(f\"Created mapping with {len(mapping_data)} entries\")\n",
    "print(\"Sample of mapping data:\")\n",
    "print(mapping_data.head())\n",
    "\n",
    "# 3. Apply gene mapping to convert probe-level measurements to gene expression data\n",
    "print(\"\\nConverting probe measurements to gene expression data...\")\n",
    "try:\n",
    "    gene_data = apply_gene_mapping(gene_data, mapping_data)\n",
    "    print(f\"Successfully mapped probes to {len(gene_data)} genes\")\n",
    "    print(\"First few genes in the mapped data:\")\n",
    "    print(gene_data.index[:10])\n",
    "    \n",
    "    # Normalize gene symbols to ensure consistency\n",
    "    print(\"\\nNormalizing gene symbols...\")\n",
    "    gene_data = normalize_gene_symbols_in_index(gene_data)\n",
    "    print(f\"After normalization: {len(gene_data)} genes\")\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\"Saved processed gene data to {out_gene_data_file}\")\n",
    "    \n",
    "except Exception as e:\n",
    "    print(f\"Error in gene mapping: {e}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "362ea7da",
   "metadata": {},
   "source": [
    "### Step 7: Data Normalization and Linking"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "2f788ec6",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T07:11:40.331996Z",
     "iopub.status.busy": "2025-03-25T07:11:40.331882Z",
     "iopub.status.idle": "2025-03-25T07:11:41.025195Z",
     "shell.execute_reply": "2025-03-25T07:11:41.024844Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Normalizing gene symbols in the expression data...\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Normalized gene data saved to ../../output/preprocess/Intellectual_Disability/gene_data/GSE98697.csv\n",
      "Normalized gene data shape: (24360, 48)\n",
      "Cannot link data: either gene data or clinical data is unavailable.\n",
      "Abnormality detected in the cohort: GSE98697. Preprocessing failed.\n",
      "Dataset usability: False\n"
     ]
    }
   ],
   "source": [
    "# 1. Normalize gene symbols in the gene expression data\n",
    "print(\"Normalizing gene symbols in the expression data...\")\n",
    "try:\n",
    "    # If previous steps have already loaded gene_data\n",
    "    normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n",
    "    \n",
    "    # Create directory if it doesn't exist\n",
    "    os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
    "    \n",
    "    # Save 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",
    "    print(f\"Normalized gene data shape: {normalized_gene_data.shape}\")\n",
    "except Exception as e:\n",
    "    print(f\"Error normalizing gene data: {e}\")\n",
    "    is_gene_available = False\n",
    "\n",
    "# 2. Link clinical and genetic data\n",
    "if is_gene_available and 'clinical_df' in locals():\n",
    "    print(\"\\nLinking clinical and genetic data...\")\n",
    "    try:\n",
    "        # Transpose normalized gene data to match clinical data format\n",
    "        gene_data_t = normalized_gene_data.T\n",
    "        \n",
    "        # Link clinical and genetic data\n",
    "        linked_data = geo_link_clinical_genetic_data(clinical_df, gene_data_t)\n",
    "        print(f\"Linked data shape: {linked_data.shape}\")\n",
    "        \n",
    "        # 3. Handle missing values systematically\n",
    "        print(\"\\nHandling missing values...\")\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 features are biased\n",
    "        print(\"\\nChecking for bias in features...\")\n",
    "        is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n",
    "        \n",
    "        # 5. Final validation and save metadata\n",
    "        print(\"\\nPerforming final validation...\")\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=\"\"\n",
    "        )\n",
    "        \n",
    "        # 6. Save the 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.\")\n",
    "    \n",
    "    except Exception as e:\n",
    "        print(f\"Error in data linking or processing: {e}\")\n",
    "        is_usable = False\n",
    "else:\n",
    "    print(\"Cannot link data: either gene data or clinical data is unavailable.\")\n",
    "    # Create a minimal dataframe for validation purposes\n",
    "    import pandas as pd\n",
    "    linked_data = pd.DataFrame({trait: [None]})\n",
    "    \n",
    "    # Perform final validation with appropriate flags\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=True,  # Not relevant since data isn't usable\n",
    "        df=linked_data,\n",
    "        note=\"Failed to link gene and clinical data.\"\n",
    "    )\n",
    "    print(f\"Dataset usability: {is_usable}\")"
   ]
  }
 ],
 "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
}