File size: 25,495 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
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "cd748dc9",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:40:21.313400Z",
     "iopub.status.busy": "2025-03-25T06:40:21.313100Z",
     "iopub.status.idle": "2025-03-25T06:40:21.482177Z",
     "shell.execute_reply": "2025-03-25T06:40:21.481783Z"
    }
   },
   "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 = \"Asthma\"\n",
    "cohort = \"GSE182797\"\n",
    "\n",
    "# Input paths\n",
    "in_trait_dir = \"../../input/GEO/Asthma\"\n",
    "in_cohort_dir = \"../../input/GEO/Asthma/GSE182797\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/Asthma/GSE182797.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/Asthma/gene_data/GSE182797.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/Asthma/clinical_data/GSE182797.csv\"\n",
    "json_path = \"../../output/preprocess/Asthma/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5cc52335",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "f0fbe750",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:40:21.483700Z",
     "iopub.status.busy": "2025-03-25T06:40:21.483552Z",
     "iopub.status.idle": "2025-03-25T06:40:21.631876Z",
     "shell.execute_reply": "2025-03-25T06:40:21.631533Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Background Information:\n",
      "!Series_title\t\"Transcriptomic profiling of adult-onset asthma related to damp and moldy buildings and idiopathic environmental intolerance [nasal biopsy]\"\n",
      "!Series_summary\t\"The objective of the study was to characterize distinct endotypes of asthma related to damp and moldy buildings and to evaluate the potential molecular similarities with idiopathic environmental intolerance (IEI). The nasal biopsy transcriptome of 88 study subjects was profiled using samples obtained at baseline.\"\n",
      "!Series_overall_design\t\"Nasal biopsy samples were collected from female adult-onset asthma patients (n=45), IEI patients (n=14) and healthy subjects (n=21) yielding 80 study subjects. Biopsies were homogenized and total RNA extracted for microarray analyses.\"\n",
      "Sample Characteristics Dictionary:\n",
      "{0: ['diagnosis: healthy', 'diagnosis: adult-onset asthma', 'diagnosis: IEI'], 1: ['gender: Female'], 2: ['age: 38.33', 'age: 38.08', 'age: 48.83', 'age: 33.42', 'age: 46.08', 'age: 45.58', 'age: 28', 'age: 30.83', 'age: 39.25', 'age: 60.17', 'age: 52.75', 'age: 25.75', 'age: 60.67', 'age: 64.67', 'age: 54.83', 'age: 57.67', 'age: 47', 'age: 47.5', 'age: 24.25', 'age: 47.67', 'age: 47.58', 'age: 18.42', 'age: 41.33', 'age: 24.5', 'age: 47.08', 'age: 41.17', 'age: 47.17', 'age: 59.83', 'age: 42.58', 'age: 56.67'], 3: ['tissue: Nasal biopsy'], 4: ['subject: 605', 'subject: 611', 'subject: 621', 'subject: 35', 'subject: 11', 'subject: 1', 'subject: 601', 'subject: 54', 'subject: 68_A', 'subject: 55', 'subject: 44', 'subject: 603_A', 'subject: 63', 'subject: 39', 'subject: 13', 'subject: 3', 'subject: 619', 'subject: 58', 'subject: 79', 'subject: 77', 'subject: 41', 'subject: 624', 'subject: 37_A', 'subject: 61', 'subject: 31', 'subject: 25', 'subject: 617', 'subject: 65', 'subject: 81', 'subject: 82']}\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": "9aee2a39",
   "metadata": {},
   "source": [
    "### Step 2: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "eb57f7f9",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:40:21.633103Z",
     "iopub.status.busy": "2025-03-25T06:40:21.632979Z",
     "iopub.status.idle": "2025-03-25T06:40:21.637920Z",
     "shell.execute_reply": "2025-03-25T06:40:21.637602Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Identified variables and conversion functions for future clinical data processing:\n",
      "trait_row = 0, convert_trait function defined\n",
      "age_row = 2, convert_age function defined\n",
      "gender_row = None, convert_gender function defined\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",
    "# Based on Series_title and Sample Characteristics, this appears to be transcriptomic profiling data\n",
    "# This is likely to contain gene expression data, not just miRNA or methylation\n",
    "is_gene_available = True\n",
    "\n",
    "# 2. Variable Availability and Data Type Conversion\n",
    "# 2.1 Data Availability\n",
    "\n",
    "# For trait (asthma):\n",
    "# Key 0 contains diagnosis information - healthy, adult-onset asthma, or IEI\n",
    "trait_row = 0\n",
    "\n",
    "# For age:\n",
    "# Key 2 contains age information with multiple unique values\n",
    "age_row = 2\n",
    "\n",
    "# For gender:\n",
    "# Key 1 shows only \"gender: Female\" - this is a constant feature with only one value\n",
    "# Since all subjects are female, this is not useful for association analysis\n",
    "gender_row = None  # Only one gender value (all Female)\n",
    "\n",
    "# 2.2 Data Type Conversion Functions\n",
    "\n",
    "def convert_trait(value):\n",
    "    \"\"\"Convert diagnosis value to binary trait (Asthma: 1, Not Asthma: 0)\"\"\"\n",
    "    if value is None:\n",
    "        return None\n",
    "    if ':' in value:\n",
    "        value = value.split(': ')[1].strip().lower()\n",
    "    \n",
    "    if value == 'adult-onset asthma':\n",
    "        return 1  # Has asthma\n",
    "    elif value == 'healthy' or value == 'iei':  # IEI (Idiopathic Environmental Intolerance) is not asthma\n",
    "        return 0  # Does not have asthma\n",
    "    else:\n",
    "        return None  # Unknown\n",
    "\n",
    "def convert_age(value):\n",
    "    \"\"\"Convert age value to continuous numeric value\"\"\"\n",
    "    if value is None:\n",
    "        return None\n",
    "    if ':' in value:\n",
    "        value = value.split(': ')[1].strip()\n",
    "    \n",
    "    try:\n",
    "        return float(value)\n",
    "    except (ValueError, TypeError):\n",
    "        return None\n",
    "\n",
    "def convert_gender(value):\n",
    "    \"\"\"Convert gender value to binary (Female: 0, Male: 1)\"\"\"\n",
    "    if value is None:\n",
    "        return None\n",
    "    if ':' in value:\n",
    "        value = value.split(': ')[1].strip().lower()\n",
    "    \n",
    "    if value == 'female':\n",
    "        return 0\n",
    "    elif value == 'male':\n",
    "        return 1\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "# 3. Save Metadata - Initial filtering\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",
    "# Note: Skipping clinical feature extraction as we don't have the properly structured clinical data yet.\n",
    "# The relevant variables (trait_row, age_row, gender_row) and conversion functions \n",
    "# (convert_trait, convert_age, convert_gender) have been identified for future steps.\n",
    "print(\"Identified variables and conversion functions for future clinical data processing:\")\n",
    "print(f\"trait_row = {trait_row}, convert_trait function defined\")\n",
    "print(f\"age_row = {age_row}, convert_age function defined\")\n",
    "print(f\"gender_row = {gender_row}, convert_gender function defined\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cb950a3d",
   "metadata": {},
   "source": [
    "### Step 3: Gene Data Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "9f4ed3dd",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:40:21.639084Z",
     "iopub.status.busy": "2025-03-25T06:40:21.638967Z",
     "iopub.status.idle": "2025-03-25T06:40:21.880595Z",
     "shell.execute_reply": "2025-03-25T06:40:21.880217Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Matrix file found: ../../input/GEO/Asthma/GSE182797/GSE182797_series_matrix.txt.gz\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene data shape: (37616, 80)\n",
      "First 20 gene/probe identifiers:\n",
      "Index(['A_19_P00315452', 'A_19_P00315492', 'A_19_P00315493', 'A_19_P00315502',\n",
      "       'A_19_P00315506', 'A_19_P00315518', 'A_19_P00315529', 'A_19_P00315551',\n",
      "       'A_19_P00315581', 'A_19_P00315584', 'A_19_P00315593', 'A_19_P00315603',\n",
      "       'A_19_P00315627', 'A_19_P00315631', 'A_19_P00315641', 'A_19_P00315647',\n",
      "       'A_19_P00315649', 'A_19_P00315668', 'A_19_P00315691', 'A_19_P00315705'],\n",
      "      dtype='object', name='ID')\n"
     ]
    }
   ],
   "source": [
    "# 1. Get the SOFT and matrix file paths again \n",
    "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
    "print(f\"Matrix file found: {matrix_file}\")\n",
    "\n",
    "# 2. Use the get_genetic_data function from the library to get the gene_data\n",
    "try:\n",
    "    gene_data = get_genetic_data(matrix_file)\n",
    "    print(f\"Gene data shape: {gene_data.shape}\")\n",
    "    \n",
    "    # 3. Print the first 20 row IDs (gene or probe identifiers)\n",
    "    print(\"First 20 gene/probe identifiers:\")\n",
    "    print(gene_data.index[:20])\n",
    "except Exception as e:\n",
    "    print(f\"Error extracting gene data: {e}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0bb6c895",
   "metadata": {},
   "source": [
    "### Step 4: Gene Identifier Review"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "90fd6c71",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:40:21.881985Z",
     "iopub.status.busy": "2025-03-25T06:40:21.881864Z",
     "iopub.status.idle": "2025-03-25T06:40:21.883830Z",
     "shell.execute_reply": "2025-03-25T06:40:21.883510Z"
    }
   },
   "outputs": [],
   "source": [
    "# Based on the gene identifiers observed in the data, these appear to be Agilent microarray \n",
    "# probe IDs (starting with A_19_P), not standard human gene symbols.\n",
    "# These identifiers will need to be mapped to official gene symbols for meaningful analysis.\n",
    "\n",
    "requires_gene_mapping = True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "69df257a",
   "metadata": {},
   "source": [
    "### Step 5: Gene Annotation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "5e5e0868",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:40:21.885047Z",
     "iopub.status.busy": "2025-03-25T06:40:21.884924Z",
     "iopub.status.idle": "2025-03-25T06:40:26.735384Z",
     "shell.execute_reply": "2025-03-25T06:40:26.734983Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene annotation preview:\n",
      "{'ID': ['GE_BrightCorner', 'DarkCorner', 'A_21_P0014386', 'A_33_P3396872', 'A_33_P3267760'], 'CONTROL_TYPE': ['pos', 'pos', 'FALSE', 'FALSE', 'FALSE'], 'REFSEQ': [nan, nan, nan, 'NM_001105533', nan], 'GB_ACC': [nan, nan, nan, 'NM_001105533', nan], 'LOCUSLINK_ID': [nan, nan, nan, 79974.0, 54880.0], 'GENE_SYMBOL': [nan, nan, nan, 'CPED1', 'BCOR'], 'GENE_NAME': [nan, nan, nan, 'cadherin-like and PC-esterase domain containing 1', 'BCL6 corepressor'], 'UNIGENE_ID': [nan, nan, nan, 'Hs.189652', nan], 'ENSEMBL_ID': [nan, nan, nan, nan, 'ENST00000378463'], 'ACCESSION_STRING': [nan, nan, nan, 'ref|NM_001105533|gb|AK025639|gb|BC030538|tc|THC2601673', 'ens|ENST00000378463'], 'CHROMOSOMAL_LOCATION': [nan, nan, 'unmapped', 'chr7:120901888-120901947', 'chrX:39909128-39909069'], 'CYTOBAND': [nan, nan, nan, 'hs|7q31.31', 'hs|Xp11.4'], 'DESCRIPTION': [nan, nan, nan, 'Homo sapiens cadherin-like and PC-esterase domain containing 1 (CPED1), transcript variant 2, mRNA [NM_001105533]', 'BCL6 corepressor [Source:HGNC Symbol;Acc:HGNC:20893] [ENST00000378463]'], 'GO_ID': [nan, nan, nan, 'GO:0005783(endoplasmic reticulum)', 'GO:0000122(negative regulation of transcription from RNA polymerase II promoter)|GO:0000415(negative regulation of histone H3-K36 methylation)|GO:0003714(transcription corepressor activity)|GO:0004842(ubiquitin-protein ligase activity)|GO:0005515(protein binding)|GO:0005634(nucleus)|GO:0006351(transcription, DNA-dependent)|GO:0007507(heart development)|GO:0008134(transcription factor binding)|GO:0030502(negative regulation of bone mineralization)|GO:0031072(heat shock protein binding)|GO:0031519(PcG protein complex)|GO:0035518(histone H2A monoubiquitination)|GO:0042476(odontogenesis)|GO:0042826(histone deacetylase binding)|GO:0044212(transcription regulatory region DNA binding)|GO:0045892(negative regulation of transcription, DNA-dependent)|GO:0051572(negative regulation of histone H3-K4 methylation)|GO:0060021(palate development)|GO:0065001(specification of axis polarity)|GO:0070171(negative regulation of tooth mineralization)'], 'SEQUENCE': [nan, nan, 'AATACATGTTTTGGTAAACACTCGGTCAGAGCACCCTCTTTCTGTGGAATCAGACTGGCA', 'GCTTATCTCACCTAATACAGGGACTATGCAACCAAGAAACTGGAAATAAAAACAAAGATA', 'CATCAAAGCTACGAGAGATCCTACACACCCAGATTTAAAAAATAATAAAAACTTAAGGGC'], 'SPOT_ID': ['GE_BrightCorner', 'DarkCorner', 'A_21_P0014386', 'A_33_P3396872', 'A_33_P3267760']}\n"
     ]
    }
   ],
   "source": [
    "# 1. 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",
    "# 2. 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": "daced846",
   "metadata": {},
   "source": [
    "### Step 6: Gene Identifier Mapping"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "ca7c8025",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:40:26.736844Z",
     "iopub.status.busy": "2025-03-25T06:40:26.736710Z",
     "iopub.status.idle": "2025-03-25T06:40:27.002577Z",
     "shell.execute_reply": "2025-03-25T06:40:27.002184Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Total probes with gene symbol mappings: 48862\n",
      "First 5 gene mapping records:\n",
      "               ID    Gene\n",
      "3   A_33_P3396872   CPED1\n",
      "4   A_33_P3267760    BCOR\n",
      "5    A_32_P194264   CHAC2\n",
      "6    A_23_P153745   IFI30\n",
      "10  A_21_P0014180  GPR146\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene expression data shape after mapping: (21476, 80)\n",
      "First 10 gene symbols after mapping:\n",
      "Index(['A1BG', 'A1BG-AS1', 'A1CF-3', 'A2M', 'A2M-1', 'A2M-AS1', 'A2ML1',\n",
      "       'A2MP1', 'A4GALT', 'AAAS'],\n",
      "      dtype='object', name='Gene')\n"
     ]
    }
   ],
   "source": [
    "# 1. Identify which columns in the gene annotation data correspond to:\n",
    "# - Probe identifiers (same format as in gene expression data)\n",
    "# - Gene symbols\n",
    "\n",
    "# The gene expression data uses identifiers starting with \"A_19_P\" format\n",
    "# In the gene annotation data, the \"ID\" column holds these probe identifiers \n",
    "# The \"GENE_SYMBOL\" column holds the gene symbols\n",
    "\n",
    "# 2. Create the gene mapping dataframe by extracting these two columns\n",
    "gene_mapping = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='GENE_SYMBOL')\n",
    "\n",
    "# Check how many probe IDs have gene symbol mappings\n",
    "print(f\"Total probes with gene symbol mappings: {len(gene_mapping)}\")\n",
    "print(\"First 5 gene mapping records:\")\n",
    "print(gene_mapping.head())\n",
    "\n",
    "# 3. Convert probe-level measurements to gene-level expression using the mapping\n",
    "# This handles the many-to-many mapping between probes and genes\n",
    "gene_data = apply_gene_mapping(gene_data, gene_mapping)\n",
    "\n",
    "print(f\"Gene expression data shape after mapping: {gene_data.shape}\")\n",
    "print(\"First 10 gene symbols after mapping:\")\n",
    "print(gene_data.index[:10])\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "51914551",
   "metadata": {},
   "source": [
    "### Step 7: Data Normalization and Linking"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "e1153410",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:40:27.004061Z",
     "iopub.status.busy": "2025-03-25T06:40:27.003933Z",
     "iopub.status.idle": "2025-03-25T06:40:37.252236Z",
     "shell.execute_reply": "2025-03-25T06:40:37.251699Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Normalized gene data saved to ../../output/preprocess/Asthma/gene_data/GSE182797.csv\n",
      "Clinical data saved to ../../output/preprocess/Asthma/clinical_data/GSE182797.csv\n",
      "Linked data shape: (80, 17832)\n",
      "Linked data preview (first 5 rows, 5 columns):\n",
      "            Asthma    Age  Gender     A1BG  A1BG-AS1\n",
      "GSM5537157     0.0  38.33     0.0  7.77916   5.86818\n",
      "GSM5537158     0.0  38.08     0.0  7.59209   5.59018\n",
      "GSM5537159     0.0  48.83     0.0  7.45290   5.83891\n",
      "GSM5537160     1.0  33.42     0.0  7.30202   5.70201\n",
      "GSM5537161     1.0  46.08     0.0  7.39065   5.76369\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Data shape after handling missing values: (66, 17832)\n",
      "For the feature 'Asthma', the least common label is '0.0' with 21 occurrences. This represents 31.82% of the dataset.\n",
      "The distribution of the feature 'Asthma' in this dataset is fine.\n",
      "\n",
      "Quartiles for 'Age':\n",
      "  25%: 39.582499999999996\n",
      "  50% (Median): 47.08\n",
      "  75%: 53.3725\n",
      "Min: 18.42\n",
      "Max: 64.67\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 66 occurrences. This represents 100.00% of the dataset.\n",
      "The distribution of the feature 'Gender' in this dataset is severely biased.\n",
      "\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "A new JSON file was created at: ../../output/preprocess/Asthma/cohort_info.json\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Linked data saved to ../../output/preprocess/Asthma/GSE182797.csv\n"
     ]
    }
   ],
   "source": [
    "# 1. Normalize gene symbols in the gene expression data\n",
    "gene_data = normalize_gene_symbols_in_index(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\"Normalized gene data saved to {out_gene_data_file}\")\n",
    "\n",
    "# Define the correct convert_trait function as established in Step 2\n",
    "def convert_trait(value: str) -> Optional[int]:\n",
    "    \"\"\"Convert trait values to binary (0 for control, 1 for Asthma).\"\"\"\n",
    "    if pd.isna(value):\n",
    "        return None\n",
    "    \n",
    "    # Extract value after colon\n",
    "    if \":\" in value:\n",
    "        value = value.split(\":\", 1)[1].strip()\n",
    "    \n",
    "    # Convert to binary\n",
    "    if \"adult-onset asthma\" in value.lower():\n",
    "        return 1  # Asthma\n",
    "    elif \"healthy\" in value.lower():\n",
    "        return 0  # Control\n",
    "    else:\n",
    "        return None  # IEI or other conditions\n",
    "\n",
    "def convert_age(value: str) -> Optional[float]:\n",
    "    \"\"\"Convert age values to float.\"\"\"\n",
    "    if pd.isna(value):\n",
    "        return None\n",
    "    \n",
    "    # Extract value after colon\n",
    "    if \":\" in value:\n",
    "        value = value.split(\":\", 1)[1].strip()\n",
    "    \n",
    "    try:\n",
    "        return float(value)\n",
    "    except ValueError:\n",
    "        return None\n",
    "\n",
    "def convert_gender(value: str) -> Optional[int]:\n",
    "    \"\"\"Convert gender values to binary (0 for female, 1 for male).\"\"\"\n",
    "    if pd.isna(value):\n",
    "        return None\n",
    "    \n",
    "    # Extract value after colon\n",
    "    if \":\" in value:\n",
    "        value = value.split(\":\", 1)[1].strip().lower()\n",
    "    \n",
    "    if \"female\" in value:\n",
    "        return 0\n",
    "    elif \"male\" in value:\n",
    "        return 1\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "# Re-extract clinical features using the appropriate conversion functions\n",
    "selected_clinical_df = geo_select_clinical_features(\n",
    "    clinical_df=clinical_data,\n",
    "    trait=trait,\n",
    "    trait_row=0,  # Correct trait row from Step 2\n",
    "    convert_trait=convert_trait,\n",
    "    age_row=2,     # Age row from Step 2\n",
    "    convert_age=convert_age,\n",
    "    gender_row=1,  # Gender row from Step 2\n",
    "    convert_gender=convert_gender\n",
    ")\n",
    "\n",
    "# Save the processed clinical data\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",
    "# 2. Link clinical and genetic data\n",
    "linked_data = geo_link_clinical_genetic_data(selected_clinical_df, gene_data)\n",
    "print(f\"Linked data shape: {linked_data.shape}\")\n",
    "print(\"Linked data preview (first 5 rows, 5 columns):\")\n",
    "print(linked_data.iloc[:5, :5] if not linked_data.empty else \"Linked data is empty\")\n",
    "\n",
    "# 3. Handle missing values\n",
    "linked_data = handle_missing_values(linked_data, trait)\n",
    "print(f\"Data shape after handling missing values: {linked_data.shape}\")\n",
    "\n",
    "# 4. Check for bias in features\n",
    "is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n",
    "\n",
    "# 5. Validate and save cohort information\n",
    "is_usable = validate_and_save_cohort_info(\n",
    "    is_final=True,\n",
    "    cohort=cohort,\n",
    "    info_path=json_path,\n",
    "    is_gene_available=True,\n",
    "    is_trait_available=True,\n",
    "    is_biased=is_biased,\n",
    "    df=linked_data,\n",
    "    note=\"Dataset contains gene expression data from adult patients with asthma related to damp/moldy buildings and controls.\"\n",
    ")\n",
    "\n",
    "# 6. Save the 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 analysis. No linked data file 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
}