File size: 37,092 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
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "0e5f2abf",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:14:04.711942Z",
     "iopub.status.busy": "2025-03-25T05:14:04.711438Z",
     "iopub.status.idle": "2025-03-25T05:14:04.885534Z",
     "shell.execute_reply": "2025-03-25T05:14:04.885179Z"
    }
   },
   "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 = \"GSE77790\"\n",
    "\n",
    "# Input paths\n",
    "in_trait_dir = \"../../input/GEO/Esophageal_Cancer\"\n",
    "in_cohort_dir = \"../../input/GEO/Esophageal_Cancer/GSE77790\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/Esophageal_Cancer/GSE77790.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/Esophageal_Cancer/gene_data/GSE77790.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/Esophageal_Cancer/clinical_data/GSE77790.csv\"\n",
    "json_path = \"../../output/preprocess/Esophageal_Cancer/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8810f510",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "18729a2a",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:14:04.887218Z",
     "iopub.status.busy": "2025-03-25T05:14:04.887042Z",
     "iopub.status.idle": "2025-03-25T05:14:05.070065Z",
     "shell.execute_reply": "2025-03-25T05:14:05.069711Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Background Information:\n",
      "!Series_title\t\"Differentially expressed genes after miRNA or siRNA transfection in human cancer cell lines II\"\n",
      "!Series_summary\t\"To identify differentially expressed genes by anti cancer treatments (microRNAs or siRNAs) in human cancer, several cell lines (pancreatic cancer, esophageal cancer, bladder cancer, prostate cancer, renal cell carcinoma and lung squamous cell carcinoma) were subjected to Agilent whole genome microarrays.\"\n",
      "!Series_overall_design\t\"Human cell lines (Panc-1, sw1990, TE8, TE9, A549, MRC-5, BOY, T24, PC3, C4-2, 786-O, A-498 and EBC-1) were treated with miRNAs (miR-375, miR-29a, miR-26a, miR-145-5p, miR-145-3p, miR-218, miR-320a), siRNAs (si-MMP11, si-LAMP1, si-LOXL2, si-PLOD2, si-UHRF1, and si-FOXM1).\"\n",
      "Sample Characteristics Dictionary:\n",
      "{0: ['cell line: EBC-1', 'cell line: C4-2', 'cell line: PC3', 'cell line: A-498', 'cell line: 786-O', 'cell line: BOY', 'cell line: T24', 'cell line: A549', 'cell line: MRC-5', 'cell line: Panc-1', 'cell line: sw1990', 'cell line: TE8', 'cell line: TE9'], 1: ['cell type: lung squamous cell carcinoma', 'cell type: prostate cancer', 'cell type: bladder cancer', 'cell type: renal cell carcinoma', 'cell type: lung fibroblast', 'cell type: pancreatic cancer', 'cell type: esophageal cancer'], 2: ['transfection: no transfection']}\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": "53d60589",
   "metadata": {},
   "source": [
    "### Step 2: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "f56bf704",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:14:05.071289Z",
     "iopub.status.busy": "2025-03-25T05:14:05.071168Z",
     "iopub.status.idle": "2025-03-25T05:14:05.078318Z",
     "shell.execute_reply": "2025-03-25T05:14:05.078014Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Clinical Data Preview:\n",
      "{0: [0.0]}\n",
      "Clinical data saved to ../../output/preprocess/Esophageal_Cancer/clinical_data/GSE77790.csv\n"
     ]
    }
   ],
   "source": [
    "# 1. Gene Expression Data Analysis\n",
    "# Based on the background information, this dataset appears to be gene expression data\n",
    "# from microarray analysis, which is suitable for our study.\n",
    "is_gene_available = True\n",
    "\n",
    "# 2. Clinical Features Analysis\n",
    "# 2.1 Data Availability\n",
    "# For trait (esophageal cancer), we can use the cell type information (row 1)\n",
    "# For age and gender, there's no information in the sample characteristics\n",
    "trait_row = 1\n",
    "age_row = None  # No age data available\n",
    "gender_row = None  # No gender data available\n",
    "\n",
    "# 2.2 Data Type Conversion Functions\n",
    "def convert_trait(value):\n",
    "    \"\"\"Convert cell type to binary trait (esophageal cancer or not)\"\"\"\n",
    "    if not isinstance(value, str):\n",
    "        return None\n",
    "    \n",
    "    # Extract the value after the colon\n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip().lower()\n",
    "    \n",
    "    # Check if it's esophageal cancer\n",
    "    if 'esophageal cancer' in value:\n",
    "        return 1\n",
    "    else:\n",
    "        return 0\n",
    "\n",
    "def convert_age(value):\n",
    "    # Not used, as age data is not available\n",
    "    return None\n",
    "\n",
    "def convert_gender(value):\n",
    "    # Not used, as gender data is not available\n",
    "    return None\n",
    "\n",
    "# 3. Save Metadata\n",
    "# Check if trait data is available (trait_row is not None)\n",
    "is_trait_available = trait_row is not None\n",
    "validate_and_save_cohort_info(\n",
    "    is_final=False, \n",
    "    cohort=cohort, \n",
    "    info_path=json_path, \n",
    "    is_gene_available=is_gene_available, \n",
    "    is_trait_available=is_trait_available\n",
    ")\n",
    "\n",
    "# 4. Clinical Feature Extraction\n",
    "# Only execute if trait_row is not None\n",
    "if trait_row is not None:\n",
    "    # Create a DataFrame from the sample characteristics dictionary provided in the previous output\n",
    "    sample_characteristics_dict = {\n",
    "        0: ['cell line: EBC-1', 'cell line: C4-2', 'cell line: PC3', 'cell line: A-498', \n",
    "            'cell line: 786-O', 'cell line: BOY', 'cell line: T24', 'cell line: A549', \n",
    "            'cell line: MRC-5', 'cell line: Panc-1', 'cell line: sw1990', 'cell line: TE8', \n",
    "            'cell line: TE9'],\n",
    "        1: ['cell type: lung squamous cell carcinoma', 'cell type: prostate cancer', \n",
    "            'cell type: bladder cancer', 'cell type: renal cell carcinoma', \n",
    "            'cell type: lung fibroblast', 'cell type: pancreatic cancer', \n",
    "            'cell type: esophageal cancer'],\n",
    "        2: ['transfection: no transfection']\n",
    "    }\n",
    "    \n",
    "    import pandas as pd\n",
    "    # Creating the clinical_data DataFrame from the dictionary\n",
    "    # We need to transpose the data to get samples as rows and features as columns\n",
    "    clinical_data = pd.DataFrame({col: values for col, values in enumerate(list(zip(*[values for values in sample_characteristics_dict.values()])))})\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 data\n",
    "    preview = preview_df(selected_clinical_df)\n",
    "    print(\"Clinical Data Preview:\")\n",
    "    print(preview)\n",
    "    \n",
    "    # Save clinical features 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=False)\n",
    "    print(f\"Clinical data saved to {out_clinical_data_file}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0d658b99",
   "metadata": {},
   "source": [
    "### Step 3: Gene Data Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "80cef9dc",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:14:05.079492Z",
     "iopub.status.busy": "2025-03-25T05:14:05.079380Z",
     "iopub.status.idle": "2025-03-25T05:14:05.372105Z",
     "shell.execute_reply": "2025-03-25T05:14:05.371720Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Found data marker at line 81\n",
      "Header line: \"ID_REF\"\t\"GSM2059404\"\t\"GSM2059405\"\t\"GSM2059406\"\t\"GSM2059407\"\t\"GSM2059408\"\t\"GSM2059409\"\t\"GSM2059410\"\t\"GSM2059411\"\t\"GSM2059412\"\t\"GSM2059413\"\t\"GSM2059414\"\t\"GSM2059415\"\t\"GSM2059416\"\t\"GSM2059417\"\t\"GSM2059418\"\t\"GSM2059419\"\t\"GSM2059420\"\t\"GSM2059421\"\t\"GSM2059422\"\t\"GSM2059423\"\t\"GSM2059424\"\t\"GSM2059425\"\t\"GSM2059426\"\t\"GSM2059427\"\t\"GSM2059428\"\t\"GSM2059429\"\t\"GSM2059430\"\t\"GSM2059431\"\t\"GSM2059432\"\t\"GSM2059433\"\t\"GSM2059434\"\t\"GSM2059435\"\n",
      "First data line: 1\t-1.492678368e-001\t9.385965497e-002\t-8.941784384e-002\t-1.349943700e-002\t-1.599001264e-002\t-8.062755446e-002\t-5.685066626e-002\t3.483449753e-002\t1.110190735e-002\t-1.109288193e-002\t-3.863425129e-002\t-4.031110222e-002\t3.436493922e-002\t6.242996551e-002\t-3.869467488e-002\t-2.818536224e-004\t-6.648348866e-002\t-7.110430995e-002\t-1.601804138e-003\t-6.578105194e-002\t-9.610465045e-004\t3.293553993e-002\t5.540124407e-002\t-7.305230142e-002\t-1.253722506e-002\t-6.620679603e-003\t-7.651308691e-002\t-5.726181154e-002\t-2.069165415e-002\t9.842492290e-003\t4.916461191e-002\t3.215693397e-002\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Index(['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13',\n",
      "       '14', '15', '16', '17', '18', '19', '20'],\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": "47b4d448",
   "metadata": {},
   "source": [
    "### Step 4: Gene Identifier Review"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "c4ac7618",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:14:05.373458Z",
     "iopub.status.busy": "2025-03-25T05:14:05.373328Z",
     "iopub.status.idle": "2025-03-25T05:14:05.375249Z",
     "shell.execute_reply": "2025-03-25T05:14:05.374960Z"
    }
   },
   "outputs": [],
   "source": [
    "# Looking at the gene identifiers in the gene expression data\n",
    "# The identifiers are numerical (1, 2, 3, etc.) which are not standard human gene symbols\n",
    "# These appear to be probe IDs that need to be mapped to gene symbols\n",
    "\n",
    "requires_gene_mapping = True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a849f4fb",
   "metadata": {},
   "source": [
    "### Step 5: Gene Annotation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "f55c9aa7",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:14:05.376402Z",
     "iopub.status.busy": "2025-03-25T05:14:05.376289Z",
     "iopub.status.idle": "2025-03-25T05:14:05.984312Z",
     "shell.execute_reply": "2025-03-25T05:14:05.983897Z"
    }
   },
   "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 = GSE77790\n",
      "Line 6: !Series_title = Differentially expressed genes after miRNA or siRNA transfection in human cancer cell lines II\n",
      "Line 7: !Series_geo_accession = GSE77790\n",
      "Line 8: !Series_status = Public on Apr 13 2016\n",
      "Line 9: !Series_submission_date = Feb 10 2016\n",
      "Line 10: !Series_last_update_date = Oct 07 2019\n",
      "Line 11: !Series_pubmed_id = 27633630\n",
      "Line 12: !Series_pubmed_id = 27862697\n",
      "Line 13: !Series_pubmed_id = 27072587\n",
      "Line 14: !Series_pubmed_id = 27779648\n",
      "Line 15: !Series_pubmed_id = 27765924\n",
      "Line 16: !Series_pubmed_id = 29050264\n",
      "Line 17: !Series_summary = To identify differentially expressed genes by anti cancer treatments (microRNAs or siRNAs) in human cancer, several cell lines (pancreatic cancer, esophageal cancer, bladder cancer, prostate cancer, renal cell carcinoma and lung squamous cell carcinoma) were subjected to Agilent whole genome microarrays.\n",
      "Line 18: !Series_overall_design = Human cell lines (Panc-1, sw1990, TE8, TE9, A549, MRC-5, BOY, T24, PC3, C4-2, 786-O, A-498 and EBC-1) were treated with miRNAs (miR-375, miR-29a, miR-26a, miR-145-5p, miR-145-3p, miR-218, miR-320a), siRNAs (si-MMP11, si-LAMP1, si-LOXL2, si-PLOD2, si-UHRF1, and si-FOXM1).\n",
      "Line 19: !Series_type = Expression profiling by array\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "Gene annotation preview:\n",
      "{'ID': [1, 2, 3, 4, 5], 'COL': [192, 192, 192, 192, 192], 'ROW': [328, 326, 324, 322, 320], 'NAME': ['GE_BrightCorner', 'DarkCorner', 'DarkCorner', 'A_21_P0014386', 'A_33_P3396872'], 'SPOT_ID': ['GE_BrightCorner', 'DarkCorner', 'DarkCorner', 'A_21_P0014386', 'A_33_P3396872'], 'CONTROL_TYPE': ['pos', 'pos', 'pos', 'FALSE', 'FALSE'], 'REFSEQ': [nan, nan, nan, nan, 'NM_001105533'], 'GB_ACC': [nan, nan, nan, nan, 'NM_001105533'], 'LOCUSLINK_ID': [nan, nan, nan, nan, 79974.0], 'GENE_SYMBOL': [nan, nan, nan, nan, 'CPED1'], 'GENE_NAME': [nan, nan, nan, nan, 'cadherin-like and PC-esterase domain containing 1'], 'UNIGENE_ID': [nan, nan, nan, nan, 'Hs.189652'], 'ENSEMBL_ID': [nan, nan, nan, nan, nan], 'TIGR_ID': [nan, nan, nan, nan, nan], 'ACCESSION_STRING': [nan, nan, nan, nan, 'ref|NM_001105533|gb|AK025639|gb|BC030538|tc|THC2601673'], 'CHROMOSOMAL_LOCATION': [nan, nan, nan, 'unmapped', 'chr7:120901888-120901947'], 'CYTOBAND': [nan, nan, nan, nan, 'hs|7q31.31'], 'DESCRIPTION': [nan, nan, nan, nan, 'Homo sapiens cadherin-like and PC-esterase domain containing 1 (CPED1), transcript variant 2, mRNA [NM_001105533]'], 'GO_ID': [nan, nan, nan, nan, 'GO:0005783(endoplasmic reticulum)'], 'SEQUENCE': [nan, nan, nan, 'AATACATGTTTTGGTAAACACTCGGTCAGAGCACCCTCTTTCTGTGGAATCAGACTGGCA', 'GCTTATCTCACCTAATACAGGGACTATGCAACCAAGAAACTGGAAATAAAAACAAAGATA'], 'SPOT_ID.1': [nan, nan, nan, nan, nan]}\n"
     ]
    }
   ],
   "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": "11b70f6c",
   "metadata": {},
   "source": [
    "### Step 6: Gene Identifier Mapping"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "a3239666",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:14:05.985608Z",
     "iopub.status.busy": "2025-03-25T05:14:05.985480Z",
     "iopub.status.idle": "2025-03-25T05:14:06.140052Z",
     "shell.execute_reply": "2025-03-25T05:14:06.139650Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene mapping preview:\n",
      "{'ID': ['5', '6', '7', '8', '12'], 'Gene': ['CPED1', 'BCOR', 'CHAC2', 'IFI30', 'GPR146']}\n",
      "\n",
      "Gene expression data after mapping:\n",
      "Number of genes: 29222\n",
      "Number of samples: 32\n",
      "Sample of first few genes:\n",
      "          GSM2059404  GSM2059405  GSM2059406\n",
      "Gene                                        \n",
      "A1BG       -0.026845    0.292602   -0.127231\n",
      "A1BG-AS1    0.000000    0.000000    0.000000\n",
      "A1CF       -0.003664    0.000000    0.000000\n",
      "A1CF-2      0.000000    0.000000    0.000000\n",
      "A1CF-3      0.086574    0.000000    0.000000\n"
     ]
    }
   ],
   "source": [
    "# 1. Determine which columns contain the identifiers and gene symbols\n",
    "# From previous output, we can see:\n",
    "# - 'ID' column contains numeric identifiers matching our gene expression data\n",
    "# - 'GENE_SYMBOL' column contains the gene symbols we need\n",
    "\n",
    "# Create a mapping dataframe with the identifier and gene symbol columns\n",
    "gene_mapping = get_gene_mapping(\n",
    "    annotation=gene_annotation,\n",
    "    prob_col='ID',\n",
    "    gene_col='GENE_SYMBOL'\n",
    ")\n",
    "\n",
    "# Preview the mapping\n",
    "print(\"Gene mapping preview:\")\n",
    "print(preview_df(gene_mapping))\n",
    "\n",
    "# 2. 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",
    "# Preview the gene expression data after mapping\n",
    "print(\"\\nGene expression data after mapping:\")\n",
    "print(f\"Number of genes: {len(gene_data)}\")\n",
    "print(f\"Number of samples: {len(gene_data.columns)}\")\n",
    "print(\"Sample of first few genes:\")\n",
    "print(gene_data.head(5).iloc[:, :3])  # Show first 5 genes, first 3 samples\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a5bba099",
   "metadata": {},
   "source": [
    "### Step 7: Data Normalization and Linking"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "94d5a16a",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:14:06.141435Z",
     "iopub.status.busy": "2025-03-25T05:14:06.141317Z",
     "iopub.status.idle": "2025-03-25T05:14:13.254506Z",
     "shell.execute_reply": "2025-03-25T05:14:13.254161Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Normalized gene data shape: (20778, 32)\n",
      "First few genes with their expression values after normalization:\n",
      "          GSM2059404  GSM2059405  GSM2059406  GSM2059407  GSM2059408  \\\n",
      "Gene                                                                   \n",
      "A1BG       -0.026845    0.292602   -0.127231   -0.125141   -0.076007   \n",
      "A1BG-AS1    0.000000    0.000000    0.000000    0.251289    0.082415   \n",
      "A1CF       -0.003664    0.000000    0.000000    0.000000    0.000000   \n",
      "A2M         0.103392    0.000000   -0.070657    0.483920   -0.159715   \n",
      "A2M-AS1    -0.022907   -0.019728   -0.104097   -0.203670   -0.555398   \n",
      "\n",
      "          GSM2059409  GSM2059410  GSM2059411  GSM2059412  GSM2059413  ...  \\\n",
      "Gene                                                                  ...   \n",
      "A1BG       -0.009207   -0.082495    0.189666   -0.237983   -0.006939  ...   \n",
      "A1BG-AS1    0.065617    0.000000    0.000000   -0.050387   -0.103464  ...   \n",
      "A1CF        0.000000   -0.243397    0.000000    0.000000    0.000000  ...   \n",
      "A2M         0.173058   -0.342849    0.435977    0.523215    0.318503  ...   \n",
      "A2M-AS1    -0.335948    0.189627    0.046185   -0.490978    0.251301  ...   \n",
      "\n",
      "          GSM2059426  GSM2059427  GSM2059428  GSM2059429  GSM2059430  \\\n",
      "Gene                                                                   \n",
      "A1BG       -0.058951   -0.083353   -0.207919   -0.198724   -0.385907   \n",
      "A1BG-AS1    0.120403    0.007354   -0.098147   -0.032209   -0.106467   \n",
      "A1CF        0.000000    0.000000    0.000000    0.000000   -0.146621   \n",
      "A2M         0.000000    0.000000    0.000000    0.000000    0.009201   \n",
      "A2M-AS1     0.344190   -0.187586    0.010471   -0.310572   -0.194673   \n",
      "\n",
      "          GSM2059431  GSM2059432  GSM2059433  GSM2059434  GSM2059435  \n",
      "Gene                                                                  \n",
      "A1BG       -0.275737    0.065018    0.106474   -0.202607    0.198972  \n",
      "A1BG-AS1    0.029031   -0.058106    0.063948    0.053285    0.147985  \n",
      "A1CF        0.000000    0.372980   -0.050298   -0.307278   -0.127532  \n",
      "A2M         0.157753    0.614686    0.000000   -0.160533   -0.044805  \n",
      "A2M-AS1    -0.230303   -0.125125    0.013175    0.209994   -0.157355  \n",
      "\n",
      "[5 rows x 32 columns]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Normalized gene data saved to ../../output/preprocess/Esophageal_Cancer/gene_data/GSE77790.csv\n",
      "Raw clinical data shape: (3, 33)\n",
      "Clinical features:\n",
      "                   GSM2059404  GSM2059405  GSM2059406  GSM2059407  GSM2059408  \\\n",
      "Esophageal_Cancer         0.0         0.0         0.0         0.0         0.0   \n",
      "\n",
      "                   GSM2059409  GSM2059410  GSM2059411  GSM2059412  GSM2059413  \\\n",
      "Esophageal_Cancer         0.0         0.0         0.0         0.0         0.0   \n",
      "\n",
      "                   ...  GSM2059426  GSM2059427  GSM2059428  GSM2059429  \\\n",
      "Esophageal_Cancer  ...         0.0         0.0         0.0         0.0   \n",
      "\n",
      "                   GSM2059430  GSM2059431  GSM2059432  GSM2059433  GSM2059434  \\\n",
      "Esophageal_Cancer         1.0         1.0         0.0         0.0         0.0   \n",
      "\n",
      "                   GSM2059435  \n",
      "Esophageal_Cancer         0.0  \n",
      "\n",
      "[1 rows x 32 columns]\n",
      "Clinical features saved to ../../output/preprocess/Esophageal_Cancer/clinical_data/GSE77790.csv\n",
      "Linked data shape: (32, 20779)\n",
      "Linked data preview (first 5 rows, first 5 columns):\n",
      "            Esophageal_Cancer      A1BG  A1BG-AS1      A1CF       A2M\n",
      "GSM2059404                0.0 -0.026845  0.000000 -0.003664  0.103392\n",
      "GSM2059405                0.0  0.292602  0.000000  0.000000  0.000000\n",
      "GSM2059406                0.0 -0.127231  0.000000  0.000000 -0.070657\n",
      "GSM2059407                0.0 -0.125141  0.251289  0.000000  0.483920\n",
      "GSM2059408                0.0 -0.076007  0.082415  0.000000 -0.159715\n",
      "Missing values before handling:\n",
      "  Trait (Esophageal_Cancer) missing: 0 out of 32\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: (32, 20779)\n",
      "For the feature 'Esophageal_Cancer', the least common label is '1.0' with 2 occurrences. This represents 6.25% of the dataset.\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
}