File size: 39,927 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
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "50c0ee70",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:42:56.489019Z",
     "iopub.status.busy": "2025-03-25T08:42:56.488835Z",
     "iopub.status.idle": "2025-03-25T08:42:56.657785Z",
     "shell.execute_reply": "2025-03-25T08:42:56.657435Z"
    }
   },
   "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 = \"GSE73637\"\n",
    "\n",
    "# Input paths\n",
    "in_trait_dir = \"../../input/GEO/Endometrioid_Cancer\"\n",
    "in_cohort_dir = \"../../input/GEO/Endometrioid_Cancer/GSE73637\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/Endometrioid_Cancer/GSE73637.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/Endometrioid_Cancer/gene_data/GSE73637.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/Endometrioid_Cancer/clinical_data/GSE73637.csv\"\n",
    "json_path = \"../../output/preprocess/Endometrioid_Cancer/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4932b9c0",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "7a794db3",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:42:56.659297Z",
     "iopub.status.busy": "2025-03-25T08:42:56.659146Z",
     "iopub.status.idle": "2025-03-25T08:42:57.082588Z",
     "shell.execute_reply": "2025-03-25T08:42:57.082226Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Background Information:\n",
      "!Series_title\t\"Prior Knowledge Transfer Across Transcriptional Datasets Using Compositional Statistics [Cell lines]\"\n",
      "!Series_summary\t\"Compositional statistics and random gene-sets were used to assign the tumor site of origin and histopathology of 18 epithelial ovarian cancer cell lines\"\n",
      "!Series_overall_design\t\"In the study presented here, we applied Gene Expression Compositional Assignment (GECA) to epithelial ovarian cell lines, 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 (GSE73551)\"\n",
      "Sample Characteristics Dictionary:\n",
      "{0: ['cell type: ovarian cells'], 1: ['cell line: COV504', 'cell line: COV362', 'cell line: UWB1.289+BRCA1', 'cell line: OV56', 'cell line: UWB1.289', 'cell line: COV318', 'cell line: NCI/ADR-RES', 'cell line: OVCAR3', 'cell line: OVCAR4', 'cell line: OVCAR8', 'cell line: IGR-OV1', 'cell line: SK-OV-3', 'cell line: OVCAR5', 'cell line: ES-2', 'cell line: TOV-21G', 'cell line: TOV-112D', 'cell line: PEO1', 'cell line: PEO4'], 2: ['tumor site of origin: Ovarian'], 3: ['histopathology: Serous', 'histopathology: Endometrioid', 'histopathology: Poorly differentiated serous', 'histopathology: Undifferentiated carcinoma', 'histopathology: Poorly differentiated carcinoma', 'histopathology: Moderately differentiated carcinoma', 'histopathology: Endometroid with serous/clear cell', 'histopathology: Well-differentiated adenocarcinoma', 'histopathology: Poorly differentiated clear cell', 'histopathology: Clear Cell']}\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": "d33e50fb",
   "metadata": {},
   "source": [
    "### Step 2: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "68646ed4",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:42:57.083902Z",
     "iopub.status.busy": "2025-03-25T08:42:57.083787Z",
     "iopub.status.idle": "2025-03-25T08:42:57.091638Z",
     "shell.execute_reply": "2025-03-25T08:42:57.091297Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Preview of clinical data:\n",
      "{'GSM1899888': [0.0], 'GSM1899889': [0.0], 'GSM1899890': [0.0], 'GSM1899891': [1.0], 'GSM1899892': [1.0], 'GSM1899893': [1.0], 'GSM1899894': [0.0], 'GSM1899895': [0.0], 'GSM1899896': [0.0], 'GSM1899897': [0.0], 'GSM1899898': [0.0], 'GSM1899899': [0.0], 'GSM1899900': [0.0], 'GSM1899901': [0.0], 'GSM1899902': [0.0], 'GSM1899903': [0.0], 'GSM1899904': [0.0], 'GSM1899905': [0.0], 'GSM1899906': [0.0], 'GSM1899907': [0.0], 'GSM1899908': [0.0], 'GSM1899909': [0.0], 'GSM1899910': [0.0], 'GSM1899911': [0.0], 'GSM1899912': [0.0], 'GSM1899913': [0.0], 'GSM1899914': [0.0], 'GSM1899915': [0.0], 'GSM1899916': [1.0], 'GSM1899917': [1.0], 'GSM1899918': [1.0], 'GSM1899919': [0.0], 'GSM1899920': [0.0], 'GSM1899921': [0.0], 'GSM1899922': [0.0], 'GSM1899923': [0.0], 'GSM1899924': [0.0], 'GSM1899925': [0.0], 'GSM1899926': [0.0], 'GSM1899927': [0.0], 'GSM1899928': [0.0], 'GSM1899929': [0.0], 'GSM1899930': [0.0], 'GSM1899931': [1.0], 'GSM1899932': [1.0], 'GSM1899933': [1.0], 'GSM1899934': [0.0], 'GSM1899935': [0.0], 'GSM1899936': [0.0], 'GSM1899937': [0.0], 'GSM1899938': [0.0], 'GSM1899939': [0.0]}\n",
      "Clinical data saved to ../../output/preprocess/Endometrioid_Cancer/clinical_data/GSE73637.csv\n"
     ]
    }
   ],
   "source": [
    "# 1. Evaluate gene expression data availability\n",
    "# This dataset appears to be gene expression data from cell lines, not miRNA or methylation data\n",
    "is_gene_available = True\n",
    "\n",
    "# 2. Variable Availability and Data Type Conversion\n",
    "# 2.1 Find keys for trait, age, and gender\n",
    "# For trait (Endometrioid Cancer), we can use histopathology (key 3)\n",
    "trait_row = 3\n",
    "\n",
    "# No age information is available in the sample characteristics\n",
    "age_row = None\n",
    "\n",
    "# No gender information is available (these are cell lines)\n",
    "gender_row = None\n",
    "\n",
    "# 2.2 Define conversion functions for each variable\n",
    "def convert_trait(value):\n",
    "    \"\"\"Convert histopathology information to binary trait values for Endometrioid Cancer\"\"\"\n",
    "    if value is None:\n",
    "        return None\n",
    "    \n",
    "    # Extract value after the colon if present\n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip()\n",
    "    \n",
    "    # Convert to binary: 1 for Endometrioid, 0 for others\n",
    "    if 'Endometrioid' in value or 'Endometroid' in value:  # Account for possible spelling variation\n",
    "        return 1\n",
    "    else:\n",
    "        return 0\n",
    "\n",
    "def convert_age(value):\n",
    "    \"\"\"Convert age information - not available for this dataset\"\"\"\n",
    "    return None\n",
    "\n",
    "def convert_gender(value):\n",
    "    \"\"\"Convert gender information - not available for this dataset\"\"\"\n",
    "    return None\n",
    "\n",
    "# 3. Save metadata\n",
    "# Check if trait data is available (i.e., if trait_row is not None)\n",
    "is_trait_available = trait_row is not None\n",
    "\n",
    "# Save the initial filtering results\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_data,  # This should be available from a previous step\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 data\n",
    "    print(\"Preview of clinical data:\")\n",
    "    print(preview_df(clinical_df))\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": "97d1b01a",
   "metadata": {},
   "source": [
    "### Step 3: Gene Data Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "90205418",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:42:57.092763Z",
     "iopub.status.busy": "2025-03-25T08:42:57.092564Z",
     "iopub.status.idle": "2025-03-25T08:42:57.734483Z",
     "shell.execute_reply": "2025-03-25T08:42:57.734102Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Found data marker at line 61\n",
      "Header line: \"ID_REF\"\t\"GSM1899888\"\t\"GSM1899889\"\t\"GSM1899890\"\t\"GSM1899891\"\t\"GSM1899892\"\t\"GSM1899893\"\t\"GSM1899894\"\t\"GSM1899895\"\t\"GSM1899896\"\t\"GSM1899897\"\t\"GSM1899898\"\t\"GSM1899899\"\t\"GSM1899900\"\t\"GSM1899901\"\t\"GSM1899902\"\t\"GSM1899903\"\t\"GSM1899904\"\t\"GSM1899905\"\t\"GSM1899906\"\t\"GSM1899907\"\t\"GSM1899908\"\t\"GSM1899909\"\t\"GSM1899910\"\t\"GSM1899911\"\t\"GSM1899912\"\t\"GSM1899913\"\t\"GSM1899914\"\t\"GSM1899915\"\t\"GSM1899916\"\t\"GSM1899917\"\t\"GSM1899918\"\t\"GSM1899919\"\t\"GSM1899920\"\t\"GSM1899921\"\t\"GSM1899922\"\t\"GSM1899923\"\t\"GSM1899924\"\t\"GSM1899925\"\t\"GSM1899926\"\t\"GSM1899927\"\t\"GSM1899928\"\t\"GSM1899929\"\t\"GSM1899930\"\t\"GSM1899931\"\t\"GSM1899932\"\t\"GSM1899933\"\t\"GSM1899934\"\t\"GSM1899935\"\t\"GSM1899936\"\t\"GSM1899937\"\t\"GSM1899938\"\t\"GSM1899939\"\n",
      "First data line: 1\t9.113926239\t9.353160006\t9.340419788\t9.068727157\t8.993265236\t9.006226326\t10.25871409\t10.13329143\t10.13550261\t9.671620081\t9.57993636\t9.361243542\t9.883231123\t8.850008948\t8.631560726\t8.812670809\t10.30292328\t10.2893897\t10.34595556\t9.009325384\t9.172475557\t9.247407779\t8.964204246\t9.020628865\t9.207742138\t10.32458758\t10.36534658\t10.35711252\t9.734924289\t9.72507106\t9.784513633\t8.790526196\t8.835592535\t8.940153313\t9.218608395\t9.328660633\t9.128393683\t9.954817706\t9.82187008\t9.811056786\t9.606890499\t9.503037579\t9.620021927\t10.6333148\t10.40253562\t10.64616983\t9.202343369\t8.832061635\t9.433059912\t9.141812092\t9.320294952\t8.881678583\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": "2f808057",
   "metadata": {},
   "source": [
    "### Step 4: Gene Identifier Review"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "c51253d7",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:42:57.735834Z",
     "iopub.status.busy": "2025-03-25T08:42:57.735717Z",
     "iopub.status.idle": "2025-03-25T08:42:57.737650Z",
     "shell.execute_reply": "2025-03-25T08:42:57.737359Z"
    }
   },
   "outputs": [],
   "source": [
    "# Looking at the identifiers in the gene expression data, I can see they are just numeric indices (1, 2, 3, etc.)\n",
    "# These are not human gene symbols but rather numeric probe IDs that need to be mapped to gene symbols\n",
    "# This is typical for microarray data where probes need to be mapped to their corresponding genes\n",
    "\n",
    "requires_gene_mapping = True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1e8f6583",
   "metadata": {},
   "source": [
    "### Step 5: Gene Annotation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "157bd939",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:42:57.738728Z",
     "iopub.status.busy": "2025-03-25T08:42:57.738623Z",
     "iopub.status.idle": "2025-03-25T08:42:58.729856Z",
     "shell.execute_reply": "2025-03-25T08:42:58.729468Z"
    }
   },
   "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 = GSE73637\n",
      "Line 6: !Series_title = Prior Knowledge Transfer Across Transcriptional Datasets Using Compositional Statistics [Cell lines]\n",
      "Line 7: !Series_geo_accession = GSE73637\n",
      "Line 8: !Series_status = Public on Nov 08 2016\n",
      "Line 9: !Series_submission_date = Sep 30 2015\n",
      "Line 10: !Series_last_update_date = Nov 10 2016\n",
      "Line 11: !Series_pubmed_id = 27353327\n",
      "Line 12: !Series_summary = Compositional statistics and random gene-sets were used to assign the tumor site of origin and histopathology of 18 epithelial ovarian cancer cell lines\n",
      "Line 13: !Series_overall_design = In the study presented here, we applied Gene Expression Compositional Assignment (GECA) to epithelial ovarian cell lines, 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 (GSE73551)\n",
      "Line 14: !Series_type = Expression profiling by array\n",
      "Line 15: !Series_contributor = Jaine,K,Blayney\n",
      "Line 16: !Series_sample_id = GSM1899888\n",
      "Line 17: !Series_sample_id = GSM1899889\n",
      "Line 18: !Series_sample_id = GSM1899890\n",
      "Line 19: !Series_sample_id = GSM1899891\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": "3d7f6387",
   "metadata": {},
   "source": [
    "### Step 6: Gene Identifier Mapping"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "f0131c8c",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:42:58.731257Z",
     "iopub.status.busy": "2025-03-25T08:42:58.731130Z",
     "iopub.status.idle": "2025-03-25T08:42:59.822573Z",
     "shell.execute_reply": "2025-03-25T08:42:59.822181Z"
    }
   },
   "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",
      "Total mapping entries: 120373\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "Gene expression data after mapping:\n",
      "Shape: (20172, 52)\n",
      "Sample of genes (first 5):\n",
      "Index(['A1BG', 'A1CF', 'A2LD1', 'A2M', 'A2ML1'], dtype='object', name='Gene')\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene expression data saved to ../../output/preprocess/Endometrioid_Cancer/gene_data/GSE73637.csv\n"
     ]
    }
   ],
   "source": [
    "# 1. Identify which columns in the gene annotation dataframe correspond to identifiers and symbols\n",
    "# From the gene annotation preview, we can see:\n",
    "# - 'ID' column contains numeric identifiers matching gene_data.index\n",
    "# - 'GeneSymbol' column contains the gene symbols we need\n",
    "\n",
    "# 2. Create a mapping dataframe from the gene annotation data\n",
    "mapping_df = gene_annotation[['ID', 'GeneSymbol']]\n",
    "mapping_df = mapping_df.rename(columns={'GeneSymbol': 'Gene'})\n",
    "mapping_df = mapping_df.dropna()\n",
    "mapping_df = mapping_df.astype({'ID': 'str'})  # Convert ID to string to match gene_data index\n",
    "\n",
    "print(\"Gene mapping preview (first 5 rows):\")\n",
    "print(mapping_df.head())\n",
    "print(f\"Total mapping entries: {len(mapping_df)}\")\n",
    "\n",
    "# 3. Apply the mapping to convert probe-level measurements to gene expression data\n",
    "gene_data = apply_gene_mapping(gene_data, mapping_df)\n",
    "\n",
    "print(\"\\nGene expression data after mapping:\")\n",
    "print(f\"Shape: {gene_data.shape}\")\n",
    "print(\"Sample of genes (first 5):\")\n",
    "print(gene_data.index[:5])\n",
    "\n",
    "# Save the gene expression data to CSV\n",
    "gene_data.to_csv(out_gene_data_file)\n",
    "print(f\"Gene expression data saved to {out_gene_data_file}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d5704c05",
   "metadata": {},
   "source": [
    "### Step 7: Data Normalization and Linking"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "9b858016",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:42:59.823931Z",
     "iopub.status.busy": "2025-03-25T08:42:59.823807Z",
     "iopub.status.idle": "2025-03-25T08:43:10.815772Z",
     "shell.execute_reply": "2025-03-25T08:43:10.815128Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Normalized gene data shape: (20036, 52)\n",
      "First few genes with their expression values after normalization:\n",
      "         GSM1899888  GSM1899889  GSM1899890  GSM1899891  GSM1899892  \\\n",
      "Gene                                                                  \n",
      "A1BG       5.263569    5.598553    5.263475    6.084976    5.997425   \n",
      "A1CF       2.647713    2.383580    2.605635    2.587824    2.507772   \n",
      "A2M        6.292947    6.771711    5.949791    6.474002    6.744352   \n",
      "A2ML1      3.756357    2.472887    3.527244    2.165761    2.767217   \n",
      "A3GALT2    6.355374    6.217401    6.484687    6.666866    6.405594   \n",
      "\n",
      "         GSM1899893  GSM1899894  GSM1899895  GSM1899896  GSM1899897  ...  \\\n",
      "Gene                                                                 ...   \n",
      "A1BG       6.125724    5.257894    5.212058    5.444705    6.021699  ...   \n",
      "A1CF       3.821882    3.124388    2.756973    3.170520    2.728037  ...   \n",
      "A2M        6.833200    7.674972    7.644879    7.283829    6.150173  ...   \n",
      "A2ML1      2.353374    2.475354    2.225454    2.432270    2.534942  ...   \n",
      "A3GALT2    6.348537    6.816183    6.693292    6.754839    6.271786  ...   \n",
      "\n",
      "         GSM1899930  GSM1899931  GSM1899932  GSM1899933  GSM1899934  \\\n",
      "Gene                                                                  \n",
      "A1BG       7.236568    6.078750    6.354082    6.612614    5.132084   \n",
      "A1CF       2.643583    2.481840    2.706462    2.628780    3.202872   \n",
      "A2M        6.844386   19.750863   19.743618   19.835477    7.906550   \n",
      "A2ML1      2.533890    2.317816    2.400485    2.515641    2.524883   \n",
      "A3GALT2    6.664464    6.208147    6.399175    6.524429    6.472844   \n",
      "\n",
      "         GSM1899935  GSM1899936  GSM1899937  GSM1899938  GSM1899939  \n",
      "Gene                                                                 \n",
      "A1BG       4.797291    5.079646    5.236975    5.478133    5.114841  \n",
      "A1CF       2.380427    2.695625    2.450733    2.426742    2.828121  \n",
      "A2M       10.295305    7.889205    7.065245    8.272117    6.548691  \n",
      "A2ML1      2.730668    2.379279    2.541936    2.378526    2.484086  \n",
      "A3GALT2    6.010204    6.609448    6.638761    6.632453    6.995594  \n",
      "\n",
      "[5 rows x 52 columns]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Normalized gene data saved to ../../output/preprocess/Endometrioid_Cancer/gene_data/GSE73637.csv\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Raw clinical data shape: (4, 53)\n",
      "Clinical features:\n",
      "                     GSM1899888  GSM1899889  GSM1899890  GSM1899891  \\\n",
      "Endometrioid_Cancer         0.0         0.0         0.0         1.0   \n",
      "\n",
      "                     GSM1899892  GSM1899893  GSM1899894  GSM1899895  \\\n",
      "Endometrioid_Cancer         1.0         1.0         0.0         0.0   \n",
      "\n",
      "                     GSM1899896  GSM1899897  ...  GSM1899930  GSM1899931  \\\n",
      "Endometrioid_Cancer         0.0         0.0  ...         0.0         1.0   \n",
      "\n",
      "                     GSM1899932  GSM1899933  GSM1899934  GSM1899935  \\\n",
      "Endometrioid_Cancer         1.0         1.0         0.0         0.0   \n",
      "\n",
      "                     GSM1899936  GSM1899937  GSM1899938  GSM1899939  \n",
      "Endometrioid_Cancer         0.0         0.0         0.0         0.0  \n",
      "\n",
      "[1 rows x 52 columns]\n",
      "Clinical features saved to ../../output/preprocess/Endometrioid_Cancer/clinical_data/GSE73637.csv\n",
      "Linked data shape: (52, 20037)\n",
      "Linked data preview (first 5 rows, first 5 columns):\n",
      "            Endometrioid_Cancer      A1BG      A1CF       A2M     A2ML1\n",
      "GSM1899888                  0.0  5.263569  2.647713  6.292947  3.756357\n",
      "GSM1899889                  0.0  5.598553  2.383580  6.771711  2.472887\n",
      "GSM1899890                  0.0  5.263475  2.605635  5.949791  3.527244\n",
      "GSM1899891                  1.0  6.084976  2.587824  6.474002  2.165761\n",
      "GSM1899892                  1.0  5.997425  2.507772  6.744352  2.767217\n",
      "Missing values before handling:\n",
      "  Trait (Endometrioid_Cancer) missing: 0 out of 52\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: (52, 20037)\n",
      "For the feature 'Endometrioid_Cancer', the least common label is '1.0' with 9 occurrences. This represents 17.31% 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/GSE73637.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
}