File size: 51,430 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
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "9bc1273a",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T07:27:32.031387Z",
     "iopub.status.busy": "2025-03-25T07:27:32.031286Z",
     "iopub.status.idle": "2025-03-25T07:27:32.193013Z",
     "shell.execute_reply": "2025-03-25T07:27:32.192669Z"
    }
   },
   "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 = \"GSE181339\"\n",
    "\n",
    "# Input paths\n",
    "in_trait_dir = \"../../input/GEO/LDL_Cholesterol_Levels\"\n",
    "in_cohort_dir = \"../../input/GEO/LDL_Cholesterol_Levels/GSE181339\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/LDL_Cholesterol_Levels/GSE181339.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/LDL_Cholesterol_Levels/gene_data/GSE181339.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/LDL_Cholesterol_Levels/clinical_data/GSE181339.csv\"\n",
    "json_path = \"../../output/preprocess/LDL_Cholesterol_Levels/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "36bd6f5a",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "54c4c8e5",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T07:27:32.194411Z",
     "iopub.status.busy": "2025-03-25T07:27:32.194277Z",
     "iopub.status.idle": "2025-03-25T07:27:32.301632Z",
     "shell.execute_reply": "2025-03-25T07:27:32.301346Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Background Information:\n",
      "!Series_title\t\"Study of the usefulness of human peripheral blood mononuclear cells for the analysis of metabolic recovery after weight loss (METAHEALTH-TEST)\"\n",
      "!Series_summary\t\"The aim of this study is to design and validate a test, METAHEALTH-TEST, based on gene expression analysis in blood cells, to quickly and easily analyse metabolic health. This test will be used to analyse metabolic improvement in overweight/obese individuals and in metabolically obese normal-weight (MONW) individuals after undergoing a weight loss intervention and/or an intervention for improvement in eating habits and lifestyle. Obesity and its medical complications are a serious health problem today. Using peripheral blood mononuclear cells (PBMC) as an easily obtainable source of transcriptomic biomarkers would allow to deepen into the knowledge of adaptations in response to increased adiposity that occur in internal homeostatic tissues, without the need of using invasive biopsies. Moreover, if PBMC were able to reflect lipid metabolism gene expression pattern recovery as a result of weight loss, it would provide valuable information to know the efficacy of therapies aimed at weight loss and, in any case, it would allow to personalize them according to the evolution of obese patients until the desired metabolic recovery is achieved.\"\n",
      "!Series_overall_design\t\"Apparently healthy subjects aged 18 to 45 years old, including men and women were recruited and classified into two groups depending on their body mass index (BMI). Normal-weight (NW) group (BMI <25 kg/m2) was composed of 20 subjects and overweight-obese (OW-OB) group (BMI ≥25 kg/m2) of 27 subjects. The inclusion criteria were: subjects with no chronic disease who did not take regular medication or drugs. To avoid potential bias, both groups include approx. 50% men/women and there was no difference in their average age. We recruited 6 additional NW individuals presenting 1 metabolic alteration related to MetS (high plasma total or LDL-cholesterol, plasma triglycerides, or plasma C-reactive protein (CRP) concentrations, or hypertension). They were classified as  metabolically obese normal-weight (MONW) individuals. Subjects from the OW-OB group followed a 6-month weight loss program which included a low-calorie food plan (30% reduction in the individual energy requirements) with dietary sessions and exercise counselling. Dietary sessions were offered by a nutritionist every fifteen days who provided face-to-face counselling that was individually adjusted to each subject with the aim of reducing 5% to 10% of initial body weight. Neither dietary supplements nor vitamins were provided and all participants consumed self-selected foods. 20 out of the 27 OW-OB subjects who started the study completed the 6-month weight loss program. All the volunteers underwent what we called the fasting test which consisted of collecting blood samples after 4 and after 6 hours after having had a standard breakfast. The blood extractions were performed by skilled health personnel; once in the NW and MONW groups,and three times (at the baseline point, and after 3 and 6 months of nutritional intervention) in the OW-OB group. Blood was collected using Vacutainer® EDTA tubes. After blood collection, the samples were processed immediately to obtain the PBMC fraction. PBMC were isolated using Ficoll-Paque Plus density gradient media. Total RNA from PBMC samples was extracted using Tripure Reagent and then purified with E.Z.N.A. Total RNA Kit I and precipitated with isopropanol. Isolated RNA was quantified using a NanoDrop ND 1000 spectrophotometer. Its integrity was confirmed using agarose gel electrophoresis and the RIN tool using the Agilent 2100 Bioanalyzer System. For the microarray experiment the following samples were selected: 12 paired samples from the NW group after both 4h and 6h of fasting, 12 paired samples from the OW-OB group after both 4h and 6h of fasting, 12 paired samples from the OW-OB group after the 6-month weight loss programm after both 4h and 6h of fasting, and 6 samples from the MONW group after 6h of fasting at the beginning of the study. For final data analysis, 2 duplicate RNA samples were taken along and confirmed for reproducibility but excluded for overall analyses thereafter: US22502548_257236338304_S01_GE2_1200_Dec17_2_2.txt and US22502548_257236338312_S01_GE2_1200_Dec17_1_2.txt.\"\n",
      "Sample Characteristics Dictionary:\n",
      "{0: ['gender: Man', 'gender: Woman'], 1: ['group: NW', 'group: OW/OB', 'group: MONW'], 2: ['age: 21', 'age: 23', 'age: 10', 'age: 17', 'age: 11', 'age: 1', 'age: 18', 'age: 12', 'age: 8', 'age: 14', 'age: 26', 'age: 4', 'age: 2', 'age: 3', 'age: 7', 'age: 13', 'age: 15', 'age: 9', 'age: 30', 'age: 19'], 3: ['fasting time: 6hr', 'fasting time: 4hr'], 4: ['timepoint: 0months', 'timepoint: 6months']}\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": "8ea5d818",
   "metadata": {},
   "source": [
    "### Step 2: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "2becffb1",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T07:27:32.302778Z",
     "iopub.status.busy": "2025-03-25T07:27:32.302676Z",
     "iopub.status.idle": "2025-03-25T07:27:32.306791Z",
     "shell.execute_reply": "2025-03-25T07:27:32.306499Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Initial filtering for GSE181339 completed.\n",
      "is_gene_available: True\n",
      "is_trait_available: True\n"
     ]
    }
   ],
   "source": [
    "# Check gene expression data availability\n",
    "is_gene_available = True  # Based on the background info, the dataset includes gene expression data from PBMC\n",
    "\n",
    "# Identify the keys for trait, age, and gender data\n",
    "trait_row = 1  # Group (OW/OB vs NW/MONW) is related to LDL cholesterol levels\n",
    "age_row = 2    # Age is available in row 2\n",
    "gender_row = 0  # Gender is available in row 0\n",
    "\n",
    "# Convert trait function (binary: 1 for OW/OB, 0 for NW/MONW)\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",
    "    \n",
    "    if 'OW/OB' in value:\n",
    "        return 1  # Overweight/Obese is associated with higher LDL cholesterol\n",
    "    elif 'NW' in value or 'MONW' in value:\n",
    "        return 0  # Normal weight (includes metabolically obese normal weight)\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "# Convert age function (continuous)\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",
    "    \n",
    "    try:\n",
    "        return float(value)  # Convert to float for continuous variable\n",
    "    except:\n",
    "        return None\n",
    "\n",
    "# Convert gender function (binary: 0 for female, 1 for male)\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()\n",
    "    \n",
    "    if value.lower() == 'man':\n",
    "        return 1\n",
    "    elif value.lower() == 'woman':\n",
    "        return 0\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "# Check trait data availability\n",
    "is_trait_available = trait_row is not None\n",
    "\n",
    "# Save metadata for 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",
    "# Since we don't have the actual clinical_data.csv file available, \n",
    "# we'll skip the part where we would extract and save clinical features.\n",
    "# In a real scenario, we would load the file and process it.\n",
    "print(f\"Initial filtering for {cohort} completed.\")\n",
    "print(f\"is_gene_available: {is_gene_available}\")\n",
    "print(f\"is_trait_available: {is_trait_available}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "eda45653",
   "metadata": {},
   "source": [
    "### Step 3: Gene Data Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "4a7335af",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T07:27:32.307899Z",
     "iopub.status.busy": "2025-03-25T07:27:32.307798Z",
     "iopub.status.idle": "2025-03-25T07:27:32.474321Z",
     "shell.execute_reply": "2025-03-25T07:27:32.473928Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Examining matrix file structure...\n",
      "Line 0: !Series_title\t\"Study of the usefulness of human peripheral blood mononuclear cells for the analysis of metabolic recovery after weight loss (METAHEALTH-TEST)\"\n",
      "Line 1: !Series_geo_accession\t\"GSE181339\"\n",
      "Line 2: !Series_status\t\"Public on Oct 11 2023\"\n",
      "Line 3: !Series_submission_date\t\"Aug 02 2021\"\n",
      "Line 4: !Series_last_update_date\t\"Oct 12 2023\"\n",
      "Line 5: !Series_pubmed_id\t\"36564895\"\n",
      "Line 6: !Series_summary\t\"The aim of this study is to design and validate a test, METAHEALTH-TEST, based on gene expression analysis in blood cells, to quickly and easily analyse metabolic health. This test will be used to analyse metabolic improvement in overweight/obese individuals and in metabolically obese normal-weight (MONW) individuals after undergoing a weight loss intervention and/or an intervention for improvement in eating habits and lifestyle. Obesity and its medical complications are a serious health problem today. Using peripheral blood mononuclear cells (PBMC) as an easily obtainable source of transcriptomic biomarkers would allow to deepen into the knowledge of adaptations in response to increased adiposity that occur in internal homeostatic tissues, without the need of using invasive biopsies. Moreover, if PBMC were able to reflect lipid metabolism gene expression pattern recovery as a result of weight loss, it would provide valuable information to know the efficacy of therapies aimed at weight loss and, in any case, it would allow to personalize them according to the evolution of obese patients until the desired metabolic recovery is achieved.\"\n",
      "Line 7: !Series_overall_design\t\"Apparently healthy subjects aged 18 to 45 years old, including men and women were recruited and classified into two groups depending on their body mass index (BMI). Normal-weight (NW) group (BMI <25 kg/m2) was composed of 20 subjects and overweight-obese (OW-OB) group (BMI ≥25 kg/m2) of 27 subjects. The inclusion criteria were: subjects with no chronic disease who did not take regular medication or drugs. To avoid potential bias, both groups include approx. 50% men/women and there was no difference in their average age. We recruited 6 additional NW individuals presenting 1 metabolic alteration related to MetS (high plasma total or LDL-cholesterol, plasma triglycerides, or plasma C-reactive protein (CRP) concentrations, or hypertension). They were classified as  metabolically obese normal-weight (MONW) individuals. Subjects from the OW-OB group followed a 6-month weight loss program which included a low-calorie food plan (30% reduction in the individual energy requirements) with dietary sessions and exercise counselling. Dietary sessions were offered by a nutritionist every fifteen days who provided face-to-face counselling that was individually adjusted to each subject with the aim of reducing 5% to 10% of initial body weight. Neither dietary supplements nor vitamins were provided and all participants consumed self-selected foods. 20 out of the 27 OW-OB subjects who started the study completed the 6-month weight loss program. All the volunteers underwent what we called the fasting test which consisted of collecting blood samples after 4 and after 6 hours after having had a standard breakfast. The blood extractions were performed by skilled health personnel; once in the NW and MONW groups,and three times (at the baseline point, and after 3 and 6 months of nutritional intervention) in the OW-OB group. Blood was collected using Vacutainer® EDTA tubes. After blood collection, the samples were processed immediately to obtain the PBMC fraction. PBMC were isolated using Ficoll-Paque Plus density gradient media. Total RNA from PBMC samples was extracted using Tripure Reagent and then purified with E.Z.N.A. Total RNA Kit I and precipitated with isopropanol. Isolated RNA was quantified using a NanoDrop ND 1000 spectrophotometer. Its integrity was confirmed using agarose gel electrophoresis and the RIN tool using the Agilent 2100 Bioanalyzer System. For the microarray experiment the following samples were selected: 12 paired samples from the NW group after both 4h and 6h of fasting, 12 paired samples from the OW-OB group after both 4h and 6h of fasting, 12 paired samples from the OW-OB group after the 6-month weight loss programm after both 4h and 6h of fasting, and 6 samples from the MONW group after 6h of fasting at the beginning of the study. For final data analysis, 2 duplicate RNA samples were taken along and confirmed for reproducibility but excluded for overall analyses thereafter: US22502548_257236338304_S01_GE2_1200_Dec17_2_2.txt and US22502548_257236338312_S01_GE2_1200_Dec17_1_2.txt.\"\n",
      "Line 8: !Series_type\t\"Expression profiling by array\"\n",
      "Line 9: !Series_contributor\t\"Andrea,,Costa\"\n",
      "Found table marker at line 73\n",
      "First few lines after marker:\n",
      "\"ID_REF\"\t\"GSM5494930\"\t\"GSM5494931\"\t\"GSM5494932\"\t\"GSM5494933\"\t\"GSM5494934\"\t\"GSM5494935\"\t\"GSM5494936\"\t\"GSM5494937\"\t\"GSM5494938\"\t\"GSM5494939\"\t\"GSM5494940\"\t\"GSM5494941\"\t\"GSM5494942\"\t\"GSM5494943\"\t\"GSM5494944\"\t\"GSM5494945\"\t\"GSM5494946\"\t\"GSM5494947\"\t\"GSM5494948\"\t\"GSM5494949\"\t\"GSM5494950\"\t\"GSM5494951\"\t\"GSM5494952\"\t\"GSM5494953\"\t\"GSM5494954\"\t\"GSM5494955\"\t\"GSM5494956\"\t\"GSM5494957\"\t\"GSM5494958\"\t\"GSM5494959\"\t\"GSM5494960\"\t\"GSM5494961\"\t\"GSM5494962\"\t\"GSM5494963\"\t\"GSM5494964\"\t\"GSM5494965\"\t\"GSM5494966\"\t\"GSM5494967\"\t\"GSM5494968\"\t\"GSM5494969\"\t\"GSM5494970\"\t\"GSM5494971\"\t\"GSM5494972\"\t\"GSM5494973\"\t\"GSM5494974\"\t\"GSM5494975\"\t\"GSM5494976\"\t\"GSM5494977\"\t\"GSM5494978\"\t\"GSM5494979\"\t\"GSM5494980\"\t\"GSM5494981\"\t\"GSM5494982\"\t\"GSM5494983\"\t\"GSM5494984\"\t\"GSM5494985\"\t\"GSM5494986\"\t\"GSM5494987\"\t\"GSM5494988\"\t\"GSM5494989\"\t\"GSM5494990\"\t\"GSM5494991\"\t\"GSM5494992\"\t\"GSM5494993\"\t\"GSM5494994\"\t\"GSM5494995\"\t\"GSM5494996\"\t\"GSM5494997\"\t\"GSM5494998\"\t\"GSM5494999\"\t\"GSM5495000\"\t\"GSM5495001\"\t\"GSM5495002\"\t\"GSM5495003\"\t\"GSM5495004\"\t\"GSM5495005\"\t\"GSM5495006\"\t\"GSM5495007\"\n",
      "7\t5.505549\t5.513184\t4.986265\t5.34687\t5.531071\t4.848168\t5.063753\t5.133687\t6.971369\t6.581063\t6.469598\t5.972684\t6.124647\t6.603485\t6.154104\t5.799994\t5.810976\t5.77895\t6.282068\t6.155602\t5.558879\t5.939724\t6.169508\t6.012495\t6.112754\t7.05701\t5.948184\t6.253492\t6.145209\t5.873297\t5.690129\t5.779266\t5.888188\t5.961754\t6.492493\t6.25369\t5.762496\t6.533717\t6.394949\t6.339394\t5.587312\t6.414605\t6.227815\t5.955446\t6.09718\t5.887282\t6.382618\t6.040156\t6.512289\t6.364771\t6.644875\t5.944295\t6.149508\t6.268175\t6.119982\t5.892942\t6.201005\t5.974697\t5.374998\t5.398644\t5.082128\t5.600227\t5.983128\t6.103793\t6.101672\t5.884327\t6.097565\t5.773985\t5.930267\t5.864811\t6.180203\t6.302292\t6.279264\t6.346574\t7.841532\t6.446191\t6.009474\t5.820668\n",
      "8\t14.922929\t14.996884\t15.558723\t15.464692\t14.914828\t14.921011\t14.656432\t15.027612\t15.462935\t14.993909\t15.262447\t14.612335\t15.207867\t15.209807\t14.879528\t15.527347\t15.035588\t15.132298\t15.313993\t15.451625\t16.142666\t14.875801\t14.971059\t15.353953\t15.087346\t15.251997\t15.317115\t14.988095\t14.621997\t15.151247\t15.010133\t14.923497\t15.531133\t15.285224\t14.905221\t15.536831\t15.241272\t15.398222\t14.539708\t14.932713\t15.063128\t15.114803\t14.793398\t14.970698\t14.607143\t14.475372\t14.730024\t14.923804\t15.003395\t14.838272\t15.588068\t15.092851\t15.687654\t14.846865\t14.862714\t14.967665\t14.477184\t14.87888\t14.597994\t15.81092\t14.640387\t14.537613\t15.554037\t15.346956\t15.462577\t15.37509\t14.774837\t15.242668\t14.720862\t14.991377\t15.062609\t14.941717\t15.565374\t15.562799\t15.232485\t14.845854\t14.843489\t15.120225\n",
      "15\t10.185238\t9.826678\t9.003106\t10.440502\t8.448914\t9.775237\t9.587976\t8.860986\t8.913982\t9.646833\t10.130646\t10.07278\t9.5312\t10.056921\t9.89091\t10.155951\t8.51654\t8.487544\t10.189746\t9.988826\t10.365952\t8.605956\t10.177882\t10.472448\t8.998965\t9.911163\t10.197054\t8.886235\t8.612626\t8.770158\t8.633061\t10.037281\t10.283977\t9.320836\t8.594053\t9.014564\t10.037389\t9.049387\t9.82014\t9.758829\t10.146848\t9.087988\t10.340562\t10.208371\t10.087296\t9.855468\t9.341209\t10.067554\t10.364152\t10.210018\t9.980003\t8.712087\t8.903468\t9.975896\t9.198854\t8.65962\t8.284059\t9.87256\t10.199504\t9.99437\t9.590778\t9.83201\t8.999032\t10.486789\t9.552434\t8.732777\t9.096958\t10.16344\t9.531411\t9.13721\t10.327923\t9.672288\t9.841389\t9.210932\t9.74689\t8.812242\t8.95233\t8.907866\n",
      "18\t10.064262\t10.235713\t9.925906\t9.915432\t9.793022\t9.425392\t9.561722\t9.583471\t10.332012\t9.625713\t9.78245\t9.749461\t9.747383\t9.565639\t9.456456\t9.979806\t9.734987\t9.745968\t9.721762\t9.864293\t10.134593\t9.817755\t9.6036\t9.837126\t9.934213\t9.864634\t9.950142\t9.692286\t9.517572\t9.984704\t9.764962\t9.873304\t9.944047\t10.114367\t9.920472\t10.209765\t9.853772\t10.210892\t9.581328\t9.724865\t9.862105\t9.936256\t9.598453\t9.777438\t9.59766\t9.456882\t9.568474\t9.793513\t9.559975\t9.652655\t9.638011\t9.774169\t10.116939\t9.456399\t9.496144\t9.820175\t9.354549\t9.334237\t9.565438\t9.282867\t9.087564\t9.059908\t10.19391\t9.74297\t9.634186\t9.891539\t9.842507\t9.629963\t9.351078\t9.505807\t9.616248\t9.68966\t9.452713\t9.733175\t9.73394\t9.405109\t9.631529\t9.408484\n",
      "Total lines examined: 74\n",
      "\n",
      "Attempting to extract gene data from matrix file...\n",
      "Successfully extracted gene data with 22463 rows\n",
      "First 20 gene IDs:\n",
      "Index(['7', '8', '15', '18', '20', '21', '24', '25', '29', '32', '39', '41',\n",
      "       '42', '44', '45', '46', '48', '51', '53', '55'],\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": "db617be4",
   "metadata": {},
   "source": [
    "### Step 4: Gene Identifier Review"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "693b4756",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T07:27:32.475553Z",
     "iopub.status.busy": "2025-03-25T07:27:32.475437Z",
     "iopub.status.idle": "2025-03-25T07:27:32.477358Z",
     "shell.execute_reply": "2025-03-25T07:27:32.477072Z"
    }
   },
   "outputs": [],
   "source": [
    "# Examining the gene identifiers\n",
    "# The identifiers in this dataset are numeric values like '7', '8', '15', etc.\n",
    "# These are not standard human gene symbols (which would typically be like BRCA1, TP53, etc.)\n",
    "# These appear to be probe IDs from a microarray platform that need mapping to gene symbols\n",
    "\n",
    "# For Agilent microarrays (likely used here based on the file names in the metadata), \n",
    "# these would be probe IDs that require mapping to gene symbols\n",
    "\n",
    "requires_gene_mapping = True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b4b64d03",
   "metadata": {},
   "source": [
    "### Step 5: Gene Annotation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "1076e355",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T07:27:32.478461Z",
     "iopub.status.busy": "2025-03-25T07:27:32.478360Z",
     "iopub.status.idle": "2025-03-25T07:27:35.844716Z",
     "shell.execute_reply": "2025-03-25T07:27:35.844332Z"
    }
   },
   "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 1815168 rows\n",
      "\n",
      "Gene annotation preview (first few rows):\n",
      "{'ID': ['1', '2', '3', '4', '5'], 'COL': ['192', '192', '192', '192', '192'], 'ROW': [328.0, 326.0, 324.0, 322.0, 320.0], 'NAME': ['GE_BrightCorner', 'DarkCorner', 'DarkCorner', 'A_21_P0014386', 'A_33_P3396872'], 'SPOT_ID': ['GE_BrightCorner', 'DarkCorner', 'DarkCorner', 'A_21_P0014386', 'A_33_P3396872'], 'CONTROL_TYPE': ['pos', 'pos', 'pos', 'FALSE', 'FALSE'], 'REFSEQ': [nan, nan, nan, nan, 'NM_001105533'], 'GB_ACC': [nan, nan, nan, nan, 'NM_001105533'], 'LOCUSLINK_ID': [nan, nan, nan, nan, 79974.0], 'GENE_SYMBOL': [nan, nan, nan, nan, 'CPED1'], 'GENE_NAME': [nan, nan, nan, nan, 'cadherin-like and PC-esterase domain containing 1'], 'UNIGENE_ID': [nan, nan, nan, nan, 'Hs.189652'], 'ENSEMBL_ID': [nan, nan, nan, nan, nan], 'TIGR_ID': [nan, nan, nan, nan, nan], 'ACCESSION_STRING': [nan, nan, nan, nan, 'ref|NM_001105533|gb|AK025639|gb|BC030538|tc|THC2601673'], 'CHROMOSOMAL_LOCATION': [nan, nan, nan, 'unmapped', 'chr7:120901888-120901947'], 'CYTOBAND': [nan, nan, nan, nan, 'hs|7q31.31'], 'DESCRIPTION': [nan, nan, nan, nan, 'Homo sapiens cadherin-like and PC-esterase domain containing 1 (CPED1), transcript variant 2, mRNA [NM_001105533]'], 'GO_ID': [nan, nan, nan, nan, 'GO:0005783(endoplasmic reticulum)'], 'SEQUENCE': [nan, nan, nan, 'AATACATGTTTTGGTAAACACTCGGTCAGAGCACCCTCTTTCTGTGGAATCAGACTGGCA', 'GCTTATCTCACCTAATACAGGGACTATGCAACCAAGAAACTGGAAATAAAAACAAAGATA'], 'SPOT_ID.1': [nan, nan, nan, nan, nan]}\n",
      "\n",
      "Column names in gene annotation data:\n",
      "['ID', 'COL', 'ROW', 'NAME', 'SPOT_ID', 'CONTROL_TYPE', 'REFSEQ', 'GB_ACC', 'LOCUSLINK_ID', 'GENE_SYMBOL', 'GENE_NAME', 'UNIGENE_ID', 'ENSEMBL_ID', 'TIGR_ID', 'ACCESSION_STRING', 'CHROMOSOMAL_LOCATION', 'CYTOBAND', 'DESCRIPTION', 'GO_ID', 'SEQUENCE', 'SPOT_ID.1']\n",
      "\n",
      "The dataset contains GenBank accessions (GB_ACC) that could be used for gene mapping.\n",
      "Number of rows with GenBank accessions: 43063 out of 1815168\n",
      "\n",
      "The dataset contains genomic regions (SPOT_ID) that could be used for location-based gene mapping.\n",
      "Example SPOT_ID format: GE_BrightCorner\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": "f62ba7b7",
   "metadata": {},
   "source": [
    "### Step 6: Gene Identifier Mapping"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "10886054",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T07:27:35.846045Z",
     "iopub.status.busy": "2025-03-25T07:27:35.845912Z",
     "iopub.status.idle": "2025-03-25T07:27:36.075960Z",
     "shell.execute_reply": "2025-03-25T07:27:36.075577Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Creating gene mapping from ID to GENE_SYMBOL...\n",
      "Created mapping with 51544 entries\n",
      "\n",
      "Preview of gene mapping (first few rows):\n",
      "{'ID': ['5', '6', '7', '8', '12'], 'Gene': ['CPED1', 'BCOR', 'CHAC2', 'IFI30', 'GPR146']}\n",
      "\n",
      "Converting probe-level measurements to gene expression data...\n",
      "Generated gene expression data for 13263 genes across 78 samples\n",
      "\n",
      "Preview of gene expression data (first few genes):\n",
      "{'GSM5494930': [9.356389, 6.588705, 20.173181, 6.087023, 8.855058], 'GSM5494931': [9.580217, 6.861172, 17.179827, 5.95844, 8.172307], 'GSM5494932': [9.920784, 7.055549, 18.935323, 6.690681, 8.768802], 'GSM5494933': [9.504974, 6.792186, 15.861170000000001, 5.814862, 8.708854], 'GSM5494934': [9.533504, 7.192053, 19.192128, 5.822462, 8.534389], 'GSM5494935': [9.926714, 7.000017, 18.942311, 5.521768, 8.529483], 'GSM5494936': [10.22561, 7.219546, 17.853802, 5.832344, 8.113828], 'GSM5494937': [9.708488, 6.974349, 19.511087, 5.259415, 8.449762], 'GSM5494938': [9.759847, 7.343875, 16.303942, 6.574513, 8.988748], 'GSM5494939': [9.47079, 6.878397, 18.09518, 6.160754, 8.586938], 'GSM5494940': [9.301762, 7.038205, 17.974497, 6.521225, 8.397392], 'GSM5494941': [9.486415, 7.187312, 16.378500000000003, 6.461885, 8.413836], 'GSM5494942': [9.778403, 7.21115, 17.042836, 6.238289, 8.581843], 'GSM5494943': [9.639646, 7.304646, 16.089571, 6.407465, 8.790874], 'GSM5494944': [9.851406, 7.49419, 18.350989, 6.512684, 8.76262], 'GSM5494945': [9.491799, 6.960925, 16.011148, 6.193269, 8.102275], 'GSM5494946': [9.74283, 7.268229, 18.73379, 6.170744, 8.196657], 'GSM5494947': [9.549647, 7.324799, 18.078671, 6.462451, 8.491391], 'GSM5494948': [9.622837, 7.065253, 17.268362, 6.106689, 8.650949], 'GSM5494949': [9.513321, 6.537181, 16.843821000000002, 6.494337, 8.24583], 'GSM5494950': [9.743037, 7.081944, 14.209713, 5.779243, 8.632592], 'GSM5494951': [9.399325, 6.972205, 19.530254, 6.736743, 8.624784], 'GSM5494952': [9.735064, 6.907421, 18.805143, 6.331769, 8.829643], 'GSM5494953': [9.558283, 7.1352, 15.101119999999998, 6.808208, 8.675891], 'GSM5494954': [9.51678, 7.086544, 18.665492, 6.700143, 8.440068], 'GSM5494955': [9.607118, 7.182644, 17.058763, 6.621115, 8.737458], 'GSM5494956': [9.658808, 7.186418, 18.630422, 6.361554, 8.592055], 'GSM5494957': [9.494373, 7.346374, 19.983679000000002, 6.243052, 8.4665], 'GSM5494958': [9.691968, 7.132297, 18.352528, 6.490395, 8.479383], 'GSM5494959': [9.698231, 7.207859, 15.701426000000001, 6.101232, 8.737245], 'GSM5494960': [9.404548, 6.817162, 18.47748, 5.766225, 8.411443], 'GSM5494961': [9.304625, 7.278671, 18.377622000000002, 6.066413, 8.840154], 'GSM5494962': [9.482641, 7.370924, 14.59717, 6.810132, 8.550024], 'GSM5494963': [10.045286, 7.328169, 17.862781, 6.460326, 8.308073], 'GSM5494964': [9.711437, 7.129156, 17.464674, 6.317675, 8.644895], 'GSM5494965': [10.116942, 7.524096, 17.050591, 6.697627, 8.945281], 'GSM5494966': [8.947412, 6.438277, 18.909685, 6.374476, 8.574571], 'GSM5494967': [10.127205, 7.465297, 15.374077999999999, 7.18533, 9.344898], 'GSM5494968': [9.617403, 6.926085, 18.105584, 6.192621, 8.287652], 'GSM5494969': [9.551575, 7.278695, 19.657156999999998, 6.4287, 8.658957], 'GSM5494970': [9.606255, 7.154087, 18.554582, 6.113621, 8.742076], 'GSM5494971': [9.604029, 6.985805, 19.099449, 6.233673, 8.360106], 'GSM5494972': [9.407395, 7.201473, 19.230311, 6.256655, 8.639842], 'GSM5494973': [9.793409, 7.138982, 16.316110000000002, 6.633977, 8.721043], 'GSM5494974': [9.544266, 7.112893, 18.389977000000002, 6.339157, 8.460167], 'GSM5494975': [9.385533, 7.194303, 19.728878, 6.1674, 8.731697], 'GSM5494976': [10.29834, 7.475633, 17.943363, 6.099371, 8.660782], 'GSM5494977': [9.715398, 7.037935, 17.543459, 6.501769, 8.633853], 'GSM5494978': [9.482425, 7.020486, 20.177095, 6.57203, 8.603072], 'GSM5494979': [9.559322, 7.163986, 17.972496999999997, 6.842611, 8.500171], 'GSM5494980': [9.378919, 7.168739, 17.593228, 6.88236, 8.845056], 'GSM5494981': [10.055475, 7.379824, 17.102331, 6.221762, 8.787181], 'GSM5494982': [10.15919, 7.442457, 15.288854, 6.652704, 9.276813], 'GSM5494983': [9.994448, 7.276868, 16.793799, 6.648585, 8.802396], 'GSM5494984': [9.57273, 7.538716, 20.010534, 6.210924, 8.615408], 'GSM5494985': [9.994737, 7.454247, 18.365508, 6.189638, 8.6647], 'GSM5494986': [9.77491, 7.477437, 20.439484999999998, 6.054297, 8.972597], 'GSM5494987': [9.906497, 7.318392, 18.305521, 6.320098, 9.027577], 'GSM5494988': [9.914605, 7.104903, 17.122252000000003, 6.084417, 8.679564], 'GSM5494989': [10.072871, 7.321826, 13.62705, 6.028966, 8.708282], 'GSM5494990': [9.860987, 7.362111, 17.857756000000002, 5.725288, 9.020149], 'GSM5494991': [9.451344, 7.156343, 20.64152, 5.893008, 8.468242], 'GSM5494992': [9.980359, 7.782282, 15.234746, 6.534148, 9.807104], 'GSM5494993': [9.548148, 7.099076, 18.734581, 6.338871, 8.506818], 'GSM5494994': [9.342493, 6.950646, 19.717869, 6.175639, 8.842184], 'GSM5494995': [9.597727, 7.528876, 15.780026, 7.087084, 9.176563], 'GSM5494996': [9.482261, 7.279483, 20.529989999999998, 6.285192, 8.811751], 'GSM5494997': [9.680972, 7.026798, 18.546249, 5.851725, 8.490664], 'GSM5494998': [9.660515, 7.156529, 17.280807000000003, 6.127357, 8.59397], 'GSM5494999': [9.746332, 7.415667, 17.241833, 6.364952, 8.789716], 'GSM5495000': [9.346438, 6.886812, 19.899225, 6.492505, 8.413128], 'GSM5495001': [9.634528, 7.035713, 18.472963, 6.551022, 8.61698], 'GSM5495002': [9.404676, 7.473619, 18.465769, 6.204353, 8.656094], 'GSM5495003': [9.83897, 7.523552, 18.093965, 6.697867, 8.84868], 'GSM5495004': [9.807525, 7.071518, 17.998734, 6.329302, 8.45666], 'GSM5495005': [9.834407, 7.480286, 17.425105, 6.283686, 8.722496], 'GSM5495006': [9.777699, 7.482379, 19.405704999999998, 6.623779, 8.856997], 'GSM5495007': [10.079459, 7.548277, 17.48235, 6.797948, 8.62795]}\n",
      "\n",
      "Found 4 out of 5 common genes in the mapped data\n",
      "Found genes: ['TP53', 'BRCA1', 'TNF', 'APOE']\n",
      "\n",
      "Normalizing gene symbols...\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "After normalization: 12283 unique genes\n"
     ]
    }
   ],
   "source": [
    "# 1. Determine which columns to use for gene ID mapping\n",
    "# Based on gene_annotation preview, 'ID' column contains numeric identifiers matching gene expression IDs\n",
    "# 'GENE_SYMBOL' column contains the target gene symbols\n",
    "\n",
    "# Extract gene mapping from annotation using these columns\n",
    "print(\"Creating gene mapping from ID to GENE_SYMBOL...\")\n",
    "mapping_df = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='GENE_SYMBOL')\n",
    "print(f\"Created mapping with {len(mapping_df)} entries\")\n",
    "\n",
    "# Preview first few rows of the mapping\n",
    "print(\"\\nPreview of gene mapping (first few rows):\")\n",
    "print(preview_df(mapping_df.head()))\n",
    "\n",
    "# 2. Apply the gene mapping to convert probe-level measurements to gene expression\n",
    "print(\"\\nConverting probe-level measurements to gene expression data...\")\n",
    "gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)\n",
    "print(f\"Generated gene expression data for {len(gene_data.index)} genes across {len(gene_data.columns)} samples\")\n",
    "\n",
    "# 3. Preview the gene expression data\n",
    "print(\"\\nPreview of gene expression data (first few genes):\")\n",
    "print(preview_df(gene_data.head()))\n",
    "\n",
    "# 4. Check if the mapping was successful by looking at the presence of common gene symbols\n",
    "common_genes = ['TP53', 'BRCA1', 'TNF', 'IL6', 'APOE']\n",
    "found_genes = [gene for gene in common_genes if gene in gene_data.index]\n",
    "print(f\"\\nFound {len(found_genes)} out of {len(common_genes)} common genes in the mapped data\")\n",
    "if found_genes:\n",
    "    print(f\"Found genes: {found_genes}\")\n",
    "\n",
    "# Normalize gene symbols in index to ensure consistency\n",
    "print(\"\\nNormalizing gene symbols...\")\n",
    "gene_data = normalize_gene_symbols_in_index(gene_data)\n",
    "print(f\"After normalization: {len(gene_data.index)} unique genes\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "de3c9466",
   "metadata": {},
   "source": [
    "### Step 7: Data Normalization and Linking"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "3720c396",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T07:27:36.077375Z",
     "iopub.status.busy": "2025-03-25T07:27:36.077256Z",
     "iopub.status.idle": "2025-03-25T07:27:41.516510Z",
     "shell.execute_reply": "2025-03-25T07:27:41.516127Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "Saving normalized gene data...\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Normalized gene data saved to ../../output/preprocess/LDL_Cholesterol_Levels/gene_data/GSE181339.csv\n",
      "\n",
      "Extracting clinical data...\n",
      "Clinical data saved to ../../output/preprocess/LDL_Cholesterol_Levels/clinical_data/GSE181339.csv\n",
      "Clinical data shape: (3, 78)\n",
      "Trait information available: True\n",
      "\n",
      "Linking clinical and genetic data...\n",
      "Created linked data with 78 samples and 12286 features\n",
      "\n",
      "Handling missing values...\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "After handling missing values: 78 samples and 12286 features\n",
      "\n",
      "Evaluating feature bias...\n",
      "For the feature 'LDL_Cholesterol_Levels', the least common label is '0.0' with 30 occurrences. This represents 38.46% of the dataset.\n",
      "The distribution of the feature 'LDL_Cholesterol_Levels' in this dataset is fine.\n",
      "\n",
      "Quartiles for 'Age':\n",
      "  25%: 8.0\n",
      "  50% (Median): 11.0\n",
      "  75%: 18.75\n",
      "Min: 1.0\n",
      "Max: 30.0\n",
      "The distribution of the feature 'Age' in this dataset is fine.\n",
      "\n",
      "For the feature 'Gender', the least common label is '1.0' with 39 occurrences. This represents 50.00% of the dataset.\n",
      "The distribution of the feature 'Gender' in this dataset is fine.\n",
      "\n",
      "Trait bias determination: False\n",
      "Final linked data shape: 78 samples and 12286 features\n",
      "\n",
      "Performing final validation...\n",
      "\n",
      "Dataset usability for LDL_Cholesterol_Levels association studies: True\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Final linked data saved to ../../output/preprocess/LDL_Cholesterol_Levels/GSE181339.csv\n"
     ]
    }
   ],
   "source": [
    "# 1. Save the normalized gene expression data from the previous step\n",
    "print(\"\\nSaving 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",
    "# 2. Extract clinical data from the matrix file\n",
    "print(\"\\nExtracting clinical data...\")\n",
    "try:\n",
    "    # Get the file paths again to make sure we have them\n",
    "    soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
    "    \n",
    "    # Extract background information and clinical data\n",
    "    background_info, clinical_data = get_background_and_clinical_data(\n",
    "        matrix_file, \n",
    "        prefixes_a=['!Series_title', '!Series_summary', '!Series_overall_design'],\n",
    "        prefixes_b=['!Sample_geo_accession', '!Sample_characteristics_ch1']\n",
    "    )\n",
    "    \n",
    "    # Process clinical data using trait information from Step 2\n",
    "    trait_row = 1  # Based on analysis in step 2 - group (OW/OB vs NW/MONW)\n",
    "    gender_row = 0  # Gender data\n",
    "    age_row = 2     # Age data\n",
    "    \n",
    "    # Define conversion functions based on Step 2\n",
    "    def convert_trait(value):\n",
    "        \"\"\"Convert trait value (binary: 1 for OW/OB, 0 for NW/MONW)\"\"\"\n",
    "        if pd.isna(value):\n",
    "            return None\n",
    "        \n",
    "        # Extract value after colon if present\n",
    "        if ':' in value:\n",
    "            value = value.split(':', 1)[1].strip()\n",
    "        \n",
    "        if 'OW/OB' in value:\n",
    "            return 1  # Overweight/Obese is associated with higher LDL cholesterol\n",
    "        elif 'NW' in value or 'MONW' in value:\n",
    "            return 0  # Normal weight (includes metabolically obese normal weight)\n",
    "        else:\n",
    "            return None\n",
    "\n",
    "    def convert_gender(value):\n",
    "        \"\"\"Convert gender value to binary (0: female, 1: male)\"\"\"\n",
    "        if pd.isna(value):\n",
    "            return None\n",
    "        \n",
    "        # Extract value after colon if present\n",
    "        if ':' in value:\n",
    "            value = value.split(':', 1)[1].strip()\n",
    "        \n",
    "        # Convert gender\n",
    "        if value.lower() == 'woman':\n",
    "            return 0\n",
    "        elif value.lower() == 'man':\n",
    "            return 1\n",
    "        else:\n",
    "            return None\n",
    "    \n",
    "    def convert_age(value):\n",
    "        \"\"\"Convert age value to float\"\"\"\n",
    "        if pd.isna(value):\n",
    "            return None\n",
    "        \n",
    "        # Extract value after colon if present\n",
    "        if ':' in value:\n",
    "            value = value.split(':', 1)[1].strip()\n",
    "        \n",
    "        try:\n",
    "            return float(value)  # Convert to float for continuous variable\n",
    "        except:\n",
    "            return None\n",
    "    \n",
    "    # Extract clinical features\n",
    "    selected_clinical_df = geo_select_clinical_features(\n",
    "        clinical_df=clinical_data,\n",
    "        trait=trait,\n",
    "        trait_row=trait_row,\n",
    "        convert_trait=convert_trait,\n",
    "        age_row=age_row,\n",
    "        convert_age=convert_age,\n",
    "        gender_row=gender_row,\n",
    "        convert_gender=convert_gender\n",
    "    )\n",
    "    \n",
    "    # Save the 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",
    "    print(f\"Clinical data shape: {selected_clinical_df.shape}\")\n",
    "    \n",
    "    # Check if we have valid trait information\n",
    "    is_trait_available = trait_row is not None and not selected_clinical_df.loc[trait].isnull().all()\n",
    "    print(f\"Trait information available: {is_trait_available}\")\n",
    "    \n",
    "except Exception as e:\n",
    "    print(f\"Error extracting clinical data: {e}\")\n",
    "    is_trait_available = False\n",
    "    selected_clinical_df = pd.DataFrame()\n",
    "\n",
    "# 3. Link clinical and genetic data\n",
    "print(\"\\nLinking clinical and genetic data...\")\n",
    "try:\n",
    "    if is_trait_available and not selected_clinical_df.empty:\n",
    "        # Link clinical and genetic data\n",
    "        linked_data = geo_link_clinical_genetic_data(selected_clinical_df, gene_data)\n",
    "        print(f\"Created linked data with {linked_data.shape[0]} samples and {linked_data.shape[1]} features\")\n",
    "    else:\n",
    "        print(\"Cannot link data: clinical data is not available\")\n",
    "        linked_data = pd.DataFrame()\n",
    "        is_trait_available = False\n",
    "except Exception as e:\n",
    "    print(f\"Error linking clinical and genetic data: {e}\")\n",
    "    is_trait_available = False\n",
    "    linked_data = pd.DataFrame()\n",
    "\n",
    "# 4. Handle missing values in the linked data\n",
    "if is_trait_available and not linked_data.empty:\n",
    "    print(\"\\nHandling missing values...\")\n",
    "    try:\n",
    "        # Rename the first column to the trait name for consistency\n",
    "        if linked_data.columns[0] != trait:\n",
    "            linked_data = linked_data.rename(columns={linked_data.columns[0]: trait})\n",
    "        \n",
    "        linked_data = handle_missing_values(linked_data, trait)\n",
    "        print(f\"After handling missing values: {linked_data.shape[0]} samples and {linked_data.shape[1]} features\")\n",
    "    except Exception as e:\n",
    "        print(f\"Error handling missing values: {e}\")\n",
    "        \n",
    "    # 5. Determine whether the trait and demographic features are biased\n",
    "    print(\"\\nEvaluating feature bias...\")\n",
    "    try:\n",
    "        is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n",
    "        print(f\"Trait bias determination: {is_biased}\")\n",
    "        print(f\"Final linked data shape: {linked_data.shape[0]} samples and {linked_data.shape[1]} features\")\n",
    "    except Exception as e:\n",
    "        print(f\"Error evaluating feature bias: {e}\")\n",
    "        is_biased = True\n",
    "else:\n",
    "    print(\"\\nSkipping missing value handling and bias evaluation as linked data is not available\")\n",
    "    is_biased = True\n",
    "\n",
    "# 6. Validate and save cohort information\n",
    "print(\"\\nPerforming final validation...\")\n",
    "note = \"\"\n",
    "if not is_trait_available:\n",
    "    note = \"Dataset does not contain required trait information\"\n",
    "elif is_biased:\n",
    "    note = \"Dataset has severe bias in the trait distribution\"\n",
    "\n",
    "is_usable = validate_and_save_cohort_info(\n",
    "    is_final=True,\n",
    "    cohort=cohort,\n",
    "    info_path=json_path,\n",
    "    is_gene_available=is_gene_available,\n",
    "    is_trait_available=is_trait_available,\n",
    "    is_biased=is_biased,\n",
    "    df=linked_data,\n",
    "    note=note\n",
    ")\n",
    "\n",
    "# 7. Save the linked data if usable\n",
    "print(f\"\\nDataset usability for {trait} association studies: {is_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\"Final linked data saved to {out_data_file}\")\n",
    "else:\n",
    "    if note:\n",
    "        print(f\"Reason: {note}\")\n",
    "    else:\n",
    "        print(\"Dataset does not meet quality criteria for the specified trait\")"
   ]
  }
 ],
 "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
}