File size: 50,287 Bytes
82732bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "623427dd",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:12:11.350220Z",
     "iopub.status.busy": "2025-03-25T05:12:11.350066Z",
     "iopub.status.idle": "2025-03-25T05:12:11.526085Z",
     "shell.execute_reply": "2025-03-25T05:12:11.525707Z"
    }
   },
   "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 = \"Esophageal_Cancer\"\n",
    "cohort = \"GSE107754\"\n",
    "\n",
    "# Input paths\n",
    "in_trait_dir = \"../../input/GEO/Esophageal_Cancer\"\n",
    "in_cohort_dir = \"../../input/GEO/Esophageal_Cancer/GSE107754\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/Esophageal_Cancer/GSE107754.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/Esophageal_Cancer/gene_data/GSE107754.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/Esophageal_Cancer/clinical_data/GSE107754.csv\"\n",
    "json_path = \"../../output/preprocess/Esophageal_Cancer/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "29d265d4",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "97b38726",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:12:11.527632Z",
     "iopub.status.busy": "2025-03-25T05:12:11.527454Z",
     "iopub.status.idle": "2025-03-25T05:12:11.838225Z",
     "shell.execute_reply": "2025-03-25T05:12:11.837829Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Background Information:\n",
      "!Series_title\t\"A novel genomic signature predicting FDG uptake in diverse metastatic tumors\"\n",
      "!Series_summary\t\"Purpose: Building a universal genomic signature predicting the intensity of FDG uptake in diverse metastatic tumors may allow us to understand better the biological processes underlying this phenomenon and their requirements of glucose uptake.\"\n",
      "!Series_summary\t\"Methods: A balanced training set (n=71) of metastatic tumors including some of the most frequent histologies, with matched PET/CT quantification measurements and whole human genome gene expression microarrays, was used to build the signature. Selection of microarray features was carried out exclusively on the basis of their strong association with FDG uptake (as measured by SUVmean35) by means of univariate linear regression. A thorough bioinformatics study of these genes was performed and multivariable models were built by fitting several state of the art regression techniques to the training set for comparison.\"\n",
      "!Series_summary\t\"Results: The 909 probes with the strongest association with the SUVmean35 (comprising 742 identifiable genes and 62 probes not matched to a symbol) were used to build the signature. Partial Least Squares using 3 components (PLS-3) was the best performing model in the training dataset cross-validation (Root Mean Square Error, RMSE=0.443) and was validated further in an independent validation dataset (n=13) obtaining a performance within the 95% CI of that obtained in the training dataset (RMSE=0.645). Significantly overrepresented biological processes correlating with the SUVmean35 were identified beyond glycolysis, such as ribosome biogenesis and DNA replication (correlating with a higher SUVmean35), and cytoskeleton reorganization and autophagy (correlating with a lower SUVmean35), among others.\"\n",
      "!Series_summary\t\"Conclusions: PLS-3 is a signature predicting accurately the intensity of FDG uptake in diverse metastatic tumors. FDG-PET might help in the design of specific targeted therapies directed to counteract the identified malignant biological processes more likely activated in a tumor as inferred from the SUVmean35 and also from its variations in response to antineoplastic treatments.\"\n",
      "!Series_overall_design\t\"Whole human genome microarrays from biopsies of human metastatic tumors (71 patients) with matched SUVmean35 measurements, this submission includes the 71 patients of the training set used to build the genomic signature predicting FDG uptake in diverse metastatic tumors. This dataset is complemented with a validation set comprised of 13 patients.\"\n",
      "Sample Characteristics Dictionary:\n",
      "{0: ['gender: Male', 'gender: Female'], 1: ['dataset: Validation set', 'dataset: Training set'], 2: ['biopsy location: Lung', 'biopsy location: Lymph node', 'biopsy location: Primary', 'biopsy location: Liver', 'biopsy location: Retroperitoneal implant', 'tissue: Pancreatic cancer', 'tissue: Esophagus cancer', 'tissue: Breast cancer', 'tissue: Colorectal cancer', 'tissue: Ovarian cancer', 'tissue: Head&neck cancer', 'tissue: Lung cancer', 'tissue: Malignant Melanoma', 'tissue: Endometrial cancer', 'tissue: Cervix cancer', 'tissue: Soft tissue sarcoma', 'tissue: Gastric cancer', 'tissue: Unknown primary', 'tissue: Malignant Mesothelioma', 'tissue: Thyroid cancer', 'tissue: Testes cancer', 'tissue: Non Hodgkin lymphoma', 'tissue: Merkel cell carcinoma', 'tissue: Vaginal cancer', 'tissue: Kidney cancer', 'tissue: Cervical cancer', 'tissue: Bile duct cancer', 'tissue: Urothelial cancer'], 3: ['suvmean35: 4.09', 'suvmean35: 8.36', 'suvmean35: 5.18', 'suvmean35: 10.74', 'suvmean35: 8.62', 'suvmean35: 8.02', 'suvmean35: 6.87', 'suvmean35: 4.93', 'suvmean35: 1.96', 'suvmean35: 8.83', 'suvmean35: 3.96', 'suvmean35: 3.38', 'suvmean35: 9.95', 'suvmean35: 5.19', 'suvmean35: 7.22', 'suvmean35: 5.02', 'suvmean35: 4.92', 'suvmean35: 4.99', 'suvmean35: 4.01', 'suvmean35: 2.52', 'suvmean35: 5.52', 'suvmean35: 8.38', 'suvmean35: 3.46', 'suvmean35: 4.07', 'suvmean35: 4.67', 'suvmean35: 7.09', 'suvmean35: 4.83', 'suvmean35: 6.7', 'suvmean35: 3.95', 'suvmean35: 5.03']}\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": "5a9e4ef9",
   "metadata": {},
   "source": [
    "### Step 2: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "1bb1361a",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:12:11.840005Z",
     "iopub.status.busy": "2025-03-25T05:12:11.839879Z",
     "iopub.status.idle": "2025-03-25T05:12:11.856307Z",
     "shell.execute_reply": "2025-03-25T05:12:11.855962Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Preview of clinical features: {0: [0.0, 1.0], 1: [0.0, 0.0], 2: [0.0, nan], 3: [0.0, nan], 4: [0.0, nan], 5: [0.0, nan], 6: [1.0, nan], 7: [0.0, nan], 8: [0.0, nan], 9: [0.0, nan], 10: [0.0, nan], 11: [0.0, nan], 12: [0.0, nan], 13: [0.0, nan], 14: [0.0, nan], 15: [0.0, nan], 16: [0.0, nan], 17: [0.0, nan], 18: [0.0, nan], 19: [0.0, nan], 20: [0.0, nan], 21: [0.0, nan], 22: [0.0, nan], 23: [0.0, nan], 24: [0.0, nan], 25: [0.0, nan], 26: [0.0, nan], 27: [0.0, nan], 28: [nan, nan], 29: [nan, nan]}\n",
      "Clinical data saved to: ../../output/preprocess/Esophageal_Cancer/clinical_data/GSE107754.csv\n"
     ]
    }
   ],
   "source": [
    "import pandas as pd\n",
    "import os\n",
    "import re\n",
    "import json\n",
    "from typing import Optional, Callable, Dict, Any\n",
    "\n",
    "# 1. Analyze gene expression data availability\n",
    "# Based on the background information, this appears to be gene expression microarray data\n",
    "# The series summary mentions \"whole human genome gene expression microarrays\"\n",
    "is_gene_available = True\n",
    "\n",
    "# 2. Analyze clinical features\n",
    "# 2.1 Data Availability\n",
    "# For trait - Esophageal Cancer, look at row 2 where tissue types are mentioned\n",
    "trait_row = 2  # Row containing tissue information\n",
    "\n",
    "# For gender, it's in row 0\n",
    "gender_row = 0  # Row containing gender information\n",
    "\n",
    "# For age, I don't see age information in the sample characteristics\n",
    "age_row = None  # Age data not available\n",
    "\n",
    "# 2.2 Data Type Conversion functions\n",
    "def convert_trait(value):\n",
    "    \"\"\"Convert tissue type to binary for Esophageal Cancer.\"\"\"\n",
    "    if pd.isna(value) or not isinstance(value, str):\n",
    "        return None\n",
    "    \n",
    "    # Extract the value after colon\n",
    "    match = re.search(r':\\s*(.+)', value)\n",
    "    if not match:\n",
    "        return None\n",
    "    \n",
    "    tissue_value = match.group(1).strip().lower()\n",
    "    \n",
    "    # Check if it's esophageal cancer (binary classification)\n",
    "    if 'esophagus cancer' in tissue_value:\n",
    "        return 1\n",
    "    else:\n",
    "        return 0\n",
    "\n",
    "def convert_gender(value):\n",
    "    \"\"\"Convert gender to binary (0 for female, 1 for male).\"\"\"\n",
    "    if pd.isna(value) or not isinstance(value, str):\n",
    "        return None\n",
    "    \n",
    "    # Extract the value after colon\n",
    "    match = re.search(r':\\s*(.+)', value)\n",
    "    if not match:\n",
    "        return None\n",
    "    \n",
    "    gender_value = match.group(1).strip().lower()\n",
    "    \n",
    "    if 'female' in gender_value:\n",
    "        return 0\n",
    "    elif 'male' in gender_value:\n",
    "        return 1\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "def convert_age(value):\n",
    "    \"\"\"Placeholder function for age conversion (not used as age is not available).\"\"\"\n",
    "    return None\n",
    "\n",
    "# 3. Save metadata for initial filtering\n",
    "# Trait data is available if trait_row is not None\n",
    "is_trait_available = trait_row is not None\n",
    "\n",
    "# Initial validation\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. Extract clinical features if trait data is available\n",
    "if trait_row is not None:\n",
    "    # Load or create clinical data in the correct format\n",
    "    # The sample characteristics dictionary is not in the right format for direct conversion to DataFrame\n",
    "    # We need to find an existing clinical data file or properly structure the data\n",
    "    \n",
    "    clinical_data_path = os.path.join(in_cohort_dir, \"clinical_data.csv\")\n",
    "    \n",
    "    if os.path.exists(clinical_data_path):\n",
    "        clinical_data = pd.read_csv(clinical_data_path)\n",
    "    else:\n",
    "        # Create a proper DataFrame structure where columns are samples and rows are features\n",
    "        # Assuming we need to create it from the sample_dict\n",
    "        sample_dict = {\n",
    "            0: ['gender: Male', 'gender: Female'],\n",
    "            1: ['dataset: Validation set', 'dataset: Training set'],\n",
    "            2: ['biopsy location: Lung', 'biopsy location: Lymph node', 'biopsy location: Primary', \n",
    "                'biopsy location: Liver', 'biopsy location: Retroperitoneal implant', \n",
    "                'tissue: Pancreatic cancer', 'tissue: Esophagus cancer', 'tissue: Breast cancer', \n",
    "                'tissue: Colorectal cancer', 'tissue: Ovarian cancer', 'tissue: Head&neck cancer', \n",
    "                'tissue: Lung cancer', 'tissue: Malignant Melanoma', 'tissue: Endometrial cancer', \n",
    "                'tissue: Cervix cancer', 'tissue: Soft tissue sarcoma', 'tissue: Gastric cancer', \n",
    "                'tissue: Unknown primary', 'tissue: Malignant Mesothelioma', 'tissue: Thyroid cancer', \n",
    "                'tissue: Testes cancer', 'tissue: Non Hodgkin lymphoma', 'tissue: Merkel cell carcinoma', \n",
    "                'tissue: Vaginal cancer', 'tissue: Kidney cancer', 'tissue: Cervical cancer', \n",
    "                'tissue: Bile duct cancer', 'tissue: Urothelial cancer'],\n",
    "            3: ['suvmean35: 4.09', 'suvmean35: 8.36', 'suvmean35: 5.18', 'suvmean35: 10.74', \n",
    "                'suvmean35: 8.62', 'suvmean35: 8.02', 'suvmean35: 6.87', 'suvmean35: 4.93', \n",
    "                'suvmean35: 1.96', 'suvmean35: 8.83', 'suvmean35: 3.96', 'suvmean35: 3.38', \n",
    "                'suvmean35: 9.95', 'suvmean35: 5.19', 'suvmean35: 7.22', 'suvmean35: 5.02', \n",
    "                'suvmean35: 4.92', 'suvmean35: 4.99', 'suvmean35: 4.01', 'suvmean35: 2.52', \n",
    "                'suvmean35: 5.52', 'suvmean35: 8.38', 'suvmean35: 3.46', 'suvmean35: 4.07', \n",
    "                'suvmean35: 4.67', 'suvmean35: 7.09', 'suvmean35: 4.83', 'suvmean35: 6.7', \n",
    "                'suvmean35: 3.95', 'suvmean35: 5.03']\n",
    "        }\n",
    "        \n",
    "        # Create an index of feature rows\n",
    "        index = list(sample_dict.keys())\n",
    "        \n",
    "        # Find the maximum number of samples (columns) needed\n",
    "        max_cols = max(len(values) for values in sample_dict.values())\n",
    "        \n",
    "        # Create an empty DataFrame with the right dimensions\n",
    "        clinical_data = pd.DataFrame(index=index, columns=range(max_cols))\n",
    "        \n",
    "        # Fill in the DataFrame\n",
    "        for row, values in sample_dict.items():\n",
    "            for col, value in enumerate(values):\n",
    "                clinical_data.loc[row, col] = value\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",
    "        gender_row=gender_row,\n",
    "        convert_gender=convert_gender,\n",
    "        age_row=age_row,\n",
    "        convert_age=convert_age\n",
    "    )\n",
    "    \n",
    "    # Preview the extracted features\n",
    "    preview = preview_df(clinical_features)\n",
    "    print(f\"Preview of clinical features: {preview}\")\n",
    "    \n",
    "    # Save the processed clinical data\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",
    "    print(f\"Clinical data saved to: {out_clinical_data_file}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0d90ddac",
   "metadata": {},
   "source": [
    "### Step 3: Gene Data Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "9c983200",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:12:11.857634Z",
     "iopub.status.busy": "2025-03-25T05:12:11.857517Z",
     "iopub.status.idle": "2025-03-25T05:12:12.263518Z",
     "shell.execute_reply": "2025-03-25T05:12:12.263174Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Found data marker at line 74\n",
      "Header line: \"ID_REF\"\t\"GSM2878070\"\t\"GSM2878071\"\t\"GSM2878072\"\t\"GSM2878073\"\t\"GSM2878074\"\t\"GSM2878075\"\t\"GSM2878076\"\t\"GSM2878077\"\t\"GSM2878078\"\t\"GSM2878079\"\t\"GSM2878080\"\t\"GSM2878081\"\t\"GSM2878082\"\t\"GSM2891194\"\t\"GSM2891195\"\t\"GSM2891196\"\t\"GSM2891197\"\t\"GSM2891198\"\t\"GSM2891199\"\t\"GSM2891200\"\t\"GSM2891201\"\t\"GSM2891202\"\t\"GSM2891203\"\t\"GSM2891204\"\t\"GSM2891205\"\t\"GSM2891206\"\t\"GSM2891207\"\t\"GSM2891208\"\t\"GSM2891209\"\t\"GSM2891210\"\t\"GSM2891211\"\t\"GSM2891212\"\t\"GSM2891213\"\t\"GSM2891214\"\t\"GSM2891215\"\t\"GSM2891216\"\t\"GSM2891217\"\t\"GSM2891218\"\t\"GSM2891219\"\t\"GSM2891220\"\t\"GSM2891221\"\t\"GSM2891222\"\t\"GSM2891223\"\t\"GSM2891224\"\t\"GSM2891225\"\t\"GSM2891226\"\t\"GSM2891227\"\t\"GSM2891228\"\t\"GSM2891229\"\t\"GSM2891230\"\t\"GSM2891231\"\t\"GSM2891232\"\t\"GSM2891233\"\t\"GSM2891234\"\t\"GSM2891235\"\t\"GSM2891236\"\t\"GSM2891237\"\t\"GSM2891238\"\t\"GSM2891239\"\t\"GSM2891240\"\t\"GSM2891241\"\t\"GSM2891242\"\t\"GSM2891243\"\t\"GSM2891244\"\t\"GSM2891245\"\t\"GSM2891246\"\t\"GSM2891247\"\t\"GSM2891248\"\t\"GSM2891249\"\t\"GSM2891250\"\t\"GSM2891251\"\t\"GSM2891252\"\t\"GSM2891253\"\t\"GSM2891254\"\t\"GSM2891255\"\t\"GSM2891256\"\t\"GSM2891257\"\t\"GSM2891258\"\t\"GSM2891259\"\t\"GSM2891260\"\t\"GSM2891261\"\t\"GSM2891262\"\t\"GSM2891263\"\t\"GSM2891264\"\n",
      "First data line: \"A_23_P100001\"\t9.573244642\t9.298651171\t10.77599722\t11.00185427\t9.95489404\t10.47234414\t10.36470678\t11.29547995\t10.6379278\t12.59984726\t9.441342686\t9.411939603\t11.10415919\t10.69280947\t10.21081919\t11.18560381\t13.0405095\t12.63050537\t12.28075271\t8.887157917\t10.98167311\t11.10697503\t10.20069523\t10.50192028\t10.71215514\t12.22059826\t11.40980119\t10.29921193\t10.02228522\t10.20111345\t10.70147544\t8.652688571\t10.73582686\t10.59802642\t10.30502944\t10.15381209\t10.92708466\t11.16442513\t10.8438334\t12.74815701\t11.22011517\t10.52200921\t9.268506372\t9.918579617\t10.11228179\t13.21834905\t9.820645381\t10.57072742\t10.73195927\t9.946199692\t10.09127387\t11.41043888\t9.644003704\t9.212649281\t12.50538835\t9.993892741\t11.75190015\t11.25805045\t11.4339889\t12.29500316\t10.91652064\t11.72956311\t11.74664518\t10.03651693\t9.316040132\t10.35883285\t12.00354988\t12.47704263\t10.71443489\t10.62737159\t10.13220636\t8.54273083\t10.27193153\t10.82911329\t10.70459762\t12.0410874\t10.43479019\t11.85550831\t9.884177813\t11.57649029\t10.8692247\t8.96839008\t10.99250487\t12.28805295\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Index(['A_23_P100001', 'A_23_P100011', 'A_23_P100022', 'A_23_P100056',\n",
      "       'A_23_P100074', 'A_23_P100092', 'A_23_P100103', 'A_23_P100111',\n",
      "       'A_23_P100127', 'A_23_P100133', 'A_23_P100141', 'A_23_P100156',\n",
      "       'A_23_P100177', 'A_23_P100189', 'A_23_P100196', 'A_23_P100203',\n",
      "       'A_23_P100220', 'A_23_P100240', 'A_23_P10025', 'A_23_P100263'],\n",
      "      dtype='object', name='ID')\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",
    "# 2. First, let's examine the structure of the matrix file to understand its format\n",
    "import gzip\n",
    "\n",
    "# Peek at the first few lines of the file to understand its structure\n",
    "with gzip.open(matrix_file, 'rt') as file:\n",
    "    # Read first 100 lines to find the header structure\n",
    "    for i, line in enumerate(file):\n",
    "        if '!series_matrix_table_begin' in line:\n",
    "            print(f\"Found data marker at line {i}\")\n",
    "            # Read the next line which should be the header\n",
    "            header_line = next(file)\n",
    "            print(f\"Header line: {header_line.strip()}\")\n",
    "            # And the first data line\n",
    "            first_data_line = next(file)\n",
    "            print(f\"First data line: {first_data_line.strip()}\")\n",
    "            break\n",
    "        if i > 100:  # Limit search to first 100 lines\n",
    "            print(\"Matrix table marker not found in first 100 lines\")\n",
    "            break\n",
    "\n",
    "# 3. Now try to get the genetic data with better error handling\n",
    "try:\n",
    "    gene_data = get_genetic_data(matrix_file)\n",
    "    print(gene_data.index[:20])\n",
    "except KeyError as e:\n",
    "    print(f\"KeyError: {e}\")\n",
    "    \n",
    "    # Alternative approach: manually extract the data\n",
    "    print(\"\\nTrying alternative approach to read the gene data:\")\n",
    "    with gzip.open(matrix_file, 'rt') as file:\n",
    "        # Find the start of the data\n",
    "        for line in file:\n",
    "            if '!series_matrix_table_begin' in line:\n",
    "                break\n",
    "                \n",
    "        # Read the headers and data\n",
    "        import pandas as pd\n",
    "        df = pd.read_csv(file, sep='\\t', index_col=0)\n",
    "        print(f\"Column names: {df.columns[:5]}\")\n",
    "        print(f\"First 20 row IDs: {df.index[:20]}\")\n",
    "        gene_data = df\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "91bede2f",
   "metadata": {},
   "source": [
    "### Step 4: Gene Identifier Review"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "8dacb025",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:12:12.264759Z",
     "iopub.status.busy": "2025-03-25T05:12:12.264636Z",
     "iopub.status.idle": "2025-03-25T05:12:12.266623Z",
     "shell.execute_reply": "2025-03-25T05:12:12.266297Z"
    }
   },
   "outputs": [],
   "source": [
    "# Examining the gene identifiers from the output\n",
    "# The identifiers (like A_23_P100001) appear to be Agilent microarray probe IDs\n",
    "# These are not standard human gene symbols and will need to be mapped to gene symbols\n",
    "\n",
    "requires_gene_mapping = True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1eb382c7",
   "metadata": {},
   "source": [
    "### Step 5: Gene Annotation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "d7bf9f5b",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:12:12.267629Z",
     "iopub.status.busy": "2025-03-25T05:12:12.267521Z",
     "iopub.status.idle": "2025-03-25T05:12:12.702203Z",
     "shell.execute_reply": "2025-03-25T05:12:12.701780Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Examining SOFT file structure:\n",
      "Line 0: ^DATABASE = GeoMiame\n",
      "Line 1: !Database_name = Gene Expression Omnibus (GEO)\n",
      "Line 2: !Database_institute = NCBI NLM NIH\n",
      "Line 3: !Database_web_link = http://www.ncbi.nlm.nih.gov/geo\n",
      "Line 4: !Database_email = [email protected]\n",
      "Line 5: ^SERIES = GSE107754\n",
      "Line 6: !Series_title = A novel genomic signature predicting FDG uptake in diverse metastatic tumors\n",
      "Line 7: !Series_geo_accession = GSE107754\n",
      "Line 8: !Series_status = Public on Jan 22 2018\n",
      "Line 9: !Series_submission_date = Dec 06 2017\n",
      "Line 10: !Series_last_update_date = Jan 23 2019\n",
      "Line 11: !Series_pubmed_id = 29349517\n",
      "Line 12: !Series_summary = Purpose: Building a universal genomic signature predicting the intensity of FDG uptake in diverse metastatic tumors may allow us to understand better the biological processes underlying this phenomenon and their requirements of glucose uptake.\n",
      "Line 13: !Series_summary = Methods: A balanced training set (n=71) of metastatic tumors including some of the most frequent histologies, with matched PET/CT quantification measurements and whole human genome gene expression microarrays, was used to build the signature. Selection of microarray features was carried out exclusively on the basis of their strong association with FDG uptake (as measured by SUVmean35) by means of univariate linear regression. A thorough bioinformatics study of these genes was performed and multivariable models were built by fitting several state of the art regression techniques to the training set for comparison.\n",
      "Line 14: !Series_summary = Results: The 909 probes with the strongest association with the SUVmean35 (comprising 742 identifiable genes and 62 probes not matched to a symbol) were used to build the signature. Partial Least Squares using 3 components (PLS-3) was the best performing model in the training dataset cross-validation (Root Mean Square Error, RMSE=0.443) and was validated further in an independent validation dataset (n=13) obtaining a performance within the 95% CI of that obtained in the training dataset (RMSE=0.645). Significantly overrepresented biological processes correlating with the SUVmean35 were identified beyond glycolysis, such as ribosome biogenesis and DNA replication (correlating with a higher SUVmean35), and cytoskeleton reorganization and autophagy (correlating with a lower SUVmean35), among others.\n",
      "Line 15: !Series_summary = Conclusions: PLS-3 is a signature predicting accurately the intensity of FDG uptake in diverse metastatic tumors. FDG-PET might help in the design of specific targeted therapies directed to counteract the identified malignant biological processes more likely activated in a tumor as inferred from the SUVmean35 and also from its variations in response to antineoplastic treatments.\n",
      "Line 16: !Series_overall_design = Whole human genome microarrays from biopsies of human metastatic tumors (71 patients) with matched SUVmean35 measurements, this submission includes the 71 patients of the training set used to build the genomic signature predicting FDG uptake in diverse metastatic tumors. This dataset is complemented with a validation set comprised of 13 patients.\n",
      "Line 17: !Series_type = Expression profiling by array\n",
      "Line 18: !Series_contributor = Ramon,G,Manzano\n",
      "Line 19: !Series_contributor = Elena,M,Martinez Navarro\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "Gene annotation preview:\n",
      "{'ID': ['A_23_P100001', 'A_23_P100011', 'A_23_P100022', 'A_23_P100056', 'A_23_P100074'], 'SPOT_ID': ['A_23_P100001', 'A_23_P100011', 'A_23_P100022', 'A_23_P100056', 'A_23_P100074'], 'CONTROL_TYPE': ['FALSE', 'FALSE', 'FALSE', 'FALSE', 'FALSE'], 'REFSEQ': ['NM_207446', 'NM_005829', 'NM_014848', 'NM_194272', 'NM_020371'], 'GB_ACC': ['NM_207446', 'NM_005829', 'NM_014848', 'NM_194272', 'NM_020371'], 'GENE': [400451.0, 10239.0, 9899.0, 348093.0, 57099.0], 'GENE_SYMBOL': ['FAM174B', 'AP3S2', 'SV2B', 'RBPMS2', 'AVEN'], 'GENE_NAME': ['family with sequence similarity 174, member B', 'adaptor-related protein complex 3, sigma 2 subunit', 'synaptic vesicle glycoprotein 2B', 'RNA binding protein with multiple splicing 2', 'apoptosis, caspase activation inhibitor'], 'UNIGENE_ID': ['Hs.27373', 'Hs.632161', 'Hs.21754', 'Hs.436518', 'Hs.555966'], 'ENSEMBL_ID': ['ENST00000557398', nan, 'ENST00000557410', 'ENST00000300069', 'ENST00000306730'], 'TIGR_ID': [nan, nan, nan, nan, nan], 'ACCESSION_STRING': ['ref|NM_207446|ens|ENST00000557398|ens|ENST00000553393|ens|ENST00000327355', 'ref|NM_005829|ref|NM_001199058|ref|NR_023361|ref|NR_037582', 'ref|NM_014848|ref|NM_001167580|ens|ENST00000557410|ens|ENST00000330276', 'ref|NM_194272|ens|ENST00000300069|gb|AK127873|gb|AK124123', 'ref|NM_020371|ens|ENST00000306730|gb|AF283508|gb|BC010488'], 'CHROMOSOMAL_LOCATION': ['chr15:93160848-93160789', 'chr15:90378743-90378684', 'chr15:91838329-91838388', 'chr15:65032375-65032316', 'chr15:34158739-34158680'], 'CYTOBAND': ['hs|15q26.1', 'hs|15q26.1', 'hs|15q26.1', 'hs|15q22.31', 'hs|15q14'], 'DESCRIPTION': ['Homo sapiens family with sequence similarity 174, member B (FAM174B), mRNA [NM_207446]', 'Homo sapiens adaptor-related protein complex 3, sigma 2 subunit (AP3S2), transcript variant 1, mRNA [NM_005829]', 'Homo sapiens synaptic vesicle glycoprotein 2B (SV2B), transcript variant 1, mRNA [NM_014848]', 'Homo sapiens RNA binding protein with multiple splicing 2 (RBPMS2), mRNA [NM_194272]', 'Homo sapiens apoptosis, caspase activation inhibitor (AVEN), mRNA [NM_020371]'], 'GO_ID': ['GO:0016020(membrane)|GO:0016021(integral to membrane)', 'GO:0005794(Golgi apparatus)|GO:0006886(intracellular protein transport)|GO:0008565(protein transporter activity)|GO:0016020(membrane)|GO:0016192(vesicle-mediated transport)|GO:0030117(membrane coat)|GO:0030659(cytoplasmic vesicle membrane)|GO:0031410(cytoplasmic vesicle)', 'GO:0001669(acrosomal vesicle)|GO:0006836(neurotransmitter transport)|GO:0016020(membrane)|GO:0016021(integral to membrane)|GO:0022857(transmembrane transporter activity)|GO:0030054(cell junction)|GO:0030672(synaptic vesicle membrane)|GO:0031410(cytoplasmic vesicle)|GO:0045202(synapse)', 'GO:0000166(nucleotide binding)|GO:0003676(nucleic acid binding)', 'GO:0005515(protein binding)|GO:0005622(intracellular)|GO:0005624(membrane fraction)|GO:0006915(apoptosis)|GO:0006916(anti-apoptosis)|GO:0012505(endomembrane system)|GO:0016020(membrane)'], 'SEQUENCE': ['ATCTCATGGAAAAGCTGGATTCCTCTGCCTTACGCAGAAACACCCGGGCTCCATCTGCCA', 'TCAAGTATTGGCCTGACATAGAGTCCTTAAGACAAGCAAAGACAAGCAAGGCAAGCACGT', 'ATGTCGGCTGTGGAGGGTTAAAGGGATGAGGCTTTCCTTTGTTTAGCAAATCTGTTCACA', 'CCCTGTCAGATAAGTTTAATGTTTAGTTTGAGGCATGAAGAAGAAAAGGGTTTCCATTCT', 'GACCAGCCAGTTTACAAGCATGTCTCAAGCTAGTGTGTTCCATTATGCTCACAGCAGTAA']}\n"
     ]
    }
   ],
   "source": [
    "# 1. Let's first examine the structure of the SOFT file before trying to parse it\n",
    "import gzip\n",
    "\n",
    "# Look at the first few lines of the SOFT file to understand its structure\n",
    "print(\"Examining SOFT file structure:\")\n",
    "try:\n",
    "    with gzip.open(soft_file, 'rt') as file:\n",
    "        # Read first 20 lines to understand the file structure\n",
    "        for i, line in enumerate(file):\n",
    "            if i < 20:\n",
    "                print(f\"Line {i}: {line.strip()}\")\n",
    "            else:\n",
    "                break\n",
    "except Exception as e:\n",
    "    print(f\"Error reading SOFT file: {e}\")\n",
    "\n",
    "# 2. Now let's try a more robust approach to extract the gene annotation\n",
    "# Instead of using the library function which failed, we'll implement a custom approach\n",
    "try:\n",
    "    # First, look for the platform section which contains gene annotation\n",
    "    platform_data = []\n",
    "    with gzip.open(soft_file, 'rt') as file:\n",
    "        in_platform_section = False\n",
    "        for line in file:\n",
    "            if line.startswith('^PLATFORM'):\n",
    "                in_platform_section = True\n",
    "                continue\n",
    "            if in_platform_section and line.startswith('!platform_table_begin'):\n",
    "                # Next line should be the header\n",
    "                header = next(file).strip()\n",
    "                platform_data.append(header)\n",
    "                # Read until the end of the platform table\n",
    "                for table_line in file:\n",
    "                    if table_line.startswith('!platform_table_end'):\n",
    "                        break\n",
    "                    platform_data.append(table_line.strip())\n",
    "                break\n",
    "    \n",
    "    # If we found platform data, convert it to a DataFrame\n",
    "    if platform_data:\n",
    "        import pandas as pd\n",
    "        import io\n",
    "        platform_text = '\\n'.join(platform_data)\n",
    "        gene_annotation = pd.read_csv(io.StringIO(platform_text), delimiter='\\t', \n",
    "                                      low_memory=False, on_bad_lines='skip')\n",
    "        print(\"\\nGene annotation preview:\")\n",
    "        print(preview_df(gene_annotation))\n",
    "    else:\n",
    "        print(\"Could not find platform table in SOFT file\")\n",
    "        \n",
    "        # Try an alternative approach - extract mapping from other sections\n",
    "        with gzip.open(soft_file, 'rt') as file:\n",
    "            for line in file:\n",
    "                if 'ANNOTATION information' in line or 'annotation information' in line:\n",
    "                    print(f\"Found annotation information: {line.strip()}\")\n",
    "                if line.startswith('!Platform_title') or line.startswith('!platform_title'):\n",
    "                    print(f\"Platform title: {line.strip()}\")\n",
    "            \n",
    "except Exception as e:\n",
    "    print(f\"Error processing gene annotation: {e}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "be8e1d19",
   "metadata": {},
   "source": [
    "### Step 6: Gene Identifier Mapping"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "129a1d1b",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:12:12.703492Z",
     "iopub.status.busy": "2025-03-25T05:12:12.703348Z",
     "iopub.status.idle": "2025-03-25T05:12:19.290676Z",
     "shell.execute_reply": "2025-03-25T05:12:19.290320Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene mapping preview:\n",
      "             ID     Gene\n",
      "0  A_23_P100001  FAM174B\n",
      "1  A_23_P100011    AP3S2\n",
      "2  A_23_P100022     SV2B\n",
      "3  A_23_P100056   RBPMS2\n",
      "4  A_23_P100074     AVEN\n",
      "Gene expression data shape: (18488, 84)\n",
      "Gene expression data preview (first 5 genes, first 5 samples):\n",
      "          GSM2878070  GSM2878071  GSM2878072  GSM2878073  GSM2878074\n",
      "Gene                                                                \n",
      "A1BG       16.675251   18.589095   17.665959   20.260758   17.885257\n",
      "A1BG-AS1    8.138944    9.361230    8.513994    9.269932    9.537095\n",
      "A1CF       15.194191   15.252929   16.779446   19.487898   15.190126\n",
      "A2LD1       9.231020    9.510204    9.701203    8.614287    8.349443\n",
      "A2M        14.936963   14.432973   15.230273   14.494223   15.789791\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene expression data saved to: ../../output/preprocess/Esophageal_Cancer/gene_data/GSE107754.csv\n"
     ]
    }
   ],
   "source": [
    "# Let's first rerun the gene annotation extraction with the proper function\n",
    "# We'll try using the library function now that we understand the file structure\n",
    "gene_annotation = get_gene_annotation(soft_file)\n",
    "\n",
    "# From the preview, we can see:\n",
    "# - 'ID' column in the annotation contains probe IDs that match expression data index\n",
    "# - 'GENE_SYMBOL' column contains the human gene symbols we need to map to\n",
    "\n",
    "# 1. Extract the mapping between probe IDs and gene symbols\n",
    "gene_mapping = get_gene_mapping(gene_annotation, 'ID', 'GENE_SYMBOL')\n",
    "\n",
    "# 2. Print a preview of the mapping to verify\n",
    "print(\"Gene mapping preview:\")\n",
    "print(gene_mapping.head())\n",
    "\n",
    "# 3. Apply the gene mapping to convert probe-level expression to gene-level expression\n",
    "gene_data = apply_gene_mapping(gene_data, gene_mapping)\n",
    "\n",
    "# 4. Print the dimensions and preview of the gene expression data\n",
    "print(f\"Gene expression data shape: {gene_data.shape}\")\n",
    "print(\"Gene expression data preview (first 5 genes, first 5 samples):\")\n",
    "print(gene_data.iloc[:5, :5])\n",
    "\n",
    "# 5. Save the gene expression data to the specified output file\n",
    "out_gene_dir = os.path.dirname(out_gene_data_file)\n",
    "os.makedirs(out_gene_dir, 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": "6a00b120",
   "metadata": {},
   "source": [
    "### Step 7: Data Normalization and Linking"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "ee7a05e1",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:12:19.292028Z",
     "iopub.status.busy": "2025-03-25T05:12:19.291894Z",
     "iopub.status.idle": "2025-03-25T05:12:25.902816Z",
     "shell.execute_reply": "2025-03-25T05:12:25.902279Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Normalized gene data shape: (18247, 84)\n",
      "First few genes with their expression values after normalization:\n",
      "          GSM2878070  GSM2878071  GSM2878072  GSM2878073  GSM2878074  \\\n",
      "Gene                                                                   \n",
      "A1BG       16.675251   18.589095   17.665959   20.260758   17.885257   \n",
      "A1BG-AS1    8.138944    9.361230    8.513994    9.269932    9.537095   \n",
      "A1CF       15.194191   15.252929   16.779446   19.487898   15.190126   \n",
      "A2M        14.936963   14.432973   15.230273   14.494223   15.789791   \n",
      "A2ML1      10.363561   11.081253    9.592718   10.258384   11.055192   \n",
      "\n",
      "          GSM2878075  GSM2878076  GSM2878077  GSM2878078  GSM2878079  ...  \\\n",
      "Gene                                                                  ...   \n",
      "A1BG       23.469022   17.237170   21.554459   18.427697   19.441237  ...   \n",
      "A1BG-AS1    9.026286    8.261324    9.419955    8.954172    8.822408  ...   \n",
      "A1CF       19.816419   15.124037   18.691166   15.129180   15.509904  ...   \n",
      "A2M        15.585660   14.984473   14.855128   15.018056   14.465856  ...   \n",
      "A2ML1       9.692235    9.878473    9.688524    9.687150    9.146547  ...   \n",
      "\n",
      "          GSM2891255  GSM2891256  GSM2891257  GSM2891258  GSM2891259  \\\n",
      "Gene                                                                   \n",
      "A1BG       18.111288   19.849660   16.432489   19.875191   17.694450   \n",
      "A1BG-AS1    9.421176    8.532598    8.138147    8.611568    8.818973   \n",
      "A1CF       15.198185   16.659247   15.001932   15.475466   15.330651   \n",
      "A2M        14.864289   14.535093   13.781049   15.672631   15.351216   \n",
      "A2ML1       9.459754   10.088872    9.996023   10.241353   13.157317   \n",
      "\n",
      "          GSM2891260  GSM2891261  GSM2891262  GSM2891263  GSM2891264  \n",
      "Gene                                                                  \n",
      "A1BG       20.178957   19.395664   20.745208   19.434408   18.734236  \n",
      "A1BG-AS1    7.737613    9.399768    7.667535    9.134555    8.301228  \n",
      "A1CF       20.560980   15.226321   20.339693   15.531251   15.570731  \n",
      "A2M        15.361097   14.925851   14.086261   13.401129   14.841858  \n",
      "A2ML1       9.183133    9.212320    9.285009   10.476271    9.171710  \n",
      "\n",
      "[5 rows x 84 columns]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Normalized gene data saved to ../../output/preprocess/Esophageal_Cancer/gene_data/GSE107754.csv\n",
      "Raw clinical data shape: (4, 85)\n",
      "Clinical features:\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "                   GSM2878070  GSM2878071  GSM2878072  GSM2878073  GSM2878074  \\\n",
      "Esophageal_Cancer         0.0         0.0         0.0         0.0         0.0   \n",
      "Gender                    1.0         0.0         1.0         1.0         0.0   \n",
      "\n",
      "                   GSM2878075  GSM2878076  GSM2878077  GSM2878078  GSM2878079  \\\n",
      "Esophageal_Cancer         0.0         0.0         0.0         0.0         0.0   \n",
      "Gender                    1.0         0.0         0.0         0.0         0.0   \n",
      "\n",
      "                   ...  GSM2891255  GSM2891256  GSM2891257  GSM2891258  \\\n",
      "Esophageal_Cancer  ...         0.0         0.0         0.0         0.0   \n",
      "Gender             ...         1.0         1.0         1.0         1.0   \n",
      "\n",
      "                   GSM2891259  GSM2891260  GSM2891261  GSM2891262  GSM2891263  \\\n",
      "Esophageal_Cancer         0.0         0.0         0.0         0.0         0.0   \n",
      "Gender                    0.0         1.0         0.0         1.0         1.0   \n",
      "\n",
      "                   GSM2891264  \n",
      "Esophageal_Cancer         0.0  \n",
      "Gender                    1.0  \n",
      "\n",
      "[2 rows x 84 columns]\n",
      "Clinical features saved to ../../output/preprocess/Esophageal_Cancer/clinical_data/GSE107754.csv\n",
      "Linked data shape: (84, 18249)\n",
      "Linked data preview (first 5 rows, first 5 columns):\n",
      "            Esophageal_Cancer  Gender       A1BG  A1BG-AS1       A1CF\n",
      "GSM2878070                0.0     1.0  16.675251  8.138944  15.194191\n",
      "GSM2878071                0.0     0.0  18.589095  9.361230  15.252929\n",
      "GSM2878072                0.0     1.0  17.665959  8.513994  16.779446\n",
      "GSM2878073                0.0     1.0  20.260758  9.269932  19.487898\n",
      "GSM2878074                0.0     0.0  17.885257  9.537095  15.190126\n",
      "Missing values before handling:\n",
      "  Trait (Esophageal_Cancer) missing: 0 out of 84\n",
      "  Gender missing: 0 out of 84\n",
      "  Genes with >20% missing: 0\n",
      "  Samples with >5% missing genes: 0\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Data shape after handling missing values: (84, 18249)\n",
      "For the feature 'Esophageal_Cancer', the least common label is '1.0' with 4 occurrences. This represents 4.76% of the dataset.\n",
      "The distribution of the feature 'Esophageal_Cancer' in this dataset is severely biased.\n",
      "\n",
      "For the feature 'Gender', the least common label is '1.0' with 35 occurrences. This represents 41.67% of the dataset.\n",
      "The distribution of the feature 'Gender' in this dataset is fine.\n",
      "\n",
      "Data was determined to be unusable or empty and was not saved\n"
     ]
    }
   ],
   "source": [
    "# 1. Normalize gene symbols in the gene expression data\n",
    "normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n",
    "print(f\"Normalized gene data shape: {normalized_gene_data.shape}\")\n",
    "print(\"First few genes with their expression values after normalization:\")\n",
    "print(normalized_gene_data.head())\n",
    "\n",
    "# Save the normalized gene data\n",
    "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
    "normalized_gene_data.to_csv(out_gene_data_file)\n",
    "print(f\"Normalized gene data saved to {out_gene_data_file}\")\n",
    "\n",
    "# 2. Check if trait data is available before proceeding with clinical data extraction\n",
    "if trait_row is None:\n",
    "    print(\"Trait row is None. Cannot extract trait information from clinical data.\")\n",
    "    # Create an empty dataframe for clinical features\n",
    "    clinical_features = pd.DataFrame()\n",
    "    \n",
    "    # Create an empty dataframe for linked data\n",
    "    linked_data = pd.DataFrame()\n",
    "    \n",
    "    # Validate and save cohort info\n",
    "    validate_and_save_cohort_info(\n",
    "        is_final=True, \n",
    "        cohort=cohort, \n",
    "        info_path=json_path, \n",
    "        is_gene_available=True, \n",
    "        is_trait_available=False,  # Trait data is not available\n",
    "        is_biased=True,  # Not applicable but required\n",
    "        df=pd.DataFrame(),  # Empty dataframe\n",
    "        note=\"Dataset contains gene expression data but lacks clear trait indicators for Duchenne Muscular Dystrophy status.\"\n",
    "    )\n",
    "    print(\"Data was determined to be unusable due to missing trait indicators and was not saved\")\n",
    "else:\n",
    "    try:\n",
    "        # Get the file paths for the matrix file to extract clinical data\n",
    "        _, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
    "        \n",
    "        # Get raw clinical data from the matrix file\n",
    "        _, clinical_raw = get_background_and_clinical_data(matrix_file)\n",
    "        \n",
    "        # Verify clinical data structure\n",
    "        print(\"Raw clinical data shape:\", clinical_raw.shape)\n",
    "        \n",
    "        # Extract clinical features using the defined conversion functions\n",
    "        clinical_features = geo_select_clinical_features(\n",
    "            clinical_df=clinical_raw,\n",
    "            trait=trait,\n",
    "            trait_row=trait_row,\n",
    "            convert_trait=convert_trait,\n",
    "            age_row=age_row,\n",
    "            convert_age=convert_age,\n",
    "            gender_row=gender_row,\n",
    "            convert_gender=convert_gender\n",
    "        )\n",
    "        \n",
    "        print(\"Clinical features:\")\n",
    "        print(clinical_features)\n",
    "        \n",
    "        # Save clinical features to file\n",
    "        os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
    "        clinical_features.to_csv(out_clinical_data_file)\n",
    "        print(f\"Clinical features saved to {out_clinical_data_file}\")\n",
    "        \n",
    "        # 3. Link clinical and genetic data\n",
    "        linked_data = geo_link_clinical_genetic_data(clinical_features, normalized_gene_data)\n",
    "        print(f\"Linked data shape: {linked_data.shape}\")\n",
    "        print(\"Linked data preview (first 5 rows, first 5 columns):\")\n",
    "        print(linked_data.iloc[:5, :5])\n",
    "        \n",
    "        # 4. Handle missing values\n",
    "        print(\"Missing values before handling:\")\n",
    "        print(f\"  Trait ({trait}) missing: {linked_data[trait].isna().sum()} out of {len(linked_data)}\")\n",
    "        if 'Age' in linked_data.columns:\n",
    "            print(f\"  Age missing: {linked_data['Age'].isna().sum()} out of {len(linked_data)}\")\n",
    "        if 'Gender' in linked_data.columns:\n",
    "            print(f\"  Gender missing: {linked_data['Gender'].isna().sum()} out of {len(linked_data)}\")\n",
    "        \n",
    "        gene_cols = [col for col in linked_data.columns if col not in [trait, 'Age', 'Gender']]\n",
    "        print(f\"  Genes with >20% missing: {sum(linked_data[gene_cols].isna().mean() > 0.2)}\")\n",
    "        print(f\"  Samples with >5% missing genes: {sum(linked_data[gene_cols].isna().mean(axis=1) > 0.05)}\")\n",
    "        \n",
    "        cleaned_data = handle_missing_values(linked_data, trait)\n",
    "        print(f\"Data shape after handling missing values: {cleaned_data.shape}\")\n",
    "        \n",
    "        # 5. Evaluate bias in trait and demographic features\n",
    "        is_trait_biased = False\n",
    "        if len(cleaned_data) > 0:\n",
    "            trait_biased, cleaned_data = judge_and_remove_biased_features(cleaned_data, trait)\n",
    "            is_trait_biased = trait_biased\n",
    "        else:\n",
    "            print(\"No data remains after handling missing values.\")\n",
    "            is_trait_biased = True\n",
    "        \n",
    "        # 6. Final validation and save\n",
    "        is_usable = validate_and_save_cohort_info(\n",
    "            is_final=True, \n",
    "            cohort=cohort, \n",
    "            info_path=json_path, \n",
    "            is_gene_available=True, \n",
    "            is_trait_available=True, \n",
    "            is_biased=is_trait_biased, \n",
    "            df=cleaned_data,\n",
    "            note=\"Dataset contains gene expression data comparing Duchenne muscular dystrophy vs healthy samples.\"\n",
    "        )\n",
    "        \n",
    "        # 7. Save if usable\n",
    "        if is_usable and len(cleaned_data) > 0:\n",
    "            os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n",
    "            cleaned_data.to_csv(out_data_file)\n",
    "            print(f\"Linked data saved to {out_data_file}\")\n",
    "        else:\n",
    "            print(\"Data was determined to be unusable or empty and was not saved\")\n",
    "            \n",
    "    except Exception as e:\n",
    "        print(f\"Error processing data: {e}\")\n",
    "        # Handle the error case by still recording cohort info\n",
    "        validate_and_save_cohort_info(\n",
    "            is_final=True, \n",
    "            cohort=cohort, \n",
    "            info_path=json_path, \n",
    "            is_gene_available=True, \n",
    "            is_trait_available=False,  # Mark as not available due to processing issues\n",
    "            is_biased=True, \n",
    "            df=pd.DataFrame(),  # Empty dataframe\n",
    "            note=f\"Error processing data: {str(e)}\"\n",
    "        )\n",
    "        print(\"Data was determined to be unusable and was not saved\")"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.16"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}