File size: 40,093 Bytes
32677ff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "7e88c4c8",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:42:37.496499Z",
     "iopub.status.busy": "2025-03-25T08:42:37.496318Z",
     "iopub.status.idle": "2025-03-25T08:42:37.663193Z",
     "shell.execute_reply": "2025-03-25T08:42:37.662830Z"
    }
   },
   "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 = \"Endometrioid_Cancer\"\n",
    "cohort = \"GSE73551\"\n",
    "\n",
    "# Input paths\n",
    "in_trait_dir = \"../../input/GEO/Endometrioid_Cancer\"\n",
    "in_cohort_dir = \"../../input/GEO/Endometrioid_Cancer/GSE73551\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/Endometrioid_Cancer/GSE73551.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/Endometrioid_Cancer/gene_data/GSE73551.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/Endometrioid_Cancer/clinical_data/GSE73551.csv\"\n",
    "json_path = \"../../output/preprocess/Endometrioid_Cancer/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "97874008",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "05de641f",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:42:37.664645Z",
     "iopub.status.busy": "2025-03-25T08:42:37.664505Z",
     "iopub.status.idle": "2025-03-25T08:42:38.078574Z",
     "shell.execute_reply": "2025-03-25T08:42:38.078163Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Background Information:\n",
      "!Series_title\t\"Prior Knowledge Transfer Across Transcriptional Datasets Using Compositional Statistics [Tumor]\"\n",
      "!Series_summary\t\"An expert-pathologist-reviewed epithelial ovarian cancer reference library (n = 50) used to assign the histopathology of epithelial ovarian cell lines using compositional statistics and random gene-sets\"\n",
      "!Series_overall_design\t\"In the study presented here, we applied Gene Expression Compositional Assignment (GECA) to epithelial ovarian cell lines (GSE73637), using first a reference library of solid tumors (expO [http://www.intgen.org/expo/]) and then a second library of expert pathologically-reviewed epithelial ovarian cancer samples\"\n",
      "Sample Characteristics Dictionary:\n",
      "{0: ['cell type: MUCINOUS', 'cell type: CLEAR CELL', 'cell type: SEROUS LOW-GRADE', 'cell type: ENDOMETRIOID', 'cell type: SEROUS'], 1: ['tissue: Epithelial Ovarian Cancer']}\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": "cef083fa",
   "metadata": {},
   "source": [
    "### Step 2: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "466dd418",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:42:38.080070Z",
     "iopub.status.busy": "2025-03-25T08:42:38.079945Z",
     "iopub.status.idle": "2025-03-25T08:42:38.087761Z",
     "shell.execute_reply": "2025-03-25T08:42:38.087467Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Preview of clinical features:\n",
      "{'MUCINOUS': [0.0], 'CLEAR CELL': [0.0], 'SEROUS LOW-GRADE': [0.0], 'ENDOMETRIOID': [1.0], 'SEROUS': [0.0]}\n",
      "Clinical features saved to ../../output/preprocess/Endometrioid_Cancer/clinical_data/GSE73551.csv\n"
     ]
    }
   ],
   "source": [
    "# 1. Gene Expression Data Availability\n",
    "# Based on the series title and overall design, this dataset appears to contain transcriptional data\n",
    "is_gene_available = True\n",
    "\n",
    "# 2. Variable Availability and Data Type Conversion\n",
    "# 2.1 Data Availability\n",
    "# For trait (Endometrioid_Cancer), we can use the cell type information in row 0\n",
    "trait_row = 0\n",
    "\n",
    "# Age data is not available in the sample characteristics\n",
    "age_row = None\n",
    "\n",
    "# Gender data is not available in the sample characteristics\n",
    "gender_row = None\n",
    "\n",
    "# 2.2 Data Type Conversion\n",
    "def convert_trait(value):\n",
    "    \"\"\"\n",
    "    Convert the cell type value to a binary trait for Endometrioid Cancer\n",
    "    1 for endometrioid, 0 for other types\n",
    "    \"\"\"\n",
    "    if pd.isna(value):\n",
    "        return None\n",
    "        \n",
    "    # Extract the value after colon if it exists\n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip()\n",
    "    \n",
    "    # Check if the cell type is endometrioid (case insensitive)\n",
    "    if 'endometrioid' in value.lower():\n",
    "        return 1\n",
    "    else:\n",
    "        return 0\n",
    "\n",
    "# Age conversion function (not used since age data is not available)\n",
    "def convert_age(value):\n",
    "    return None\n",
    "\n",
    "# Gender conversion function (not used since gender data is not available)\n",
    "def convert_gender(value):\n",
    "    return None\n",
    "\n",
    "# 3. Save Metadata\n",
    "# Determine if trait data is available (trait_row is not None)\n",
    "is_trait_available = trait_row is not None\n",
    "\n",
    "# Validate and save cohort 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",
    "    # Since we don't have a CSV file, we'll use the sample characteristics dictionary directly\n",
    "    # Create the clinical_data dataframe from the sample characteristics dictionary\n",
    "    sample_char_dict = {0: ['cell type: MUCINOUS', 'cell type: CLEAR CELL', 'cell type: SEROUS LOW-GRADE', \n",
    "                           'cell type: ENDOMETRIOID', 'cell type: SEROUS'], \n",
    "                        1: ['tissue: Epithelial Ovarian Cancer']}\n",
    "    \n",
    "    # Convert sample characteristics dictionary to a dataframe\n",
    "    # We need to create a dataframe with samples as columns and characteristics as rows\n",
    "    # First, extract unique values for each characteristic\n",
    "    unique_values = {}\n",
    "    for key, values in sample_char_dict.items():\n",
    "        unique_values[key] = values\n",
    "    \n",
    "    # Create a dummy dataframe with this information\n",
    "    # In a real dataset, we would have sample IDs as columns, but here we'll use the cell types as samples\n",
    "    samples = []\n",
    "    for value in unique_values[0]:  # Use cell types as samples\n",
    "        sample_name = value.split(\": \")[1] if \": \" in value else value\n",
    "        samples.append(sample_name)\n",
    "    \n",
    "    # Create the dataframe\n",
    "    data = {sample: [] for sample in samples}\n",
    "    for i, cell_type in enumerate(samples):\n",
    "        data[cell_type] = [f\"cell type: {cell_type}\" if j == 0 else unique_values[j][0] for j in range(len(unique_values))]\n",
    "    \n",
    "    clinical_data = pd.DataFrame(data)\n",
    "    \n",
    "    # Extract clinical features\n",
    "    clinical_features = geo_select_clinical_features(\n",
    "        clinical_df=clinical_data,\n",
    "        trait=trait,\n",
    "        trait_row=trait_row,\n",
    "        convert_trait=convert_trait,\n",
    "        age_row=age_row,\n",
    "        convert_age=convert_age,\n",
    "        gender_row=gender_row,\n",
    "        convert_gender=convert_gender\n",
    "    )\n",
    "    \n",
    "    # Preview the dataframe\n",
    "    preview = preview_df(clinical_features)\n",
    "    print(\"Preview of clinical features:\")\n",
    "    print(preview)\n",
    "    \n",
    "    # Save the clinical features to the specified 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"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "576a8192",
   "metadata": {},
   "source": [
    "### Step 3: Gene Data Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "99cee681",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:42:38.088903Z",
     "iopub.status.busy": "2025-03-25T08:42:38.088794Z",
     "iopub.status.idle": "2025-03-25T08:42:38.729244Z",
     "shell.execute_reply": "2025-03-25T08:42:38.728849Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Found data marker at line 59\n",
      "Header line: \"ID_REF\"\t\"GSM1897741\"\t\"GSM1897744\"\t\"GSM1897746\"\t\"GSM1897748\"\t\"GSM1897750\"\t\"GSM1897752\"\t\"GSM1897753\"\t\"GSM1897755\"\t\"GSM1897757\"\t\"GSM1897759\"\t\"GSM1897761\"\t\"GSM1897763\"\t\"GSM1897765\"\t\"GSM1897767\"\t\"GSM1897769\"\t\"GSM1897770\"\t\"GSM1897772\"\t\"GSM1897774\"\t\"GSM1897776\"\t\"GSM1897778\"\t\"GSM1897780\"\t\"GSM1897782\"\t\"GSM1897784\"\t\"GSM1897786\"\t\"GSM1897787\"\t\"GSM1897789\"\t\"GSM1897792\"\t\"GSM1897794\"\t\"GSM1897795\"\t\"GSM1897797\"\t\"GSM1897799\"\t\"GSM1897801\"\t\"GSM1897802\"\t\"GSM1897804\"\t\"GSM1897806\"\t\"GSM1897808\"\t\"GSM1897810\"\t\"GSM1897812\"\t\"GSM1897814\"\t\"GSM1897816\"\t\"GSM1897818\"\t\"GSM1897820\"\t\"GSM1897822\"\t\"GSM1897823\"\t\"GSM1897825\"\t\"GSM1897827\"\t\"GSM1897829\"\t\"GSM1897831\"\t\"GSM1897833\"\t\"GSM1897835\"\n",
      "First data line: 1\t5.403790297\t4.892553637\t5.326199224\t5.170940973\t5.427630826\t5.516932949\t5.470710937\t4.98660365\t5.133514638\t5.230458349\t4.990772814\t5.662734397\t5.696864862\t5.147933271\t4.86309129\t5.394637232\t5.381253066\t5.842655059\t5.545258599\t5.707996433\t5.684696894\t5.428043787\t5.099403081\t5.572583866\t5.715332586\t5.218152374\t4.765819974\t5.376930844\t6.175791799\t5.014040109\t4.829511887\t5.217120904\t4.591215425\t5.630381621\t5.19785045\t5.666201739\t5.509745722\t5.455583973\t4.731499955\t4.649977023\t5.034881723\t4.920999754\t5.041737535\t4.820794888\t5.334202161\t5.51383308\t5.340668225\t4.904084267\t5.331123029\t5.742880178\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": "68afb96f",
   "metadata": {},
   "source": [
    "### Step 4: Gene Identifier Review"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "857c8a3a",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:42:38.730571Z",
     "iopub.status.busy": "2025-03-25T08:42:38.730442Z",
     "iopub.status.idle": "2025-03-25T08:42:38.732354Z",
     "shell.execute_reply": "2025-03-25T08:42:38.732064Z"
    }
   },
   "outputs": [],
   "source": [
    "# The gene identifiers shown in the data are numeric IDs (1, 2, 3, etc.), not human gene symbols.\n",
    "# These are likely probe IDs or some other form of identifier that needs to be mapped to gene symbols.\n",
    "\n",
    "requires_gene_mapping = True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2ea15c1a",
   "metadata": {},
   "source": [
    "### Step 5: Gene Annotation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "e5c238f0",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:42:38.733522Z",
     "iopub.status.busy": "2025-03-25T08:42:38.733413Z",
     "iopub.status.idle": "2025-03-25T08:42:39.792452Z",
     "shell.execute_reply": "2025-03-25T08:42:39.791907Z"
    }
   },
   "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 = GSE73551\n",
      "Line 6: !Series_title = Prior Knowledge Transfer Across Transcriptional Datasets Using Compositional Statistics [Tumor]\n",
      "Line 7: !Series_geo_accession = GSE73551\n",
      "Line 8: !Series_status = Public on Nov 08 2016\n",
      "Line 9: !Series_submission_date = Sep 29 2015\n",
      "Line 10: !Series_last_update_date = Nov 10 2016\n",
      "Line 11: !Series_pubmed_id = 27353327\n",
      "Line 12: !Series_summary = An expert-pathologist-reviewed epithelial ovarian cancer reference library (n = 50) used to assign the histopathology of epithelial ovarian cell lines using compositional statistics and random gene-sets\n",
      "Line 13: !Series_overall_design = In the study presented here, we applied Gene Expression Compositional Assignment (GECA) to epithelial ovarian cell lines (GSE73637), using first a reference library of solid tumors (expO [http://www.intgen.org/expo/]) and then a second library of expert pathologically-reviewed epithelial ovarian cancer samples\n",
      "Line 14: !Series_type = Expression profiling by array\n",
      "Line 15: !Series_contributor = Jaine,K,Blayney\n",
      "Line 16: !Series_sample_id = GSM1897741\n",
      "Line 17: !Series_sample_id = GSM1897744\n",
      "Line 18: !Series_sample_id = GSM1897746\n",
      "Line 19: !Series_sample_id = GSM1897748\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "Gene annotation preview:\n",
      "{'ID': [1, 2, 3, 4, 5], 'ProbeSetID': ['200000_s_at', '200001_at', '200002_at', '200003_s_at', '200004_at'], 'GeneSymbol': ['PRPF8', 'CAPNS1', 'RPL35', 'RPL28', 'EIF4G2'], 'Array': ['Ovarian Cancer DSA', 'Ovarian Cancer DSA', 'Ovarian Cancer DSA', 'Ovarian Cancer DSA', 'Ovarian Cancer DSA'], 'Annotation Date': ['10-Jan-11', '10-Jan-11', '10-Jan-11', '10-Jan-11', '10-Jan-11'], 'Sequence Type': ['Affymetrix human normalisation control', 'Affymetrix human normalisation control', 'Affymetrix human normalisation control', 'Affymetrix human normalisation control', 'Affymetrix human normalisation control'], 'Ensembl Version': ['release 60', 'release 60', 'release 60', 'release 60', 'release 60'], 'Ensembl Genome Version': ['GRCh37', 'GRCh37', 'GRCh37', 'GRCh37', 'GRCh37'], 'Orientation / Description': ['Sense (Fully Exonic)', 'Sense (Fully Exonic)', 'Sense (Fully Exonic)', 'Sense (Fully Exonic)', 'Sense (Fully Exonic)'], 'No. probes aligned': ['9', '8', '8', '9', '11'], 'Probeset mapping position': ['Chr 17: 1554017-1554762', 'Chr 19: 36640714-36641203', 'Chr 9: 127622482-127623828', 'Chr 19: 55897742-55898063', 'Chr 11: 10818748-10819118'], 'Ensembl Gene ID': ['ENSG00000174231', 'ENSG00000126247', 'ENSG00000136942', 'ENSG00000108107', 'ENSG00000110321'], 'Chromosomal location': ['Chr 17p11.1', 'Chr 19p11', 'Chr 9p11.1', 'Chr 19p11', 'Chr 11p11.11'], 'Strand': ['Reverse Strand', 'Forward Strand', 'Reverse Strand', 'Forward Strand', 'Reverse Strand'], 'Gene Description': ['PRP8 pre-mRNA processing factor 8 homolog (S. cerevisiae) [Source:HGNC Symbol;Acc:17340]', 'calpain, small subunit 1 [Source:HGNC Symbol;Acc:1481]', 'ribosomal protein L35 [Source:HGNC Symbol;Acc:10344]', 'ribosomal protein L28 [Source:HGNC Symbol;Acc:10330]', 'eukaryotic translation initiation factor 4 gamma, 2 [Source:HGNC Symbol;Acc:3297]'], 'Entrez Gene': ['10594', '826', '11224', '6158', '1982'], 'Alias Gene Symbols': ['PRP8 /// PRPF8-001 /// PRPC8 /// HPRP8 /// RP13 /// Prp8', 'CDPS /// 30K /// CANPS /// CAPNS1-201 /// CAPNS1-202 /// CANP /// CSS1 /// CAPN4 /// CALPAIN4', 'RPL35-002 /// RPL35-005 /// RPL35-001 /// RPL35-004 /// RPL35-003', 'RPL28-203 /// RPL28-201 /// RPL28-205 /// FLJ43307 /// RPL28-202 /// RPL28-204', 'DAP5 /// AAG1 /// EIF4G2-204 /// EIF4G2-203 /// NAT1 /// p97 /// EIF4G2-202 /// FLJ41344 /// EIF4G2-201 /// P97'], 'Ensembl Transcript ID': ['ENST00000304992', 'ENST00000457326 /// ENST00000246533', 'ENST00000493018 /// ENST00000348462 /// ENST00000487431 /// ENST00000373570 /// ENST00000495728', 'ENST00000431533', 'ENST00000396525 /// ENST00000339995 /// ENST00000429377'], 'RefSeq Transcript ID': ['NM_006445.3', '--- /// NM_001003962.1 // NM_001749.2', '--- /// NM_007209.3 /// --- /// --- /// ---', 'NM_001136136.1', 'NM_001042559.2 /// NM_001172705.1 // NM_001418.3 /// NM_001172705.1'], 'Unigene ID': ['Hs.181368', '--- /// ---', '--- /// --- /// --- /// --- /// Hs.182825', '---', '--- /// Hs.183684 /// Hs.183684'], 'ORF': ['PRPF8', 'CAPNS1', 'RPL35', 'RPL28', 'EIF4G2'], 'GB_ACC': ['NM_006445', 'NM_001003962', 'NM_007209', 'NM_001136136', 'NM_001042559'], 'SPOT_ID': ['ENST00000304992', 'ENST00000457326 ENST00000246533', 'ENST00000493018 ENST00000348462 ENST00000487431 ENST00000373570 ENST00000495728', 'ENST00000431533', 'ENST00000396525 ENST00000339995 ENST00000429377']}\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": "1db458e0",
   "metadata": {},
   "source": [
    "### Step 6: Gene Identifier Mapping"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "ff355004",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:42:39.793896Z",
     "iopub.status.busy": "2025-03-25T08:42:39.793767Z",
     "iopub.status.idle": "2025-03-25T08:42:40.879058Z",
     "shell.execute_reply": "2025-03-25T08:42:40.878603Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene mapping preview (first 5 rows):\n",
      "  ID    Gene\n",
      "0  1   PRPF8\n",
      "1  2  CAPNS1\n",
      "2  3   RPL35\n",
      "3  4   RPL28\n",
      "4  5  EIF4G2\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "Gene data shape after mapping: (20172, 50)\n",
      "Gene data preview (first 5 genes, first 3 samples):\n",
      "       GSM1897741  GSM1897744  GSM1897746\n",
      "Gene                                     \n",
      "A1BG     5.331976    5.578752    5.536849\n",
      "A1CF     3.920673    2.936927    3.194641\n",
      "A2LD1   14.586115   16.210582   14.578840\n",
      "A2M     14.252609   10.769140   10.335943\n",
      "A2ML1    3.600177    2.762048    2.728659\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "Gene expression data saved to ../../output/preprocess/Endometrioid_Cancer/gene_data/GSE73551.csv\n"
     ]
    }
   ],
   "source": [
    "# 1. Identify the appropriate columns in the gene annotation data\n",
    "# From the preview, we can see that 'ID' in gene_annotation corresponds to the numeric IDs (1, 2, 3) in gene_data\n",
    "# The 'GeneSymbol' column contains the human gene symbols we want to map to\n",
    "\n",
    "# 2. Create a gene mapping dataframe\n",
    "gene_mapping = get_gene_mapping(gene_annotation, prob_col=\"ID\", gene_col=\"GeneSymbol\")\n",
    "print(\"Gene mapping preview (first 5 rows):\")\n",
    "print(gene_mapping.head())\n",
    "\n",
    "# 3. Apply the gene mapping to convert probe-level measurements to gene expression\n",
    "# This will handle the many-to-many relation between probes and genes\n",
    "gene_data = apply_gene_mapping(gene_data, gene_mapping)\n",
    "print(f\"\\nGene data shape after mapping: {gene_data.shape}\")\n",
    "print(\"Gene data preview (first 5 genes, first 3 samples):\")\n",
    "if gene_data.shape[0] > 0 and gene_data.shape[1] > 0:\n",
    "    preview_cols = min(3, gene_data.shape[1])\n",
    "    print(gene_data.iloc[:5, :preview_cols])\n",
    "\n",
    "# Save the processed 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\"\\nGene expression data saved to {out_gene_data_file}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "13e3783f",
   "metadata": {},
   "source": [
    "### Step 7: Data Normalization and Linking"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "7aa8ef46",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:42:40.880680Z",
     "iopub.status.busy": "2025-03-25T08:42:40.880560Z",
     "iopub.status.idle": "2025-03-25T08:42:52.442987Z",
     "shell.execute_reply": "2025-03-25T08:42:52.442312Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Normalized gene data shape: (20036, 50)\n",
      "First few genes with their expression values after normalization:\n",
      "         GSM1897741  GSM1897744  GSM1897746  GSM1897748  GSM1897750  \\\n",
      "Gene                                                                  \n",
      "A1BG       5.331976    5.578752    5.536849    5.161539    5.352578   \n",
      "A1CF       3.920673    2.936927    3.194641    3.082743    2.935914   \n",
      "A2M       14.252609   10.769140   10.335943   10.783329   11.617907   \n",
      "A2ML1      3.600177    2.762048    2.728659    3.291211    3.406832   \n",
      "A3GALT2    6.455418    6.153991    6.062100    5.696409    5.895500   \n",
      "\n",
      "         GSM1897752  GSM1897753  GSM1897755  GSM1897757  GSM1897759  ...  \\\n",
      "Gene                                                                 ...   \n",
      "A1BG       5.062424    5.628661    4.694100    5.454426    5.214719  ...   \n",
      "A1CF       3.430515    6.307725    3.109970    3.176425    3.403035  ...   \n",
      "A2M        7.886267   10.788412   11.061511   11.618258   10.487040  ...   \n",
      "A2ML1      6.553377    3.206583    7.694877    3.070904    3.106801  ...   \n",
      "A3GALT2    5.641279    6.284191    5.969538    5.889430    6.129745  ...   \n",
      "\n",
      "         GSM1897818  GSM1897820  GSM1897822  GSM1897823  GSM1897825  \\\n",
      "Gene                                                                  \n",
      "A1BG       5.354290    5.522464    5.067847    5.140292    5.279861   \n",
      "A1CF       2.754772    2.965057    3.518125    3.141298    3.156165   \n",
      "A2M       10.046690   12.844992    7.895416    9.973413   11.412809   \n",
      "A2ML1      2.945756    2.956432    3.009950    3.091285    3.152198   \n",
      "A3GALT2    6.301145    5.991926    5.945347    6.257818    5.868759   \n",
      "\n",
      "         GSM1897827  GSM1897829  GSM1897831  GSM1897833  GSM1897835  \n",
      "Gene                                                                 \n",
      "A1BG       5.642801    5.019582    5.618265    5.508222    6.029443  \n",
      "A1CF       3.491213    3.618391    3.173946    3.919150    3.474716  \n",
      "A2M        9.416339   10.433374   10.761468   10.874345   10.987057  \n",
      "A2ML1      3.036763    6.832390    3.636048    2.911268    3.050173  \n",
      "A3GALT2    6.253857    5.889241    5.830122    6.084974    6.563145  \n",
      "\n",
      "[5 rows x 50 columns]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Normalized gene data saved to ../../output/preprocess/Endometrioid_Cancer/gene_data/GSE73551.csv\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Raw clinical data shape: (2, 51)\n",
      "Clinical features:\n",
      "                     GSM1897741  GSM1897744  GSM1897746  GSM1897748  \\\n",
      "Endometrioid_Cancer         0.0         0.0         0.0         1.0   \n",
      "\n",
      "                     GSM1897750  GSM1897752  GSM1897753  GSM1897755  \\\n",
      "Endometrioid_Cancer         1.0         0.0         0.0         0.0   \n",
      "\n",
      "                     GSM1897757  GSM1897759  ...  GSM1897818  GSM1897820  \\\n",
      "Endometrioid_Cancer         0.0         0.0  ...         0.0         0.0   \n",
      "\n",
      "                     GSM1897822  GSM1897823  GSM1897825  GSM1897827  \\\n",
      "Endometrioid_Cancer         0.0         0.0         0.0         0.0   \n",
      "\n",
      "                     GSM1897829  GSM1897831  GSM1897833  GSM1897835  \n",
      "Endometrioid_Cancer         0.0         0.0         0.0         0.0  \n",
      "\n",
      "[1 rows x 50 columns]\n",
      "Clinical features saved to ../../output/preprocess/Endometrioid_Cancer/clinical_data/GSE73551.csv\n",
      "Linked data shape: (50, 20037)\n",
      "Linked data preview (first 5 rows, first 5 columns):\n",
      "            Endometrioid_Cancer      A1BG      A1CF        A2M     A2ML1\n",
      "GSM1897741                  0.0  5.331976  3.920673  14.252609  3.600177\n",
      "GSM1897744                  0.0  5.578752  2.936927  10.769140  2.762048\n",
      "GSM1897746                  0.0  5.536849  3.194641  10.335943  2.728659\n",
      "GSM1897748                  1.0  5.161539  3.082743  10.783329  3.291211\n",
      "GSM1897750                  1.0  5.352578  2.935914  11.617907  3.406832\n",
      "Missing values before handling:\n",
      "  Trait (Endometrioid_Cancer) missing: 0 out of 50\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: (50, 20037)\n",
      "For the feature 'Endometrioid_Cancer', the least common label is '1.0' with 9 occurrences. This represents 18.00% of the dataset.\n",
      "The distribution of the feature 'Endometrioid_Cancer' in this dataset is fine.\n",
      "\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Linked data saved to ../../output/preprocess/Endometrioid_Cancer/GSE73551.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
}