File size: 40,545 Bytes
82732bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "fd56f70d",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:13:50.750133Z",
     "iopub.status.busy": "2025-03-25T05:13:50.750032Z",
     "iopub.status.idle": "2025-03-25T05:13:50.907429Z",
     "shell.execute_reply": "2025-03-25T05:13:50.907082Z"
    }
   },
   "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 = \"GSE75241\"\n",
    "\n",
    "# Input paths\n",
    "in_trait_dir = \"../../input/GEO/Esophageal_Cancer\"\n",
    "in_cohort_dir = \"../../input/GEO/Esophageal_Cancer/GSE75241\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/Esophageal_Cancer/GSE75241.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/Esophageal_Cancer/gene_data/GSE75241.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/Esophageal_Cancer/clinical_data/GSE75241.csv\"\n",
    "json_path = \"../../output/preprocess/Esophageal_Cancer/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "031574a0",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "f636a22a",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:13:50.908821Z",
     "iopub.status.busy": "2025-03-25T05:13:50.908684Z",
     "iopub.status.idle": "2025-03-25T05:13:50.969210Z",
     "shell.execute_reply": "2025-03-25T05:13:50.968902Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Background Information:\n",
      "!Series_title\t\"Gene expression profile of esophageal squamous cell carcinoma\"\n",
      "!Series_summary\t\"The goal was to identify the differently expressed genes between esophageal tumor and nonmalignant surrounding mucosa\"\n",
      "!Series_overall_design\t\"15 paired ESCC samples and matched nonmalignant mucosa were analyzed\"\n",
      "Sample Characteristics Dictionary:\n",
      "{0: ['patient: 1', 'patient: 2', 'patient: 3', 'patient: 4', 'patient: 5', 'patient: 6', 'patient: 7', 'patient: 8', 'patient: 9', 'patient: 10', 'patient: 11', 'patient: 12', 'patient: 14', 'patient: 15', 'patient: 16'], 1: ['tissue: nonmalignant surrounding mucosa', 'tissue: esophageal tumor'], 2: [nan, 'tumor differentiation: poor', 'tumor differentiation: moderate', 'tumor differentiation: well']}\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": "445577fe",
   "metadata": {},
   "source": [
    "### Step 2: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "c7dfb039",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:13:50.970416Z",
     "iopub.status.busy": "2025-03-25T05:13:50.970311Z",
     "iopub.status.idle": "2025-03-25T05:13:50.977217Z",
     "shell.execute_reply": "2025-03-25T05:13:50.976934Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Clinical Data Preview:\n",
      "{'GSM1946756': [0.0], 'GSM1946757': [1.0], 'GSM1946758': [0.0], 'GSM1946759': [1.0], 'GSM1946760': [0.0], 'GSM1946761': [1.0], 'GSM1946762': [0.0], 'GSM1946763': [1.0], 'GSM1946764': [0.0], 'GSM1946765': [1.0], 'GSM1946766': [0.0], 'GSM1946767': [1.0], 'GSM1946768': [0.0], 'GSM1946769': [1.0], 'GSM1946770': [0.0], 'GSM1946771': [1.0], 'GSM1946772': [0.0], 'GSM1946773': [1.0], 'GSM1946774': [0.0], 'GSM1946775': [1.0], 'GSM1946776': [0.0], 'GSM1946777': [1.0], 'GSM1946778': [0.0], 'GSM1946779': [1.0], 'GSM1946780': [0.0], 'GSM1946781': [1.0], 'GSM1946782': [0.0], 'GSM1946783': [1.0], 'GSM1946784': [0.0], 'GSM1946785': [1.0]}\n",
      "Clinical data saved to ../../output/preprocess/Esophageal_Cancer/clinical_data/GSE75241.csv\n"
     ]
    }
   ],
   "source": [
    "# 1. Gene Expression Data Availability\n",
    "# Based on the background information, this dataset contains gene expression data\n",
    "# comparing esophageal squamous cell carcinoma tumor samples with non-malignant tissue\n",
    "is_gene_available = True\n",
    "\n",
    "# 2. Variable Availability and Data Type Conversion\n",
    "# 2.1 Identify the rows in the sample characteristics dictionary for each variable\n",
    "\n",
    "# For trait - tissue type (tumor vs normal)\n",
    "trait_row = 1  # The key 1 has tumor vs non-malignant surrounding mucosa\n",
    "\n",
    "# For age - not available in the provided data\n",
    "age_row = None  # Age is not mentioned in the sample characteristics\n",
    "\n",
    "# For gender - not available in the provided data\n",
    "gender_row = None  # Gender is not mentioned in the sample characteristics\n",
    "\n",
    "# 2.2 Data Type Conversion Functions\n",
    "\n",
    "def convert_trait(value):\n",
    "    \"\"\"\n",
    "    Convert tissue type to binary:\n",
    "    0 - nonmalignant surrounding mucosa (control)\n",
    "    1 - esophageal tumor (case)\n",
    "    \"\"\"\n",
    "    if value is None or pd.isna(value):\n",
    "        return None\n",
    "    \n",
    "    # Extract the value after the colon\n",
    "    if \":\" in value:\n",
    "        value = value.split(\":\", 1)[1].strip()\n",
    "    \n",
    "    if \"tumor\" in value.lower():\n",
    "        return 1\n",
    "    elif \"nonmalignant\" in value.lower() or \"surrounding mucosa\" in value.lower():\n",
    "        return 0\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "def convert_age(value):\n",
    "    \"\"\"Placeholder function for age conversion (not used)\"\"\"\n",
    "    return None\n",
    "\n",
    "def convert_gender(value):\n",
    "    \"\"\"Placeholder function for gender conversion (not used)\"\"\"\n",
    "    return None\n",
    "\n",
    "# 3. Save Metadata\n",
    "# Determine trait data availability\n",
    "is_trait_available = trait_row is not None\n",
    "\n",
    "# Save initial validation information\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",
    "if trait_row is not None:\n",
    "    # Extract clinical features\n",
    "    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 clinical dataframe\n",
    "    print(\"Clinical Data Preview:\")\n",
    "    print(preview_df(clinical_df))\n",
    "    \n",
    "    # Create directory if it doesn't exist\n",
    "    os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
    "    \n",
    "    # Save clinical data to CSV\n",
    "    clinical_df.to_csv(out_clinical_data_file)\n",
    "    print(f\"Clinical data saved to {out_clinical_data_file}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "02797370",
   "metadata": {},
   "source": [
    "### Step 3: Gene Data Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "2af0a122",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:13:50.978352Z",
     "iopub.status.busy": "2025-03-25T05:13:50.978252Z",
     "iopub.status.idle": "2025-03-25T05:13:51.041615Z",
     "shell.execute_reply": "2025-03-25T05:13:51.041182Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Found data marker at line 64\n",
      "Header line: \"ID_REF\"\t\"GSM1946756\"\t\"GSM1946757\"\t\"GSM1946758\"\t\"GSM1946759\"\t\"GSM1946760\"\t\"GSM1946761\"\t\"GSM1946762\"\t\"GSM1946763\"\t\"GSM1946764\"\t\"GSM1946765\"\t\"GSM1946766\"\t\"GSM1946767\"\t\"GSM1946768\"\t\"GSM1946769\"\t\"GSM1946770\"\t\"GSM1946771\"\t\"GSM1946772\"\t\"GSM1946773\"\t\"GSM1946774\"\t\"GSM1946775\"\t\"GSM1946776\"\t\"GSM1946777\"\t\"GSM1946778\"\t\"GSM1946779\"\t\"GSM1946780\"\t\"GSM1946781\"\t\"GSM1946782\"\t\"GSM1946783\"\t\"GSM1946784\"\t\"GSM1946785\"\n",
      "First data line: 2315554\t8.17671\t8.3064\t8.2427\t8.39671\t8.51383\t8.12902\t8.30535\t8.38525\t7.97932\t8.13759\t8.328\t8.35267\t8.23582\t8.12066\t8.45462\t7.89502\t7.98993\t8.2095\t8.26696\t7.91252\t8.22498\t8.40417\t8.08198\t8.26314\t8.35753\t8.09386\t8.06862\t7.72916\t8.21028\t8.10057\n",
      "Index(['2315554', '2315633', '2315674', '2315739', '2315894', '2315918',\n",
      "       '2315951', '2316218', '2316245', '2316379', '2316558', '2316605',\n",
      "       '2316746', '2316905', '2316953', '2317246', '2317317', '2317434',\n",
      "       '2317472', '2317512'],\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": "f47d0721",
   "metadata": {},
   "source": [
    "### Step 4: Gene Identifier Review"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "43d55899",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:13:51.042933Z",
     "iopub.status.busy": "2025-03-25T05:13:51.042827Z",
     "iopub.status.idle": "2025-03-25T05:13:51.044616Z",
     "shell.execute_reply": "2025-03-25T05:13:51.044349Z"
    }
   },
   "outputs": [],
   "source": [
    "# Looking at the identifiers in the gene expression data (2315554, 2315633, etc.)\n",
    "# These appear to be numerical IDs rather than human gene symbols\n",
    "# They are likely probe IDs from a microarray platform and need to be mapped to gene symbols\n",
    "\n",
    "requires_gene_mapping = True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d97a8f65",
   "metadata": {},
   "source": [
    "### Step 5: Gene Annotation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "b4aea801",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:13:51.045841Z",
     "iopub.status.busy": "2025-03-25T05:13:51.045744Z",
     "iopub.status.idle": "2025-03-25T05:13:52.397509Z",
     "shell.execute_reply": "2025-03-25T05:13:52.397149Z"
    }
   },
   "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 = GSE75241\n",
      "Line 6: !Series_title = Gene expression profile of esophageal squamous cell carcinoma\n",
      "Line 7: !Series_geo_accession = GSE75241\n",
      "Line 8: !Series_status = Public on Jun 26 2019\n",
      "Line 9: !Series_submission_date = Nov 20 2015\n",
      "Line 10: !Series_last_update_date = Jan 13 2020\n",
      "Line 11: !Series_pubmed_id = 29682174\n",
      "Line 12: !Series_pubmed_id = 31901859\n",
      "Line 13: !Series_summary = The goal was to identify the differently expressed genes between esophageal tumor and nonmalignant surrounding mucosa\n",
      "Line 14: !Series_overall_design = 15 paired ESCC samples and matched nonmalignant mucosa were analyzed\n",
      "Line 15: !Series_type = Expression profiling by array\n",
      "Line 16: !Series_contributor = Pedro,P,Nicolau-Neto\n",
      "Line 17: !Series_contributor = Paulo,P,Santos\n",
      "Line 18: !Series_sample_id = GSM1946756\n",
      "Line 19: !Series_sample_id = GSM1946757\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "Gene annotation preview:\n",
      "{'ID': [2315100, 2315106, 2315109, 2315111, 2315113], 'GB_LIST': ['NR_024005,NR_034090,NR_024004,AK093685', 'DQ786314', nan, nan, 'DQ786265'], 'SPOT_ID': ['chr1:11884-14409', 'chr1:14760-15198', 'chr1:19408-19712', 'chr1:25142-25532', 'chr1:27563-27813'], 'seqname': ['chr1', 'chr1', 'chr1', 'chr1', 'chr1'], 'RANGE_GB': ['NC_000001.10', 'NC_000001.10', 'NC_000001.10', 'NC_000001.10', 'NC_000001.10'], 'RANGE_STRAND': ['+', '+', '+', '+', '+'], 'RANGE_START': ['11884', '14760', '19408', '25142', '27563'], 'RANGE_STOP': ['14409', '15198', '19712', '25532', '27813'], 'total_probes': ['20', '8', '4', '4', '4'], 'gene_assignment': ['NR_024005 // DDX11L2 // DEAD/H (Asp-Glu-Ala-Asp/His) box polypeptide 11 like 2 // 2q13 // 84771 /// NR_034090 // DDX11L9 // DEAD/H (Asp-Glu-Ala-Asp/His) box polypeptide 11 like 9 // 15q26.3 // 100288486 /// NR_024004 // DDX11L2 // DEAD/H (Asp-Glu-Ala-Asp/His) box polypeptide 11 like 2 // 2q13 // 84771 /// AK093685 // DDX11L2 // DEAD/H (Asp-Glu-Ala-Asp/His) box polypeptide 11 like 2 // 2q13 // 84771', '---', '---', '---', '---'], 'mrna_assignment': ['NR_024005 // RefSeq // Homo sapiens DEAD/H (Asp-Glu-Ala-Asp/His) box polypeptide 11 like 2 (DDX11L2), transcript variant 2, non-coding RNA. // chr1 // 100 // 80 // 16 // 16 // 0 /// NR_034090 // RefSeq // Homo sapiens DEAD/H (Asp-Glu-Ala-Asp/His) box polypeptide 11 like 9 (DDX11L9), non-coding RNA. // chr1 // 100 // 80 // 16 // 16 // 0 /// NR_024004 // RefSeq // Homo sapiens DEAD/H (Asp-Glu-Ala-Asp/His) box polypeptide 11 like 2 (DDX11L2), transcript variant 1, non-coding RNA. // chr1 // 100 // 75 // 15 // 15 // 0 /// AK093685 // GenBank // Homo sapiens cDNA FLJ36366 fis, clone THYMU2007824. // chr1 // 94 // 80 // 15 // 16 // 0 /// ENST00000513886 // ENSEMBL // cdna:known chromosome:GRCh37:16:61555:64090:1 gene:ENSG00000233614 // chr1 // 100 // 80 // 16 // 16 // 0 /// ENST00000456328 // ENSEMBL // cdna:known chromosome:GRCh37:1:11869:14409:1 gene:ENSG00000223972 // chr1 // 100 // 80 // 16 // 16 // 0 /// ENST00000518655 // ENSEMBL // cdna:known chromosome:GRCh37:1:11869:14409:1 gene:ENSG00000253101 // chr1 // 100 // 80 // 16 // 16 // 0', 'DQ786314 // GenBank // Homo sapiens clone HLS_IMAGE_811138 mRNA sequence. // chr1 // 100 // 38 // 3 // 3 // 0', '---', '---', 'DQ786265 // GenBank // Homo sapiens clone HLS_IMAGE_298685 mRNA sequence. // chr1 // 100 // 100 // 4 // 4 // 0'], 'category': ['main', 'main', '---', '---', 'main']}\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": "dc9313e4",
   "metadata": {},
   "source": [
    "### Step 6: Gene Identifier Mapping"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "4cf703d9",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:13:52.398861Z",
     "iopub.status.busy": "2025-03-25T05:13:52.398734Z",
     "iopub.status.idle": "2025-03-25T05:13:55.552990Z",
     "shell.execute_reply": "2025-03-25T05:13:55.552515Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene annotation columns: ['ID', 'GB_LIST', 'SPOT_ID', 'seqname', 'RANGE_GB', 'RANGE_STRAND', 'RANGE_START', 'RANGE_STOP', 'total_probes', 'gene_assignment', 'mrna_assignment', 'category']\n",
      "Mapping dataframe shape: (316481, 2)\n",
      "First few rows of mapping:\n",
      "        ID                                               Gene\n",
      "0  2315100  NR_024005 // DDX11L2 // DEAD/H (Asp-Glu-Ala-As...\n",
      "1  2315106                                                ---\n",
      "2  2315109                                                ---\n",
      "3  2315111                                                ---\n",
      "4  2315113                                                ---\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene expression data shape after mapping: (48895, 30)\n",
      "First few rows of gene expression data:\n",
      "      GSM1946756  GSM1946757  GSM1946758  GSM1946759  GSM1946760  GSM1946761  \\\n",
      "Gene                                                                           \n",
      "A-     19.686233   21.078992   19.644611   19.255770   19.082776   19.978018   \n",
      "A-2     3.041177    3.179220    3.144313    3.210930    3.121263    3.458567   \n",
      "A-52    4.624367    4.627967    4.647400    4.688933    4.598800    4.648167   \n",
      "A-E     1.734940    1.726010    1.729277    1.715336    1.663119    1.794793   \n",
      "A-I     6.196227    6.294127    6.293147    6.598947    6.161653    6.351923   \n",
      "\n",
      "      GSM1946762  GSM1946763  GSM1946764  GSM1946765  ...  GSM1946776  \\\n",
      "Gene                                                  ...               \n",
      "A-     19.205867   19.183984   19.728438   19.648668  ...   19.475774   \n",
      "A-2     3.038037    3.072120    3.068183    3.080643  ...    3.016570   \n",
      "A-52    4.695467    4.721133    4.626467    4.796533  ...    4.695800   \n",
      "A-E     1.751473    1.746305    1.639704    1.660835  ...    1.796903   \n",
      "A-I     6.257723    6.555667    6.270857    6.587713  ...    6.281370   \n",
      "\n",
      "      GSM1946777  GSM1946778  GSM1946779  GSM1946780  GSM1946781  GSM1946782  \\\n",
      "Gene                                                                           \n",
      "A-     19.881772   19.397177   20.176165   19.485679   19.773278   20.317010   \n",
      "A-2     3.227047    3.088177    3.113230    3.013857    3.107053    3.052563   \n",
      "A-52    4.711133    4.706633    4.729300    4.625967    4.579533    4.736200   \n",
      "A-E     1.887610    1.749953    1.701367    1.706467    1.683693    1.708582   \n",
      "A-I     6.410690    6.281490    6.437733    6.231920    6.498627    6.332860   \n",
      "\n",
      "      GSM1946783  GSM1946784  GSM1946785  \n",
      "Gene                                      \n",
      "A-     20.407381   19.243382   19.567424  \n",
      "A-2     3.206957    3.061277    3.094650  \n",
      "A-52    4.700967    4.663533    4.680933  \n",
      "A-E     1.644940    1.774332    1.727359  \n",
      "A-I     6.451783    6.306790    6.386287  \n",
      "\n",
      "[5 rows x 30 columns]\n",
      "Gene expression data shape after normalization: (18418, 30)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene expression data saved to ../../output/preprocess/Esophageal_Cancer/gene_data/GSE75241.csv\n"
     ]
    }
   ],
   "source": [
    "# 1. Identify the columns for gene IDs and gene symbols in the annotation dataframe\n",
    "# Based on the preview, we need:\n",
    "# - 'ID' column for probe IDs which matches the gene expression data index\n",
    "# - 'gene_assignment' column which contains gene symbols\n",
    "\n",
    "# First, let's parse the gene annotation properly \n",
    "gene_annotation = get_gene_annotation(soft_file)\n",
    "\n",
    "# Display the columns to confirm we have the right ones\n",
    "print(\"Gene annotation columns:\", gene_annotation.columns.tolist())\n",
    "\n",
    "# 2. Create a mapping dataframe with probe IDs and gene symbols\n",
    "# Extract the ID column and gene_assignment column\n",
    "if 'ID' in gene_annotation.columns and 'gene_assignment' in gene_annotation.columns:\n",
    "    mapping_df = get_gene_mapping(gene_annotation, 'ID', 'gene_assignment')\n",
    "    print(f\"Mapping dataframe shape: {mapping_df.shape}\")\n",
    "    print(\"First few rows of mapping:\")\n",
    "    print(mapping_df.head())\n",
    "    \n",
    "    # 3. Apply the gene mapping to convert probe-level measurements to gene expression data\n",
    "    # This handles the many-to-many relationships as described\n",
    "    gene_data = apply_gene_mapping(gene_data, mapping_df)\n",
    "    print(f\"Gene expression data shape after mapping: {gene_data.shape}\")\n",
    "    print(\"First few rows of gene expression data:\")\n",
    "    print(gene_data.head())\n",
    "    \n",
    "    # Normalize gene symbols to official symbols and aggregate duplicate genes\n",
    "    gene_data = normalize_gene_symbols_in_index(gene_data)\n",
    "    print(f\"Gene expression data shape after normalization: {gene_data.shape}\")\n",
    "    \n",
    "    # Save the gene expression data\n",
    "    os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
    "    gene_data.to_csv(out_gene_data_file)\n",
    "    print(f\"Gene expression data saved to {out_gene_data_file}\")\n",
    "else:\n",
    "    print(\"Error: Required columns not found in gene annotation dataframe\")\n",
    "    print(\"Available columns:\", gene_annotation.columns.tolist())\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d11e3914",
   "metadata": {},
   "source": [
    "### Step 7: Data Normalization and Linking"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "3577addf",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:13:55.554512Z",
     "iopub.status.busy": "2025-03-25T05:13:55.554210Z",
     "iopub.status.idle": "2025-03-25T05:14:03.639294Z",
     "shell.execute_reply": "2025-03-25T05:14:03.638706Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Normalized gene data shape: (18418, 30)\n",
      "First few genes with their expression values after normalization:\n",
      "          GSM1946756  GSM1946757  GSM1946758  GSM1946759  GSM1946760  \\\n",
      "Gene                                                                   \n",
      "A1BG        2.011265    1.946160    1.979805    2.054520    1.964573   \n",
      "A1BG-AS1    2.011265    1.946160    1.979805    2.054520    1.964573   \n",
      "A1CF        1.566023    1.530593    1.628517    1.542593    1.563090   \n",
      "A2M         4.416360    4.980305    4.217160    4.178945    4.489790   \n",
      "A2ML1       6.222100    5.579050    6.362350    5.534400    6.413550   \n",
      "\n",
      "          GSM1946761  GSM1946762  GSM1946763  GSM1946764  GSM1946765  ...  \\\n",
      "Gene                                                                  ...   \n",
      "A1BG        1.938865    1.984317    2.031433    1.959395     1.96234  ...   \n",
      "A1BG-AS1    1.938865    1.984317    2.031433    1.959395     1.96234  ...   \n",
      "A1CF        1.496433    1.624193    1.644417    1.559427     1.51756  ...   \n",
      "A2M         5.703700    3.795370    5.072700    4.543965     5.35270  ...   \n",
      "A2ML1       5.610750    6.239700    5.720800    6.172350     5.47575  ...   \n",
      "\n",
      "          GSM1946776  GSM1946777  GSM1946778  GSM1946779  GSM1946780  \\\n",
      "Gene                                                                   \n",
      "A1BG        1.994905    1.950978    2.016523    1.996433    1.952212   \n",
      "A1BG-AS1    1.994905    1.950978    2.016523    1.996433    1.952212   \n",
      "A1CF        1.684330    1.558917    1.637427    1.563087    1.576770   \n",
      "A2M         4.134060    4.864150    4.580130    5.123950    4.257135   \n",
      "A2ML1       6.057000    4.311355    6.217400    2.849605    6.131650   \n",
      "\n",
      "          GSM1946781  GSM1946782  GSM1946783  GSM1946784  GSM1946785  \n",
      "Gene                                                                  \n",
      "A1BG         1.94519    1.977313    1.872837    2.027700    1.996077  \n",
      "A1BG-AS1     1.94519    1.977313    1.872837    2.027700    1.996077  \n",
      "A1CF         1.59521    1.600170    1.479100    1.570997    1.578763  \n",
      "A2M          5.41210    4.288080    5.623400    3.803960    4.879335  \n",
      "A2ML1        5.16890    6.133500    5.276850    6.085500    5.920700  \n",
      "\n",
      "[5 rows x 30 columns]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Normalized gene data saved to ../../output/preprocess/Esophageal_Cancer/gene_data/GSE75241.csv\n",
      "Raw clinical data shape: (3, 31)\n",
      "Clinical features:\n",
      "                   GSM1946756  GSM1946757  GSM1946758  GSM1946759  GSM1946760  \\\n",
      "Esophageal_Cancer         0.0         1.0         0.0         1.0         0.0   \n",
      "\n",
      "                   GSM1946761  GSM1946762  GSM1946763  GSM1946764  GSM1946765  \\\n",
      "Esophageal_Cancer         1.0         0.0         1.0         0.0         1.0   \n",
      "\n",
      "                   ...  GSM1946776  GSM1946777  GSM1946778  GSM1946779  \\\n",
      "Esophageal_Cancer  ...         0.0         1.0         0.0         1.0   \n",
      "\n",
      "                   GSM1946780  GSM1946781  GSM1946782  GSM1946783  GSM1946784  \\\n",
      "Esophageal_Cancer         0.0         1.0         0.0         1.0         0.0   \n",
      "\n",
      "                   GSM1946785  \n",
      "Esophageal_Cancer         1.0  \n",
      "\n",
      "[1 rows x 30 columns]\n",
      "Clinical features saved to ../../output/preprocess/Esophageal_Cancer/clinical_data/GSE75241.csv\n",
      "Linked data shape: (30, 18419)\n",
      "Linked data preview (first 5 rows, first 5 columns):\n",
      "            Esophageal_Cancer      A1BG  A1BG-AS1      A1CF       A2M\n",
      "GSM1946756                0.0  2.011265  2.011265  1.566023  4.416360\n",
      "GSM1946757                1.0  1.946160  1.946160  1.530593  4.980305\n",
      "GSM1946758                0.0  1.979805  1.979805  1.628517  4.217160\n",
      "GSM1946759                1.0  2.054520  2.054520  1.542593  4.178945\n",
      "GSM1946760                0.0  1.964573  1.964573  1.563090  4.489790\n",
      "Missing values before handling:\n",
      "  Trait (Esophageal_Cancer) missing: 0 out of 30\n",
      "  Genes with >20% missing: 0\n",
      "  Samples with >5% missing genes: 0\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Data shape after handling missing values: (30, 18419)\n",
      "For the feature 'Esophageal_Cancer', the least common label is '0.0' with 15 occurrences. This represents 50.00% of the dataset.\n",
      "The distribution of the feature 'Esophageal_Cancer' in this dataset is fine.\n",
      "\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Linked data saved to ../../output/preprocess/Esophageal_Cancer/GSE75241.csv\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
}