File size: 27,127 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
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "a3bc0cc4",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:27:09.683700Z",
     "iopub.status.busy": "2025-03-25T06:27:09.683604Z",
     "iopub.status.idle": "2025-03-25T06:27:09.843821Z",
     "shell.execute_reply": "2025-03-25T06:27:09.843508Z"
    }
   },
   "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 = \"GSE185909\"\n",
    "\n",
    "# Input paths\n",
    "in_trait_dir = \"../../input/GEO/Alzheimers_Disease\"\n",
    "in_cohort_dir = \"../../input/GEO/Alzheimers_Disease/GSE185909\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/Alzheimers_Disease/GSE185909.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/Alzheimers_Disease/gene_data/GSE185909.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/Alzheimers_Disease/clinical_data/GSE185909.csv\"\n",
    "json_path = \"../../output/preprocess/Alzheimers_Disease/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "27a6537a",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "6171e204",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:27:09.845147Z",
     "iopub.status.busy": "2025-03-25T06:27:09.845011Z",
     "iopub.status.idle": "2025-03-25T06:27:09.993432Z",
     "shell.execute_reply": "2025-03-25T06:27:09.993094Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Background Information:\n",
      "!Series_title\t\"Co-expression network analysis of frontal cortex during the progression of Alzheimer’s disease   \"\n",
      "!Series_summary\t\"Using WGCNA and enrichment analyses to identify pathway level differences between individuals with no cognitive impairment, mild cognitive impairment, and Alzheimer’s disease.\"\n",
      "!Series_summary\t\"Frozen frontal cortex (BA10) tissue from NCI, MCI, and mild/moderate AD cases (n = 12/group) representing both genders was acquired postmortem from participants in the Rush Religious Orders Study, a longitudinal clinical pathologic study of aging and AD in elderly Catholic clergy\"\n",
      "!Series_overall_design\t\"Nimblegen expression array human frontal cortex - NCI (No Cognative Impairment) vs. MCI (Mild Cognative Impairment) vs. AD (alzheimers disease);  Labeled cDNA was digested and hybridized to NimbleGen 12 x 135K human arrays for 18 hrs at 42°C and analyzed on a GenePix 4200A scanner (Molecular Devices). Probe intensity levels were quantified with RMA preprocessing (NimbleScan v2.5, Roche)\"\n",
      "Sample Characteristics Dictionary:\n",
      "{0: ['diagnosis: AD', 'diagnosis: MCI', 'diagnosis: NCI'], 1: ['Sex: Male', 'Sex: Female'], 2: ['age_death: 83.8110882957', 'age_death: 80.5338809035', 'age_death: 85.1635865845', 'age_death: 83.3976728268', 'age_death: 76.3093771389', 'age_death: 80.3230663929', 'age_death: 92.1916495551', 'age_death: 85.6399726215', 'age_death: 86.2477754962', 'age_death: 87.3839835729', 'age_death: 82.9349760438', 'age_death: 89.2156057495', 'age_death: 88.0465434634', 'age_death: 90.0314852841', 'age_death: 72.7063655031'], 3: ['post_mortem_interval: 12', 'post_mortem_interval: 4.5833333333', 'post_mortem_interval: 3.25', 'post_mortem_interval: 7.5833333333', 'post_mortem_interval: 2.5', 'post_mortem_interval: 2.6666666667', 'post_mortem_interval: 3.0833333333', 'post_mortem_interval: 3.6666666667', 'post_mortem_interval: 4.5', 'post_mortem_interval: 3.1666666667', 'post_mortem_interval: 13.4166666667', 'post_mortem_interval: 3.9166666667', 'post_mortem_interval: 2.75', 'post_mortem_interval: 7.75'], 4: ['years_education: 18', 'years_education: 21', 'years_education: 16', 'years_education: 15', 'years_education: 25', 'years_education: 8', 'years_education: 20', 'years_education: 22'], 5: ['brain_weight: 1160', 'brain_weight: 1480', 'brain_weight: 1060', 'brain_weight: 1320', 'brain_weight: 1340', 'brain_weight: 1260', 'brain_weight: 1100', 'brain_weight: 1050', 'brain_weight: 1150', 'brain_weight: 1310', 'brain_weight: 1570', 'brain_weight: 1240', 'brain_weight: 1090', 'brain_weight: 1380'], 6: ['cogdx: 4', 'cogdx: 2', 'cogdx: 1', 'cogdx: 3'], 7: ['scmmse30_last_valid: 15', 'scmmse30_last_valid: 27', 'scmmse30_last_valid: 28', 'scmmse30_last_valid: 22', 'scmmse30_last_valid: 20', 'scmmse30_last_valid: 29', 'scmmse30_last_valid: 14', 'scmmse30_last_valid: 18', 'scmmse30_last_valid: 24', 'scmmse30_last_valid: 26', 'scmmse30_last_valid: 30'], 8: ['globcog: -2.1816786639', 'globcog: -0.4065097289', 'globcog: -0.185109059', 'globcog: -1.2008515629', 'globcog: 0.2545211363', 'globcog: -1.1819698561', 'globcog: -0.5206275244', 'globcog: -2.8522349533', 'globcog: -1.4945772374', 'globcog: -1.2390838727', 'globcog: -0.1242229923', 'globcog: -0.263746112', 'globcog: -0.7849454354', 'globcog: -0.8658969549', 'globcog: -0.4237302883'], 9: ['cerad: 2', 'cerad: 4', 'cerad: 1'], 10: ['braak: 2', 'braak: 5', 'braak: 3', 'braak: 4'], 11: ['niareagan: 3', 'niareagan: 2', 'niareagan: 1']}\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": "7804665f",
   "metadata": {},
   "source": [
    "### Step 2: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "24d5d839",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:27:09.995221Z",
     "iopub.status.busy": "2025-03-25T06:27:09.994933Z",
     "iopub.status.idle": "2025-03-25T06:27:10.004473Z",
     "shell.execute_reply": "2025-03-25T06:27:10.004188Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Preview of clinical data:\n",
      "{'GSM5625602': [1.0, 83.8110882957, 1.0], 'GSM5625603': [1.0, 83.8110882957, 1.0], 'GSM5625604': [0.0, 80.5338809035, 1.0], 'GSM5625605': [0.0, 80.5338809035, 1.0], 'GSM5625606': [0.0, 85.1635865845, 0.0], 'GSM5625607': [0.0, 85.1635865845, 0.0], 'GSM5625608': [1.0, 83.3976728268, 1.0], 'GSM5625609': [1.0, 83.3976728268, 1.0], 'GSM5625610': [0.0, 76.3093771389, 1.0], 'GSM5625611': [1.0, 80.3230663929, 1.0], 'GSM5625612': [1.0, 80.3230663929, 1.0], 'GSM5625613': [1.0, 80.3230663929, 1.0], 'GSM5625614': [1.0, 80.3230663929, 1.0], 'GSM5625615': [0.0, 92.1916495551, 0.0], 'GSM5625616': [0.0, 92.1916495551, 0.0], 'GSM5625617': [0.0, 92.1916495551, 0.0], 'GSM5625618': [1.0, 85.6399726215, 0.0], 'GSM5625619': [1.0, 85.6399726215, 0.0], 'GSM5625620': [1.0, 86.2477754962, 1.0], 'GSM5625621': [1.0, 86.2477754962, 1.0], 'GSM5625622': [1.0, 86.2477754962, 1.0], 'GSM5625623': [1.0, 87.3839835729, 1.0], 'GSM5625624': [1.0, 87.3839835729, 1.0], 'GSM5625625': [0.0, 82.9349760438, 0.0], 'GSM5625626': [0.0, 82.9349760438, 0.0], 'GSM5625627': [0.0, 89.2156057495, 1.0], 'GSM5625628': [0.0, 89.2156057495, 1.0], 'GSM5625629': [1.0, 88.0465434634, 1.0], 'GSM5625630': [1.0, 88.0465434634, 1.0], 'GSM5625631': [0.0, 90.0314852841, 0.0], 'GSM5625632': [0.0, 90.0314852841, 0.0], 'GSM5625633': [0.0, 90.0314852841, 0.0], 'GSM5625634': [0.0, 90.0314852841, 0.0], 'GSM5625635': [0.0, 72.7063655031, 1.0], 'GSM5625636': [0.0, 72.7063655031, 1.0]}\n",
      "Clinical data saved to ../../output/preprocess/Alzheimers_Disease/clinical_data/GSE185909.csv\n"
     ]
    }
   ],
   "source": [
    "# 1. Gene Expression Data Availability\n",
    "# From the background information, this dataset contains gene expression data from NimbleGen expression array\n",
    "is_gene_available = True\n",
    "\n",
    "# 2. Variable Availability and Data Type Conversion\n",
    "# 2.1 Data Availability\n",
    "\n",
    "# Trait (Alzheimer's Disease): Row 0 contains diagnosis information\n",
    "trait_row = 0\n",
    "\n",
    "# Age: Row 2 contains age information\n",
    "age_row = 2\n",
    "\n",
    "# Gender: Row 1 contains gender information\n",
    "gender_row = 1\n",
    "\n",
    "# 2.2 Data Type Conversion\n",
    "\n",
    "def convert_trait(value):\n",
    "    \"\"\"Convert diagnosis to binary: 1 for AD, 0 for non-AD (NCI, MCI)\"\"\"\n",
    "    if not value or \":\" not in value:\n",
    "        return None\n",
    "    \n",
    "    diagnosis = value.split(\": \")[1].strip().upper()\n",
    "    \n",
    "    if diagnosis == \"AD\":\n",
    "        return 1\n",
    "    elif diagnosis in [\"NCI\", \"MCI\"]:\n",
    "        return 0\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "def convert_age(value):\n",
    "    \"\"\"Convert age to continuous numeric value\"\"\"\n",
    "    if not value or \":\" not in value:\n",
    "        return None\n",
    "    \n",
    "    try:\n",
    "        age = float(value.split(\": \")[1].strip())\n",
    "        return age\n",
    "    except:\n",
    "        return None\n",
    "\n",
    "def convert_gender(value):\n",
    "    \"\"\"Convert gender to binary: 0 for Female, 1 for Male\"\"\"\n",
    "    if not value or \":\" not in value:\n",
    "        return None\n",
    "    \n",
    "    gender = value.split(\": \")[1].strip().lower()\n",
    "    \n",
    "    if gender == \"female\":\n",
    "        return 0\n",
    "    elif gender == \"male\":\n",
    "        return 1\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "# 3. Save Metadata\n",
    "# Trait data is available if trait_row is not None\n",
    "is_trait_available = trait_row is not None\n",
    "validate_and_save_cohort_info(\n",
    "    is_final=False,\n",
    "    cohort=cohort,\n",
    "    info_path=json_path,\n",
    "    is_gene_available=is_gene_available,\n",
    "    is_trait_available=is_trait_available\n",
    ")\n",
    "\n",
    "# 4. Clinical Feature Extraction (if trait_row is not None)\n",
    "if trait_row is not None:\n",
    "    # clinical_data is assumed to be available from a previous step\n",
    "    clinical_df = geo_select_clinical_features(\n",
    "        clinical_data,  # Assuming this was created in a previous step\n",
    "        trait=trait,\n",
    "        trait_row=trait_row,\n",
    "        convert_trait=convert_trait,\n",
    "        age_row=age_row,\n",
    "        convert_age=convert_age,\n",
    "        gender_row=gender_row,\n",
    "        convert_gender=convert_gender\n",
    "    )\n",
    "    \n",
    "    # Preview the processed data\n",
    "    print(\"Preview of clinical data:\")\n",
    "    print(preview_df(clinical_df))\n",
    "    \n",
    "    # Save the processed data\n",
    "    os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
    "    clinical_df.to_csv(out_clinical_data_file, index=False)\n",
    "    print(f\"Clinical data saved to {out_clinical_data_file}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3cf8bd71",
   "metadata": {},
   "source": [
    "### Step 3: Gene Data Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "e709c499",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:27:10.006057Z",
     "iopub.status.busy": "2025-03-25T06:27:10.005952Z",
     "iopub.status.idle": "2025-03-25T06:27:10.174829Z",
     "shell.execute_reply": "2025-03-25T06:27:10.174493Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "First 20 gene/probe identifiers:\n",
      "Index(['AB000409', 'AB000463', 'AB000781', 'AB001328', 'AB002294', 'AB002308',\n",
      "       'AB002311', 'AB002313', 'AB002360', 'AB002377', 'AB002381', 'AB002382',\n",
      "       'AB002384', 'AB003177', 'AB003333', 'AB006589', 'AB006590', 'AB006621',\n",
      "       'AB006625', 'AB007457'],\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": "285babd9",
   "metadata": {},
   "source": [
    "### Step 4: Gene Identifier Review"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "2b62ce2d",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:27:10.176471Z",
     "iopub.status.busy": "2025-03-25T06:27:10.176364Z",
     "iopub.status.idle": "2025-03-25T06:27:10.178223Z",
     "shell.execute_reply": "2025-03-25T06:27:10.177948Z"
    }
   },
   "outputs": [],
   "source": [
    "# Based on my biomedical knowledge, these identifiers appear to be GenBank accession numbers\n",
    "# (starting with \"AB\" followed by numbers), not standard human gene symbols.\n",
    "# Standard human gene symbols would typically be alphabetical like APOE, BRCA1, etc.\n",
    "# These accession numbers need to be mapped to gene symbols for meaningful analysis.\n",
    "\n",
    "requires_gene_mapping = True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "57682ed9",
   "metadata": {},
   "source": [
    "### Step 5: Gene Annotation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "f5e4a996",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:27:10.179480Z",
     "iopub.status.busy": "2025-03-25T06:27:10.179379Z",
     "iopub.status.idle": "2025-03-25T06:27:11.835768Z",
     "shell.execute_reply": "2025-03-25T06:27:11.835402Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene annotation preview:\n",
      "{'ID': ['AB000409', 'AB000463', 'AB000781', 'AB001328', 'AB002294'], 'GB_ACC': ['AB000409', 'AB000463', 'AB000781', 'AB001328', 'AB002294'], 'DESCRIPTION': ['MAP kinase interacting serine/threonine kinase 1', 'SH3-domain binding protein 2', 'kinase non-catalytic C-lobe domain (KIND) containing 1', 'solute carrier family 15 (oligopeptide transporter), member 1', 'zinc finger protein 646']}\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": "8d8c902c",
   "metadata": {},
   "source": [
    "### Step 6: Gene Identifier Mapping"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "a7a1f1e2",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:27:11.837905Z",
     "iopub.status.busy": "2025-03-25T06:27:11.837790Z",
     "iopub.status.idle": "2025-03-25T06:27:12.080170Z",
     "shell.execute_reply": "2025-03-25T06:27:12.079842Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene annotation columns:\n",
      "['ID', 'GB_ACC', 'DESCRIPTION']\n",
      "\n",
      "More detailed view of gene annotation:\n",
      "         ID    GB_ACC                                                    DESCRIPTION\n",
      "0  AB000409  AB000409               MAP kinase interacting serine/threonine kinase 1\n",
      "1  AB000463  AB000463                                   SH3-domain binding protein 2\n",
      "2  AB000781  AB000781         kinase non-catalytic C-lobe domain (KIND) containing 1\n",
      "3  AB001328  AB001328  solute carrier family 15 (oligopeptide transporter), member 1\n",
      "4  AB002294  AB002294                                        zinc finger protein 646\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "Number of genes after mapping and normalization: 1772\n",
      "First 10 genes:\n",
      "Index(['A4GALT', 'AAA1', 'AADAC', 'AARD', 'ABCC11', 'ABCC9', 'ABCD1', 'ABCE1',\n",
      "       'ABI3', 'ABRAXAS2'],\n",
      "      dtype='object', name='Gene')\n"
     ]
    }
   ],
   "source": [
    "# 1. Re-examine the gene annotation data to understand available fields\n",
    "print(\"Gene annotation columns:\")\n",
    "print(gene_annotation.columns.tolist())\n",
    "\n",
    "# Let's see more rows to better understand the data structure\n",
    "print(\"\\nMore detailed view of gene annotation:\")\n",
    "print(gene_annotation.head().to_string())\n",
    "\n",
    "# Based on the DESCRIPTION field containing full gene names, we need to extract gene symbols \n",
    "# The 'ID' column contains the identifiers that match with gene expression data\n",
    "\n",
    "# 2. Create the mapping dataframe using the appropriate columns\n",
    "id_col = 'ID'\n",
    "gene_col = 'DESCRIPTION'  # We'll keep this but properly extract symbols from it\n",
    "\n",
    "# Create the mapping dataframe\n",
    "mapping_df = get_gene_mapping(gene_annotation, id_col, gene_col)\n",
    "\n",
    "# 3. Apply gene mapping with proper extraction of gene symbols\n",
    "gene_data = apply_gene_mapping(gene_data, mapping_df)\n",
    "\n",
    "# Normalize gene symbols to standard format after mapping\n",
    "gene_data = normalize_gene_symbols_in_index(gene_data)\n",
    "\n",
    "# Print the number of genes and preview first genes\n",
    "print(f\"\\nNumber of genes after mapping and normalization: {len(gene_data)}\")\n",
    "print(\"First 10 genes:\")\n",
    "print(gene_data.index[:10])\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e142d9e4",
   "metadata": {},
   "source": [
    "### Step 7: Data Normalization and Linking"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "926a4043",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:27:12.081796Z",
     "iopub.status.busy": "2025-03-25T06:27:12.081679Z",
     "iopub.status.idle": "2025-03-25T06:27:12.622064Z",
     "shell.execute_reply": "2025-03-25T06:27:12.621665Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Normalizing gene symbols...\n",
      "Gene data shape after normalization: (1772, 35)\n",
      "Normalized gene data saved to ../../output/preprocess/Alzheimers_Disease/gene_data/GSE185909.csv\n",
      "Loading the original clinical data...\n",
      "Extracting clinical features...\n",
      "Clinical data preview:\n",
      "{'GSM5625602': [1.0, 83.8110882957, 1.0], 'GSM5625603': [1.0, 83.8110882957, 1.0], 'GSM5625604': [0.0, 80.5338809035, 1.0], 'GSM5625605': [0.0, 80.5338809035, 1.0], 'GSM5625606': [0.0, 85.1635865845, 0.0], 'GSM5625607': [0.0, 85.1635865845, 0.0], 'GSM5625608': [1.0, 83.3976728268, 1.0], 'GSM5625609': [1.0, 83.3976728268, 1.0], 'GSM5625610': [0.0, 76.3093771389, 1.0], 'GSM5625611': [1.0, 80.3230663929, 1.0], 'GSM5625612': [1.0, 80.3230663929, 1.0], 'GSM5625613': [1.0, 80.3230663929, 1.0], 'GSM5625614': [1.0, 80.3230663929, 1.0], 'GSM5625615': [0.0, 92.1916495551, 0.0], 'GSM5625616': [0.0, 92.1916495551, 0.0], 'GSM5625617': [0.0, 92.1916495551, 0.0], 'GSM5625618': [1.0, 85.6399726215, 0.0], 'GSM5625619': [1.0, 85.6399726215, 0.0], 'GSM5625620': [1.0, 86.2477754962, 1.0], 'GSM5625621': [1.0, 86.2477754962, 1.0], 'GSM5625622': [1.0, 86.2477754962, 1.0], 'GSM5625623': [1.0, 87.3839835729, 1.0], 'GSM5625624': [1.0, 87.3839835729, 1.0], 'GSM5625625': [0.0, 82.9349760438, 0.0], 'GSM5625626': [0.0, 82.9349760438, 0.0], 'GSM5625627': [0.0, 89.2156057495, 1.0], 'GSM5625628': [0.0, 89.2156057495, 1.0], 'GSM5625629': [1.0, 88.0465434634, 1.0], 'GSM5625630': [1.0, 88.0465434634, 1.0], 'GSM5625631': [0.0, 90.0314852841, 0.0], 'GSM5625632': [0.0, 90.0314852841, 0.0], 'GSM5625633': [0.0, 90.0314852841, 0.0], 'GSM5625634': [0.0, 90.0314852841, 0.0], 'GSM5625635': [0.0, 72.7063655031, 1.0], 'GSM5625636': [0.0, 72.7063655031, 1.0]}\n",
      "Clinical data saved to ../../output/preprocess/Alzheimers_Disease/clinical_data/GSE185909.csv\n",
      "Linking clinical and genetic data...\n",
      "Linked data shape: (35, 1775)\n",
      "Handling missing values...\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Linked data shape after handling missing values: (35, 1775)\n",
      "Checking for bias in trait distribution...\n",
      "For the feature 'Alzheimers_Disease', the least common label is '1.0' with 17 occurrences. This represents 48.57% of the dataset.\n",
      "The distribution of the feature 'Alzheimers_Disease' in this dataset is fine.\n",
      "\n",
      "Quartiles for 'Age':\n",
      "  25%: 81.73442847365001\n",
      "  50% (Median): 85.6399726215\n",
      "  75%: 88.63107460645\n",
      "Min: 72.7063655031\n",
      "Max: 92.1916495551\n",
      "The distribution of the feature 'Age' in this dataset is fine.\n",
      "\n",
      "For the feature 'Gender', the least common label is '0.0' with 13 occurrences. This represents 37.14% of the dataset.\n",
      "The distribution of the feature 'Gender' in this dataset is fine.\n",
      "\n",
      "Dataset usability: True\n",
      "Linked data saved to ../../output/preprocess/Alzheimers_Disease/GSE185909.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
}