File size: 45,920 Bytes
7ae1978
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "ff50ae3e",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T07:27:42.412301Z",
     "iopub.status.busy": "2025-03-25T07:27:42.412118Z",
     "iopub.status.idle": "2025-03-25T07:27:42.575235Z",
     "shell.execute_reply": "2025-03-25T07:27:42.574767Z"
    }
   },
   "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 = \"LDL_Cholesterol_Levels\"\n",
    "cohort = \"GSE28893\"\n",
    "\n",
    "# Input paths\n",
    "in_trait_dir = \"../../input/GEO/LDL_Cholesterol_Levels\"\n",
    "in_cohort_dir = \"../../input/GEO/LDL_Cholesterol_Levels/GSE28893\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/LDL_Cholesterol_Levels/GSE28893.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/LDL_Cholesterol_Levels/gene_data/GSE28893.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/LDL_Cholesterol_Levels/clinical_data/GSE28893.csv\"\n",
    "json_path = \"../../output/preprocess/LDL_Cholesterol_Levels/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b0bb5e09",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "51ea9ebd",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T07:27:42.576803Z",
     "iopub.status.busy": "2025-03-25T07:27:42.576656Z",
     "iopub.status.idle": "2025-03-25T07:27:42.663059Z",
     "shell.execute_reply": "2025-03-25T07:27:42.662581Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Background Information:\n",
      "!Series_title\t\"Genetic identification, replication, and functional fine-mapping of expression quantitative trait loci in primary human liver tissue [Illumina Expression Array]\"\n",
      "!Series_summary\t\"Most loci identified in genome wide association studies (GWAS) of complex traits reside in non-coding DNA and may contribute to phenotype via changes in gene regulation. The discovery of expression quantitative trait loci (?eQTLs?) can thus be used to more precisely identify modest but real disease associations and provide insights into their underlying molecular mechanisms. This is particularly true for analyses of expression in non-transformed cells from tissues relevant to the complex traits of interest. We have conducted two independent studies to identify genetic, including both SNPs and copy-number variants, and environmental determinants of human liver gene expression variation. We analyzed two sets of primary livers (primary dataset: n=220; replication dataset: n=60) using Agilent and Illumina expression arrays and Illumina SNP genotyping (550K). At least 30% of genetic and non-genetic factors that meet genome-wide significance (p <1 x10-9) in one study fail to replicate in the second study, suggesting that artifacts, like unknown SNPs that affect RNA-probe hybridization or hidden confounding variables, often result in statistically significant but biologically irrelevant correlations. These data confirm the value of independent replications to enrich for truly predictive eQTLs, and given our study design we are able to identify hundreds of reproducible correlations. We show that such information can be used to provide insights into disease-relevant phenotypes, with specific examples including eQTLs related to lipid levels (e.g. LDL cholesterol), immune system function (e.g. HLA), and drug response (e.g. warfarin). Furthermore, in the interest of both fine-mapping and mechanistic annotation, we hypothesized that promoters and 3?UTRs are enriched for causal eQTL variants. Therefore, we re-sequenced the promoter and 3?UTR regions of 25 genes with eQTLs, cloned each discovered haplotype, and quantified their impact on transcription using a luciferase-based assay. These data reveal multiple examples of robust, haplotype-specific in vitro functional differences that correlate directly with in vivo expression levels. This suggests that many eQTLs can be rapidly fine-mapped to one or a few single-nucleotide variants and mechanistically characterized using such assays. Integration of functional assays with eQTL discovery, and eQTLs with complex trait associations, is a powerful means to exploit GWAS data and improve their biological interpretability.\"\n",
      "!Series_overall_design\t\"RNA expression levels were quantified on Illumina gene expression microarrays for 60 normal human livers. Expression quantitative trait loci were identified by genome wide association mapping.\"\n",
      "Sample Characteristics Dictionary:\n",
      "{0: ['tissue: Primary Liver'], 1: ['age: 21', 'age: 15', 'age: 32', 'age: 45', 'age: 42', 'age: 46', 'age: 28', 'age: 9', 'age: 19', 'age: 52', 'age: 25', 'age: 24', 'age: 59', 'age: 51', 'age: 38', 'age: 49', 'age: 62', 'age: 50', 'age: 7', 'age: 39', 'age: 11', 'age: 48', 'age: 68', 'age: 10', 'age: 70', 'age: 60', 'age: 63', 'age: 30', 'age: 64', 'age: 26'], 2: ['gender: M', 'gender: F'], 3: ['ancestry (pc 1): -0.0117287', 'ancestry (pc 1): -0.00831958', 'ancestry (pc 1): 0.204173', 'ancestry (pc 1): -0.00859255', 'ancestry (pc 1): -0.0108323', 'ancestry (pc 1): 0.00667825', 'ancestry (pc 1): -0.0128097', 'ancestry (pc 1): -0.00579505', 'ancestry (pc 1): -0.0116622', 'ancestry (pc 1): -0.010341', 'ancestry (pc 1): -0.0101109', 'ancestry (pc 1): -0.00922923', 'ancestry (pc 1): -0.00999538', 'ancestry (pc 1): -0.0109824', 'ancestry (pc 1): 0.0391148', 'ancestry (pc 1): -0.0121107', 'ancestry (pc 1): -0.00530347', 'ancestry (pc 1): -0.00817143', 'ancestry (pc 1): -0.00673814', 'ancestry (pc 1): -0.0142317', 'ancestry (pc 1): -0.00960678', 'ancestry (pc 1): -0.00733583', 'ancestry (pc 1): -0.00774648', 'ancestry (pc 1): -0.00857621', 'ancestry (pc 1): -0.00909772', 'ancestry (pc 1): -0.00819896', 'ancestry (pc 1): 0.111411', 'ancestry (pc 1): -0.00940823', 'ancestry (pc 1): 0.0100608', 'ancestry (pc 1): -0.00922416'], 4: ['ancestry (pc 2): 0.000418281', 'ancestry (pc 2): 0.00664124', 'ancestry (pc 2): 0.083547', 'ancestry (pc 2): -0.00130658', 'ancestry (pc 2): -0.00135363', 'ancestry (pc 2): -0.034668', 'ancestry (pc 2): 0.00761551', 'ancestry (pc 2): -0.00194575', 'ancestry (pc 2): 0.00483231', 'ancestry (pc 2): 0.00677443', 'ancestry (pc 2): 0.00722381', 'ancestry (pc 2): -0.0118771', 'ancestry (pc 2): 0.00568975', 'ancestry (pc 2): 0.00371197', 'ancestry (pc 2): -0.0666379', 'ancestry (pc 2): 0.00425485', 'ancestry (pc 2): -0.00128296', 'ancestry (pc 2): 0.00857196', 'ancestry (pc 2): 0.00457323', 'ancestry (pc 2): 0.00690231', 'ancestry (pc 2): 0.00924564', 'ancestry (pc 2): 0.00827269', 'ancestry (pc 2): 0.00278654', 'ancestry (pc 2): 0.00508776', 'ancestry (pc 2): 0.0113785', 'ancestry (pc 2): 0.00365574', 'ancestry (pc 2): 0.0552398', 'ancestry (pc 2): 0.00594393', 'ancestry (pc 2): -0.0382021', 'ancestry (pc 2): 0.00650548']}\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": "8bd56944",
   "metadata": {},
   "source": [
    "### Step 2: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "c04cb4ae",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T07:27:42.664181Z",
     "iopub.status.busy": "2025-03-25T07:27:42.664071Z",
     "iopub.status.idle": "2025-03-25T07:27:42.669246Z",
     "shell.execute_reply": "2025-03-25T07:27:42.668819Z"
    }
   },
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "import os\n",
    "import re\n",
    "from typing import Optional, Dict, Any, Callable\n",
    "\n",
    "# 1. Gene Expression Data Availability\n",
    "# Based on the background information, this dataset contains gene expression data from liver tissue\n",
    "# The series summary mentions \"Illumina Expression Array\" and gene expression quantification\n",
    "is_gene_available = True\n",
    "\n",
    "# 2. Variable Availability and Data Type Conversion\n",
    "# 2.1 Data Availability\n",
    "\n",
    "# For trait (LDL_Cholesterol_Levels)\n",
    "# The background information mentions LDL cholesterol levels, but it's not directly in the sample characteristics\n",
    "# Since the study is about eQTLs related to lipid levels including LDL cholesterol, this information might have been\n",
    "# collected but not shown in the sample characteristics. In this case, we'll set trait_row to None.\n",
    "trait_row = None\n",
    "\n",
    "# For age\n",
    "# Age data is available in row 1 of the sample characteristics dictionary\n",
    "age_row = 1\n",
    "\n",
    "# For gender\n",
    "# Gender data is available in row 2 of the sample characteristics dictionary\n",
    "gender_row = 2\n",
    "\n",
    "# 2.2 Data Type Conversion\n",
    "# Since trait data is not available, we'll define a placeholder function\n",
    "def convert_trait(value):\n",
    "    return None\n",
    "\n",
    "# Age is a continuous variable\n",
    "def convert_age(value):\n",
    "    if value is None or not isinstance(value, str):\n",
    "        return None\n",
    "    \n",
    "    # Extract the age value after colon\n",
    "    match = re.search(r'age:\\s*(\\d+)', value)\n",
    "    if match:\n",
    "        return float(match.group(1))\n",
    "    return None\n",
    "\n",
    "# Gender is a binary variable (0 for female, 1 for male)\n",
    "def convert_gender(value):\n",
    "    if value is None or not isinstance(value, str):\n",
    "        return None\n",
    "    \n",
    "    # Extract the gender value after colon\n",
    "    match = re.search(r'gender:\\s*(\\w+)', value)\n",
    "    if match:\n",
    "        gender = match.group(1).upper()\n",
    "        if gender == 'F':\n",
    "            return 0\n",
    "        elif gender == 'M':\n",
    "            return 1\n",
    "    return None\n",
    "\n",
    "# 3. Save Metadata\n",
    "is_trait_available = trait_row is not None\n",
    "\n",
    "# Initial filtering on dataset usability\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",
    "if trait_row is not None:\n",
    "    clinical_data = pd.read_csv(os.path.join(in_cohort_dir, \"clinical_data.csv\"))\n",
    "    \n",
    "    # Extract clinical features\n",
    "    clinical_features = geo_select_clinical_features(\n",
    "        clinical_df=clinical_data,\n",
    "        trait=trait,\n",
    "        trait_row=trait_row,\n",
    "        convert_trait=convert_trait,\n",
    "        age_row=age_row,\n",
    "        convert_age=convert_age,\n",
    "        gender_row=gender_row,\n",
    "        convert_gender=convert_gender\n",
    "    )\n",
    "    \n",
    "    # Preview the dataframe\n",
    "    preview = preview_df(clinical_features)\n",
    "    print(\"Clinical Features Preview:\")\n",
    "    print(preview)\n",
    "    \n",
    "    # Save clinical data to CSV\n",
    "    os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
    "    clinical_features.to_csv(out_clinical_data_file, index=False)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bf6d7963",
   "metadata": {},
   "source": [
    "### Step 3: Gene Data Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "3fd27014",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T07:27:42.670411Z",
     "iopub.status.busy": "2025-03-25T07:27:42.670211Z",
     "iopub.status.idle": "2025-03-25T07:27:42.831667Z",
     "shell.execute_reply": "2025-03-25T07:27:42.831133Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Examining matrix file structure...\n",
      "Line 0: !Series_title\t\"Genetic identification, replication, and functional fine-mapping of expression quantitative trait loci in primary human liver tissue [Illumina Expression Array]\"\n",
      "Line 1: !Series_geo_accession\t\"GSE28893\"\n",
      "Line 2: !Series_status\t\"Public on Jun 27 2011\"\n",
      "Line 3: !Series_submission_date\t\"Apr 27 2011\"\n",
      "Line 4: !Series_last_update_date\t\"Aug 12 2019\"\n",
      "Line 5: !Series_pubmed_id\t\"21637794\"\n",
      "Line 6: !Series_pubmed_id\t\"23935528\"\n",
      "Line 7: !Series_summary\t\"Most loci identified in genome wide association studies (GWAS) of complex traits reside in non-coding DNA and may contribute to phenotype via changes in gene regulation. The discovery of expression quantitative trait loci (?eQTLs?) can thus be used to more precisely identify modest but real disease associations and provide insights into their underlying molecular mechanisms. This is particularly true for analyses of expression in non-transformed cells from tissues relevant to the complex traits of interest. We have conducted two independent studies to identify genetic, including both SNPs and copy-number variants, and environmental determinants of human liver gene expression variation. We analyzed two sets of primary livers (primary dataset: n=220; replication dataset: n=60) using Agilent and Illumina expression arrays and Illumina SNP genotyping (550K). At least 30% of genetic and non-genetic factors that meet genome-wide significance (p <1 x10-9) in one study fail to replicate in the second study, suggesting that artifacts, like unknown SNPs that affect RNA-probe hybridization or hidden confounding variables, often result in statistically significant but biologically irrelevant correlations. These data confirm the value of independent replications to enrich for truly predictive eQTLs, and given our study design we are able to identify hundreds of reproducible correlations. We show that such information can be used to provide insights into disease-relevant phenotypes, with specific examples including eQTLs related to lipid levels (e.g. LDL cholesterol), immune system function (e.g. HLA), and drug response (e.g. warfarin). Furthermore, in the interest of both fine-mapping and mechanistic annotation, we hypothesized that promoters and 3?UTRs are enriched for causal eQTL variants. Therefore, we re-sequenced the promoter and 3?UTR regions of 25 genes with eQTLs, cloned each discovered haplotype, and quantified their impact on transcription using a luciferase-based assay. These data reveal multiple examples of robust, haplotype-specific in vitro functional differences that correlate directly with in vivo expression levels. This suggests that many eQTLs can be rapidly fine-mapped to one or a few single-nucleotide variants and mechanistically characterized using such assays. Integration of functional assays with eQTL discovery, and eQTLs with complex trait associations, is a powerful means to exploit GWAS data and improve their biological interpretability.\"\n",
      "Line 8: !Series_overall_design\t\"RNA expression levels were quantified on Illumina gene expression microarrays for 60 normal human livers. Expression quantitative trait loci were identified by genome wide association mapping.\"\n",
      "Line 9: !Series_type\t\"Expression profiling by array\"\n",
      "Found table marker at line 68\n",
      "First few lines after marker:\n",
      "\"ID_REF\"\t\"GSM715884\"\t\"GSM715885\"\t\"GSM715886\"\t\"GSM715887\"\t\"GSM715888\"\t\"GSM715889\"\t\"GSM715890\"\t\"GSM715891\"\t\"GSM715892\"\t\"GSM715893\"\t\"GSM715894\"\t\"GSM715895\"\t\"GSM715896\"\t\"GSM715897\"\t\"GSM715898\"\t\"GSM715899\"\t\"GSM715900\"\t\"GSM715901\"\t\"GSM715902\"\t\"GSM715903\"\t\"GSM715904\"\t\"GSM715905\"\t\"GSM715906\"\t\"GSM715907\"\t\"GSM715908\"\t\"GSM715909\"\t\"GSM715910\"\t\"GSM715911\"\t\"GSM715912\"\t\"GSM715913\"\t\"GSM715914\"\t\"GSM715915\"\t\"GSM715916\"\t\"GSM715917\"\t\"GSM715918\"\t\"GSM715919\"\t\"GSM715920\"\t\"GSM715921\"\t\"GSM715922\"\t\"GSM715923\"\t\"GSM715924\"\t\"GSM715925\"\t\"GSM715926\"\t\"GSM715927\"\t\"GSM715928\"\t\"GSM715929\"\t\"GSM715930\"\t\"GSM715931\"\t\"GSM715932\"\t\"GSM715933\"\t\"GSM715934\"\t\"GSM715935\"\t\"GSM715936\"\t\"GSM715937\"\t\"GSM715938\"\t\"GSM715939\"\t\"GSM715940\"\t\"GSM715941\"\t\"GSM715942\"\t\"GSM715943\"\n",
      "\"ILMN_1651209\"\t7.194926663\t7.434210023\t8.174428166\t7.349381579\t7.367590885\t7.336035039\t7.32543608\t7.327150294\t7.269298566\t7.450281375\t7.671130933\t7.260234309\t7.15384425\t7.505053413\t7.157638412\t7.452926071\t7.370835819\t7.31921539\t7.397062014\t7.143623877\t7.34953993\t7.527500583\t7.128095922\t7.313710022\t7.389755609\t7.481177184\t7.365958869\t7.333544897\t7.323569472\t7.292968712\t7.433754602\t7.390367759\t7.211245142\t7.308729517\t7.409170534\t7.290797689\t7.500724991\t7.318405591\t7.597709431\t7.190628305\t7.258729968\t7.49749406\t7.301142201\t7.367547706\t7.303352003\t7.407503699\t7.279479866\t7.257033429\t7.415282389\t7.333655802\t7.579634072\t7.494708155\t7.353729316\t7.274122522\t7.467624411\t7.43056248\t7.335489735\t7.389888722\t7.414503743\t7.741368385\n",
      "\"ILMN_1651217\"\t7.174910534\t7.218686049\t7.122487737\t7.238101409\t7.129788196\t7.032300536\t7.124279635\t7.191167991\t7.337991975\t7.153221519\t7.056671533\t7.034585645\t7.175388292\t7.06716256\t7.301211122\t7.116713671\t7.117283751\t7.174774143\t7.124224384\t7.048145927\t7.08103465\t7.196386034\t7.221834771\t7.243640729\t7.285560124\t7.253556144\t7.254107096\t7.398767428\t7.102007998\t7.32388661\t7.195156459\t7.185854334\t7.139722906\t7.608030921\t7.171711766\t7.281520195\t6.991275997\t7.193530444\t7.312106026\t7.299032057\t7.184657278\t7.290422959\t7.235848219\t7.224713311\t7.266003996\t7.005503284\t7.384311533\t7.274617947\t7.160930741\t7.210472342\t7.245494639\t7.202871962\t7.217367372\t7.224274179\t7.170524999\t7.114392478\t7.226574064\t7.129035582\t7.191425999\t7.124504567\n",
      "\"ILMN_1651228\"\t13.03370067\t13.5122052\t14.13032629\t12.8565256\t13.90872508\t13.06268051\t13.0064722\t13.3827062\t13.36572936\t13.92735022\t13.44048833\t13.29510075\t13.02202054\t13.11218429\t13.02831178\t13.52325821\t13.0140288\t12.68911476\t13.57773835\t13.14909647\t13.68315337\t13.09872163\t13.49280729\t13.30384244\t12.90148262\t13.50332475\t12.60042238\t13.47282418\t13.44479758\t12.38911354\t13.23504625\t12.98844319\t13.42385878\t13.12612109\t13.11711294\t13.75196841\t13.03022713\t12.73628978\t12.71420001\t12.98638315\t12.81242431\t13.07586826\t12.7753364\t13.66399823\t12.98818797\t12.71983689\t12.69597832\t13.24686119\t13.61128925\t13.40692401\t12.98262539\t13.37130605\t12.74027167\t13.52063988\t13.44043045\t12.99289279\t13.0675393\t13.58634719\t13.63891553\t12.92109714\n",
      "\"ILMN_1651229\"\t8.616524495\t9.517457187\t10.15873658\t9.144223426\t9.507161858\t8.943526441\t8.757662466\t8.893246499\t9.382594715\t8.762705464\t10.02739022\t9.13171552\t8.683584392\t9.479415488\t8.73486081\t9.611261951\t9.533767534\t8.69034888\t8.841472468\t8.634179243\t10.03255782\t8.828215635\t8.523200595\t8.764161588\t8.658320591\t9.084730141\t8.971336249\t9.677248387\t9.898347976\t8.688208955\t8.835980332\t8.783315957\t9.106025323\t8.333146399\t8.814922451\t8.881631511\t9.25966263\t8.948614626\t9.323165654\t8.922891075\t8.71922203\t8.992534003\t8.868068323\t8.723256021\t9.4527664\t9.11643915\t8.571826669\t8.733002174\t8.990353776\t9.154967553\t8.828046054\t9.026126286\t8.581436171\t9.131945085\t8.910908563\t8.647767992\t9.111757805\t8.688295048\t9.49188239\t9.390317485\n",
      "Total lines examined: 69\n",
      "\n",
      "Attempting to extract gene data from matrix file...\n",
      "Successfully extracted gene data with 22177 rows\n",
      "First 20 gene IDs:\n",
      "Index(['ILMN_1651209', 'ILMN_1651217', 'ILMN_1651228', 'ILMN_1651229',\n",
      "       'ILMN_1651234', 'ILMN_1651235', 'ILMN_1651236', 'ILMN_1651237',\n",
      "       'ILMN_1651238', 'ILMN_1651254', 'ILMN_1651259', 'ILMN_1651260',\n",
      "       'ILMN_1651261', 'ILMN_1651262', 'ILMN_1651268', 'ILMN_1651278',\n",
      "       'ILMN_1651282', 'ILMN_1651286', 'ILMN_1651296', 'ILMN_1651298'],\n",
      "      dtype='object', name='ID')\n",
      "\n",
      "Gene expression data available: True\n"
     ]
    }
   ],
   "source": [
    "# 1. Get the file paths for the SOFT file and matrix file\n",
    "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
    "\n",
    "# Add diagnostic code to check file content and structure\n",
    "print(\"Examining matrix file structure...\")\n",
    "with gzip.open(matrix_file, 'rt') as file:\n",
    "    table_marker_found = False\n",
    "    lines_read = 0\n",
    "    for i, line in enumerate(file):\n",
    "        lines_read += 1\n",
    "        if '!series_matrix_table_begin' in line:\n",
    "            table_marker_found = True\n",
    "            print(f\"Found table marker at line {i}\")\n",
    "            # Read a few lines after the marker to check data structure\n",
    "            next_lines = [next(file, \"\").strip() for _ in range(5)]\n",
    "            print(\"First few lines after marker:\")\n",
    "            for next_line in next_lines:\n",
    "                print(next_line)\n",
    "            break\n",
    "        if i < 10:  # Print first few lines to see file structure\n",
    "            print(f\"Line {i}: {line.strip()}\")\n",
    "        if i > 100:  # Don't read the entire file\n",
    "            break\n",
    "    \n",
    "    if not table_marker_found:\n",
    "        print(\"Table marker '!series_matrix_table_begin' not found in first 100 lines\")\n",
    "    print(f\"Total lines examined: {lines_read}\")\n",
    "\n",
    "# 2. Try extracting gene expression data from the matrix file again with better diagnostics\n",
    "try:\n",
    "    print(\"\\nAttempting to extract gene data from matrix file...\")\n",
    "    gene_data = get_genetic_data(matrix_file)\n",
    "    if gene_data.empty:\n",
    "        print(\"Extracted gene expression data is empty\")\n",
    "        is_gene_available = False\n",
    "    else:\n",
    "        print(f\"Successfully extracted gene data with {len(gene_data.index)} rows\")\n",
    "        print(\"First 20 gene IDs:\")\n",
    "        print(gene_data.index[:20])\n",
    "        is_gene_available = True\n",
    "except Exception as e:\n",
    "    print(f\"Error extracting gene data: {str(e)}\")\n",
    "    print(\"This dataset appears to have an empty or malformed gene expression matrix\")\n",
    "    is_gene_available = False\n",
    "\n",
    "print(f\"\\nGene expression data available: {is_gene_available}\")\n",
    "\n",
    "# If data extraction failed, try an alternative approach using pandas directly\n",
    "if not is_gene_available:\n",
    "    print(\"\\nTrying alternative approach to read gene expression data...\")\n",
    "    try:\n",
    "        with gzip.open(matrix_file, 'rt') as file:\n",
    "            # Skip lines until we find the marker\n",
    "            for line in file:\n",
    "                if '!series_matrix_table_begin' in line:\n",
    "                    break\n",
    "            \n",
    "            # Try to read the data directly with pandas\n",
    "            gene_data = pd.read_csv(file, sep='\\t', index_col=0)\n",
    "            \n",
    "            if not gene_data.empty:\n",
    "                print(f\"Successfully extracted gene data with alternative method: {gene_data.shape}\")\n",
    "                print(\"First 20 gene IDs:\")\n",
    "                print(gene_data.index[:20])\n",
    "                is_gene_available = True\n",
    "            else:\n",
    "                print(\"Alternative extraction method also produced empty data\")\n",
    "    except Exception as e:\n",
    "        print(f\"Alternative extraction failed: {str(e)}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "531e4cfd",
   "metadata": {},
   "source": [
    "### Step 4: Gene Identifier Review"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "e0354e79",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T07:27:42.832994Z",
     "iopub.status.busy": "2025-03-25T07:27:42.832878Z",
     "iopub.status.idle": "2025-03-25T07:27:42.835153Z",
     "shell.execute_reply": "2025-03-25T07:27:42.834727Z"
    }
   },
   "outputs": [],
   "source": [
    "# Examining the gene identifiers in the gene expression data\n",
    "# The identifiers start with \"ILMN_\" which indicates they are Illumina probe IDs,\n",
    "# not standard human gene symbols.\n",
    "# Illumina probe IDs need to be mapped to standard gene symbols for meaningful analysis.\n",
    "\n",
    "requires_gene_mapping = True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4542f415",
   "metadata": {},
   "source": [
    "### Step 5: Gene Annotation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "555ac579",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T07:27:42.836312Z",
     "iopub.status.busy": "2025-03-25T07:27:42.836206Z",
     "iopub.status.idle": "2025-03-25T07:27:45.484568Z",
     "shell.execute_reply": "2025-03-25T07:27:45.484026Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Extracting gene annotation data from SOFT file...\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Successfully extracted gene annotation data with 1352865 rows\n",
      "\n",
      "Gene annotation preview (first few rows):\n",
      "{'ID': ['ILMN_1698220', 'ILMN_1810835', 'ILMN_1782944', 'ILMN_1692858', 'ILMN_1668162'], 'Species': ['Homo sapiens', 'Homo sapiens', 'Homo sapiens', 'Homo sapiens', 'Homo sapiens'], 'Source': ['RefSeq', 'RefSeq', 'RefSeq', 'RefSeq', 'RefSeq'], 'Search_Key': ['ILMN_13666', 'ILMN_10478', 'ILMN_27850', 'ILMN_10309', 'ILMN_7652'], 'Transcript': ['ILMN_13666', 'ILMN_175835', 'ILMN_27850', 'ILMN_10309', 'ILMN_7652'], 'ILMN_Gene': ['PHTF2', 'SPRR3', 'GPR37L1', 'FBXO25', 'DGAT2L3'], 'Source_Reference_ID': ['NM_020432.2', 'NM_005416.1', 'NM_004767.2', 'NM_012173.3', 'NM_001013579.1'], 'RefSeq_ID': ['NM_020432.2', 'NM_005416.1', 'NM_004767.2', 'NM_012173.3', 'NM_001013579.1'], 'Entrez_Gene_ID': [57157.0, 6707.0, 9283.0, 26260.0, 158833.0], 'GI': [40254932.0, 4885606.0, 31377792.0, 34878756.0, 61888901.0], 'Accession': ['NM_020432.2', 'NM_005416.1', 'NM_004767.2', 'NM_012173.3', 'NM_001013579.1'], 'Symbol': ['PHTF2', 'SPRR3', 'GPR37L1', 'FBXO25', 'DGAT2L3'], 'Protein_Product': ['NP_065165.2', 'NP_005407.1', 'NP_004758.2', 'NP_036305.2', 'NP_001013597.1'], 'Array_Address_Id': [2900438.0, 2640692.0, 1690440.0, 1030747.0, 6480482.0], 'Probe_Type': ['S', 'S', 'S', 'A', 'S'], 'Probe_Start': [4677.0, 683.0, 2372.0, 1937.0, 782.0], 'SEQUENCE': ['CAAAGAGAATTGTGGCAGATGTTGTGTGTGAACTGTTGTTTCTTTGCCAC', 'GAAGCCAACCACCAGATGCTGGACACCCTCTTCCCATCTGTTTCTGTGTC', 'GATCCCTGGGTTGCCCTGTCCCAACCTCCTTGTTAGGTGCTTTCCCATAG', 'CTGGGGTTGGGGGCTGGTCTGTGCATAATCCTGGACTGTGATGGGAACAG', 'GTCAAGGCTCCACTGGGCTCCTGCCATACTCCAGGCCTATTGTCACTGTG'], 'Chromosome': ['7', '1', '1', '8', 'X'], 'Probe_Chr_Orientation': ['+', '+', '+', '+', '+'], 'Probe_Coordinates': ['77424374-77424423', '151242655-151242704', '200365170-200365219', '409448-409497', '69376459-69376508'], 'Definition': ['Homo sapiens putative homeodomain transcription factor 2 (PHTF2), mRNA.', 'Homo sapiens small proline-rich protein 3 (SPRR3), mRNA.', 'Homo sapiens G protein-coupled receptor 37 like 1 (GPR37L1), mRNA.', 'Homo sapiens F-box protein 25 (FBXO25), transcript variant 3, mRNA.', 'Homo sapiens diacylglycerol O-acyltransferase 2-like 3 (DGAT2L3), mRNA.'], 'Ontology_Component': ['endoplasmic reticulum [goid 5783] [pmid 11256614] [evidence IDA]', 'cornified envelope [goid 1533] [pmid 15232223] [evidence TAS]', 'membrane [goid 16020] [evidence IEA]; integral to membrane [goid 16021] [pmid 9539149] [evidence NAS]', 'ubiquitin ligase complex [goid 151] [pmid 10531035] [evidence NAS]', 'membrane [goid 16020] [evidence IEA]; integral to membrane [goid 16021] [evidence IEA]; endoplasmic reticulum [goid 5783] [evidence IEA]'], 'Ontology_Process': [nan, 'keratinocyte differentiation [goid 30216] [pmid 8325635] [evidence NAS]; wound healing [goid 42060] [pmid 10510474] [evidence TAS]; epidermis development [goid 8544] [pmid 8325635] [evidence NAS]; keratinization [goid 31424] [evidence IEA]', 'G-protein coupled receptor protein signaling pathway [goid 7186] [evidence IEA]; signal transduction [goid 7165] [evidence IEA]', 'protein ubiquitination [goid 16567] [pmid 10531035] [evidence NAS]', 'lipid biosynthesis [goid 8610] [evidence IEA]; lipid metabolism [goid 6629] [evidence IEA]'], 'Ontology_Function': [nan, 'structural molecule activity [goid 5198] [pmid 15232223] [evidence TAS]; protein binding [goid 5515] [pmid 10510474] [evidence IPI]', 'receptor activity [goid 4872] [evidence IEA]; G-protein coupled receptor activity, unknown ligand [goid 16526] [pmid 9539149] [evidence NAS]; rhodopsin-like receptor activity [goid 1584] [evidence IEA]', 'ubiquitin-protein ligase activity [goid 4842] [pmid 10531035] [evidence NAS]', 'acyltransferase activity [goid 8415] [evidence IEA]; transferase activity [goid 16740] [evidence IEA]'], 'Synonyms': ['DKFZP564F013; FLJ33324; MGC86999', nan, 'ET(B)R-LP-2; ETBR-LP-2', 'MGC51975; MGC20256; FBX25', 'AWAT1; DGA2'], 'GB_ACC': ['NM_020432.2', 'NM_005416.1', 'NM_004767.2', 'NM_012173.3', 'NM_001013579.1']}\n",
      "\n",
      "Column names in gene annotation data:\n",
      "['ID', 'Species', 'Source', 'Search_Key', 'Transcript', 'ILMN_Gene', 'Source_Reference_ID', 'RefSeq_ID', 'Entrez_Gene_ID', 'GI', 'Accession', 'Symbol', 'Protein_Product', 'Array_Address_Id', 'Probe_Type', 'Probe_Start', 'SEQUENCE', 'Chromosome', 'Probe_Chr_Orientation', 'Probe_Coordinates', 'Definition', 'Ontology_Component', 'Ontology_Process', 'Ontology_Function', 'Synonyms', 'GB_ACC']\n",
      "\n",
      "The dataset contains GenBank accessions (GB_ACC) that could be used for gene mapping.\n",
      "Number of rows with GenBank accessions: 22185 out of 1352865\n"
     ]
    }
   ],
   "source": [
    "# 1. Extract gene annotation data from the SOFT file\n",
    "print(\"Extracting gene annotation data from SOFT file...\")\n",
    "try:\n",
    "    # Use the library function to extract gene annotation\n",
    "    gene_annotation = get_gene_annotation(soft_file)\n",
    "    print(f\"Successfully extracted gene annotation data with {len(gene_annotation.index)} rows\")\n",
    "    \n",
    "    # Preview the annotation DataFrame\n",
    "    print(\"\\nGene annotation preview (first few rows):\")\n",
    "    print(preview_df(gene_annotation))\n",
    "    \n",
    "    # Show column names to help identify which columns we need for mapping\n",
    "    print(\"\\nColumn names in gene annotation data:\")\n",
    "    print(gene_annotation.columns.tolist())\n",
    "    \n",
    "    # Check for relevant mapping columns\n",
    "    if 'GB_ACC' in gene_annotation.columns:\n",
    "        print(\"\\nThe dataset contains GenBank accessions (GB_ACC) that could be used for gene mapping.\")\n",
    "        # Count non-null values in GB_ACC column\n",
    "        non_null_count = gene_annotation['GB_ACC'].count()\n",
    "        print(f\"Number of rows with GenBank accessions: {non_null_count} out of {len(gene_annotation)}\")\n",
    "    \n",
    "    if 'SPOT_ID' in gene_annotation.columns:\n",
    "        print(\"\\nThe dataset contains genomic regions (SPOT_ID) that could be used for location-based gene mapping.\")\n",
    "        print(\"Example SPOT_ID format:\", gene_annotation['SPOT_ID'].iloc[0])\n",
    "    \n",
    "except Exception as e:\n",
    "    print(f\"Error processing gene annotation data: {e}\")\n",
    "    is_gene_available = False\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2e77345c",
   "metadata": {},
   "source": [
    "### Step 6: Gene Identifier Mapping"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "22feb2c3",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T07:27:45.485936Z",
     "iopub.status.busy": "2025-03-25T07:27:45.485809Z",
     "iopub.status.idle": "2025-03-25T07:27:46.245480Z",
     "shell.execute_reply": "2025-03-25T07:27:46.244841Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Created gene mapping with 22185 entries\n",
      "Gene mapping preview:\n",
      "{'ID': ['ILMN_1698220', 'ILMN_1810835', 'ILMN_1782944', 'ILMN_1692858', 'ILMN_1668162'], 'Gene': ['PHTF2', 'SPRR3', 'GPR37L1', 'FBXO25', 'DGAT2L3']}\n",
      "Converted gene expression data from 22185 probes to 17609 unique genes\n",
      "Gene expression data preview (first 5 genes):\n",
      "{'GSM715884': [7.315778891, 21.197534268, 13.49944062, 7.188333454, 8.290600696], 'GSM715885': [7.699255452, 21.18170217, 13.9009021, 7.478674426, 7.541270113], 'GSM715886': [7.844632744, 21.328099792, 14.50270895, 7.425757607, 9.068905985], 'GSM715887': [7.232842539, 21.268624722, 11.76765243, 7.230454103, 7.323105565], 'GSM715888': [7.545822084, 20.945850837000002, 13.24399428, 7.400273045, 7.41528032], 'GSM715889': [7.539958013, 21.158119622, 13.10943042, 7.22065998, 7.334521849], 'GSM715890': [7.782385734, 21.109217142, 12.86917595, 7.208619332, 7.48532806], 'GSM715891': [7.531429413, 21.255664041, 13.7789095, 7.299108018, 7.834953184], 'GSM715892': [7.106076682, 21.041989047, 13.79984947, 7.244201147, 8.52992836], 'GSM715893': [7.324180368, 20.714080329, 13.68232111, 7.199025479, 7.601192903], 'GSM715894': [8.042459363, 21.129429672, 12.64200689, 7.420803619, 7.221622995], 'GSM715895': [7.707909158, 20.822460108, 13.78949176, 7.281098464, 7.239006519], 'GSM715896': [7.700390235, 21.394259696, 13.47138908, 7.182194724, 7.128511812], 'GSM715897': [7.359120548, 21.096795749, 12.86831219, 7.211913517, 7.948913544], 'GSM715898': [7.653133102, 20.86832811, 13.36373743, 7.212683702, 8.046723036], 'GSM715899': [7.381122582, 21.565808536, 13.73415286, 7.134075092, 7.673921526], 'GSM715900': [7.508919381, 21.22594897, 13.78625726, 7.135997748, 8.79220885], 'GSM715901': [7.607381232, 21.288012462, 13.87272442, 7.238777883, 7.425694876], 'GSM715902': [7.659169576, 20.955071688, 13.63825729, 7.186743435, 7.579173274], 'GSM715903': [7.669637389, 21.377563143, 14.12620315, 6.99424754, 7.622603439], 'GSM715904': [7.475413931, 21.301802483, 13.87525641, 7.231787495, 7.206401343], 'GSM715905': [7.433977569, 21.408363108, 12.83591274, 7.276198042, 7.653249677], 'GSM715906': [7.46509501, 21.211119206, 13.41030118, 7.215241754, 7.490987675], 'GSM715907': [7.416377192, 21.027364797, 13.65957041, 7.310271724, 7.323552167], 'GSM715908': [7.760013948, 20.887586854, 13.5436495, 7.142329624, 7.462480711], 'GSM715909': [7.451292456, 21.076032203, 13.68474472, 7.154740748, 7.695662738], 'GSM715910': [7.748995485, 21.223680371, 13.92224086, 7.168179503, 7.542546125], 'GSM715911': [7.299829142, 21.165948257, 13.64912287, 7.152085125, 8.035706834], 'GSM715912': [7.675733437, 21.065406129, 13.97010166, 7.324215547, 8.048874431], 'GSM715913': [7.427993723, 21.254629241, 12.95668518, 7.122528963, 7.910118829], 'GSM715914': [7.692663663, 21.071878843, 13.86746811, 7.12217125, 7.505448288], 'GSM715915': [7.692432648, 21.213655434, 12.73096925, 7.247419182, 7.734865024], 'GSM715916': [7.782867133, 20.951088595, 13.29812693, 7.047850009, 7.49041566], 'GSM715917': [7.308086718, 20.983192706, 13.65178992, 7.168097946, 7.453694757], 'GSM715918': [7.408893456, 21.169463182, 14.07823557, 7.170332824, 8.345468742], 'GSM715919': [7.421329872, 21.12317298, 13.71704475, 7.139417207, 7.538278435], 'GSM715920': [7.8232231, 21.498628158, 13.54091901, 7.158728108, 7.451829281], 'GSM715921': [7.373193788, 20.949374249, 13.12983906, 7.209105189, 8.064323894], 'GSM715922': [7.832314227, 21.145253625, 13.40008847, 7.264342838, 8.200238686], 'GSM715923': [7.957495185, 21.298613967, 12.95605764, 7.179501884, 7.403764275], 'GSM715924': [7.556127341, 21.272388366999998, 13.41721555, 7.209596286, 7.895225642], 'GSM715925': [7.848742246, 20.995728237, 13.88595299, 7.227547774, 8.045309174], 'GSM715926': [7.896315674, 21.102942522, 13.63792815, 7.183427739, 8.174676645], 'GSM715927': [7.871461421, 21.336321948, 14.05353188, 7.144853575, 7.717909351], 'GSM715928': [7.949594535, 21.190638085, 13.64844753, 7.227331149, 8.433786604], 'GSM715929': [7.57439659, 21.148350953, 13.24724151, 7.140491446, 7.985021107], 'GSM715930': [7.454159715, 21.460738885, 12.68323127, 7.313569695, 7.907067634], 'GSM715931': [7.297496501, 21.324944031, 13.42700782, 7.329004673, 9.202581159], 'GSM715932': [7.376770539, 21.099541395, 13.4540232, 7.16650482, 8.254788615], 'GSM715933': [7.993078504, 21.239532403, 13.63456551, 7.262939359, 7.39097163], 'GSM715934': [7.560047019, 20.987922014, 13.81679855, 7.240061751, 7.401507352], 'GSM715935': [7.411614953, 21.2500738, 14.00564728, 7.144881767, 7.515477637], 'GSM715936': [7.496997775, 21.42553271, 13.41372695, 7.291503018, 7.338206956], 'GSM715937': [7.476091662, 21.043260817, 13.05845554, 7.05837902, 7.399591019], 'GSM715938': [7.874863944, 21.358644508, 13.34523934, 7.222540855, 7.561967423], 'GSM715939': [7.781836761, 21.170979868, 12.49730886, 7.21888024, 7.364776662], 'GSM715940': [7.142543848, 21.081589092999998, 13.23843091, 7.081178405, 7.82377491], 'GSM715941': [7.218709405, 20.989789669, 13.89142446, 7.286220884, 7.892099104], 'GSM715942': [7.695994299, 21.08277043, 14.12420859, 7.258924042, 7.747856581], 'GSM715943': [7.505209515, 21.111377512, 13.60697304, 7.414371057, 7.428901129]}\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene expression data saved to ../../output/preprocess/LDL_Cholesterol_Levels/gene_data/GSE28893.csv\n"
     ]
    }
   ],
   "source": [
    "# 1. Identify the columns for gene identifiers and gene symbols in the annotation data\n",
    "# From the gene annotation preview, we can see:\n",
    "# - 'ID' column contains Illumina probe IDs (ILMN_*) which match our gene expression data identifiers\n",
    "# - 'Symbol' column contains the standard human gene symbols we want to map to\n",
    "\n",
    "# 2. Extract the gene mapping dataframe (probe ID to gene symbol)\n",
    "prob_col = 'ID'\n",
    "gene_col = 'Symbol'\n",
    "gene_mapping = get_gene_mapping(gene_annotation, prob_col, gene_col)\n",
    "print(f\"Created gene mapping with {len(gene_mapping)} entries\")\n",
    "print(\"Gene mapping preview:\")\n",
    "print(preview_df(gene_mapping))\n",
    "\n",
    "# 3. Convert probe-level measurements to gene-level expression data\n",
    "# Apply the mapping to convert probe IDs to gene symbols\n",
    "gene_data = apply_gene_mapping(gene_data, gene_mapping)\n",
    "print(f\"Converted gene expression data from {len(gene_mapping)} probes to {len(gene_data)} unique genes\")\n",
    "print(\"Gene expression data preview (first 5 genes):\")\n",
    "print(preview_df(gene_data, 5))\n",
    "\n",
    "# Save the gene expression data to a CSV file\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"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0371e39d",
   "metadata": {},
   "source": [
    "### Step 7: Data Normalization and Linking"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "29c64f7b",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T07:27:46.246872Z",
     "iopub.status.busy": "2025-03-25T07:27:46.246749Z",
     "iopub.status.idle": "2025-03-25T07:27:46.974502Z",
     "shell.execute_reply": "2025-03-25T07:27:46.973865Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "Normalizing gene symbols...\n",
      "Loaded gene data with 17609 genes and 60 samples\n",
      "After normalization: 16991 genes\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Normalized gene data saved to ../../output/preprocess/LDL_Cholesterol_Levels/gene_data/GSE28893.csv\n",
      "\n",
      "Assessing clinical data availability...\n",
      "Required trait data (LDL_Cholesterol_Levels) is not available in the sample characteristics\n",
      "\n",
      "Performing final validation...\n",
      "Abnormality detected in the cohort: GSE28893. Preprocessing failed.\n",
      "\n",
      "Dataset usability for LDL_Cholesterol_Levels association studies: False\n",
      "Reason: Dataset does not contain required trait information (LDL_Cholesterol_Levels)\n"
     ]
    }
   ],
   "source": [
    "# 1. Normalize gene symbols in the gene expression data\n",
    "print(\"\\nNormalizing gene symbols...\")\n",
    "try:\n",
    "    # Load gene data that was saved in step 6\n",
    "    gene_data = pd.read_csv(out_gene_data_file, index_col=0)\n",
    "    print(f\"Loaded gene data with {gene_data.shape[0]} genes and {gene_data.shape[1]} samples\")\n",
    "    \n",
    "    # Normalize gene symbols using NCBI Gene database\n",
    "    gene_data = normalize_gene_symbols_in_index(gene_data)\n",
    "    print(f\"After normalization: {gene_data.shape[0]} genes\")\n",
    "    \n",
    "    # Save the normalized 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",
    "    is_gene_available = True\n",
    "except Exception as e:\n",
    "    print(f\"Error normalizing gene data: {e}\")\n",
    "    is_gene_available = False\n",
    "\n",
    "# 2. Clinical data analysis\n",
    "# Based on the review of sample characteristics in Step 1, \n",
    "# we observed the trait (LDL_Cholesterol_Levels) is not directly available\n",
    "print(\"\\nAssessing clinical data availability...\")\n",
    "# From Step 2, we determined:\n",
    "trait_row = None  # LDL_Cholesterol_Levels not directly available in sample characteristics\n",
    "age_row = 1  # Age is in row 1\n",
    "gender_row = 2  # Gender is in row 2\n",
    "\n",
    "is_trait_available = trait_row is not None\n",
    "\n",
    "# Skip clinical data extraction since trait is not available\n",
    "if not is_trait_available:\n",
    "    print(\"Required trait data (LDL_Cholesterol_Levels) is not available in the sample characteristics\")\n",
    "    selected_clinical_df = pd.DataFrame()\n",
    "    linked_data = pd.DataFrame()  # Empty dataframe since we can't link without trait data\n",
    "else:\n",
    "    # This block wouldn't execute but is kept for completeness\n",
    "    print(\"This dataset has trait information available\")\n",
    "\n",
    "# 3. Validate and save cohort information - final validation\n",
    "print(\"\\nPerforming final validation...\")\n",
    "note = \"Dataset does not contain required trait information (LDL_Cholesterol_Levels)\"\n",
    "\n",
    "# Create empty DataFrame as required by the validation function\n",
    "linked_data = pd.DataFrame()\n",
    "\n",
    "# For datasets without trait data, is_biased should be set to True\n",
    "# (as the absence of trait data makes it unusable for trait analysis)\n",
    "is_usable = validate_and_save_cohort_info(\n",
    "    is_final=True,\n",
    "    cohort=cohort,\n",
    "    info_path=json_path,\n",
    "    is_gene_available=is_gene_available,\n",
    "    is_trait_available=is_trait_available,\n",
    "    is_biased=True,  # Set to True when trait data is missing\n",
    "    df=linked_data,\n",
    "    note=note\n",
    ")\n",
    "\n",
    "# 4. Dataset is not usable for this trait, so we don't save linked data\n",
    "print(f\"\\nDataset usability for {trait} association studies: {is_usable}\")\n",
    "print(f\"Reason: {note}\")"
   ]
  }
 ],
 "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
}