File size: 26,702 Bytes
92d2f89
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "28b6d53b",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:27:13.344866Z",
     "iopub.status.busy": "2025-03-25T06:27:13.344761Z",
     "iopub.status.idle": "2025-03-25T06:27:13.501981Z",
     "shell.execute_reply": "2025-03-25T06:27:13.501543Z"
    }
   },
   "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 = \"Alzheimers_Disease\"\n",
    "cohort = \"GSE214417\"\n",
    "\n",
    "# Input paths\n",
    "in_trait_dir = \"../../input/GEO/Alzheimers_Disease\"\n",
    "in_cohort_dir = \"../../input/GEO/Alzheimers_Disease/GSE214417\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/Alzheimers_Disease/GSE214417.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/Alzheimers_Disease/gene_data/GSE214417.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/Alzheimers_Disease/clinical_data/GSE214417.csv\"\n",
    "json_path = \"../../output/preprocess/Alzheimers_Disease/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f46457a6",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "d4e4aa21",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:27:13.503463Z",
     "iopub.status.busy": "2025-03-25T06:27:13.503326Z",
     "iopub.status.idle": "2025-03-25T06:27:13.594963Z",
     "shell.execute_reply": "2025-03-25T06:27:13.594401Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Background Information:\n",
      "!Series_title\t\"Long-term Urolithin A treatment ameliorates disease pathology in Alzheimer's Disease mouse models\"\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: hippocampus'], 1: ['treatment: water', 'treatment: Urolithin A_5m', 'treatment: water+washout', 'treatment: Urolithin A_5m+washout_1m'], 2: ['Sex: Male'], 3: ['age: 8 months', 'age: 9 months'], 4: ['strain: B6.Cg-Tg(APPswe,PSEN1dE9)85Dbo/J'], 5: ['genotype: - APP - PSEN', 'genotype: + APP + PSEN']}\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": "6da67395",
   "metadata": {},
   "source": [
    "### Step 2: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "73c7f4f8",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:27:13.596645Z",
     "iopub.status.busy": "2025-03-25T06:27:13.596536Z",
     "iopub.status.idle": "2025-03-25T06:27:13.606750Z",
     "shell.execute_reply": "2025-03-25T06:27:13.606194Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Clinical Features Preview:\n",
      "{'GSM6567822': [0.0, 8.0], 'GSM6567823': [0.0, 8.0], 'GSM6567824': [0.0, 8.0], 'GSM6567825': [0.0, 8.0], 'GSM6567826': [1.0, 8.0], 'GSM6567827': [1.0, 8.0], 'GSM6567828': [1.0, 8.0], 'GSM6567829': [1.0, 8.0], 'GSM6567830': [1.0, 8.0], 'GSM6567831': [1.0, 8.0], 'GSM6567832': [1.0, 8.0], 'GSM6567833': [0.0, 9.0], 'GSM6567834': [0.0, 9.0], 'GSM6567835': [0.0, 9.0], 'GSM6567836': [0.0, 9.0], 'GSM6567837': [0.0, 9.0], 'GSM6567838': [1.0, 9.0], 'GSM6567839': [1.0, 9.0], 'GSM6567840': [1.0, 9.0], 'GSM6567841': [1.0, 9.0], 'GSM6567842': [1.0, 9.0], 'GSM6567843': [1.0, 9.0], 'GSM6567844': [1.0, 9.0], 'GSM6567845': [1.0, 9.0]}\n",
      "Clinical features saved to ../../output/preprocess/Alzheimers_Disease/clinical_data/GSE214417.csv\n"
     ]
    }
   ],
   "source": [
    "import pandas as pd\n",
    "import os\n",
    "import json\n",
    "from typing import Optional, Callable, Dict, Any\n",
    "\n",
    "# 1. Gene Expression Data Availability\n",
    "# Looking at the background information, this appears to be gene expression data from mouse models of Alzheimer's disease\n",
    "is_gene_available = True\n",
    "\n",
    "# 2. Variable Availability and Data Type Conversion\n",
    "# 2.1 Data Availability\n",
    "# For trait, we can use the genotype information (key 5) which distinguishes AD vs control mice\n",
    "trait_row = 5  # 'genotype: - APP - PSEN' vs 'genotype: + APP + PSEN'\n",
    "\n",
    "# Age information is available at key 3\n",
    "age_row = 3  # 'age: 8 months', 'age: 9 months'\n",
    "\n",
    "# Gender information is available at key 2, but it's a constant (all Male)\n",
    "gender_row = None  # Only one value 'Sex: Male', so it's not useful for association studies\n",
    "\n",
    "# 2.2 Data Type Conversion Functions\n",
    "def convert_trait(value):\n",
    "    if value is None:\n",
    "        return None\n",
    "    # Extract the part after the colon\n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip()\n",
    "    \n",
    "    # The genotype with \"+\" indicates Alzheimer's disease model, \"-\" indicates control\n",
    "    if '+ APP + PSEN' in value:\n",
    "        return 1  # AD model\n",
    "    elif '- APP - PSEN' in value:\n",
    "        return 0  # Control\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "def convert_age(value):\n",
    "    if value is None:\n",
    "        return None\n",
    "    # Extract the part after the colon\n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip()\n",
    "    \n",
    "    # Extract the numeric age in months\n",
    "    if 'months' in value or 'month' in value:\n",
    "        try:\n",
    "            # Extract just the number\n",
    "            age_value = value.split()[0]\n",
    "            return float(age_value)\n",
    "        except (ValueError, IndexError):\n",
    "            return None\n",
    "    return None\n",
    "\n",
    "# Not used but defined for completeness\n",
    "def convert_gender(value):\n",
    "    if value is None:\n",
    "        return None\n",
    "    # Extract the part after the colon\n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip()\n",
    "    \n",
    "    value = value.lower()\n",
    "    if 'female' in value:\n",
    "        return 0\n",
    "    elif 'male' in value:\n",
    "        return 1\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "# 3. Save Metadata\n",
    "is_trait_available = trait_row is not None\n",
    "validate_and_save_cohort_info(\n",
    "    is_final=False,\n",
    "    cohort=cohort,\n",
    "    info_path=json_path,\n",
    "    is_gene_available=is_gene_available,\n",
    "    is_trait_available=is_trait_available\n",
    ")\n",
    "\n",
    "# 4. Clinical Feature Extraction\n",
    "# Since trait_row is not None, we need to extract clinical features\n",
    "if trait_row is not None:\n",
    "    # Assume clinical_data is already defined from a previous step\n",
    "    # If not, we would need to load it\n",
    "    try:\n",
    "        # Load clinical data if it's not already available\n",
    "        clinical_data_file = os.path.join(in_cohort_dir, \"clinical_data.csv\")\n",
    "        if 'clinical_data' not in locals():\n",
    "            clinical_data = pd.read_csv(clinical_data_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",
    "            age_row=age_row,\n",
    "            convert_age=convert_age\n",
    "            # gender_row and convert_gender are None since gender is constant\n",
    "        )\n",
    "        \n",
    "        # Preview the extracted clinical features\n",
    "        preview = preview_df(clinical_features)\n",
    "        print(\"Clinical Features Preview:\")\n",
    "        print(preview)\n",
    "        \n",
    "        # Create the directory if it doesn't exist\n",
    "        os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
    "        \n",
    "        # Save the clinical features to a CSV file\n",
    "        clinical_features.to_csv(out_clinical_data_file, index=False)\n",
    "        print(f\"Clinical features saved to {out_clinical_data_file}\")\n",
    "    except Exception as e:\n",
    "        print(f\"Error in clinical feature extraction: {str(e)}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5b5dbbe8",
   "metadata": {},
   "source": [
    "### Step 3: Gene Data Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "7b8cc1fc",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:27:13.608438Z",
     "iopub.status.busy": "2025-03-25T06:27:13.608298Z",
     "iopub.status.idle": "2025-03-25T06:27:13.706600Z",
     "shell.execute_reply": "2025-03-25T06:27:13.705958Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "First 20 gene/probe identifiers:\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"
     ]
    }
   ],
   "source": [
    "# 1. First get the file paths again to access the matrix file\n",
    "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
    "\n",
    "# 2. Use the get_genetic_data function from the library to get the gene_data from the matrix_file\n",
    "gene_data = get_genetic_data(matrix_file)\n",
    "\n",
    "# 3. Print the first 20 row IDs (gene or probe identifiers) for future observation\n",
    "print(\"First 20 gene/probe identifiers:\")\n",
    "print(gene_data.index[:20])\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a2107889",
   "metadata": {},
   "source": [
    "### Step 4: Gene Identifier Review"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "276a1ca7",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:27:13.708387Z",
     "iopub.status.busy": "2025-03-25T06:27:13.708276Z",
     "iopub.status.idle": "2025-03-25T06:27:13.710989Z",
     "shell.execute_reply": "2025-03-25T06:27:13.710461Z"
    }
   },
   "outputs": [],
   "source": [
    "# The identifiers are numeric values (1, 2, 3, etc.) and not human gene symbols\n",
    "# These appear to be row numbers or possibly probe IDs that need to be mapped to actual gene symbols\n",
    "\n",
    "requires_gene_mapping = True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c261031d",
   "metadata": {},
   "source": [
    "### Step 5: Gene Annotation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "4af777e6",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:27:13.712646Z",
     "iopub.status.busy": "2025-03-25T06:27:13.712543Z",
     "iopub.status.idle": "2025-03-25T06:27:16.388211Z",
     "shell.execute_reply": "2025-03-25T06:27:16.387518Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene annotation preview:\n",
      "{'ID': ['1', '2', '3', '4', '5'], 'COL': ['192', '192', '192', '192', '192'], 'ROW': ['328', '326', '324', '322', '320'], 'NAME': ['GE_BrightCorner', 'DarkCorner', 'DarkCorner', 'A_51_P399985', 'A_55_P2508138'], 'SPOT_ID': ['CONTROL', 'CONTROL', 'CONTROL', nan, nan], 'CONTROL_TYPE': ['pos', 'pos', 'pos', 'FALSE', 'FALSE'], 'REFSEQ': [nan, nan, nan, 'NM_015742', 'NR_028378'], 'GB_ACC': [nan, nan, nan, 'NM_015742', 'NR_028378'], 'LOCUSLINK_ID': [nan, nan, nan, 17925.0, 100034739.0], 'GENE_SYMBOL': [nan, nan, nan, 'Myo9b', 'Gm17762'], 'GENE_NAME': [nan, nan, nan, 'myosin IXb', 'predicted gene, 17762'], 'UNIGENE_ID': [nan, nan, nan, 'Mm.33779', 'Mm.401643'], 'ENSEMBL_ID': [nan, nan, nan, 'ENSMUST00000170242', nan], 'ACCESSION_STRING': [nan, nan, nan, 'ref|NM_015742|ref|NM_001142322|ref|NM_001142323|ens|ENSMUST00000170242', 'ref|NR_028378|gb|AK171729|gb|AK045818|gb|AK033161'], 'CHROMOSOMAL_LOCATION': [nan, nan, nan, 'chr8:73884459-73884518', 'chr2:17952143-17952202'], 'CYTOBAND': [nan, nan, nan, 'mm|8qB3.3', 'mm|2qA3'], 'DESCRIPTION': [nan, nan, nan, 'Mus musculus myosin IXb (Myo9b), transcript variant 3, mRNA [NM_015742]', 'Mus musculus predicted gene, 17762 (Gm17762), long non-coding RNA [NR_028378]'], 'GO_ID': [nan, nan, nan, 'GO:0000146(microfilament motor activity)|GO:0000166(nucleotide binding)|GO:0001726(ruffle)|GO:0002548(monocyte chemotaxis)|GO:0003774(motor activity)|GO:0003779(actin binding)|GO:0005096(GTPase activator activity)|GO:0005516(calmodulin binding)|GO:0005524(ATP binding)|GO:0005622(intracellular)|GO:0005737(cytoplasm)|GO:0005856(cytoskeleton)|GO:0005884(actin filament)|GO:0005938(cell cortex)|GO:0007165(signal transduction)|GO:0007266(Rho protein signal transduction)|GO:0008152(metabolic process)|GO:0008270(zinc ion binding)|GO:0016020(membrane)|GO:0016459(myosin complex)|GO:0016887(ATPase activity)|GO:0030010(establishment of cell polarity)|GO:0030027(lamellipodium)|GO:0030898(actin-dependent ATPase activity)|GO:0031941(filamentous actin)|GO:0032433(filopodium tip)|GO:0033275(actin-myosin filament sliding)|GO:0035556(intracellular signal transduction)|GO:0043008(ATP-dependent protein binding)|GO:0043531(ADP binding)|GO:0043547(positive regulation of GTPase activity)|GO:0046872(metal ion binding)|GO:0048246(macrophage chemotaxis)|GO:0048471(perinuclear region of cytoplasm)|GO:0051015(actin filament binding)|GO:0072673(lamellipodium morphogenesis)', nan], 'SEQUENCE': [nan, nan, nan, 'ACGGAGCCAGGGACTTGGAACCTTTAGGAACAATCAGTGCATCCGGTGACAGCCTGGGTT', 'GGAAAGTACTTCAGCTTCACTCTTTAATTCTCCTTTACTACAATTAAAACTTTCGGTCAG'], 'SPOT_ID.1': [nan, nan, nan, nan, nan]}\n"
     ]
    }
   ],
   "source": [
    "# 1. First get the file paths using geo_get_relevant_filepaths function\n",
    "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
    "\n",
    "# 2. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.\n",
    "gene_annotation = get_gene_annotation(soft_file)\n",
    "\n",
    "# 3. Use the 'preview_df' function from the library to preview the data and print out the results.\n",
    "print(\"Gene annotation preview:\")\n",
    "print(preview_df(gene_annotation))\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cb8600fe",
   "metadata": {},
   "source": [
    "### Step 6: Gene Identifier Mapping"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "18b90c7d",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:27:16.390454Z",
     "iopub.status.busy": "2025-03-25T06:27:16.390317Z",
     "iopub.status.idle": "2025-03-25T06:27:16.541429Z",
     "shell.execute_reply": "2025-03-25T06:27:16.540769Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Mapped gene expression data (first 5 genes):\n",
      "            GSM6567822  GSM6567823  GSM6567824  GSM6567825  GSM6567826  \\\n",
      "Gene                                                                     \n",
      "A130033P14       -0.24       -0.18       -0.21       -0.30       -0.23   \n",
      "A230055C15        0.25        0.45        0.41        0.32        0.39   \n",
      "A330044H09        0.85        0.91        0.90        0.78        0.90   \n",
      "A430057O09       -1.21       -1.04       -1.26       -1.15       -1.19   \n",
      "A430085C19       -0.68       -0.95       -0.83       -0.89       -0.92   \n",
      "\n",
      "            GSM6567827  GSM6567828  GSM6567829  GSM6567830  GSM6567831  ...  \\\n",
      "Gene                                                                    ...   \n",
      "A130033P14       -0.18       -0.20       -0.19       -0.16       -0.18  ...   \n",
      "A230055C15        0.33        0.37        0.39        0.41        0.41  ...   \n",
      "A330044H09        0.91        0.87        0.90        0.82        0.91  ...   \n",
      "A430057O09       -1.22       -1.09       -1.21       -1.23       -1.19  ...   \n",
      "A430085C19       -0.62       -0.88       -0.90       -0.95       -1.12  ...   \n",
      "\n",
      "            GSM6567836  GSM6567837  GSM6567838  GSM6567839  GSM6567840  \\\n",
      "Gene                                                                     \n",
      "A130033P14       -0.40       -0.23       -0.31       -0.24       -0.34   \n",
      "A230055C15        0.38        0.44        0.24        0.19        0.29   \n",
      "A330044H09        0.87        0.94        0.85        0.86        1.01   \n",
      "A430057O09       -1.21       -1.21       -0.97       -1.32       -1.27   \n",
      "A430085C19       -1.19       -0.88       -0.95       -1.10        0.00   \n",
      "\n",
      "            GSM6567841  GSM6567842  GSM6567843  GSM6567844  GSM6567845  \n",
      "Gene                                                                    \n",
      "A130033P14       -0.35       -0.34        0.38       -0.18       -0.25  \n",
      "A230055C15        0.20        0.22        0.13        0.12        0.19  \n",
      "A330044H09        0.78        0.81        0.80        0.84        0.82  \n",
      "A430057O09       -1.30       -1.17       -1.11       -1.17       -1.21  \n",
      "A430085C19       -1.33       -1.19       -1.11       -1.20       -1.23  \n",
      "\n",
      "[5 rows x 24 columns]\n",
      "Shape of mapped gene expression data: (511, 24)\n"
     ]
    }
   ],
   "source": [
    "# 1. Identify the appropriate columns in gene_annotation for mapping\n",
    "# The gene expression data uses numeric identifiers that correspond to the 'ID' column\n",
    "# The gene symbols are stored in the 'GENE_SYMBOL' column\n",
    "\n",
    "# 2. Create gene mapping dataframe using the get_gene_mapping function\n",
    "gene_mapping = get_gene_mapping(gene_annotation, 'ID', 'GENE_SYMBOL')\n",
    "\n",
    "# 3. Apply the gene mapping to convert probe-level measurements to gene expression data\n",
    "# The apply_gene_mapping function handles the many-to-many relationship as described\n",
    "gene_data = apply_gene_mapping(gene_data, gene_mapping)\n",
    "\n",
    "# Preview the mapped gene expression data\n",
    "print(\"Mapped gene expression data (first 5 genes):\")\n",
    "print(gene_data.head(5))\n",
    "print(f\"Shape of mapped gene expression data: {gene_data.shape}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e5d249dc",
   "metadata": {},
   "source": [
    "### Step 7: Data Normalization and Linking"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "9a917ea7",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:27:16.543357Z",
     "iopub.status.busy": "2025-03-25T06:27:16.543242Z",
     "iopub.status.idle": "2025-03-25T06:27:16.697731Z",
     "shell.execute_reply": "2025-03-25T06:27:16.697215Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Normalizing gene symbols...\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene data shape after normalization: (30, 24)\n",
      "Normalized gene data saved to ../../output/preprocess/Alzheimers_Disease/gene_data/GSE214417.csv\n",
      "Loading the original clinical data...\n",
      "Extracting clinical features...\n",
      "Clinical data preview:\n",
      "{'GSM6567822': [0.0, 8.0], 'GSM6567823': [0.0, 8.0], 'GSM6567824': [0.0, 8.0], 'GSM6567825': [0.0, 8.0], 'GSM6567826': [1.0, 8.0], 'GSM6567827': [1.0, 8.0], 'GSM6567828': [1.0, 8.0], 'GSM6567829': [1.0, 8.0], 'GSM6567830': [1.0, 8.0], 'GSM6567831': [1.0, 8.0], 'GSM6567832': [1.0, 8.0], 'GSM6567833': [0.0, 9.0], 'GSM6567834': [0.0, 9.0], 'GSM6567835': [0.0, 9.0], 'GSM6567836': [0.0, 9.0], 'GSM6567837': [0.0, 9.0], 'GSM6567838': [1.0, 9.0], 'GSM6567839': [1.0, 9.0], 'GSM6567840': [1.0, 9.0], 'GSM6567841': [1.0, 9.0], 'GSM6567842': [1.0, 9.0], 'GSM6567843': [1.0, 9.0], 'GSM6567844': [1.0, 9.0], 'GSM6567845': [1.0, 9.0]}\n",
      "Clinical data saved to ../../output/preprocess/Alzheimers_Disease/clinical_data/GSE214417.csv\n",
      "Linking clinical and genetic data...\n",
      "Linked data shape: (24, 32)\n",
      "Handling missing values...\n",
      "Linked data shape after handling missing values: (24, 32)\n",
      "Checking for bias in trait distribution...\n",
      "For the feature 'Alzheimers_Disease', the least common label is '0.0' with 9 occurrences. This represents 37.50% of the dataset.\n",
      "The distribution of the feature 'Alzheimers_Disease' in this dataset is fine.\n",
      "\n",
      "Quartiles for 'Age':\n",
      "  25%: 8.0\n",
      "  50% (Median): 9.0\n",
      "  75%: 9.0\n",
      "Min: 8.0\n",
      "Max: 9.0\n",
      "The distribution of the feature 'Age' in this dataset is fine.\n",
      "\n",
      "Dataset usability: True\n",
      "Linked data saved to ../../output/preprocess/Alzheimers_Disease/GSE214417.csv\n"
     ]
    }
   ],
   "source": [
    "# 1. Normalize gene symbols in the gene expression data\n",
    "print(\"Normalizing 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 to a CSV file\n",
    "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
    "normalized_gene_data.to_csv(out_gene_data_file)\n",
    "print(f\"Normalized gene data saved to {out_gene_data_file}\")\n",
    "\n",
    "# 2. Link the clinical and genetic data\n",
    "print(\"Loading the original clinical data...\")\n",
    "# Get the matrix file again to ensure we have the proper data\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",
    "print(\"Extracting clinical features...\")\n",
    "# Use the clinical_data obtained directly from the matrix file\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",
    "print(\"Clinical data preview:\")\n",
    "print(preview_df(selected_clinical_df))\n",
    "\n",
    "# Save the clinical data to a CSV file\n",
    "os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
    "selected_clinical_df.to_csv(out_clinical_data_file)\n",
    "print(f\"Clinical data saved to {out_clinical_data_file}\")\n",
    "\n",
    "# Link clinical and genetic data using the normalized gene data\n",
    "print(\"Linking clinical and genetic data...\")\n",
    "linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)\n",
    "print(f\"Linked data shape: {linked_data.shape}\")\n",
    "\n",
    "# 3. Handle missing values in the linked data\n",
    "print(\"Handling 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",
    "# 4. Check if trait is biased\n",
    "print(\"Checking for bias in trait distribution...\")\n",
    "is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n",
    "\n",
    "# 5. Final validation\n",
    "note = \"Dataset contains gene expression data from bronchial brushings from control individuals and patients with asthma after rhinovirus infection in vivo, as described in the study 'Rhinovirus-induced epithelial RIG-I inflammasome suppresses antiviral immunity and promotes inflammation in asthma and COVID-19'.\"\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",
    "print(f\"Dataset usability: {is_usable}\")\n",
    "\n",
    "# 6. Save linked data if 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(\"Dataset is not usable for trait-gene association studies due to bias or other issues.\")"
   ]
  }
 ],
 "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
}