File size: 48,702 Bytes
f88156f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "52a47238",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T07:02:08.713416Z",
     "iopub.status.busy": "2025-03-25T07:02:08.713155Z",
     "iopub.status.idle": "2025-03-25T07:02:08.877251Z",
     "shell.execute_reply": "2025-03-25T07:02:08.876916Z"
    }
   },
   "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 = \"Breast_Cancer\"\n",
    "cohort = \"GSE236725\"\n",
    "\n",
    "# Input paths\n",
    "in_trait_dir = \"../../input/GEO/Breast_Cancer\"\n",
    "in_cohort_dir = \"../../input/GEO/Breast_Cancer/GSE236725\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/Breast_Cancer/GSE236725.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/Breast_Cancer/gene_data/GSE236725.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/Breast_Cancer/clinical_data/GSE236725.csv\"\n",
    "json_path = \"../../output/preprocess/Breast_Cancer/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "349ee99c",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "53a42ffc",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T07:02:08.878614Z",
     "iopub.status.busy": "2025-03-25T07:02:08.878476Z",
     "iopub.status.idle": "2025-03-25T07:02:09.098266Z",
     "shell.execute_reply": "2025-03-25T07:02:09.097885Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Background Information:\n",
      "!Series_title\t\"The 31 pairs of FF and FFPE data for the development of 72GC for FFPE in 2014\"\n",
      "!Series_summary\t\"The study aimed to develop the 72GC (the 72-gene classifier) for recurrence-risk prediction for patients with estrogen receptor positive and node-negative breast cancer. 72-GC could differentiate the high-risk from the low-risk patients with a high statistical significance, and is considered to be applicable to formalin-fixed, paraffin embedded (FFPE) tumor tissues because the results of 72-GC on FF (fresh-frozen) tissues and FFPE tissues showed a high concordance.  J06 31 pairs of FF (fresh‑frozen) and FFPE data are included in the concordance analysis of 72GC high/low results between FF and FFPE (Table 3). A long time passed, and now it is unclear how these 31 cases were distributed among the analysis.    *Note: This old data has been updated multiple times by the other members.  Then, there are some differences from the original paper and unclear points still remain.  Therefore, do not use it for formal analysis aimed at public insurance coverage etc. This is for research purposes only. Please cite this paper when writing a new paper.   PMID: 24461457  DOI: 10.1016/j.clbc.2013.11.006\"\n",
      "!Series_overall_design\t\"RNA was extracted from 31 pairs of FF (fresh frozen) and FFPE (Formalin-fixed paraffin-embedded) tumor samples obtained from radical breast cancer surgery and hybridized on Affymetrix microarrays.\"\n",
      "Sample Characteristics Dictionary:\n",
      "{0: ['assay: FF', 'assay: FFPE'], 1: ['distant.recurrence: Yes', 'distant.recurrence: No'], 2: ['distant.recurrence.free.survival.year: 3.783', 'distant.recurrence.free.survival.year: 1.261', 'distant.recurrence.free.survival.year: 1.119', 'distant.recurrence.free.survival.year: 1', 'distant.recurrence.free.survival.year: 8.5', 'distant.recurrence.free.survival.year: 8', 'distant.recurrence.free.survival.year: 7.5', 'distant.recurrence.free.survival.year: 7', 'distant.recurrence.free.survival.year: 6.5', 'distant.recurrence.free.survival.year: 2.75', 'distant.recurrence.free.survival.year: 3.666666667', 'distant.recurrence.free.survival.year: 4', 'distant.recurrence.free.survival.year: 2'], 3: ['pair: pair 001', 'pair: pair 002', 'pair: pair 003', 'pair: pair 004', 'pair: pair 005', 'pair: pair 006', 'pair: pair 007', 'pair: pair 008', 'pair: pair 009', 'pair: pair 010', 'pair: pair 011', 'pair: pair 012', 'pair: pair 013', 'pair: pair 014', 'pair: pair 015', 'pair: pair 016', 'pair: pair 017', 'pair: pair 018', 'pair: pair 019', 'pair: pair 020', 'pair: pair 021', 'pair: pair 022', 'pair: pair 023', 'pair: pair 024', 'pair: pair 025', 'pair: pair 026', 'pair: pair 027', 'pair: pair 028', 'pair: pair 029', 'pair: pair 030'], 4: ['tissue: FF tumor', 'tissue: FFPE tumor'], 5: ['disease state: breast 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": "a50a8203",
   "metadata": {},
   "source": [
    "### Step 2: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "3ce4e874",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T07:02:09.099647Z",
     "iopub.status.busy": "2025-03-25T07:02:09.099540Z",
     "iopub.status.idle": "2025-03-25T07:02:09.121693Z",
     "shell.execute_reply": "2025-03-25T07:02:09.121363Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Available files in ../../input/GEO/Breast_Cancer/GSE236725: ['GSE236725_family.soft.gz', 'GSE236725_series_matrix.txt.gz']\n",
      "No clinical data file found. Creating DataFrame from sample characteristics dictionary.\n",
      "Preview of extracted clinical features:\n",
      "{'TITLES': [0.0]}\n",
      "Clinical data saved to: ../../output/preprocess/Breast_Cancer/clinical_data/GSE236725.csv\n"
     ]
    }
   ],
   "source": [
    "# 1. Gene Expression Data Availability\n",
    "# According to the background information, this dataset contains gene expression data from Affymetrix microarrays\n",
    "is_gene_available = True\n",
    "\n",
    "# 2.1 Data Availability\n",
    "# For trait: Looking at the sample characteristics, distant.recurrence (key 1) indicates breast cancer recurrence\n",
    "trait_row = 1  # 'distant.recurrence: Yes/No' is our target trait\n",
    "\n",
    "# For age: There is no age information available in the sample characteristics\n",
    "age_row = None\n",
    "\n",
    "# For gender: No gender information is available in the sample characteristics\n",
    "gender_row = None\n",
    "\n",
    "# 2.2 Data Type Conversion Functions\n",
    "def convert_trait(value):\n",
    "    \"\"\"Convert breast cancer recurrence status to binary.\"\"\"\n",
    "    if value is None:\n",
    "        return None\n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip()\n",
    "    if value.lower() == 'yes':\n",
    "        return 1  # Recurrence present\n",
    "    elif value.lower() == 'no':\n",
    "        return 0  # No recurrence\n",
    "    return None\n",
    "\n",
    "def convert_age(value):\n",
    "    \"\"\"Convert age to continuous values.\n",
    "    Not used in this dataset as age information is unavailable.\"\"\"\n",
    "    return None\n",
    "\n",
    "def convert_gender(value):\n",
    "    \"\"\"Convert gender to binary (0=female, 1=male).\n",
    "    Not used in this dataset as gender information is unavailable.\"\"\"\n",
    "    return None\n",
    "\n",
    "# 3. Save Metadata\n",
    "# Determine trait data availability\n",
    "is_trait_available = trait_row is not None\n",
    "validate_and_save_cohort_info(is_final=False, cohort=cohort, info_path=json_path, \n",
    "                             is_gene_available=is_gene_available, \n",
    "                             is_trait_available=is_trait_available)\n",
    "\n",
    "# 4. Clinical Feature Extraction\n",
    "if trait_row is not None:\n",
    "    # We'll need to use the existing clinical data that has been loaded in a previous step\n",
    "    # Find available files in the cohort directory\n",
    "    available_files = os.listdir(in_cohort_dir)\n",
    "    print(f\"Available files in {in_cohort_dir}: {available_files}\")\n",
    "    \n",
    "    # Check for different possible clinical data files\n",
    "    clinical_file_name = None\n",
    "    for file in available_files:\n",
    "        if 'clinical' in file.lower() or 'characteristics' in file.lower() or 'phenotype' in file.lower():\n",
    "            clinical_file_name = file\n",
    "            break\n",
    "    \n",
    "    if clinical_file_name:\n",
    "        # If we found a clinical data file, load it\n",
    "        clinical_data = pd.read_csv(os.path.join(in_cohort_dir, clinical_file_name))\n",
    "        print(f\"Loaded clinical data from {clinical_file_name}\")\n",
    "    else:\n",
    "        # If no clinical data file is found, we'll create a DataFrame from the sample characteristics dictionary\n",
    "        # that was provided in the previous step's output\n",
    "        print(\"No clinical data file found. Creating DataFrame from sample characteristics dictionary.\")\n",
    "        \n",
    "        # Since we don't directly have the sample_characteristics variable, we need to create a representative DataFrame\n",
    "        # from what we can infer from the sample characteristics dictionary shown in the previous output\n",
    "        \n",
    "        # Create a sample DataFrame based on the sample characteristics dictionary\n",
    "        # We'll assume the format matches what geo_select_clinical_features expects\n",
    "        sample_characteristics = {}\n",
    "        \n",
    "        # From the dictionary in the output, key 1 contains distant.recurrence data\n",
    "        sample_characteristics[1] = ['distant.recurrence: Yes', 'distant.recurrence: No']\n",
    "        \n",
    "        # Create a dataframe with columns matching what's expected by geo_select_clinical_features\n",
    "        clinical_data = pd.DataFrame(index=range(len(sample_characteristics[1])), columns=['TITLES'])\n",
    "        clinical_data.iloc[:, 0] = sample_characteristics[1]\n",
    "    \n",
    "    # Extract the clinical features using the function from the library\n",
    "    selected_clinical_df = geo_select_clinical_features(\n",
    "        clinical_df=clinical_data,\n",
    "        trait=trait,\n",
    "        trait_row=trait_row,\n",
    "        convert_trait=convert_trait,\n",
    "        age_row=age_row,\n",
    "        convert_age=convert_age,\n",
    "        gender_row=gender_row,\n",
    "        convert_gender=convert_gender\n",
    "    )\n",
    "    \n",
    "    # Preview the extracted clinical features\n",
    "    print(\"Preview of extracted clinical features:\")\n",
    "    print(preview_df(selected_clinical_df))\n",
    "    \n",
    "    # Save the clinical data to the specified path\n",
    "    os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
    "    selected_clinical_df.to_csv(out_clinical_data_file, index=False)\n",
    "    print(f\"Clinical data saved to: {out_clinical_data_file}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7e0cc53d",
   "metadata": {},
   "source": [
    "### Step 3: Gene Data Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "d47a51cd",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T07:02:09.122825Z",
     "iopub.status.busy": "2025-03-25T07:02:09.122723Z",
     "iopub.status.idle": "2025-03-25T07:02:09.489248Z",
     "shell.execute_reply": "2025-03-25T07:02:09.488870Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "SOFT file: ../../input/GEO/Breast_Cancer/GSE236725/GSE236725_family.soft.gz\n",
      "Matrix file: ../../input/GEO/Breast_Cancer/GSE236725/GSE236725_series_matrix.txt.gz\n",
      "Found the matrix table marker at line 67\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene data shape: (54675, 62)\n",
      "First 20 gene/probe identifiers:\n",
      "['1007_s_at', '1053_at', '117_at', '121_at', '1255_g_at', '1294_at', '1316_at', '1320_at', '1405_i_at', '1431_at', '1438_at', '1487_at', '1494_f_at', '1552256_a_at', '1552257_a_at', '1552258_at', '1552261_at', '1552263_at', '1552264_a_at', '1552266_at']\n"
     ]
    }
   ],
   "source": [
    "# 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",
    "print(f\"SOFT file: {soft_file}\")\n",
    "print(f\"Matrix file: {matrix_file}\")\n",
    "\n",
    "# Set gene availability flag\n",
    "is_gene_available = True  # Initially assume gene data is available\n",
    "\n",
    "# First check if the matrix file contains the expected marker\n",
    "found_marker = False\n",
    "marker_row = None\n",
    "try:\n",
    "    with gzip.open(matrix_file, 'rt') as file:\n",
    "        for i, line in enumerate(file):\n",
    "            if \"!series_matrix_table_begin\" in line:\n",
    "                found_marker = True\n",
    "                marker_row = i\n",
    "                print(f\"Found the matrix table marker at line {i}\")\n",
    "                break\n",
    "    \n",
    "    if not found_marker:\n",
    "        print(\"Warning: Could not find '!series_matrix_table_begin' marker in the file.\")\n",
    "        is_gene_available = False\n",
    "        \n",
    "    # If marker was found, try to extract gene data\n",
    "    if is_gene_available:\n",
    "        try:\n",
    "            # Try using the library function\n",
    "            gene_data = get_genetic_data(matrix_file)\n",
    "            \n",
    "            if gene_data.shape[0] == 0:\n",
    "                print(\"Warning: Extracted gene data has 0 rows.\")\n",
    "                is_gene_available = False\n",
    "            else:\n",
    "                print(f\"Gene data shape: {gene_data.shape}\")\n",
    "                # Print the first 20 gene/probe identifiers\n",
    "                print(\"First 20 gene/probe identifiers:\")\n",
    "                print(gene_data.index[:20].tolist())\n",
    "        except Exception as e:\n",
    "            print(f\"Error extracting gene data with get_genetic_data(): {e}\")\n",
    "            is_gene_available = False\n",
    "    \n",
    "    # If gene data extraction failed, examine file content to diagnose\n",
    "    if not is_gene_available:\n",
    "        print(\"Examining file content to diagnose the issue:\")\n",
    "        try:\n",
    "            with gzip.open(matrix_file, 'rt') as file:\n",
    "                # Print lines around the marker if found\n",
    "                if marker_row is not None:\n",
    "                    for i, line in enumerate(file):\n",
    "                        if i >= marker_row - 2 and i <= marker_row + 10:\n",
    "                            print(f\"Line {i}: {line.strip()[:100]}...\")\n",
    "                        if i > marker_row + 10:\n",
    "                            break\n",
    "                else:\n",
    "                    # If marker not found, print first 10 lines\n",
    "                    for i, line in enumerate(file):\n",
    "                        if i < 10:\n",
    "                            print(f\"Line {i}: {line.strip()[:100]}...\")\n",
    "                        else:\n",
    "                            break\n",
    "        except Exception as e2:\n",
    "            print(f\"Error examining file: {e2}\")\n",
    "        \n",
    "except Exception as e:\n",
    "    print(f\"Error processing file: {e}\")\n",
    "    is_gene_available = False\n",
    "\n",
    "# Update validation information if gene data extraction failed\n",
    "if not is_gene_available:\n",
    "    print(\"Gene expression data could not be successfully extracted from this dataset.\")\n",
    "    # Update the validation record since gene data isn't available\n",
    "    is_trait_available = False  # We already determined trait data isn't available in step 2\n",
    "    validate_and_save_cohort_info(is_final=False, cohort=cohort, info_path=json_path,\n",
    "                                 is_gene_available=is_gene_available, is_trait_available=is_trait_available)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f60d1861",
   "metadata": {},
   "source": [
    "### Step 4: Gene Identifier Review"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "1ffb9979",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T07:02:09.490574Z",
     "iopub.status.busy": "2025-03-25T07:02:09.490453Z",
     "iopub.status.idle": "2025-03-25T07:02:09.492346Z",
     "shell.execute_reply": "2025-03-25T07:02:09.492071Z"
    }
   },
   "outputs": [],
   "source": [
    "# The identifiers shown (1007_s_at, 1053_at, etc.) are Affymetrix probe IDs, \n",
    "# not human gene symbols. These are identifiers from Affymetrix microarray platforms\n",
    "# and need to be mapped to standard gene symbols for meaningful analysis.\n",
    "\n",
    "requires_gene_mapping = True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1fc7febc",
   "metadata": {},
   "source": [
    "### Step 5: Gene Annotation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "d7e18c8f",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T07:02:09.493501Z",
     "iopub.status.busy": "2025-03-25T07:02:09.493400Z",
     "iopub.status.idle": "2025-03-25T07:02:15.575399Z",
     "shell.execute_reply": "2025-03-25T07:02:15.574861Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "Gene annotation preview:\n",
      "Columns in gene annotation: ['ID', 'GB_ACC', 'SPOT_ID', 'Species Scientific Name', 'Annotation Date', 'Sequence Type', 'Sequence Source', 'Target Description', 'Representative Public ID', 'Gene Title', 'Gene Symbol', 'ENTREZ_GENE_ID', 'RefSeq Transcript ID', 'Gene Ontology Biological Process', 'Gene Ontology Cellular Component', 'Gene Ontology Molecular Function']\n",
      "{'ID': ['1007_s_at', '1053_at', '117_at'], 'GB_ACC': ['U48705', 'M87338', 'X51757'], 'SPOT_ID': [nan, nan, nan], 'Species Scientific Name': ['Homo sapiens', 'Homo sapiens', 'Homo sapiens'], 'Annotation Date': ['Oct 6, 2014', 'Oct 6, 2014', 'Oct 6, 2014'], 'Sequence Type': ['Exemplar sequence', 'Exemplar sequence', 'Exemplar sequence'], 'Sequence Source': ['Affymetrix Proprietary Database', 'GenBank', 'Affymetrix Proprietary Database'], 'Target Description': ['U48705 /FEATURE=mRNA /DEFINITION=HSU48705 Human receptor tyrosine kinase DDR gene, complete cds', 'M87338 /FEATURE= /DEFINITION=HUMA1SBU Human replication factor C, 40-kDa subunit (A1) mRNA, complete cds', \"X51757 /FEATURE=cds /DEFINITION=HSP70B Human heat-shock protein HSP70B' gene\"], 'Representative Public ID': ['U48705', 'M87338', 'X51757'], 'Gene Title': ['discoidin domain receptor tyrosine kinase 1 /// microRNA 4640', 'replication factor C (activator 1) 2, 40kDa', \"heat shock 70kDa protein 6 (HSP70B')\"], 'Gene Symbol': ['DDR1 /// MIR4640', 'RFC2', 'HSPA6'], 'ENTREZ_GENE_ID': ['780 /// 100616237', '5982', '3310'], 'RefSeq Transcript ID': ['NM_001202521 /// NM_001202522 /// NM_001202523 /// NM_001954 /// NM_013993 /// NM_013994 /// NR_039783 /// XM_005249385 /// XM_005249386 /// XM_005249387 /// XM_005249389 /// XM_005272873 /// XM_005272874 /// XM_005272875 /// XM_005272877 /// XM_005275027 /// XM_005275028 /// XM_005275030 /// XM_005275031 /// XM_005275162 /// XM_005275163 /// XM_005275164 /// XM_005275166 /// XM_005275457 /// XM_005275458 /// XM_005275459 /// XM_005275461 /// XM_006715185 /// XM_006715186 /// XM_006715187 /// XM_006715188 /// XM_006715189 /// XM_006715190 /// XM_006725501 /// XM_006725502 /// XM_006725503 /// XM_006725504 /// XM_006725505 /// XM_006725506 /// XM_006725714 /// XM_006725715 /// XM_006725716 /// XM_006725717 /// XM_006725718 /// XM_006725719 /// XM_006725720 /// XM_006725721 /// XM_006725722 /// XM_006725827 /// XM_006725828 /// XM_006725829 /// XM_006725830 /// XM_006725831 /// XM_006725832 /// XM_006726017 /// XM_006726018 /// XM_006726019 /// XM_006726020 /// XM_006726021 /// XM_006726022 /// XR_427836 /// XR_430858 /// XR_430938 /// XR_430974 /// XR_431015', 'NM_001278791 /// NM_001278792 /// NM_001278793 /// NM_002914 /// NM_181471 /// XM_006716080', 'NM_002155'], 'Gene Ontology Biological Process': ['0001558 // regulation of cell growth // inferred from electronic annotation /// 0001952 // regulation of cell-matrix adhesion // inferred from electronic annotation /// 0006468 // protein phosphorylation // inferred from electronic annotation /// 0007155 // cell adhesion // traceable author statement /// 0007169 // transmembrane receptor protein tyrosine kinase signaling pathway // inferred from electronic annotation /// 0007565 // female pregnancy // inferred from electronic annotation /// 0007566 // embryo implantation // inferred from electronic annotation /// 0007595 // lactation // inferred from electronic annotation /// 0008285 // negative regulation of cell proliferation // inferred from electronic annotation /// 0010715 // regulation of extracellular matrix disassembly // inferred from mutant phenotype /// 0014909 // smooth muscle cell migration // inferred from mutant phenotype /// 0016310 // phosphorylation // inferred from electronic annotation /// 0018108 // peptidyl-tyrosine phosphorylation // inferred from electronic annotation /// 0030198 // extracellular matrix organization // traceable author statement /// 0038063 // collagen-activated tyrosine kinase receptor signaling pathway // inferred from direct assay /// 0038063 // collagen-activated tyrosine kinase receptor signaling pathway // inferred from mutant phenotype /// 0038083 // peptidyl-tyrosine autophosphorylation // inferred from direct assay /// 0043583 // ear development // inferred from electronic annotation /// 0044319 // wound healing, spreading of cells // inferred from mutant phenotype /// 0046777 // protein autophosphorylation // inferred from direct assay /// 0060444 // branching involved in mammary gland duct morphogenesis // inferred from electronic annotation /// 0060749 // mammary gland alveolus development // inferred from electronic annotation /// 0061302 // smooth muscle cell-matrix adhesion // inferred from mutant phenotype', '0000278 // mitotic cell cycle // traceable author statement /// 0000722 // telomere maintenance via recombination // traceable author statement /// 0000723 // telomere maintenance // traceable author statement /// 0006260 // DNA replication // traceable author statement /// 0006271 // DNA strand elongation involved in DNA replication // traceable author statement /// 0006281 // DNA repair // traceable author statement /// 0006283 // transcription-coupled nucleotide-excision repair // traceable author statement /// 0006289 // nucleotide-excision repair // traceable author statement /// 0006297 // nucleotide-excision repair, DNA gap filling // traceable author statement /// 0015979 // photosynthesis // inferred from electronic annotation /// 0015995 // chlorophyll biosynthetic process // inferred from electronic annotation /// 0032201 // telomere maintenance via semi-conservative replication // traceable author statement', '0000902 // cell morphogenesis // inferred from electronic annotation /// 0006200 // ATP catabolic process // inferred from direct assay /// 0006950 // response to stress // inferred from electronic annotation /// 0006986 // response to unfolded protein // traceable author statement /// 0034605 // cellular response to heat // inferred from direct assay /// 0042026 // protein refolding // inferred from direct assay /// 0070370 // cellular heat acclimation // inferred from mutant phenotype'], 'Gene Ontology Cellular Component': ['0005576 // extracellular region // inferred from electronic annotation /// 0005615 // extracellular space // inferred from direct assay /// 0005886 // plasma membrane // traceable author statement /// 0005887 // integral component of plasma membrane // traceable author statement /// 0016020 // membrane // inferred from electronic annotation /// 0016021 // integral component of membrane // inferred from electronic annotation /// 0043235 // receptor complex // inferred from direct assay /// 0070062 // extracellular vesicular exosome // inferred from direct assay', '0005634 // nucleus // inferred from electronic annotation /// 0005654 // nucleoplasm // traceable author statement /// 0005663 // DNA replication factor C complex // inferred from direct assay', '0005737 // cytoplasm // inferred from direct assay /// 0005814 // centriole // inferred from direct assay /// 0005829 // cytosol // inferred from direct assay /// 0008180 // COP9 signalosome // inferred from direct assay /// 0070062 // extracellular vesicular exosome // inferred from direct assay /// 0072562 // blood microparticle // inferred from direct assay'], 'Gene Ontology Molecular Function': ['0000166 // nucleotide binding // inferred from electronic annotation /// 0004672 // protein kinase activity // inferred from electronic annotation /// 0004713 // protein tyrosine kinase activity // inferred from electronic annotation /// 0004714 // transmembrane receptor protein tyrosine kinase activity // traceable author statement /// 0005515 // protein binding // inferred from physical interaction /// 0005518 // collagen binding // inferred from direct assay /// 0005518 // collagen binding // inferred from mutant phenotype /// 0005524 // ATP binding // inferred from electronic annotation /// 0016301 // kinase activity // inferred from electronic annotation /// 0016740 // transferase activity // inferred from electronic annotation /// 0016772 // transferase activity, transferring phosphorus-containing groups // inferred from electronic annotation /// 0038062 // protein tyrosine kinase collagen receptor activity // inferred from direct assay /// 0046872 // metal ion binding // inferred from electronic annotation', '0000166 // nucleotide binding // inferred from electronic annotation /// 0003677 // DNA binding // inferred from electronic annotation /// 0005515 // protein binding // inferred from physical interaction /// 0005524 // ATP binding // inferred from electronic annotation /// 0016851 // magnesium chelatase activity // inferred from electronic annotation /// 0017111 // nucleoside-triphosphatase activity // inferred from electronic annotation', '0000166 // nucleotide binding // inferred from electronic annotation /// 0005524 // ATP binding // inferred from electronic annotation /// 0019899 // enzyme binding // inferred from physical interaction /// 0031072 // heat shock protein binding // inferred from physical interaction /// 0042623 // ATPase activity, coupled // inferred from direct assay /// 0051082 // unfolded protein binding // inferred from direct assay']}\n",
      "\n",
      "Examining ID and Gene Symbol columns format (first 3 rows):\n",
      "Row 0: ID=1007_s_at, Gene Symbol=DDR1 /// MIR4640\n",
      "Row 1: ID=1053_at, Gene Symbol=RFC2\n",
      "Row 2: ID=117_at, Gene Symbol=HSPA6\n",
      "\n",
      "Gene Symbol column completeness: 45782/3444587 rows (1.33%)\n"
     ]
    }
   ],
   "source": [
    "# 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.\n",
    "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
    "gene_annotation = get_gene_annotation(soft_file)\n",
    "\n",
    "# 2. Analyze the gene annotation dataframe to identify which columns contain the gene identifiers and gene symbols\n",
    "print(\"\\nGene annotation preview:\")\n",
    "print(f\"Columns in gene annotation: {gene_annotation.columns.tolist()}\")\n",
    "print(preview_df(gene_annotation, n=3))\n",
    "\n",
    "# Looking at the output, it appears the gene symbols are in the 'Gene Symbol' column\n",
    "# and the probe IDs are in the 'ID' column\n",
    "print(\"\\nExamining ID and Gene Symbol columns format (first 3 rows):\")\n",
    "if 'ID' in gene_annotation.columns and 'Gene Symbol' in gene_annotation.columns:\n",
    "    for i in range(min(3, len(gene_annotation))):\n",
    "        print(f\"Row {i}: ID={gene_annotation['ID'].iloc[i]}, Gene Symbol={gene_annotation['Gene Symbol'].iloc[i]}\")\n",
    "\n",
    "    # Check the quality and completeness of the mapping\n",
    "    non_null_symbols = gene_annotation['Gene Symbol'].notna().sum()\n",
    "    total_rows = len(gene_annotation)\n",
    "    print(f\"\\nGene Symbol column completeness: {non_null_symbols}/{total_rows} rows ({non_null_symbols/total_rows:.2%})\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bdd1dcc4",
   "metadata": {},
   "source": [
    "### Step 6: Gene Identifier Mapping"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "bc2e3377",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T07:02:15.577267Z",
     "iopub.status.busy": "2025-03-25T07:02:15.577141Z",
     "iopub.status.idle": "2025-03-25T07:02:17.091192Z",
     "shell.execute_reply": "2025-03-25T07:02:17.090540Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene mapping dataframe shape: (45782, 2)\n",
      "Preview of mapping dataframe:\n",
      "{'ID': ['1007_s_at', '1053_at', '117_at', '121_at', '1255_g_at'], 'Gene': ['DDR1 /// MIR4640', 'RFC2', 'HSPA6', 'PAX8', 'GUCA1A']}\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Original gene expression data shape: (54675, 62)\n",
      "Mapped gene expression data shape: (21278, 62)\n",
      "Preview of mapped gene expression data:\n",
      "{'GSM7574510': [8.256737349, 6.911184187, 8.633719548], 'GSM7574511': [5.758196709, 4.392330888, 7.459701646], 'GSM7574512': [7.90550267, 7.006615101, 10.748925159], 'GSM7574513': [7.621566619, 5.523093236, 10.236430428], 'GSM7574514': [7.746445504, 7.535800803, 12.058622905], 'GSM7574515': [8.310367085, 7.079364514, 11.198075410000001], 'GSM7574516': [7.775885539, 6.449054113, 7.317667267], 'GSM7574517': [7.525905291, 4.108699329, 11.644830382999999], 'GSM7574518': [7.849060138, 6.652675857, 10.843219882], 'GSM7574519': [8.408982277, 7.172603935, 8.447698456000001], 'GSM7574520': [7.445540368, 7.694966106, 7.320610432], 'GSM7574521': [8.128703262, 6.623905779, 10.761083019], 'GSM7574522': [7.667458, 7.469764175, 7.452024023], 'GSM7574523': [8.775423107, 6.766474906, 7.213160362], 'GSM7574524': [8.11916547, 6.245697206, 8.056183743], 'GSM7574525': [8.177690232, 6.172318479, 13.284788616], 'GSM7574526': [8.136775977, 7.09796609, 8.131592694], 'GSM7574527': [8.297344298, 6.434156606, 11.595796579], 'GSM7574528': [7.431410694, 6.64686572, 10.476946695999999], 'GSM7574529': [8.713039588, 6.748985385, 10.749540576000001], 'GSM7574530': [8.331387461, 7.512020621, 11.879697800999999], 'GSM7574531': [7.8881212, 7.240897767, 10.863394679], 'GSM7574532': [7.478973649, 6.558100745, 4.992333038], 'GSM7574533': [7.970266005, 6.934754473, 10.312180726000001], 'GSM7574534': [7.561374113, 7.228850344, 11.022103153], 'GSM7574535': [7.705867366, 5.809383796, 10.278933313], 'GSM7574536': [8.210263809, 6.772160146, 10.600944558], 'GSM7574537': [7.980945634, 6.525703732, 9.617139316], 'GSM7574538': [8.164029004, 6.891750929, 9.310452083000001], 'GSM7574539': [7.814696798, 6.897164637, 12.503602064999999], 'GSM7574540': [8.097350994, 6.537120438, 11.44321193], 'GSM7574541': [5.012088385, 4.888756203, 8.751517028], 'GSM7574542': [4.99607066, 8.159317746, 13.280822518], 'GSM7574543': [8.315677864, 5.372022577, 10.632795492], 'GSM7574544': [5.667760226, 8.7221496, 11.862118737], 'GSM7574545': [7.164599533, 5.284856085, 12.942488485999998], 'GSM7574546': [7.426006303, 9.305963874, 6.136913815], 'GSM7574547': [6.834267711, 7.930745309, 10.027409973000001], 'GSM7574548': [4.908083743, 5.761854369, 8.10273689], 'GSM7574549': [6.632099007, 9.604585157, 13.927885449], 'GSM7574550': [6.867929773, 8.393647578, 6.4431305640000005], 'GSM7574551': [1.580178364, 8.067539733, 9.712235671], 'GSM7574552': [4.717930875, 8.932476039, 10.127385043], 'GSM7574553': [6.144538407, 8.889025519, 11.578069263], 'GSM7574554': [1.906067329, 7.742702426, 8.068408462999999], 'GSM7574555': [4.168156829, 9.348911301, 7.5960199], 'GSM7574556': [4.68827463, 5.658048444, 11.659756006999999], 'GSM7574557': [5.490239827, 8.522212527, 7.933114678999999], 'GSM7574558': [4.151734109, 4.602846895, 10.544586183], 'GSM7574559': [5.544552367, 7.495081424, 11.907627233], 'GSM7574560': [7.45829569, 5.255392303, 15.162937359], 'GSM7574561': [2.169220476, 7.00546475, 11.868842057], 'GSM7574562': [5.438713301, 7.773810684, 10.723137962], 'GSM7574563': [2.193749913, 8.111533526, 13.362417750999999], 'GSM7574564': [4.394292332, 8.650141361, 10.067019597], 'GSM7574565': [4.913318839, 8.486558974, 14.346668095], 'GSM7574566': [7.961891568, 9.123096312, 7.1648182259999995], 'GSM7574567': [1.885848717, 7.979035239, 10.819972741], 'GSM7574568': [4.879857628, 8.12539782, 8.757945172], 'GSM7574569': [5.042971969, 8.295288517, 12.78955345], 'GSM7574570': [4.273824868, 8.065982489, 10.038928358], 'GSM7574571': [4.343633999, 8.895245123, 10.889364859]}\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene expression data saved to: ../../output/preprocess/Breast_Cancer/gene_data/GSE236725.csv\n"
     ]
    }
   ],
   "source": [
    "# 1. Identify which columns contain gene identifiers and gene symbols\n",
    "# From our analysis, we can see that:\n",
    "# - The 'ID' column in the gene annotation contains Affymetrix probe IDs (e.g., \"1007_s_at\")\n",
    "# - The 'Gene Symbol' column contains the human gene symbols (e.g., \"DDR1 /// MIR4640\")\n",
    "\n",
    "# These match what we need for mapping:\n",
    "prob_col = 'ID'          # The column with probe IDs that match our expression data index\n",
    "gene_col = 'Gene Symbol' # The column with gene symbols we want to map to\n",
    "\n",
    "# 2. Get a gene mapping dataframe using the library function\n",
    "mapping_df = get_gene_mapping(gene_annotation, prob_col, gene_col)\n",
    "print(f\"Gene mapping dataframe shape: {mapping_df.shape}\")\n",
    "print(\"Preview of mapping dataframe:\")\n",
    "print(preview_df(mapping_df, n=5))\n",
    "\n",
    "# 3. Convert probe-level expression to gene-level expression\n",
    "# Extract the gene expression data using the function from the library\n",
    "gene_expr_df = get_genetic_data(matrix_file)\n",
    "print(f\"Original gene expression data shape: {gene_expr_df.shape}\")\n",
    "\n",
    "# Apply the gene mapping to convert probe-level to gene-level expression\n",
    "gene_data = apply_gene_mapping(gene_expr_df, mapping_df)\n",
    "print(f\"Mapped gene expression data shape: {gene_data.shape}\")\n",
    "print(\"Preview of mapped gene expression data:\")\n",
    "print(preview_df(gene_data, n=3))\n",
    "\n",
    "# Save the gene expression data to the specified output path\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"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4d23caef",
   "metadata": {},
   "source": [
    "### Step 7: Data Normalization and Linking"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "0d942bf7",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T07:02:17.093615Z",
     "iopub.status.busy": "2025-03-25T07:02:17.093470Z",
     "iopub.status.idle": "2025-03-25T07:02:28.490972Z",
     "shell.execute_reply": "2025-03-25T07:02:28.490294Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene data shape before normalization: (21278, 62)\n",
      "Gene data shape after normalization: (19845, 62)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Normalized gene data saved to ../../output/preprocess/Breast_Cancer/gene_data/GSE236725.csv\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Extracted clinical data shape: (1, 62)\n",
      "Preview of clinical data (first 5 samples):\n",
      "               GSM7574510  GSM7574511  GSM7574512  GSM7574513  GSM7574514\n",
      "Breast_Cancer         1.0         1.0         1.0         1.0         0.0\n",
      "Clinical data saved to ../../output/preprocess/Breast_Cancer/clinical_data/GSE236725.csv\n",
      "Gene data columns (first 5): ['GSM7574510', 'GSM7574511', 'GSM7574512', 'GSM7574513', 'GSM7574514']\n",
      "Clinical data columns (first 5): ['GSM7574510', 'GSM7574511', 'GSM7574512', 'GSM7574513', 'GSM7574514']\n",
      "Found 62 common samples between gene and clinical data\n",
      "Initial linked data shape: (62, 19846)\n",
      "Preview of linked data (first 5 rows, first 5 columns):\n",
      "            Breast_Cancer      A1BG  A1BG-AS1       A1CF        A2M\n",
      "GSM7574510            1.0  8.256737  6.911184   8.633720  19.862964\n",
      "GSM7574511            1.0  5.758197  4.392331   7.459702  19.472159\n",
      "GSM7574512            1.0  7.905503  7.006615  10.748925  21.226190\n",
      "GSM7574513            1.0  7.621567  5.523093  10.236430  18.931035\n",
      "GSM7574514            0.0  7.746446  7.535801  12.058623  18.542354\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Linked data shape after handling missing values: (62, 19846)\n",
      "For the feature 'Breast_Cancer', the least common label is '1.0' with 16 occurrences. This represents 25.81% of the dataset.\n",
      "The distribution of the feature 'Breast_Cancer' in this dataset is fine.\n",
      "\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Linked data saved to ../../output/preprocess/Breast_Cancer/GSE236725.csv\n"
     ]
    }
   ],
   "source": [
    "# 1. Normalize gene symbols in the gene expression data\n",
    "try:\n",
    "    # Make sure the directory exists\n",
    "    os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
    "    \n",
    "    # Use the gene_data variable from the previous step (don't try to load it from file)\n",
    "    print(f\"Gene data shape before normalization: {gene_data.shape}\")\n",
    "    \n",
    "    # Apply normalization to gene symbols\n",
    "    normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n",
    "    print(f\"Gene data shape after normalization: {normalized_gene_data.shape}\")\n",
    "    \n",
    "    # Save the normalized gene data\n",
    "    normalized_gene_data.to_csv(out_gene_data_file)\n",
    "    print(f\"Normalized gene data saved to {out_gene_data_file}\")\n",
    "    \n",
    "    # Use the normalized data for further processing\n",
    "    gene_data = normalized_gene_data\n",
    "    is_gene_available = True\n",
    "except Exception as e:\n",
    "    print(f\"Error normalizing gene data: {e}\")\n",
    "    is_gene_available = False\n",
    "\n",
    "# 2. Load clinical data - respecting the analysis from Step 2\n",
    "# From Step 2, we determined:\n",
    "# trait_row = None  # No Breast Cancer subtype data available\n",
    "# age_row = 2\n",
    "# gender_row = None\n",
    "is_trait_available = trait_row is not None\n",
    "\n",
    "# Skip clinical feature extraction when trait_row is None\n",
    "if is_trait_available:\n",
    "    try:\n",
    "        # Load the clinical data from file\n",
    "        soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
    "        background_info, clinical_data = get_background_and_clinical_data(matrix_file)\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",
    "            gender_row=gender_row,\n",
    "            convert_gender=convert_gender,\n",
    "            age_row=age_row,\n",
    "            convert_age=convert_age\n",
    "        )\n",
    "        \n",
    "        print(f\"Extracted clinical data shape: {clinical_features.shape}\")\n",
    "        print(\"Preview of clinical data (first 5 samples):\")\n",
    "        print(clinical_features.iloc[:, :5])\n",
    "        \n",
    "        # Save the properly extracted clinical data\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 data saved to {out_clinical_data_file}\")\n",
    "    except Exception as e:\n",
    "        print(f\"Error extracting clinical data: {e}\")\n",
    "        is_trait_available = False\n",
    "else:\n",
    "    print(f\"No trait data ({trait}) available in this dataset based on previous analysis.\")\n",
    "\n",
    "# 3. Link clinical and genetic data if both are available\n",
    "if is_trait_available and is_gene_available:\n",
    "    try:\n",
    "        # Debug the column names to ensure they match\n",
    "        print(f\"Gene data columns (first 5): {gene_data.columns[:5].tolist()}\")\n",
    "        print(f\"Clinical data columns (first 5): {clinical_features.columns[:5].tolist()}\")\n",
    "        \n",
    "        # Check for common sample IDs\n",
    "        common_samples = set(gene_data.columns).intersection(clinical_features.columns)\n",
    "        print(f\"Found {len(common_samples)} common samples between gene and clinical data\")\n",
    "        \n",
    "        if len(common_samples) > 0:\n",
    "            # Link the clinical and genetic data\n",
    "            linked_data = geo_link_clinical_genetic_data(clinical_features, gene_data)\n",
    "            print(f\"Initial linked data shape: {linked_data.shape}\")\n",
    "            \n",
    "            # Debug the trait values before handling missing values\n",
    "            print(\"Preview of linked data (first 5 rows, first 5 columns):\")\n",
    "            print(linked_data.iloc[:5, :5])\n",
    "            \n",
    "            # Handle missing values\n",
    "            linked_data = handle_missing_values(linked_data, trait)\n",
    "            print(f\"Linked data shape after handling missing values: {linked_data.shape}\")\n",
    "            \n",
    "            if linked_data.shape[0] > 0:\n",
    "                # Check for bias in trait and demographic features\n",
    "                is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n",
    "                \n",
    "                # Validate the data quality and save cohort info\n",
    "                note = \"Dataset contains gene expression data from triple negative breast cancer vs. luminal tumors, but no explicit breast cancer subtype labels in the sample characteristics.\"\n",
    "                is_usable = validate_and_save_cohort_info(\n",
    "                    is_final=True,\n",
    "                    cohort=cohort,\n",
    "                    info_path=json_path,\n",
    "                    is_gene_available=is_gene_available,\n",
    "                    is_trait_available=is_trait_available,\n",
    "                    is_biased=is_biased,\n",
    "                    df=linked_data,\n",
    "                    note=note\n",
    "                )\n",
    "                \n",
    "                # Save the linked data if it's usable\n",
    "                if is_usable:\n",
    "                    os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n",
    "                    linked_data.to_csv(out_data_file)\n",
    "                    print(f\"Linked data saved to {out_data_file}\")\n",
    "                else:\n",
    "                    print(\"Data not usable for the trait study - not saving final linked data.\")\n",
    "            else:\n",
    "                print(\"After handling missing values, no samples remain.\")\n",
    "                validate_and_save_cohort_info(\n",
    "                    is_final=True,\n",
    "                    cohort=cohort,\n",
    "                    info_path=json_path,\n",
    "                    is_gene_available=is_gene_available,\n",
    "                    is_trait_available=is_trait_available,\n",
    "                    is_biased=True,\n",
    "                    df=pd.DataFrame(),\n",
    "                    note=\"No valid samples after handling missing values.\"\n",
    "                )\n",
    "        else:\n",
    "            print(\"No common samples found between gene expression and clinical data.\")\n",
    "            validate_and_save_cohort_info(\n",
    "                is_final=True,\n",
    "                cohort=cohort,\n",
    "                info_path=json_path,\n",
    "                is_gene_available=is_gene_available,\n",
    "                is_trait_available=is_trait_available,\n",
    "                is_biased=True,\n",
    "                df=pd.DataFrame(),\n",
    "                note=\"No common samples between gene expression and clinical data.\"\n",
    "            )\n",
    "    except Exception as e:\n",
    "        print(f\"Error linking or processing data: {e}\")\n",
    "        validate_and_save_cohort_info(\n",
    "            is_final=True,\n",
    "            cohort=cohort,\n",
    "            info_path=json_path,\n",
    "            is_gene_available=is_gene_available,\n",
    "            is_trait_available=is_trait_available,\n",
    "            is_biased=True,  # Assume biased if there's an error\n",
    "            df=pd.DataFrame(),  # Empty dataframe for metadata\n",
    "            note=f\"Error in data processing: {str(e)}\"\n",
    "        )\n",
    "else:\n",
    "    # Create an empty DataFrame for metadata purposes\n",
    "    empty_df = pd.DataFrame()\n",
    "    \n",
    "    # We can't proceed with linking if either trait or gene data is missing\n",
    "    print(\"Cannot proceed with data linking due to missing trait or gene data.\")\n",
    "    validate_and_save_cohort_info(\n",
    "        is_final=True,\n",
    "        cohort=cohort,\n",
    "        info_path=json_path,\n",
    "        is_gene_available=is_gene_available,\n",
    "        is_trait_available=is_trait_available,\n",
    "        is_biased=True,  # Data is unusable if we're missing components\n",
    "        df=empty_df,  # Empty dataframe for metadata\n",
    "        note=\"Dataset contains gene expression data from triple negative breast cancer vs. luminal tumors, but no explicit breast cancer subtype labels in the sample characteristics.\"\n",
    "    )"
   ]
  }
 ],
 "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
}