File size: 47,312 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
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "855a6e05",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:13:40.295751Z",
     "iopub.status.busy": "2025-03-25T05:13:40.295531Z",
     "iopub.status.idle": "2025-03-25T05:13:40.463227Z",
     "shell.execute_reply": "2025-03-25T05:13:40.462892Z"
    }
   },
   "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 = \"GSE66258\"\n",
    "\n",
    "# Input paths\n",
    "in_trait_dir = \"../../input/GEO/Esophageal_Cancer\"\n",
    "in_cohort_dir = \"../../input/GEO/Esophageal_Cancer/GSE66258\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/Esophageal_Cancer/GSE66258.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/Esophageal_Cancer/gene_data/GSE66258.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/Esophageal_Cancer/clinical_data/GSE66258.csv\"\n",
    "json_path = \"../../output/preprocess/Esophageal_Cancer/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "58d4f02c",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "9f0fe125",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:13:40.464713Z",
     "iopub.status.busy": "2025-03-25T05:13:40.464561Z",
     "iopub.status.idle": "2025-03-25T05:13:40.628568Z",
     "shell.execute_reply": "2025-03-25T05:13:40.628231Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Background Information:\n",
      "!Series_title\t\"Comprehensive Analysis of Recurrence-Associated Small Non-Coding RNAs in Esophageal Cancer  [clinical study, Illumina]\"\n",
      "!Series_summary\t\"Targeted cancer therapy for squamous cell carcinoma (SCC) has made little progress largely due to a lack of knowledge of the driving genomic alterations. Small non-coding RNAs (sncRNAs) as a potential biomarker and therapeutic target to SCC remain a challenge. We analyzed sncRNAs microarray in 108 fresh frozen specimens of esophageal squamous cell carcinoma (ESCC) as discovery set and assessed associations between sncRNAs and recurrence-free survival. SncRNA signature identified was externally validated in two independent cohorts. We investigated the functional consequences of sncRNA identified and its integrative analysis of complex cancer genomics. We identified 3 recurrence-associated sncRNAs (miR-223, miR-1269a and nc886) from discovery set and proved risk prediction model externally in high and low volume centers. We uncovered through in vitro experiment that nc886 was down-regulated by hypermethylation of its promoter region and influences splicing of pre-mRNAs with minor introns by regulating expression of minor spliceosomal small nuclear RNAs (snRNAs) such as RNU4atac. Integrative analysis from lung SCC data in The Cancer Genome Atlas revealed that patients with lower expression of nc886 had more genetic alterations of TP53, DNA damage response and cell cycle genes. nc886 inhibits minor splicing to suppress expression of certain oncogenes such as PARP1 and E2F family containing minor introns. We present risk prediction model with sncRNAs for ESCC. Among them, nc886 may contribute to complete minor splicing via regulation of minor spliceosomal snRNAs supporting the notion that aberrant alteration in minor splicing might be a key driver of ESCC.\"\n",
      "!Series_overall_design\t\"Clinical study\"\n",
      "!Series_overall_design\t\"ESCC tumor samples.\"\n",
      "Sample Characteristics Dictionary:\n",
      "{0: ['tissue: esophageal squamous cell carcinoma (ESCC) tumor'], 1: ['sample id: 1', 'sample id: 2', 'sample id: 3', 'sample id: 4', 'sample id: 5', 'sample id: 6', 'sample id: 7', 'sample id: 8', 'sample id: 9', 'sample id: 10', 'sample id: 11', 'sample id: 12', 'sample id: 13', 'sample id: 14', 'sample id: 15', 'sample id: 16', 'sample id: 17', 'sample id: 18', 'sample id: 19', 'sample id: 20', 'sample id: 21', 'sample id: 22', 'sample id: 23', 'sample id: 24', 'sample id: 25', 'sample id: 26', 'sample id: 27', 'sample id: 28', 'sample id: 29', 'sample id: 30']}\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": "cf68a890",
   "metadata": {},
   "source": [
    "### Step 2: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "9879afc9",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:13:40.629820Z",
     "iopub.status.busy": "2025-03-25T05:13:40.629706Z",
     "iopub.status.idle": "2025-03-25T05:13:40.636559Z",
     "shell.execute_reply": "2025-03-25T05:13:40.636283Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Clinical Features Preview:\n",
      "{0: [1.0], 1: [nan]}\n",
      "Clinical data saved to ../../output/preprocess/Esophageal_Cancer/clinical_data/GSE66258.csv\n"
     ]
    }
   ],
   "source": [
    "# 1. Determine if gene expression data is available based on background information\n",
    "# This dataset is about small non-coding RNAs (sncRNAs) microarray in esophageal squamous cell carcinoma\n",
    "# Since it focuses on sncRNAs rather than gene expression, we'll set is_gene_available to False\n",
    "is_gene_available = False\n",
    "\n",
    "# 2. Check for trait (Esophageal Cancer), age, and gender data availability\n",
    "# Looking at the sample characteristics dictionary, we have:\n",
    "# Key 0: 'tissue: esophageal squamous cell carcinoma (ESCC) tumor'\n",
    "# Key 1: Sample IDs\n",
    "\n",
    "# 2.1 Data Availability\n",
    "# For trait data: Key 0 indicates these are all ESCC tumor samples\n",
    "trait_row = 0  # All samples are ESCC\n",
    "\n",
    "# Age and gender are not explicitly provided in the sample characteristics\n",
    "age_row = None  # Age data not available\n",
    "gender_row = None  # Gender data not available\n",
    "\n",
    "# 2.2 Data Type Conversion Functions\n",
    "def convert_trait(value):\n",
    "    \"\"\"Convert trait values to binary (1 for cancer, 0 for control)\"\"\"\n",
    "    if value is None:\n",
    "        return None\n",
    "    \n",
    "    # Extract the value after the colon if present\n",
    "    if \":\" in value:\n",
    "        value = value.split(\":\", 1)[1].strip()\n",
    "    \n",
    "    # This dataset contains only ESCC tumor samples, so all are cases\n",
    "    if \"esophageal squamous cell carcinoma\" in value.lower() or \"escc\" in value.lower():\n",
    "        return 1\n",
    "    else:\n",
    "        return None  # For any unexpected values\n",
    "\n",
    "def convert_age(value):\n",
    "    \"\"\"Convert age values to continuous integers\"\"\"\n",
    "    # Not used since age data is not available\n",
    "    return None\n",
    "\n",
    "def convert_gender(value):\n",
    "    \"\"\"Convert gender values to binary (0 for female, 1 for male)\"\"\"\n",
    "    # Not used since gender data is not available\n",
    "    return None\n",
    "\n",
    "# 3. Save initial metadata about dataset usability\n",
    "is_trait_available = trait_row is not None\n",
    "initial_validation = validate_and_save_cohort_info(\n",
    "    is_final=False,\n",
    "    cohort=cohort,\n",
    "    info_path=json_path,\n",
    "    is_gene_available=is_gene_available,\n",
    "    is_trait_available=is_trait_available\n",
    ")\n",
    "\n",
    "# 4. Clinical Feature Extraction (if trait_row is not None)\n",
    "if trait_row is not None:\n",
    "    # Assuming clinical_data is available from previous step\n",
    "    clinical_data = pd.DataFrame({\n",
    "        0: ['tissue: esophageal squamous cell carcinoma (ESCC) tumor'] * 30,\n",
    "        1: [f'sample id: {i+1}' for i in range(30)]\n",
    "    })\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",
    "    # Preview the extracted clinical features\n",
    "    preview = preview_df(selected_clinical_df)\n",
    "    print(\"Clinical Features Preview:\")\n",
    "    print(preview)\n",
    "    \n",
    "    # Save clinical data to CSV\n",
    "    os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
    "    selected_clinical_df.to_csv(out_clinical_data_file, index=True)\n",
    "    print(f\"Clinical data saved to {out_clinical_data_file}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "07860351",
   "metadata": {},
   "source": [
    "### Step 3: Gene Data Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "27ff5664",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:13:40.637584Z",
     "iopub.status.busy": "2025-03-25T05:13:40.637474Z",
     "iopub.status.idle": "2025-03-25T05:13:40.944609Z",
     "shell.execute_reply": "2025-03-25T05:13:40.944222Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Found data marker at line 67\n",
      "Header line: \"ID_REF\"\t\"GSM1618105\"\t\"GSM1618106\"\t\"GSM1618107\"\t\"GSM1618108\"\t\"GSM1618109\"\t\"GSM1618110\"\t\"GSM1618111\"\t\"GSM1618112\"\t\"GSM1618113\"\t\"GSM1618114\"\t\"GSM1618115\"\t\"GSM1618116\"\t\"GSM1618117\"\t\"GSM1618118\"\t\"GSM1618119\"\t\"GSM1618120\"\t\"GSM1618121\"\t\"GSM1618122\"\t\"GSM1618123\"\t\"GSM1618124\"\t\"GSM1618125\"\t\"GSM1618126\"\t\"GSM1618127\"\t\"GSM1618128\"\t\"GSM1618129\"\t\"GSM1618130\"\t\"GSM1618131\"\t\"GSM1618132\"\t\"GSM1618133\"\t\"GSM1618134\"\t\"GSM1618135\"\t\"GSM1618136\"\t\"GSM1618137\"\t\"GSM1618138\"\t\"GSM1618139\"\t\"GSM1618140\"\t\"GSM1618141\"\t\"GSM1618142\"\t\"GSM1618143\"\t\"GSM1618144\"\t\"GSM1618145\"\t\"GSM1618146\"\t\"GSM1618147\"\t\"GSM1618148\"\t\"GSM1618149\"\t\"GSM1618150\"\t\"GSM1618151\"\t\"GSM1618152\"\t\"GSM1618153\"\t\"GSM1618154\"\t\"GSM1618155\"\t\"GSM1618156\"\t\"GSM1618157\"\t\"GSM1618158\"\t\"GSM1618159\"\t\"GSM1618160\"\t\"GSM1618161\"\t\"GSM1618162\"\t\"GSM1618163\"\t\"GSM1618164\"\t\"GSM1618165\"\t\"GSM1618166\"\t\"GSM1618167\"\t\"GSM1618168\"\t\"GSM1618169\"\t\"GSM1618170\"\t\"GSM1618171\"\t\"GSM1618172\"\t\"GSM1618173\"\t\"GSM1618174\"\t\"GSM1618175\"\t\"GSM1618176\"\t\"GSM1618177\"\t\"GSM1618178\"\t\"GSM1618179\"\t\"GSM1618180\"\t\"GSM1618181\"\t\"GSM1618182\"\t\"GSM1618183\"\t\"GSM1618184\"\t\"GSM1618185\"\t\"GSM1618186\"\t\"GSM1618187\"\t\"GSM1618188\"\t\"GSM1618189\"\t\"GSM1618190\"\t\"GSM1618191\"\t\"GSM1618192\"\t\"GSM1618193\"\t\"GSM1618194\"\t\"GSM1618195\"\t\"GSM1618196\"\t\"GSM1618197\"\t\"GSM1618198\"\t\"GSM1618199\"\t\"GSM1618200\"\t\"GSM1618201\"\t\"GSM1618202\"\t\"GSM1618203\"\t\"GSM1618204\"\t\"GSM1618205\"\t\"GSM1618206\"\t\"GSM1618207\"\t\"GSM1618208\"\t\"GSM1618209\"\t\"GSM1618210\"\t\"GSM1618211\"\t\"GSM1618212\"\n",
      "First data line: \"ILMN_1343291\"\t14.214\t13.769\t13.896\t14.047\t13.682\t12.003\t13.543\t14.246\t13.975\t13.827\t14.173\t13.506\t13.806\t13.896\t14.088\t13.817\t13.706\t14.291\t14.121\t13.817\t14.14\t14.291\t14.2\t14.23\t14.246\t14.23\t14.11\t13.817\t14.076\t13.939\t14.11\t13.884\t13.519\t13.75\t14.173\t13.939\t14.088\t13.561\t13.633\t13.375\t13.75\t14.009\t14.291\t14.265\t13.999\t14.2\t13.706\t13.513\t13.871\t14.318\t14.123\t12.664\t13.488\t13.112\t14.101\t6.428\t13.127\t13.603\t13.509\t14.242\t14.32\t14.389\t14.389\t14.32\t12.744\t14.265\t14.291\t14.32\t13.873\t13.939\t13.175\t14.019\t14.149\t13.999\t13.859\t13.975\t13.796\t14.047\t14.131\t14.149\t13.362\t13.414\t13.975\t13.796\t13.838\t13.202\t13.656\t14.121\t14.066\t13.285\t13.698\t14.149\t14.214\t13.838\t14.265\t13.656\t14.199\t13.487\t10.351\t13.702\t6.513\t14.172\t13.389\t14.32\t13.026\t13.289\t13.947\t14.32\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Index(['ILMN_1343291', 'ILMN_1343295', 'ILMN_1651199', 'ILMN_1651209',\n",
      "       'ILMN_1651210', 'ILMN_1651221', 'ILMN_1651228', 'ILMN_1651229',\n",
      "       'ILMN_1651230', 'ILMN_1651232', 'ILMN_1651235', 'ILMN_1651236',\n",
      "       'ILMN_1651237', 'ILMN_1651238', 'ILMN_1651249', 'ILMN_1651253',\n",
      "       'ILMN_1651254', 'ILMN_1651259', 'ILMN_1651260', 'ILMN_1651262'],\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": "886c1c94",
   "metadata": {},
   "source": [
    "### Step 4: Gene Identifier Review"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "d799eee5",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:13:40.945892Z",
     "iopub.status.busy": "2025-03-25T05:13:40.945765Z",
     "iopub.status.idle": "2025-03-25T05:13:40.947752Z",
     "shell.execute_reply": "2025-03-25T05:13:40.947452Z"
    }
   },
   "outputs": [],
   "source": [
    "# Looking at the gene identifiers in the gene expression data\n",
    "# The identifiers start with \"ILMN_\" which indicates they are Illumina probe IDs\n",
    "# These are not standard human gene symbols and will need to be mapped\n",
    "# Illumina probe IDs are specific to Illumina microarray platforms and need to be\n",
    "# converted to gene symbols for cross-platform analysis\n",
    "\n",
    "requires_gene_mapping = True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "28a5937d",
   "metadata": {},
   "source": [
    "### Step 5: Gene Annotation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "a4224010",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:13:40.949027Z",
     "iopub.status.busy": "2025-03-25T05:13:40.948912Z",
     "iopub.status.idle": "2025-03-25T05:13:41.863499Z",
     "shell.execute_reply": "2025-03-25T05:13:41.863117Z"
    }
   },
   "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 = GSE66258\n",
      "Line 6: !Series_title = Comprehensive Analysis of Recurrence-Associated Small Non-Coding RNAs in Esophageal Cancer  [clinical study, Illumina]\n",
      "Line 7: !Series_geo_accession = GSE66258\n",
      "Line 8: !Series_status = Public on Jun 30 2016\n",
      "Line 9: !Series_submission_date = Feb 24 2015\n",
      "Line 10: !Series_last_update_date = Aug 13 2018\n",
      "Line 11: !Series_pubmed_id = 27507904\n",
      "Line 12: !Series_summary = Targeted cancer therapy for squamous cell carcinoma (SCC) has made little progress largely due to a lack of knowledge of the driving genomic alterations. Small non-coding RNAs (sncRNAs) as a potential biomarker and therapeutic target to SCC remain a challenge. We analyzed sncRNAs microarray in 108 fresh frozen specimens of esophageal squamous cell carcinoma (ESCC) as discovery set and assessed associations between sncRNAs and recurrence-free survival. SncRNA signature identified was externally validated in two independent cohorts. We investigated the functional consequences of sncRNA identified and its integrative analysis of complex cancer genomics. We identified 3 recurrence-associated sncRNAs (miR-223, miR-1269a and nc886) from discovery set and proved risk prediction model externally in high and low volume centers. We uncovered through in vitro experiment that nc886 was down-regulated by hypermethylation of its promoter region and influences splicing of pre-mRNAs with minor introns by regulating expression of minor spliceosomal small nuclear RNAs (snRNAs) such as RNU4atac. Integrative analysis from lung SCC data in The Cancer Genome Atlas revealed that patients with lower expression of nc886 had more genetic alterations of TP53, DNA damage response and cell cycle genes. nc886 inhibits minor splicing to suppress expression of certain oncogenes such as PARP1 and E2F family containing minor introns. We present risk prediction model with sncRNAs for ESCC. Among them, nc886 may contribute to complete minor splicing via regulation of minor spliceosomal snRNAs supporting the notion that aberrant alteration in minor splicing might be a key driver of ESCC.\n",
      "Line 13: !Series_overall_design = Clinical study\n",
      "Line 14: !Series_overall_design = ESCC tumor samples.\n",
      "Line 15: !Series_type = Expression profiling by array\n",
      "Line 16: !Series_contributor = Hyun-Sung,,Lee\n",
      "Line 17: !Series_contributor = Ju-Seog,,Lee\n",
      "Line 18: !Series_sample_id = GSM1618105\n",
      "Line 19: !Series_sample_id = GSM1618106\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "Gene annotation preview:\n",
      "{'ID': ['ILMN_1343048', 'ILMN_1343049', 'ILMN_1343050', 'ILMN_1343052', 'ILMN_1343059'], 'Species': [nan, nan, nan, nan, nan], 'Source': [nan, nan, nan, nan, nan], 'Search_Key': [nan, nan, nan, nan, nan], 'Transcript': [nan, nan, nan, nan, nan], 'ILMN_Gene': [nan, nan, nan, nan, nan], 'Source_Reference_ID': [nan, nan, nan, nan, nan], 'RefSeq_ID': [nan, nan, nan, nan, nan], 'Unigene_ID': [nan, nan, nan, nan, nan], 'Entrez_Gene_ID': [nan, nan, nan, nan, nan], 'GI': [nan, nan, nan, nan, nan], 'Accession': [nan, nan, nan, nan, nan], 'Symbol': ['phage_lambda_genome', 'phage_lambda_genome', 'phage_lambda_genome:low', 'phage_lambda_genome:low', 'thrB'], 'Protein_Product': [nan, nan, nan, nan, 'thrB'], 'Probe_Id': [nan, nan, nan, nan, nan], 'Array_Address_Id': [5090180, 6510136, 7560739, 1450438, 1240647], 'Probe_Type': [nan, nan, nan, nan, nan], 'Probe_Start': [nan, nan, nan, nan, nan], 'SEQUENCE': ['GAATAAAGAACAATCTGCTGATGATCCCTCCGTGGATCTGATTCGTGTAA', 'CCATGTGATACGAGGGCGCGTAGTTTGCATTATCGTTTTTATCGTTTCAA', 'CCGACAGATGTATGTAAGGCCAACGTGCTCAAATCTTCATACAGAAAGAT', 'TCTGTCACTGTCAGGAAAGTGGTAAAACTGCAACTCAATTACTGCAATGC', 'CTTGTGCCTGAGCTGTCAAAAGTAGAGCACGTCGCCGAGATGAAGGGCGC'], 'Chromosome': [nan, nan, nan, nan, nan], 'Probe_Chr_Orientation': [nan, nan, nan, nan, nan], 'Probe_Coordinates': [nan, nan, nan, nan, nan], 'Cytoband': [nan, nan, nan, nan, nan], 'Definition': [nan, nan, nan, nan, nan], 'Ontology_Component': [nan, nan, nan, nan, nan], 'Ontology_Process': [nan, nan, nan, nan, nan], 'Ontology_Function': [nan, nan, nan, nan, nan], 'Synonyms': [nan, nan, nan, nan, nan], 'Obsolete_Probe_Id': [nan, nan, nan, nan, nan], 'GB_ACC': [nan, nan, nan, nan, nan]}\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": "c38c8422",
   "metadata": {},
   "source": [
    "### Step 6: Gene Identifier Mapping"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "fe6076ee",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:13:41.864871Z",
     "iopub.status.busy": "2025-03-25T05:13:41.864757Z",
     "iopub.status.idle": "2025-03-25T05:13:42.045382Z",
     "shell.execute_reply": "2025-03-25T05:13:42.045014Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "First 10 genes after mapping:\n",
      "Index(['A1BG', 'A1CF', 'A26C3', 'A2BP1', 'A2LD1', 'A2M', 'A2ML1', 'A3GALT2',\n",
      "       'A4GALT', 'A4GNT'],\n",
      "      dtype='object', name='Gene')\n",
      "\n",
      "Gene expression data preview:\n",
      "{'GSM1618105': [13.117999999999999, 19.637999999999998, 19.191, 25.614, 6.718], 'GSM1618106': [13.093, 19.525, 19.544, 25.91, 7.365], 'GSM1618107': [13.135, 19.463, 19.384, 25.54, 7.696], 'GSM1618108': [12.937000000000001, 19.386, 19.560000000000002, 25.838, 6.733], 'GSM1618109': [13.074, 19.311, 19.516, 25.313000000000002, 6.61], 'GSM1618110': [15.734000000000002, 20.281, 20.258000000000003, 26.335, 6.445], 'GSM1618111': [13.414, 20.435000000000002, 19.477, 25.869, 6.401], 'GSM1618112': [13.55, 19.451, 19.393, 25.701999999999998, 7.105], 'GSM1618113': [13.66, 19.472, 19.541, 26.006, 6.604], 'GSM1618114': [12.947, 19.445999999999998, 19.651, 25.905, 7.724], 'GSM1618115': [13.169, 19.484, 19.418, 25.808, 7.036], 'GSM1618116': [13.131, 19.275, 19.697000000000003, 26.349, 6.842], 'GSM1618117': [13.463999999999999, 19.512999999999998, 19.574, 26.022000000000002, 8.286], 'GSM1618118': [13.216, 19.597, 19.493, 25.791, 6.885], 'GSM1618119': [13.325, 19.614, 19.494999999999997, 25.601, 6.863], 'GSM1618120': [13.117, 19.358, 19.374, 25.871000000000002, 6.839], 'GSM1618121': [12.966000000000001, 19.469, 19.281, 25.777, 6.55], 'GSM1618122': [13.16, 19.583, 19.4, 25.607, 7.603], 'GSM1618123': [13.02, 19.472, 19.596, 25.907, 7.164], 'GSM1618124': [13.017, 19.368, 19.249, 25.826, 7.151], 'GSM1618125': [13.1, 19.59, 19.505, 25.857, 6.828], 'GSM1618126': [12.945, 19.384, 19.787, 25.561999999999998, 7.397], 'GSM1618127': [12.911, 19.515, 19.384, 25.871000000000002, 6.818], 'GSM1618128': [12.947, 19.431, 19.688000000000002, 25.563, 7.006], 'GSM1618129': [12.897, 19.746000000000002, 19.418, 25.79, 7.132], 'GSM1618130': [13.238, 19.38, 19.376, 25.607, 7.011], 'GSM1618131': [13.215, 19.496, 19.563, 25.584, 7.317], 'GSM1618132': [13.227, 19.595, 19.399, 25.628999999999998, 7.967], 'GSM1618133': [13.313, 19.48, 19.902, 25.971, 7.636], 'GSM1618134': [13.247, 19.557, 19.575, 26.011, 7.228], 'GSM1618135': [13.15, 19.417, 19.353, 25.732, 6.711], 'GSM1618136': [13.149000000000001, 19.517, 19.37, 25.724, 7.126], 'GSM1618137': [13.165, 19.496000000000002, 19.740000000000002, 26.143, 6.637], 'GSM1618138': [13.184999999999999, 19.526, 19.405, 25.841, 6.592], 'GSM1618139': [13.193, 19.509, 19.262999999999998, 25.809, 6.891], 'GSM1618140': [13.251000000000001, 19.28, 19.107, 25.835, 6.746], 'GSM1618141': [13.256, 19.542, 19.369, 25.727, 6.896], 'GSM1618142': [13.261, 20.233, 19.27, 25.755000000000003, 7.044], 'GSM1618143': [13.248999999999999, 19.715, 19.52, 26.058, 6.733], 'GSM1618144': [13.161000000000001, 19.635, 20.626, 25.729, 7.099], 'GSM1618145': [13.144, 19.286, 19.55, 25.759, 6.432], 'GSM1618146': [13.133, 19.517, 19.303, 25.916, 6.747], 'GSM1618147': [13.467, 19.517, 19.323999999999998, 26.134999999999998, 7.059], 'GSM1618148': [13.2, 19.41, 19.716, 25.903, 7.489], 'GSM1618149': [13.285, 19.698999999999998, 19.383, 25.836, 7.605], 'GSM1618150': [13.186, 19.633, 19.198, 25.769, 7.138], 'GSM1618151': [13.356, 19.253, 19.66, 26.003999999999998, 6.651], 'GSM1618152': [13.711, 19.951999999999998, 19.358, 25.786, 6.547], 'GSM1618153': [12.989, 19.307, 19.424, 25.686, 7.453], 'GSM1618154': [13.128, 19.256, 19.406, 25.907, 6.931], 'GSM1618155': [13.219000000000001, 19.479, 19.605, 25.792, 6.661], 'GSM1618156': [15.003, 21.85, 20.048000000000002, 26.899, 6.437], 'GSM1618157': [13.132, 19.617, 19.387999999999998, 26.405, 7.528], 'GSM1618158': [13.73, 19.371, 19.289, 25.872, 6.795], 'GSM1618159': [13.155, 19.444, 19.658, 25.83, 7.26], 'GSM1618160': [13.293, 23.796, 20.0, 29.368000000000002, 6.463], 'GSM1618161': [13.794, 19.772, 19.68, 26.235999999999997, 6.803], 'GSM1618162': [13.574, 19.675, 20.416, 25.663, 8.016], 'GSM1618163': [13.831, 19.632, 19.314999999999998, 25.704, 6.395], 'GSM1618164': [13.205, 19.301, 19.423, 25.762999999999998, 6.463], 'GSM1618165': [13.177, 19.473, 19.816, 25.546, 6.928], 'GSM1618166': [13.315000000000001, 19.578, 19.613, 25.773, 6.928], 'GSM1618167': [13.343, 19.603, 19.618, 25.641, 7.279], 'GSM1618168': [13.181000000000001, 19.506, 19.56, 25.721, 8.209], 'GSM1618169': [15.019, 19.557000000000002, 19.725, 26.601, 6.421], 'GSM1618170': [13.043, 19.404, 19.415, 25.595, 6.811], 'GSM1618171': [13.327, 19.473, 19.259, 25.618, 7.23], 'GSM1618172': [13.122, 19.536, 19.366, 25.778, 6.952], 'GSM1618173': [13.894, 19.573, 19.225, 25.7, 6.653], 'GSM1618174': [13.346, 19.361, 19.356, 25.829, 6.863], 'GSM1618175': [13.197, 19.418, 19.456, 25.65, 7.272], 'GSM1618176': [13.285, 19.616, 19.369, 25.721, 6.809], 'GSM1618177': [13.135000000000002, 19.592, 19.416, 26.003999999999998, 7.645], 'GSM1618178': [13.676, 19.674, 19.544, 25.834, 6.955], 'GSM1618179': [13.338999999999999, 19.406, 19.454, 25.959, 6.893], 'GSM1618180': [13.415, 19.448, 19.646, 25.857, 7.521], 'GSM1618181': [13.18, 19.334, 19.246000000000002, 25.6, 6.539], 'GSM1618182': [13.308, 19.61, 19.304000000000002, 25.987000000000002, 6.631], 'GSM1618183': [13.221, 19.487000000000002, 19.323, 25.706, 7.653], 'GSM1618184': [13.086, 19.264, 19.458, 25.672, 7.092], 'GSM1618185': [13.704, 19.421999999999997, 19.664, 25.662, 7.765], 'GSM1618186': [13.524000000000001, 19.669, 19.353, 25.724, 6.643], 'GSM1618187': [13.443, 19.585, 19.356, 25.725, 6.832], 'GSM1618188': [13.216000000000001, 19.518, 19.323, 25.615, 8.286], 'GSM1618189': [13.619, 19.767, 19.627, 25.844, 6.494], 'GSM1618190': [13.558, 19.832, 19.511, 26.146, 6.669], 'GSM1618191': [14.736, 19.471, 19.497, 26.186, 6.955], 'GSM1618192': [13.341000000000001, 19.381999999999998, 19.316, 25.666, 8.011], 'GSM1618193': [13.233, 19.535, 19.526, 25.647, 6.861], 'GSM1618194': [14.234, 19.525, 20.104, 25.613, 6.598], 'GSM1618195': [13.306999999999999, 19.716, 19.485, 25.594, 7.109], 'GSM1618196': [13.185, 19.527, 19.438000000000002, 25.792, 7.608], 'GSM1618197': [13.321000000000002, 19.69, 19.435000000000002, 25.619999999999997, 6.991], 'GSM1618198': [13.07, 19.564, 19.281, 25.931, 6.626], 'GSM1618199': [13.182, 19.476, 19.426, 25.567, 7.097], 'GSM1618200': [13.522, 19.949, 19.428, 25.674, 6.909], 'GSM1618201': [13.102, 19.431, 19.336, 25.906, 6.756], 'GSM1618202': [13.185, 19.408, 19.524, 25.657, 7.656], 'GSM1618203': [14.084, 24.728, 19.489, 26.09, 6.421], 'GSM1618204': [15.442, 19.872, 21.82, 26.362000000000002, 6.561], 'GSM1618205': [12.912, 20.447000000000003, 19.713, 26.216, 7.629], 'GSM1618206': [13.213000000000001, 19.445, 19.603, 25.875999999999998, 6.994], 'GSM1618207': [13.847999999999999, 20.12, 19.807, 25.953, 7.575], 'GSM1618208': [13.219, 19.652, 19.6, 25.983999999999998, 7.517], 'GSM1618209': [13.843, 19.755, 20.938, 25.719, 6.517], 'GSM1618210': [13.176, 19.633, 19.256, 25.884, 6.579], 'GSM1618211': [13.225999999999999, 19.673, 19.65, 25.734, 6.817], 'GSM1618212': [13.251, 19.645, 19.173000000000002, 25.826, 6.627]}\n"
     ]
    }
   ],
   "source": [
    "# 1. Identify the columns in gene annotation that correspond to probe ID and gene symbol\n",
    "# Based on the gene annotation preview, 'ID' contains Illumina probe IDs (ILMN_*) and 'Symbol' contains gene symbols\n",
    "\n",
    "# 2. Create a gene mapping dataframe\n",
    "gene_mapping = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='Symbol')\n",
    "\n",
    "# 3. Apply the gene mapping to convert probe-level measurements to gene-level expression\n",
    "gene_data = apply_gene_mapping(gene_data, gene_mapping)\n",
    "\n",
    "# 4. Show the first few genes to verify mapping\n",
    "print(\"\\nFirst 10 genes after mapping:\")\n",
    "print(gene_data.index[:10])\n",
    "\n",
    "# 5. Preview some gene expression values\n",
    "print(\"\\nGene expression data preview:\")\n",
    "print(preview_df(gene_data))\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3688febe",
   "metadata": {},
   "source": [
    "### Step 7: Data Normalization and Linking"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "d7e484d3",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:13:42.046787Z",
     "iopub.status.busy": "2025-03-25T05:13:42.046665Z",
     "iopub.status.idle": "2025-03-25T05:13:49.883480Z",
     "shell.execute_reply": "2025-03-25T05:13:49.883022Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Normalized gene data shape: (20259, 108)\n",
      "First few genes with their expression values after normalization:\n",
      "          GSM1618105  GSM1618106  GSM1618107  GSM1618108  GSM1618109  \\\n",
      "Gene                                                                   \n",
      "A1BG          13.118      13.093      13.135      12.937      13.074   \n",
      "A1BG-AS1       6.474       6.624       6.533       6.457       6.475   \n",
      "A1CF          19.638      19.525      19.463      19.386      19.311   \n",
      "A2M           11.702      10.902       9.623       9.762      10.640   \n",
      "A2ML1          6.394       6.540       6.461       7.809       7.221   \n",
      "\n",
      "          GSM1618110  GSM1618111  GSM1618112  GSM1618113  GSM1618114  ...  \\\n",
      "Gene                                                                  ...   \n",
      "A1BG          15.734      13.414      13.550      13.660      12.947  ...   \n",
      "A1BG-AS1       6.433       6.564       6.397       6.637       6.387  ...   \n",
      "A1CF          20.281      20.435      19.451      19.472      19.446  ...   \n",
      "A2M            9.601       9.410      10.049       8.556       9.729  ...   \n",
      "A2ML1          6.699       7.991       7.482       7.434       7.918  ...   \n",
      "\n",
      "          GSM1618203  GSM1618204  GSM1618205  GSM1618206  GSM1618207  \\\n",
      "Gene                                                                   \n",
      "A1BG          14.084      15.442      12.912      13.213      13.848   \n",
      "A1BG-AS1       6.648       7.317       6.522       6.428       6.513   \n",
      "A1CF          24.728      19.872      20.447      19.445      20.120   \n",
      "A2M            9.440       7.235       7.006       9.211       8.566   \n",
      "A2ML1          7.659       6.412       6.416       8.816       7.073   \n",
      "\n",
      "          GSM1618208  GSM1618209  GSM1618210  GSM1618211  GSM1618212  \n",
      "Gene                                                                  \n",
      "A1BG          13.219      13.843      13.176      13.226      13.251  \n",
      "A1BG-AS1       6.398       6.444       6.455       6.529       6.506  \n",
      "A1CF          19.652      19.755      19.633      19.673      19.645  \n",
      "A2M            9.390       9.210       9.626       9.540       9.821  \n",
      "A2ML1          6.361       6.374       8.099       6.893       6.446  \n",
      "\n",
      "[5 rows x 108 columns]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Normalized gene data saved to ../../output/preprocess/Esophageal_Cancer/gene_data/GSE66258.csv\n",
      "Raw clinical data shape: (2, 109)\n",
      "Clinical features:\n",
      "                   GSM1618105  GSM1618106  GSM1618107  GSM1618108  GSM1618109  \\\n",
      "Esophageal_Cancer         1.0         1.0         1.0         1.0         1.0   \n",
      "\n",
      "                   GSM1618110  GSM1618111  GSM1618112  GSM1618113  GSM1618114  \\\n",
      "Esophageal_Cancer         1.0         1.0         1.0         1.0         1.0   \n",
      "\n",
      "                   ...  GSM1618203  GSM1618204  GSM1618205  GSM1618206  \\\n",
      "Esophageal_Cancer  ...         1.0         1.0         1.0         1.0   \n",
      "\n",
      "                   GSM1618207  GSM1618208  GSM1618209  GSM1618210  GSM1618211  \\\n",
      "Esophageal_Cancer         1.0         1.0         1.0         1.0         1.0   \n",
      "\n",
      "                   GSM1618212  \n",
      "Esophageal_Cancer         1.0  \n",
      "\n",
      "[1 rows x 108 columns]\n",
      "Clinical features saved to ../../output/preprocess/Esophageal_Cancer/clinical_data/GSE66258.csv\n",
      "Linked data shape: (108, 20260)\n",
      "Linked data preview (first 5 rows, first 5 columns):\n",
      "            Esophageal_Cancer    A1BG  A1BG-AS1    A1CF     A2M\n",
      "GSM1618105                1.0  13.118     6.474  19.638  11.702\n",
      "GSM1618106                1.0  13.093     6.624  19.525  10.902\n",
      "GSM1618107                1.0  13.135     6.533  19.463   9.623\n",
      "GSM1618108                1.0  12.937     6.457  19.386   9.762\n",
      "GSM1618109                1.0  13.074     6.475  19.311  10.640\n",
      "Missing values before handling:\n",
      "  Trait (Esophageal_Cancer) missing: 0 out of 108\n",
      "  Genes with >20% missing: 0\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  Samples with >5% missing genes: 0\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Data shape after handling missing values: (108, 20260)\n",
      "Quartiles for 'Esophageal_Cancer':\n",
      "  25%: 1.0\n",
      "  50% (Median): 1.0\n",
      "  75%: 1.0\n",
      "Min: 1.0\n",
      "Max: 1.0\n",
      "The distribution of the feature 'Esophageal_Cancer' in this dataset is severely biased.\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
}