File size: 32,852 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": "938f849f",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:44:58.587410Z",
     "iopub.status.busy": "2025-03-25T06:44:58.587310Z",
     "iopub.status.idle": "2025-03-25T06:44:58.750970Z",
     "shell.execute_reply": "2025-03-25T06:44:58.750626Z"
    }
   },
   "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 = \"Atherosclerosis\"\n",
    "cohort = \"GSE133601\"\n",
    "\n",
    "# Input paths\n",
    "in_trait_dir = \"../../input/GEO/Atherosclerosis\"\n",
    "in_cohort_dir = \"../../input/GEO/Atherosclerosis/GSE133601\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/Atherosclerosis/GSE133601.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/Atherosclerosis/gene_data/GSE133601.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/Atherosclerosis/clinical_data/GSE133601.csv\"\n",
    "json_path = \"../../output/preprocess/Atherosclerosis/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f4001986",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "ed6ab10b",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:44:58.752384Z",
     "iopub.status.busy": "2025-03-25T06:44:58.752249Z",
     "iopub.status.idle": "2025-03-25T06:44:58.820257Z",
     "shell.execute_reply": "2025-03-25T06:44:58.819952Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Background Information:\n",
      "!Series_title\t\"Transcriptional survey of peripheral blood links lower oxygen saturation during sleep with reduced expressions of CD1D and RAB20 that is reversed by CPAP therapy\"\n",
      "!Series_summary\t\"Sleep Disordered Breathing (SDB) is associated with a wide range of physiological changes, likely due in part to the influence of hypoxemia during sleep on gene expression. We studied gene expression in peripheral blood mononuclear cells in association with three measures of SDB: the Apnea Hypopnea Index (AHI); average oxyhemoglobin saturation (avgO2) during sleep; and minimum oxyhemoglobin saturation (minO2) during sleep. We performed discovery analysis in two community-based studies: the Multi-Ethnic Study of Atherosclerosis (MESA; N = 580) and the Framingham Offspring Study (FOS; N=571). Associations with false discovery rate (FDR) q-value<0.05 in one study were considered to have replicated if a p-value<0.05 was observed in the other study. Associations that replicated between cohorts, or with FDR q-value<0.05 in meta-analysis of the two studies, were carried forward for gene expression analysis in the blood of 15 participants from the Heart Biomarkers In Apnea Treatment (HeartBEAT) trial who had moderate or severe obstructive sleep apnea (OSA) and were studied before and after three months of treatment with continuous positive airway pressure (CPAP). We also performed Gene Set Enrichment Analysis based on all trait and cohort analyses. We identified 22 genes associated with SDB traits in both MESA and FHS. Of these, lower CD1D and RAB20 expressions were associated with lower avgO2 in MESA and FHS, and CPAP treatment increased their expression in HeartBEAT. Immunity and inflammation pathways were up-regulated in subjects with lower avgO2, i.e. in those with a more severe SDB phenotype (MESA),  whereas immuno-inflammatory processes were down-regulated in response to CPAP treatment (HeartBEAT).\"\n",
      "!Series_overall_design\t\"The Heart Biomarker Evaluation in Apnea Treatment (HeartBEAT) study is a randomized, 4-site single-blind clinical trial that investigated the efficacy of OSA therapy in reducing cardiovascular disease risk for patients with moderate-severe OSA (ClinicalTrials.gov NCT01086800). Of HeartBEAT participants randomized to the CPAP treatment group, a subsample of 15 individuals who also adhered to CPAP therapy (defined by at least 4 hours of CPAP use over the 3-month intervention period) participated in a gene expression study.  Venous blood was collected following an overnight fast in 8 mL heparinized Cell Prep Tubes containing Ficoll Hypaque (Becton Dickinson #362753) in order to separate peripheral blood mononuclear cells.  The tubes were centrifuged fresh at room temperature for 15 minutes at 2000 G to isolate the buffy coat, which was pelleted, resuspended in Millipore S-002-10F freezing medium, and cryopreserved at -80C.\"\n",
      "Sample Characteristics Dictionary:\n",
      "{0: ['tissue: peripheral blood mononuclear cells'], 1: ['subject: 10031', 'subject: 11874', 'subject: 11992', 'subject: 30234', 'subject: 30665', 'subject: 30838', 'subject: 40044', 'subject: 40266', 'subject: 40657', 'subject: 11928', 'subject: 30031', 'subject: 40269', 'subject: 30624', 'subject: 40971', 'subject: 40197'], 2: ['timepoint: pre-CPAP', 'timepoint: post-CPAP']}\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": "f5f670bd",
   "metadata": {},
   "source": [
    "### Step 2: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "35fea1be",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:44:58.821307Z",
     "iopub.status.busy": "2025-03-25T06:44:58.821204Z",
     "iopub.status.idle": "2025-03-25T06:44:58.841678Z",
     "shell.execute_reply": "2025-03-25T06:44:58.841419Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "False"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 1. Gene Expression Data Availability\n",
    "# Based on the background information, this dataset is about gene expression in peripheral blood\n",
    "# associated with SDB (Sleep Disordered Breathing). The study explicitly mentions transcriptional survey\n",
    "# and gene expression analysis.\n",
    "is_gene_available = True\n",
    "\n",
    "# 2. Variable Availability and Data Type Conversion\n",
    "# Looking at the sample characteristics dictionary:\n",
    "# - No explicit atherosclerosis trait information is directly visible\n",
    "# - No age information is visible\n",
    "# - No gender information is visible\n",
    "\n",
    "# From background information, this study is about Sleep Disordered Breathing (SDB) rather than Atherosclerosis\n",
    "# However, it mentions \"Multi-Ethnic Study of Atherosclerosis (MESA)\" as one of the source studies\n",
    "# This is not a direct measurement of atherosclerosis in the current dataset\n",
    "\n",
    "# There doesn't appear to be trait information directly related to atherosclerosis in this dataset\n",
    "trait_row = None\n",
    "\n",
    "# No age information\n",
    "age_row = None\n",
    "\n",
    "# No gender information\n",
    "gender_row = None\n",
    "\n",
    "# Define conversion functions even though they won't be used in this case\n",
    "def convert_trait(value):\n",
    "    if value is None:\n",
    "        return None\n",
    "    # Extract value after colon if present\n",
    "    if \":\" in value:\n",
    "        value = value.split(\":\", 1)[1].strip()\n",
    "    # Convert to binary based on presence of atherosclerosis\n",
    "    return None  # No conversion rule needed since trait is not available\n",
    "\n",
    "def convert_age(value):\n",
    "    if value is None:\n",
    "        return None\n",
    "    # Extract value after colon if present\n",
    "    if \":\" in value:\n",
    "        value = value.split(\":\", 1)[1].strip()\n",
    "    # Try to convert to float for continuous age\n",
    "    try:\n",
    "        return float(value)\n",
    "    except:\n",
    "        return None\n",
    "\n",
    "def convert_gender(value):\n",
    "    if value is None:\n",
    "        return None\n",
    "    # Extract value after colon if present\n",
    "    if \":\" in value:\n",
    "        value = value.split(\":\", 1)[1].strip().lower()\n",
    "    # Convert to binary (0 for female, 1 for male)\n",
    "    if value in [\"female\", \"f\"]:\n",
    "        return 0\n",
    "    elif value in [\"male\", \"m\"]:\n",
    "        return 1\n",
    "    return None\n",
    "\n",
    "# 3. Save Metadata\n",
    "# Determine trait availability\n",
    "is_trait_available = trait_row is not None\n",
    "\n",
    "# Validate and save cohort information (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 substep\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ecba9a19",
   "metadata": {},
   "source": [
    "### Step 3: Gene Data Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "a63a462e",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:44:58.842651Z",
     "iopub.status.busy": "2025-03-25T06:44:58.842551Z",
     "iopub.status.idle": "2025-03-25T06:44:58.917547Z",
     "shell.execute_reply": "2025-03-25T06:44:58.917226Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Matrix file found: ../../input/GEO/Atherosclerosis/GSE133601/GSE133601_series_matrix.txt.gz\n",
      "Gene data shape: (19684, 30)\n",
      "First 20 gene/probe identifiers:\n",
      "Index(['100009676_at', '10000_at', '10001_at', '10002_at', '100033413_at',\n",
      "       '100033414_at', '100033416_at', '100033418_at', '100033420_at',\n",
      "       '100033422_at', '100033423_at', '100033424_at', '100033425_at',\n",
      "       '100033426_at', '100033427_at', '100033428_at', '100033430_at',\n",
      "       '100033431_at', '100033432_at', '100033433_at'],\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": "e2b3fe9c",
   "metadata": {},
   "source": [
    "### Step 4: Gene Identifier Review"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "49117b80",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:44:58.918850Z",
     "iopub.status.busy": "2025-03-25T06:44:58.918743Z",
     "iopub.status.idle": "2025-03-25T06:44:58.920553Z",
     "shell.execute_reply": "2025-03-25T06:44:58.920287Z"
    }
   },
   "outputs": [],
   "source": [
    "# Examine the gene identifiers from the preview\n",
    "# The identifiers like '100009676_at', '10000_at' are probe IDs from microarray platforms\n",
    "# These are not standard human gene symbols and will need to be mapped to gene symbols\n",
    "\n",
    "requires_gene_mapping = True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "95333584",
   "metadata": {},
   "source": [
    "### Step 5: Gene Annotation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "34c7e5ec",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:44:58.921705Z",
     "iopub.status.busy": "2025-03-25T06:44:58.921607Z",
     "iopub.status.idle": "2025-03-25T06:44:59.557464Z",
     "shell.execute_reply": "2025-03-25T06:44:59.557090Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "Gene annotation preview:\n",
      "Columns in gene annotation: ['ID', 'SPOT_ID', 'Description']\n",
      "{'ID': ['1_at', '10_at', '100_at', '1000_at', '10000_at'], 'SPOT_ID': ['1', '10', '100', '1000', '10000'], 'Description': ['alpha-1-B glycoprotein', 'N-acetyltransferase 2 (arylamine N-acetyltransferase)', 'adenosine deaminase', 'cadherin 2, type 1, N-cadherin (neuronal)', 'v-akt murine thymoma viral oncogene homolog 3 (protein kinase B, gamma)']}\n",
      "\n",
      "Full gene name examples from Description column:\n",
      "['alpha-1-B glycoprotein', 'N-acetyltransferase 2 (arylamine N-acetyltransferase)', 'adenosine deaminase', 'cadherin 2, type 1, N-cadherin (neuronal)', 'v-akt murine thymoma viral oncogene homolog 3 (protein kinase B, gamma)', 'uncharacterized LOC100009676', 'mediator complex subunit 6', 'nuclear receptor subfamily 2, group E, member 3', 'N-acetylated alpha-linked acidic dipeptidase 2', 'small nucleolar RNA, C/D box 116-1']\n",
      "\n",
      "Mapping data shape: (19638, 2)\n",
      "{'ID': ['1_at', '10_at', '100_at', '1000_at', '10000_at'], 'Gene': ['alpha-1-B glycoprotein', 'N-acetyltransferase 2 (arylamine N-acetyltransferase)', 'adenosine deaminase', 'cadherin 2, type 1, N-cadherin (neuronal)', 'v-akt murine thymoma viral oncogene homolog 3 (protein kinase B, gamma)']}\n",
      "\n",
      "Number of probes with empty gene descriptions: 0\n",
      "Final mapping data shape after filtering: (19638, 2)\n",
      "{'ID': ['1_at', '10_at', '100_at', '1000_at', '10000_at'], 'Gene': ['alpha-1-B glycoprotein', 'N-acetyltransferase 2 (arylamine N-acetyltransferase)', 'adenosine deaminase', 'cadherin 2, type 1, N-cadherin (neuronal)', 'v-akt murine thymoma viral oncogene homolog 3 (protein kinase B, gamma)']}\n",
      "\n",
      "Probes in gene data: 19684\n",
      "Probes in mapping data: 19638\n",
      "Probes in both: 19638 (99.77% coverage)\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. Preview the gene annotation dataframe\n",
    "print(\"\\nGene annotation preview:\")\n",
    "print(f\"Columns in gene annotation: {gene_annotation.columns.tolist()}\")\n",
    "print(preview_df(gene_annotation, n=5))\n",
    "\n",
    "# Since we have identified that the Description column contains full gene names,\n",
    "# let's use this for our mapping instead of trying to extract symbols\n",
    "print(\"\\nFull gene name examples from Description column:\")\n",
    "print(gene_annotation['Description'].head(10).tolist())\n",
    "\n",
    "# Create mapping data using ID and Description (as Gene)\n",
    "mapping_data = gene_annotation[['ID', 'Description']].copy()\n",
    "mapping_data.rename(columns={'Description': 'Gene'}, inplace=True)\n",
    "mapping_data = mapping_data.dropna(subset=['Gene'])  # Remove rows with missing gene names\n",
    "\n",
    "# Check mapping data\n",
    "print(f\"\\nMapping data shape: {mapping_data.shape}\")\n",
    "print(preview_df(mapping_data, n=5))\n",
    "\n",
    "# Check for any empty gene descriptions\n",
    "empty_gene_count = (mapping_data['Gene'].str.strip() == '').sum()\n",
    "print(f\"\\nNumber of probes with empty gene descriptions: {empty_gene_count}\")\n",
    "\n",
    "# Filter out empty descriptions\n",
    "mapping_data = mapping_data[mapping_data['Gene'].str.strip() != '']\n",
    "print(f\"Final mapping data shape after filtering: {mapping_data.shape}\")\n",
    "print(preview_df(mapping_data, n=5))\n",
    "\n",
    "# Verify the mapping data covers a significant portion of the probes in gene_data\n",
    "gene_data_probes = set(gene_data.index)\n",
    "mapping_probes = set(mapping_data['ID'])\n",
    "common_probes = gene_data_probes.intersection(mapping_probes)\n",
    "\n",
    "print(f\"\\nProbes in gene data: {len(gene_data_probes)}\")\n",
    "print(f\"Probes in mapping data: {len(mapping_probes)}\")\n",
    "print(f\"Probes in both: {len(common_probes)} ({len(common_probes)/len(gene_data_probes):.2%} coverage)\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0579fe3b",
   "metadata": {},
   "source": [
    "### Step 6: Gene Identifier Mapping"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "1d77c5f0",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:44:59.558775Z",
     "iopub.status.busy": "2025-03-25T06:44:59.558668Z",
     "iopub.status.idle": "2025-03-25T06:44:59.732435Z",
     "shell.execute_reply": "2025-03-25T06:44:59.732073Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene mapping created with shape: (19638, 2)\n",
      "Example of mapping (first 5 rows):\n",
      "{'ID': ['1_at', '10_at', '100_at', '1000_at', '10000_at'], 'Gene': ['alpha-1-B glycoprotein', 'N-acetyltransferase 2 (arylamine N-acetyltransferase)', 'adenosine deaminase', 'cadherin 2, type 1, N-cadherin (neuronal)', 'v-akt murine thymoma viral oncogene homolog 3 (protein kinase B, gamma)']}\n",
      "Probes in both gene data and mapping: 19638 (99.77% coverage)\n",
      "Converted gene expression data shape: (2209, 30)\n",
      "Example of gene expression data (first 5 genes):\n",
      "{'GSM3912810': [44.64284666133333, 6.85290986, 10.75107161, 14.671153504, 5.728124292], 'GSM3912811': [44.31222287333333, 7.392122475, 10.7728531, 14.458826952, 6.08107333], 'GSM3912812': [44.4390841525, 7.258355125, 10.5879051, 13.966994956, 5.788481876], 'GSM3912813': [44.16653068816667, 7.124871182, 10.6206698, 14.001834505, 5.999150005], 'GSM3912814': [45.1576120165, 7.305069986, 10.37066336, 13.835656475, 5.84612428], 'GSM3912815': [45.128156772666664, 6.978934425, 10.66945533, 14.303068801, 5.811075819], 'GSM3912816': [45.57193469716667, 6.883018229, 10.76822368, 14.271389627, 5.712771516], 'GSM3912817': [44.872630321833334, 6.902896297, 10.85295124, 14.283734452000001, 5.640566351], 'GSM3912818': [43.8740966175, 7.094440663, 10.70220185, 14.564690605000001, 5.716840321], 'GSM3912819': [44.025074869166666, 7.237479137, 10.62949373, 14.403883096, 5.974590003], 'GSM3912820': [44.61549519083333, 6.964278787, 10.79712889, 14.538200255, 5.71470115], 'GSM3912821': [44.40396137366667, 6.985330744, 10.82463802, 14.423648333000001, 5.548672753], 'GSM3912822': [44.4110568165, 6.832129109, 10.83782319, 14.613005367, 5.565429464], 'GSM3912823': [44.00286435833333, 7.149337447, 10.68371052, 14.69309517, 5.932409138], 'GSM3912824': [45.41453759866667, 7.032138575, 10.6729742, 14.278396027, 5.767817763], 'GSM3912825': [44.68216692283333, 6.977689954, 10.70909441, 14.48510215, 5.748623666], 'GSM3912826': [44.968621410666664, 7.0204137, 10.69439501, 14.534092034, 5.755708549], 'GSM3912827': [45.1011267265, 6.468976946, 10.63396254, 14.470919483, 5.449706363], 'GSM3912828': [44.25095318383333, 6.727001249, 10.8826259, 14.417686576000001, 5.634848724], 'GSM3912829': [43.948061154166666, 6.906149747, 10.78952223, 14.475669278, 5.812110917], 'GSM3912830': [44.05661054916666, 7.699527022, 10.70332612, 14.485748255, 6.294751553], 'GSM3912831': [43.992306808500004, 7.363067314, 10.84225328, 14.413368357, 5.95928175], 'GSM3912832': [45.93359714216667, 6.50967496, 10.55785822, 14.058911826, 5.999884161], 'GSM3912833': [46.433625505, 6.134488025, 10.46505289, 13.831086166999999, 5.733305552], 'GSM3912834': [44.49333944716667, 6.922231559, 10.82446811, 14.226141069, 5.661581931], 'GSM3912835': [43.957809657666665, 6.847649362, 10.9003435, 14.390123750999999, 5.51482606], 'GSM3912836': [44.33750015983333, 6.588764958, 10.80933679, 14.316138831, 5.615618759], 'GSM3912837': [45.331246988833335, 6.617292847, 10.66159538, 14.245405357, 5.54080682], 'GSM3912838': [44.993840500666664, 6.609714449, 10.7898014, 14.177046299, 5.331632947], 'GSM3912839': [45.87582188583333, 6.600638845, 10.5919384, 13.858493055, 5.342390661]}\n",
      "Final gene expression data shape after normalization: (1276, 30)\n",
      "Example of normalized gene expression data (first 5 genes):\n",
      "{'GSM3912810': [20.396915665, 49.58472552, 8.027420676, 6.804712193, 95.41872589925], 'GSM3912811': [20.110278752, 49.409931868499996, 8.153951092, 6.212960256, 96.1900260995], 'GSM3912812': [19.834370278, 49.652695445, 7.71147867, 6.540273188, 95.7002006135], 'GSM3912813': [19.917013694, 49.8610374215, 7.809771545, 6.619469497, 95.6370585445], 'GSM3912814': [19.733707223, 50.217164216499995, 7.825857443, 6.565998109, 96.41634295074999], 'GSM3912815': [19.729076577, 50.1282362585, 8.098023014, 6.609393045, 96.24705986149999], 'GSM3912816': [20.31625833, 50.048215128500004, 7.895463296, 6.476880472, 95.47509986925], 'GSM3912817': [20.308040868, 49.629054249, 8.172686092, 6.307384277, 96.03258371875], 'GSM3912818': [20.417318600999998, 49.5799159055, 8.242619998, 6.547974383, 95.45241842725], 'GSM3912819': [20.090374145, 48.3721513745, 8.276584614, 6.52080939, 95.32520494325], 'GSM3912820': [20.560406905, 49.0675519335, 8.190295526, 6.656060285, 95.5485858735], 'GSM3912821': [20.215596087999998, 49.5444560065, 8.455105182, 6.289585987, 95.65133872775], 'GSM3912822': [20.585252682, 49.8776905335, 8.093056272, 6.38766593, 95.205873613], 'GSM3912823': [20.243326041, 49.843296411, 7.964348199, 6.638861833, 95.38099608975], 'GSM3912824': [20.133943770000002, 49.956334613500005, 8.054824913, 6.533353407, 95.621441439], 'GSM3912825': [20.167317121, 49.4148183355, 8.106502306, 6.705146794, 95.8597636975], 'GSM3912826': [20.107752771999998, 49.9466198455, 8.031639378, 6.32301637, 97.13934370850001], 'GSM3912827': [20.10324871, 51.26009144, 7.940186063, 6.63784442, 95.9123683015], 'GSM3912828': [20.831035887, 49.9625117155, 8.168392812, 6.436003391, 95.4193262885], 'GSM3912829': [20.425918328999998, 49.5238951615, 8.137205692, 6.516115521, 95.52267076325], 'GSM3912830': [20.166319383, 49.693211679, 8.311189127, 6.376942931, 95.88746268375], 'GSM3912831': [20.331183277, 49.6377492445, 8.220197198, 6.540001945, 95.42477972925], 'GSM3912832': [19.906053082, 51.197895128, 7.851164713, 6.506060596, 96.03833117825], 'GSM3912833': [19.711166096, 51.3367430725, 7.767860188, 6.447184763, 95.77198288700001], 'GSM3912834': [20.479715411999997, 49.8261637755, 8.319403838, 6.391721479, 95.3245278655], 'GSM3912835': [20.224079853, 49.832659074000006, 8.405160353, 6.542314554, 95.3798023995], 'GSM3912836': [20.439882233, 50.0866383435, 8.286582525, 6.245214519, 95.4771516135], 'GSM3912837': [20.294104849, 50.274626477, 8.197992805, 6.303716769, 95.44480912], 'GSM3912838': [20.254064315, 50.8546435975, 8.064886412, 6.561603057, 94.98906418375], 'GSM3912839': [19.744998547999998, 50.393856123, 7.764979137, 6.427701472, 95.213160438]}\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene expression data saved to ../../output/preprocess/Atherosclerosis/gene_data/GSE133601.csv\n"
     ]
    }
   ],
   "source": [
    "# 1. Determine which columns to use for mapping\n",
    "# From previous step, we see the 'ID' column contains probe IDs matching gene_data's index\n",
    "# The 'Description' column contains gene names, not symbols\n",
    "\n",
    "# Since extract_human_gene_symbols isn't working well with this dataset's descriptions,\n",
    "# we'll modify our approach to use the full descriptions\n",
    "\n",
    "# 2. Create a mapping dataframe using probe IDs and full gene descriptions\n",
    "mapping_data = gene_annotation[['ID', 'Description']].copy()\n",
    "mapping_data = mapping_data.rename(columns={'Description': 'Gene'})\n",
    "mapping_data = mapping_data.dropna(subset=['Gene'])\n",
    "mapping_data = mapping_data[mapping_data['Gene'].str.strip() != '']\n",
    "\n",
    "print(f\"Gene mapping created with shape: {mapping_data.shape}\")\n",
    "print(\"Example of mapping (first 5 rows):\")\n",
    "print(preview_df(mapping_data, n=5))\n",
    "\n",
    "# Check overlap with gene_data\n",
    "gene_data_probes = set(gene_data.index)\n",
    "mapping_probes = set(mapping_data['ID'])\n",
    "common_probes = gene_data_probes.intersection(mapping_probes)\n",
    "print(f\"Probes in both gene data and mapping: {len(common_probes)} ({len(common_probes)/len(gene_data_probes):.2%} coverage)\")\n",
    "\n",
    "# 3. Apply the gene mapping to convert probe-level measurements to gene-level expression\n",
    "# This handles the many-to-many relationship by:\n",
    "# - Dividing probe values equally among mapped genes\n",
    "# - Summing all contributions to each gene\n",
    "try:\n",
    "    gene_data = apply_gene_mapping(gene_data, mapping_data)\n",
    "    \n",
    "    print(f\"Converted gene expression data shape: {gene_data.shape}\")\n",
    "    print(\"Example of gene expression data (first 5 genes):\")\n",
    "    print(preview_df(gene_data, n=5))\n",
    "\n",
    "    # Normalize gene symbols to standardize and aggregate duplicate symbols\n",
    "    gene_data = normalize_gene_symbols_in_index(gene_data)\n",
    "    print(f\"Final gene expression data shape after normalization: {gene_data.shape}\")\n",
    "    print(\"Example of normalized gene expression data (first 5 genes):\")\n",
    "    print(preview_df(gene_data, n=5))\n",
    "\n",
    "    # Save the processed gene expression data\n",
    "    os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
    "    gene_data.to_csv(out_gene_data_file)\n",
    "    print(f\"Gene expression data saved to {out_gene_data_file}\")\n",
    "except Exception as e:\n",
    "    print(f\"Error during gene mapping: {e}\")\n",
    "    \n",
    "    # In case of failure, examine the mapping data more closely\n",
    "    print(\"\\nInvestigating mapping data structure:\")\n",
    "    print(f\"Number of unique probe IDs in mapping: {mapping_data['ID'].nunique()}\")\n",
    "    print(f\"Number of unique gene names in mapping: {mapping_data['Gene'].nunique()}\")\n",
    "    \n",
    "    # Check for probe-gene relationships\n",
    "    mapping_sample = mapping_data.sample(min(5, len(mapping_data)))\n",
    "    print(\"\\nSample of mapping data:\")\n",
    "    print(mapping_sample)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "182d51a5",
   "metadata": {},
   "source": [
    "### Step 7: Data Normalization and Linking"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "66d56fb2",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:44:59.734049Z",
     "iopub.status.busy": "2025-03-25T06:44:59.733914Z",
     "iopub.status.idle": "2025-03-25T06:44:59.879382Z",
     "shell.execute_reply": "2025-03-25T06:44:59.879013Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Normalizing gene symbols...\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene data shape after normalization: (1276, 30)\n",
      "First 10 normalized gene symbols:\n",
      "Index(['A4GALT', 'AAA1', 'AAR2', 'AATK', 'ABCC11', 'ABCD1', 'ABCE1', 'ABI3',\n",
      "       'ABO', 'ABRA'],\n",
      "      dtype='object', name='Gene')\n",
      "Normalized gene data saved to: ../../output/preprocess/Atherosclerosis/gene_data/GSE133601.csv\n",
      "\n",
      "Reconfirming clinical data availability...\n",
      "Sample characteristics dictionary:\n",
      "{0: ['tissue: peripheral blood mononuclear cells'], 1: ['subject: 10031', 'subject: 11874', 'subject: 11992', 'subject: 30234', 'subject: 30665', 'subject: 30838', 'subject: 40044', 'subject: 40266', 'subject: 40657', 'subject: 11928', 'subject: 30031', 'subject: 40269', 'subject: 30624', 'subject: 40971', 'subject: 40197'], 2: ['timepoint: pre-CPAP', 'timepoint: post-CPAP']}\n",
      "Dataset usability for Atherosclerosis study: False\n",
      "The GSE133601 dataset does not contain Atherosclerosis measurements and cannot be used for this specific study.\n"
     ]
    }
   ],
   "source": [
    "# 1. Normalize gene symbols using NCBI database\n",
    "print(\"Normalizing gene symbols...\")\n",
    "gene_data = pd.read_csv(out_gene_data_file, index_col=0)\n",
    "gene_data = normalize_gene_symbols_in_index(gene_data)\n",
    "print(f\"Gene data shape after normalization: {gene_data.shape}\")\n",
    "print(\"First 10 normalized gene symbols:\")\n",
    "print(gene_data.index[:10])\n",
    "\n",
    "# Save the normalized gene data\n",
    "gene_data.to_csv(out_gene_data_file)\n",
    "print(f\"Normalized gene data saved to: {out_gene_data_file}\")\n",
    "\n",
    "# 2. We've determined in Step 2 that trait data is not available (trait_row was None)\n",
    "# This is confirmed by the matrix data analysis\n",
    "print(\"\\nReconfirming clinical data availability...\")\n",
    "_, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
    "background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']\n",
    "clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']\n",
    "_, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)\n",
    "\n",
    "# Display clinical data features\n",
    "print(\"Sample characteristics dictionary:\")\n",
    "sample_characteristics_dict = get_unique_values_by_row(clinical_data)\n",
    "print(sample_characteristics_dict)\n",
    "\n",
    "# We confirmed that this dataset doesn't contain Atherosclerosis trait data\n",
    "is_trait_available = False\n",
    "\n",
    "# 3. Since we don't have trait data, we cannot create valid linked data\n",
    "# We'll report this in the cohort info and skip the remaining steps\n",
    "note = \"This GSE133601 dataset contains gene expression data related to Sleep Disordered Breathing (SDB) and CPAP therapy, but does not have direct measurements of Atherosclerosis. The study mentions Multi-Ethnic Study of Atherosclerosis (MESA) as a source study, but the current dataset focuses on oxygen saturation during sleep, not atherosclerosis.\"\n",
    "\n",
    "# 4. Validate and save cohort info (initial assessment since we can't do final validation without trait data)\n",
    "is_usable = validate_and_save_cohort_info(\n",
    "    is_final=False,  # Using initial validation since we don't have trait data for final validation\n",
    "    cohort=cohort,\n",
    "    info_path=json_path,\n",
    "    is_gene_available=True,\n",
    "    is_trait_available=is_trait_available  # Set to False based on our analysis\n",
    ")\n",
    "\n",
    "print(f\"Dataset usability for {trait} study: {is_usable}\")\n",
    "if not is_usable:\n",
    "    print(f\"The {cohort} dataset does not contain {trait} measurements and cannot be used for this specific study.\")"
   ]
  }
 ],
 "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
}