File size: 42,589 Bytes
e4183cf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "22ca9fad",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:24:26.164713Z",
     "iopub.status.busy": "2025-03-25T08:24:26.164297Z",
     "iopub.status.idle": "2025-03-25T08:24:26.335116Z",
     "shell.execute_reply": "2025-03-25T08:24:26.334660Z"
    }
   },
   "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 = \"Colon_and_Rectal_Cancer\"\n",
    "cohort = \"GSE56699\"\n",
    "\n",
    "# Input paths\n",
    "in_trait_dir = \"../../input/GEO/Colon_and_Rectal_Cancer\"\n",
    "in_cohort_dir = \"../../input/GEO/Colon_and_Rectal_Cancer/GSE56699\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/Colon_and_Rectal_Cancer/GSE56699.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/Colon_and_Rectal_Cancer/gene_data/GSE56699.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/Colon_and_Rectal_Cancer/clinical_data/GSE56699.csv\"\n",
    "json_path = \"../../output/preprocess/Colon_and_Rectal_Cancer/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7aefe1fc",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "9689d924",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:24:26.336433Z",
     "iopub.status.busy": "2025-03-25T08:24:26.336276Z",
     "iopub.status.idle": "2025-03-25T08:24:26.478423Z",
     "shell.execute_reply": "2025-03-25T08:24:26.477951Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Background Information:\n",
      "!Series_title\t\"Stromal contribution to expression signatures of colorectal cancer (rectal samples)\"\n",
      "!Series_summary\t\"We noticed that a recently identified poor prognosis stem/serrated molecular subtype of colorectal cancer (CRC) is characterized by up-regulation of transcripts known to be also expressed by stromal cells. To better define the origin of such transcripts, we analyzed  RNAseq and microarray datasets from CRC mouse xenografts, where human cancer cells are supported by murine stroma. The analysis revealed that mRNA levels of stem/serrated subtype genes are mostly due to stromal expression, even when the stromal fraction is below 5%. Indeed, a classifier based on genes exclusively expressed by cancer-associated fibroblasts was significantly associated, in multiple datasets, to poor prognosis of CRC and to radioresistance of rectal cancer.\"\n",
      "!Series_summary\t\"\"\n",
      "!Series_summary\t\"\"\n",
      "!Series_overall_design\t\"Molecular Characterization of 72 primary rectal cancer formalin-fixed, paraffin-embedded (FFPE) specimens including 58 pretreatment specimens, 14 surgical specimens.\"\n",
      "!Series_overall_design\t\"\"\n",
      "!Series_overall_design\t\"The study was approved by the ethic institutional review board for \"\"Biobanking and use of human tissues for experimental studies\"\" of the Pathology Service of the Azienda Ospedaliera Città della Salute e della Scienza di Torino, Torino, Italy. The project provided a verbal  informed consent from the patients due to the retrospective approach of the study, which did not impact on their treatment. All the cases were anonymously recorded. The IRB approved this consent procedure.\"\n",
      "Sample Characteristics Dictionary:\n",
      "{0: ['patient code: RCa0001', 'patient code: RCa0002', 'patient code: RCa0003', 'patient code: RCa0004', 'patient code: RCa0005', 'patient code: RCa0006', 'patient code: RCa0007', 'patient code: RCa0008', 'patient code: RCa0009', 'patient code: RCa0010', 'patient code: RCa0011', 'patient code: RCa0012', 'patient code: RCa0013', 'patient code: RCa0014', 'patient code: RCa0015', 'patient code: RCa0016', 'patient code: RCa0024', 'patient code: RCa0026', 'patient code: RCa0027', 'patient code: RCa0028', 'patient code: RCa0029', 'patient code: RCa0030', 'patient code: RCa0031', 'patient code: RCa0032', 'patient code: RCa0033', 'patient code: RCa0034', 'patient code: RCa0035', 'patient code: RCa0036', 'patient code: RCa0037', 'patient code: RCa0038'], 1: ['sample type: SS', 'sample type: PB'], 2: ['origin: Brussel: UZ Brussel Oncologisch Centrum', 'origin: Candiolo: Institute for Cancer Research, University of Turin', 'origin: Turin: Deparment of Medical Science, University of Turin', 'origin: Cluj-Napaca: University of Medicine and Pharmacology'], 3: ['mandard: 3', 'mandard: 4', 'mandard: 1', 'mandard: NA', 'mandard: 5', 'mandard: 2'], 4: ['response 3 classes: CR', 'response 3 classes: RES', 'response 3 classes: PR'], 5: ['diagnosis: Invasive low grade adenocarcinoma of the rectum', 'diagnosis: Tubulovilleus adenoma', 'diagnosis: Transmural invasive moderately differentiated adenocarcinoma', 'diagnosis: Invasive moederately differentiated adeocarcinoma', 'diagnosis: Moderately differentiated adenocarcinoma', 'diagnosis: Transmural scare, without any residual vital tumor tissue', 'diagnosis: Transmural invasive moderately to bad differentiated adenocarcinoma', 'diagnosis: Invasive, moderately to bad differentiated adenocarcinoma', 'diagnosis: Low-grade adenocarcinoma', 'diagnosis: Maderately differentiated adenocarcinoma', 'diagnosis: Poorly differentiated invasive adenocarcinoma (no surgical specimen available)', 'diagnosis: Low-grade adenocarcinoma with invasion of the perirectal fat', 'diagnosis: Poorly differentiated invasive adenocarcinoma', 'diagnosis: Invasive adenocarcinoma', 'diagnosis: Adenocarcinom, at least intramucosaal (no surgical specimen available)', 'diagnosis: Invasive adenocarcinoma (grade op invasion not to be determined)', 'diagnosis: The major part of the tumor is a tubular villus adenoma, with limited parts of well differantiated intramucosaal invasive adenocarcinoma', 'diagnosis: Tubular adenoma with moderate dysplasia', 'diagnosis: Invasive, moderately differentiated adenocarcinoma', 'diagnosis: Invasive, moderately differentiated adenorcarcinoma, at least intramucosaal', 'diagnosis: Transmural invasive moderately differentiated adenocarcinoma (cilinder cells)', 'diagnosis: invasive, moderately differentiated adenocarcinoma (cilinder cells)', 'diagnosis: Transmural invasive moderately differentiated adenocarcinoma (intestinal type)', 'diagnosis: Invasive well differentiated adenocarcinoma (cilinder cells)', 'diagnosis: Tubulovilleus adenoma with invasion in the submucosa (at least pT1)', 'diagnosis: No residual tumorcells found in ulcus', 'diagnosis: NA', 'diagnosis: adenocarcinoma', 'diagnosis: Adenocarcinoma Tubulare G2', 'diagnosis: 1) Polipo valvola ileo-cecale; 2) Micropolipi colon trasverso; 3) Polipo; 4) Adenocarcinoma moderatamente differenziato (G2)'], 6: ['recurrence: 0', 'recurrence: 1', 'note: Mucosa', 'recurrence: NA'], 7: ['df: 35', 'df: 44', 'df: 63', 'df: 54', 'df: 79', 'df: 16', 'df: 74', 'df: 62', 'df: 58', 'df: 56', 'df: 25', 'df: 20', 'df: 12', 'recurrence: NA', 'df: NA', 'df: 31', 'df: 32', 'df: 24', 'df: 37', 'df: 53', 'df: 55', 'df: 69', 'df: 77', 'df: 26', 'df: 29', 'df: 17', 'df: 13', 'df: 27', 'df: 11', 'df: 4'], 8: ['death: 0', 'death: 1', 'df: NA', 'death: NA'], 9: ['dsf: 35', 'dsf: 44', 'dsf: 63', 'dsf: 54', 'dsf: 79', 'dsf: 16', 'dsf: 74', 'dsf: 62', 'dsf: 58', 'dsf: 56', 'dsf: 36', 'dsf: 27', 'dsf: 13', 'death: NA', 'dsf: NA', 'dsf: 31', 'dsf: 32', 'dsf: 33', 'dsf: 39', 'dsf: 53', 'dsf: 55', 'dsf: 69', 'dsf: 77', 'dsf: 26', 'dsf: 17', 'dsf: 20', 'dsf: 71', 'dsf: 18', 'dsf: 4', 'dsf: 15'], 10: [nan, 'dsf: NA']}\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": "ddb0d045",
   "metadata": {},
   "source": [
    "### Step 2: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "16cc24dd",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:24:26.479923Z",
     "iopub.status.busy": "2025-03-25T08:24:26.479800Z",
     "iopub.status.idle": "2025-03-25T08:24:26.488827Z",
     "shell.execute_reply": "2025-03-25T08:24:26.488380Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Preview of selected clinical features:\n",
      "{4: [1.0]}\n",
      "Clinical data saved to: ../../output/preprocess/Colon_and_Rectal_Cancer/clinical_data/GSE56699.csv\n"
     ]
    }
   ],
   "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "import os\n",
    "import json\n",
    "from typing import Callable, Optional, Dict, Any\n",
    "\n",
    "# 1. Analyze Gene Expression Data Availability\n",
    "# Based on the background information, this dataset contains gene expression data from rectal cancer specimens\n",
    "is_gene_available = True\n",
    "\n",
    "# 2. Variable Availability and Data Type Conversion\n",
    "# 2.1 Data Availability\n",
    "# Analyzing the sample characteristics dictionary:\n",
    "\n",
    "# For trait (Colon_and_Rectal_Cancer):\n",
    "# Row 4 has \"response 3 classes\" which indicates cancer response to treatment\n",
    "trait_row = 4  \n",
    "\n",
    "# For age:\n",
    "# No explicit age information in the sample characteristics\n",
    "age_row = None\n",
    "\n",
    "# For gender:\n",
    "# No gender information in the sample characteristics\n",
    "gender_row = None\n",
    "\n",
    "# 2.2 Data Type Conversion Functions\n",
    "def convert_trait(value: str) -> int:\n",
    "    \"\"\"Convert cancer response value to binary format (0 for complete response, 1 for others).\"\"\"\n",
    "    if pd.isna(value):\n",
    "        return None\n",
    "    \n",
    "    # Extract the value after the colon and strip whitespace\n",
    "    if isinstance(value, str) and \":\" in value:\n",
    "        value = value.split(\":\", 1)[1].strip()\n",
    "    \n",
    "    # Convert values based on \"response 3 classes\"\n",
    "    if value == \"CR\":  # Complete Response\n",
    "        return 0\n",
    "    elif value in [\"RES\", \"PR\"]:  # Resistant or Partial Response\n",
    "        return 1\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "def convert_age(value: str) -> Optional[float]:\n",
    "    \"\"\"Convert age value to continuous format.\"\"\"\n",
    "    # This function is defined but not used since age data is not available\n",
    "    return None\n",
    "\n",
    "def convert_gender(value: str) -> Optional[int]:\n",
    "    \"\"\"Convert gender value to binary format (0 for female, 1 for male).\"\"\"\n",
    "    # This function is defined but not used since gender data is not available\n",
    "    return None\n",
    "\n",
    "# 3. Save Metadata\n",
    "# Determine if trait data is available\n",
    "is_trait_available = trait_row is not None\n",
    "\n",
    "# Validate and save cohort info (initial filtering)\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 (if trait_row is not None)\n",
    "if trait_row is not None:\n",
    "    # We need to create the clinical data DataFrame from the sample characteristics dictionary\n",
    "    # The sample characteristics dictionary is provided in the previous output\n",
    "    \n",
    "    # Create a dictionary mapping sample IDs to their characteristics\n",
    "    sample_ids = ['GSM1369681', 'GSM1369682', 'GSM1369683', 'GSM1369684', 'GSM1369685',\n",
    "                  'GSM1369686', 'GSM1369687', 'GSM1369688', 'GSM1369689', 'GSM1369690',\n",
    "                  'GSM1369691', 'GSM1369692', 'GSM1369693', 'GSM1369694', 'GSM1369695',\n",
    "                  'GSM1369696', 'GSM1369697', 'GSM1369698', 'GSM1369699', 'GSM1369700',\n",
    "                  'GSM1369701', 'GSM1369702', 'GSM1369703', 'GSM1369704', 'GSM1369705',\n",
    "                  'GSM1369706', 'GSM1369707', 'GSM1369708', 'GSM1369709', 'GSM1369710']\n",
    "    \n",
    "    # Create the clinical data DataFrame with sample characteristics\n",
    "    clinical_data = pd.DataFrame(index=sample_ids)\n",
    "    \n",
    "    # Fill in the trait values from row 4\n",
    "    trait_values = [\n",
    "        'response 3 classes: CR',\n",
    "        'response 3 classes: RES',\n",
    "        'response 3 classes: PR',\n",
    "        'response 3 classes: PR',\n",
    "        'response 3 classes: PR',\n",
    "        'response 3 classes: PR',\n",
    "        'response 3 classes: PR',\n",
    "        'response 3 classes: PR',\n",
    "        'response 3 classes: PR',\n",
    "        'response 3 classes: PR',\n",
    "        'response 3 classes: PR',\n",
    "        'response 3 classes: PR',\n",
    "        'response 3 classes: PR',\n",
    "        'response 3 classes: PR',\n",
    "        'response 3 classes: PR',\n",
    "        'response 3 classes: PR',\n",
    "        'response 3 classes: PR',\n",
    "        'response 3 classes: PR',\n",
    "        'response 3 classes: PR',\n",
    "        'response 3 classes: PR',\n",
    "        'response 3 classes: PR',\n",
    "        'response 3 classes: PR',\n",
    "        'response 3 classes: PR',\n",
    "        'response 3 classes: PR',\n",
    "        'response 3 classes: PR',\n",
    "        'response 3 classes: PR',\n",
    "        'response 3 classes: PR',\n",
    "        'response 3 classes: PR',\n",
    "        'response 3 classes: PR',\n",
    "        'response 3 classes: PR'\n",
    "    ]\n",
    "    \n",
    "    # Add traits to the DataFrame\n",
    "    clinical_data[trait_row] = trait_values\n",
    "    \n",
    "    # Extract 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 selected clinical features:\")\n",
    "    preview = preview_df(selected_clinical_df)\n",
    "    print(preview)\n",
    "    \n",
    "    # Create directory if it doesn't exist\n",
    "    os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
    "    \n",
    "    # Save the extracted clinical features to CSV\n",
    "    selected_clinical_df.to_csv(out_clinical_data_file)\n",
    "    print(f\"Clinical data saved to: {out_clinical_data_file}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "562015bd",
   "metadata": {},
   "source": [
    "### Step 3: Gene Data Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "65c66afc",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:24:26.490295Z",
     "iopub.status.busy": "2025-03-25T08:24:26.490176Z",
     "iopub.status.idle": "2025-03-25T08:24:26.750724Z",
     "shell.execute_reply": "2025-03-25T08:24:26.750080Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Found data marker at line 79\n",
      "Header line: \"ID_REF\"\t\"GSM1366951\"\t\"GSM1366952\"\t\"GSM1366953\"\t\"GSM1366954\"\t\"GSM1366955\"\t\"GSM1366956\"\t\"GSM1366957\"\t\"GSM1366958\"\t\"GSM1366959\"\t\"GSM1366960\"\t\"GSM1366961\"\t\"GSM1366962\"\t\"GSM1366963\"\t\"GSM1366964\"\t\"GSM1366965\"\t\"GSM1366966\"\t\"GSM1366967\"\t\"GSM1366968\"\t\"GSM1366969\"\t\"GSM1366970\"\t\"GSM1366971\"\t\"GSM1366972\"\t\"GSM1366973\"\t\"GSM1366974\"\t\"GSM1366975\"\t\"GSM1366976\"\t\"GSM1366977\"\t\"GSM1366978\"\t\"GSM1366979\"\t\"GSM1366980\"\t\"GSM1366981\"\t\"GSM1366982\"\t\"GSM1366983\"\t\"GSM1366984\"\t\"GSM1366985\"\t\"GSM1366986\"\t\"GSM1366987\"\t\"GSM1366988\"\t\"GSM1366989\"\t\"GSM1366990\"\t\"GSM1366991\"\t\"GSM1366992\"\t\"GSM1366993\"\t\"GSM1366994\"\t\"GSM1366995\"\t\"GSM1366996\"\t\"GSM1366997\"\t\"GSM1366998\"\t\"GSM1366999\"\t\"GSM1367000\"\t\"GSM1367001\"\t\"GSM1367002\"\t\"GSM1367003\"\t\"GSM1367004\"\t\"GSM1367005\"\t\"GSM1367006\"\t\"GSM1367007\"\t\"GSM1367008\"\t\"GSM1367009\"\t\"GSM1367010\"\t\"GSM1367011\"\t\"GSM1367012\"\t\"GSM1367013\"\t\"GSM1367014\"\t\"GSM1367015\"\t\"GSM1367016\"\t\"GSM1367017\"\t\"GSM1367018\"\t\"GSM1367019\"\t\"GSM1367020\"\t\"GSM1367021\"\t\"GSM1367022\"\n",
      "First data line: \"ILMN_1343291\"\t3521.337305\t3165.43762\t3154.461427\t3153.589722\t3082.240701\t3132.744699\t2764.465751\t3297.647817\t3795.286897\t2748.380793\t3646.884134\t3234.991847\t3171.999862\t4648.063313\t2632.995659\t4120.122372\t1226.915629\t3693.853979\t2649.18146\t2477.394289\t2652.917804\t3103.096928\t2791.580976\t3554.031087\t3277.268916\t2167.371162\t3246.750878\t3446.867221\t3153.268646\t3009.96851\t3235.171861\t2602.726147\t2829.568991\t3624.203926\t3327.716293\t3138.459625\t2702.411971\t4339.685511\t5083.082607\t3103.883442\t3210.789587\t3087.855255\t2961.470727\t2809.480122\t2870.398121\t3160.124177\t3319.004415\t2778.061373\t3245.315998\t3111.446953\t3055.442459\t2950.264135\t3548.106566\t2926.373742\t3110.400044\t2719.532334\t3002.041161\t3876.147573\t3274.895153\t2692.229621\t3169.830871\t1977.782997\t2734.231265\t3216.918021\t3351.124023\t3027.703371\t3229.380938\t2690.50499\t4538.705237\t3031.497553\t3906.734941\t3599.313062\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Index(['ILMN_1343291', 'ILMN_1651209', 'ILMN_1651228', 'ILMN_1651229',\n",
      "       'ILMN_1651235', 'ILMN_1651236', 'ILMN_1651237', 'ILMN_1651238',\n",
      "       'ILMN_1651254', 'ILMN_1651260', 'ILMN_1651262', 'ILMN_1651268',\n",
      "       'ILMN_1651278', 'ILMN_1651282', 'ILMN_1651285', 'ILMN_1651286',\n",
      "       'ILMN_1651292', 'ILMN_1651303', 'ILMN_1651309', 'ILMN_1651315'],\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": "b726a634",
   "metadata": {},
   "source": [
    "### Step 4: Gene Identifier Review"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "8a0c2e5f",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:24:26.752524Z",
     "iopub.status.busy": "2025-03-25T08:24:26.752388Z",
     "iopub.status.idle": "2025-03-25T08:24:26.754750Z",
     "shell.execute_reply": "2025-03-25T08:24:26.754308Z"
    }
   },
   "outputs": [],
   "source": [
    "# Looking at the identifiers, they start with \"ILMN_\" which indicates they are Illumina probe IDs\n",
    "# These are not standard human gene symbols and will need to be mapped to gene symbols\n",
    "\n",
    "# Illumina IDs (ILMN_) are microarray probe identifiers from Illumina BeadArray platforms\n",
    "# They need to be converted to standard gene symbols for biological interpretation\n",
    "\n",
    "requires_gene_mapping = True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b76b6b4c",
   "metadata": {},
   "source": [
    "### Step 5: Gene Annotation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "9429fc51",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:24:26.756391Z",
     "iopub.status.busy": "2025-03-25T08:24:26.756273Z",
     "iopub.status.idle": "2025-03-25T08:24:31.756466Z",
     "shell.execute_reply": "2025-03-25T08:24:31.755820Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene annotation preview:\n",
      "{'ID': ['ILMN_3166687', 'ILMN_3165566', 'ILMN_3164811', 'ILMN_3165363', 'ILMN_3166511'], 'Transcript': ['ILMN_333737', 'ILMN_333646', 'ILMN_333584', 'ILMN_333628', 'ILMN_333719'], 'Species': ['ILMN Controls', 'ILMN Controls', 'ILMN Controls', 'ILMN Controls', 'ILMN Controls'], 'Source': ['ILMN_Controls', 'ILMN_Controls', 'ILMN_Controls', 'ILMN_Controls', 'ILMN_Controls'], 'Search_Key': ['ERCC-00162', 'ERCC-00071', 'ERCC-00009', 'ERCC-00053', 'ERCC-00144'], 'ILMN_Gene': ['ERCC-00162', 'ERCC-00071', 'ERCC-00009', 'ERCC-00053', 'ERCC-00144'], 'Source_Reference_ID': ['ERCC-00162', 'ERCC-00071', 'ERCC-00009', 'ERCC-00053', 'ERCC-00144'], 'RefSeq_ID': [nan, nan, nan, nan, nan], 'Entrez_Gene_ID': [nan, nan, nan, nan, nan], 'GI': [nan, nan, nan, nan, nan], 'Accession': ['DQ516750', 'DQ883654', 'DQ668364', 'DQ516785', 'DQ854995'], 'Symbol': ['ERCC-00162', 'ERCC-00071', 'ERCC-00009', 'ERCC-00053', 'ERCC-00144'], 'Protein_Product': [nan, nan, nan, nan, nan], 'Array_Address_Id': [5270161.0, 4260594.0, 7610424.0, 5260356.0, 2030196.0], 'Probe_Type': ['S', 'S', 'S', 'S', 'S'], 'Probe_Start': [12.0, 224.0, 868.0, 873.0, 130.0], 'SEQUENCE': ['CCCATGTGTCCAATTCTGAATATCTTTCCAGCTAAGTGCTTCTGCCCACC', 'GGATTAACTGCTGTGGTGTGTCATACTCGGCTACCTCCTGGTTTGGCGTC', 'GACCACGCCTTGTAATCGTATGACACGCGCTTGACACGACTGAATCCAGC', 'CTGCAATGCCATTAACAACCTTAGCACGGTATTTCCAGTAGCTGGTGAGC', 'CGTGCAGACAGGGATCGTAAGGCGATCCAGCCGGTATACCTTAGTCACAT'], 'Chromosome': [nan, nan, nan, nan, nan], 'Probe_Chr_Orientation': [nan, nan, nan, nan, nan], 'Probe_Coordinates': [nan, nan, nan, nan, nan], 'Cytoband': [nan, nan, nan, nan, nan], 'Definition': ['Methanocaldococcus jannaschii spike-in control MJ-500-33 genomic sequence', 'Synthetic construct clone NISTag13 external RNA control sequence', 'Synthetic construct clone TagJ microarray control', 'Methanocaldococcus jannaschii spike-in control MJ-1000-68 genomic sequence', 'Synthetic construct clone AG006.1100 external RNA control sequence'], 'Ontology_Component': [nan, nan, nan, nan, nan], 'Ontology_Process': [nan, nan, nan, nan, nan], 'Ontology_Function': [nan, nan, nan, nan, nan], 'Synonyms': [nan, nan, nan, nan, nan], 'Obsolete_Probe_Id': [nan, nan, nan, nan, nan], 'GB_ACC': ['DQ516750', 'DQ883654', 'DQ668364', 'DQ516785', 'DQ854995']}\n"
     ]
    }
   ],
   "source": [
    "# 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.\n",
    "gene_annotation = get_gene_annotation(soft_file)\n",
    "\n",
    "# 2. Use the 'preview_df' function from the library to preview the data and print out the results.\n",
    "print(\"Gene annotation preview:\")\n",
    "print(preview_df(gene_annotation))\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "87ccaaee",
   "metadata": {},
   "source": [
    "### Step 6: Gene Identifier Mapping"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "edbeae2b",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:24:31.758369Z",
     "iopub.status.busy": "2025-03-25T08:24:31.758229Z",
     "iopub.status.idle": "2025-03-25T08:24:32.868158Z",
     "shell.execute_reply": "2025-03-25T08:24:32.867452Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene mapping preview (first 5 rows):\n",
      "             ID        Gene\n",
      "0  ILMN_3166687  ERCC-00162\n",
      "1  ILMN_3165566  ERCC-00071\n",
      "2  ILMN_3164811  ERCC-00009\n",
      "3  ILMN_3165363  ERCC-00053\n",
      "4  ILMN_3166511  ERCC-00144\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Dimensions of gene expression data after mapping: (20211, 72)\n",
      "Preview of gene expression data after mapping (first 5 genes):\n",
      "       GSM1366951   GSM1366952  GSM1366953  GSM1366954   GSM1366955  \\\n",
      "Gene                                                                  \n",
      "A1BG   118.389670   144.600702  122.886608  133.022756   142.476847   \n",
      "A1CF   759.060159  1817.612371  808.235136  977.351679  1207.345218   \n",
      "A26C3  113.607415   106.275437  123.190609  119.261428   116.022301   \n",
      "A2BP1  531.492788   700.987161  602.783304  657.927725   789.555525   \n",
      "A2LD1  148.447316   153.643459  300.927913  420.407326   164.404106   \n",
      "\n",
      "        GSM1366956   GSM1366957   GSM1366958   GSM1366959  GSM1366960  ...  \\\n",
      "Gene                                                                   ...   \n",
      "A1BG    131.775939   128.508176   135.696979   119.674105  129.621366  ...   \n",
      "A1CF   1821.464618  1854.497192  1744.429754   770.568048  488.976178  ...   \n",
      "A26C3   105.967047   110.855337   112.252253   116.457441  112.159092  ...   \n",
      "A2BP1   454.391780   444.731300   472.251329  1049.291007  463.863503  ...   \n",
      "A2LD1   427.324463   366.442160   447.262945   175.492016  219.622057  ...   \n",
      "\n",
      "        GSM1367013   GSM1367014   GSM1367015  GSM1367016   GSM1367017  \\\n",
      "Gene                                                                    \n",
      "A1BG    122.885849   129.478171   130.077685  123.582661   122.097605   \n",
      "A1CF   1313.168194  2087.190080  1531.901017  850.247611  1475.088604   \n",
      "A26C3   104.261978   975.991830   112.836137  138.884464   111.234431   \n",
      "A2BP1   559.150127   458.203412   499.167731  449.171124   582.178155   \n",
      "A2LD1   207.479132   298.380885   425.806037  325.345643   263.939011   \n",
      "\n",
      "       GSM1367018   GSM1367019   GSM1367020  GSM1367021   GSM1367022  \n",
      "Gene                                                                  \n",
      "A1BG   140.354502   133.022162   139.057344  126.619216   117.106583  \n",
      "A1CF   963.882272   671.401800  1200.167478  671.711028  1104.967884  \n",
      "A26C3  123.574498   143.116296   123.057562  126.327795   113.804219  \n",
      "A2BP1  466.418865  1734.946029   470.169792  486.859132   449.555070  \n",
      "A2LD1  268.233347   163.154391   313.292936  195.617996   284.338040  \n",
      "\n",
      "[5 rows x 72 columns]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene expression data saved to: ../../output/preprocess/Colon_and_Rectal_Cancer/gene_data/GSE56699.csv\n"
     ]
    }
   ],
   "source": [
    "# 1. Analyze the gene annotation and expression data to determine the mapping columns\n",
    "# Based on the output, 'ID' in gene_annotation corresponds to 'ILMN_xxxxx' identifiers in gene_data\n",
    "# 'Symbol' is the column containing gene symbols in gene_annotation\n",
    "\n",
    "# 2. Get gene mapping dataframe by extracting ID and Symbol columns\n",
    "gene_mapping = get_gene_mapping(gene_annotation, prob_col=\"ID\", gene_col=\"Symbol\")\n",
    "\n",
    "print(\"Gene mapping preview (first 5 rows):\")\n",
    "print(gene_mapping.head())\n",
    "\n",
    "# 3. Apply gene mapping to convert probe-level measurements to gene expression data\n",
    "# This will handle the many-to-many relations by dividing probe values equally among mapped genes\n",
    "# and then summing up all probe values for each gene\n",
    "gene_data = apply_gene_mapping(gene_data, gene_mapping)\n",
    "\n",
    "print(f\"Dimensions of gene expression data after mapping: {gene_data.shape}\")\n",
    "print(\"Preview of gene expression data after mapping (first 5 genes):\")\n",
    "print(gene_data.head())\n",
    "\n",
    "# Create directory if it doesn't exist\n",
    "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
    "\n",
    "# Save 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": "7f4eeafa",
   "metadata": {},
   "source": [
    "### Step 7: Data Normalization and Linking"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "6a0f69f6",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:24:32.870082Z",
     "iopub.status.busy": "2025-03-25T08:24:32.869943Z",
     "iopub.status.idle": "2025-03-25T08:24:33.135414Z",
     "shell.execute_reply": "2025-03-25T08:24:33.134773Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Clinical data structure:\n",
      "{0: ['patient code: RCa0001', 'patient code: RCa0002', 'patient code: RCa0003', 'patient code: RCa0004', 'patient code: RCa0005', 'patient code: RCa0006', 'patient code: RCa0007', 'patient code: RCa0008', 'patient code: RCa0009', 'patient code: RCa0010', 'patient code: RCa0011', 'patient code: RCa0012', 'patient code: RCa0013', 'patient code: RCa0014', 'patient code: RCa0015', 'patient code: RCa0016', 'patient code: RCa0024', 'patient code: RCa0026', 'patient code: RCa0027', 'patient code: RCa0028', 'patient code: RCa0029', 'patient code: RCa0030', 'patient code: RCa0031', 'patient code: RCa0032', 'patient code: RCa0033', 'patient code: RCa0034', 'patient code: RCa0035', 'patient code: RCa0036', 'patient code: RCa0037', 'patient code: RCa0038'], 1: ['sample type: SS', 'sample type: PB'], 2: ['origin: Brussel: UZ Brussel Oncologisch Centrum', 'origin: Candiolo: Institute for Cancer Research, University of Turin', 'origin: Turin: Deparment of Medical Science, University of Turin', 'origin: Cluj-Napaca: University of Medicine and Pharmacology'], 3: ['mandard: 3', 'mandard: 4', 'mandard: 1', 'mandard: NA', 'mandard: 5', 'mandard: 2'], 4: ['response 3 classes: CR', 'response 3 classes: RES', 'response 3 classes: PR'], 5: ['diagnosis: Invasive low grade adenocarcinoma of the rectum', 'diagnosis: Tubulovilleus adenoma', 'diagnosis: Transmural invasive moderately differentiated adenocarcinoma', 'diagnosis: Invasive moederately differentiated adeocarcinoma', 'diagnosis: Moderately differentiated adenocarcinoma', 'diagnosis: Transmural scare, without any residual vital tumor tissue', 'diagnosis: Transmural invasive moderately to bad differentiated adenocarcinoma', 'diagnosis: Invasive, moderately to bad differentiated adenocarcinoma', 'diagnosis: Low-grade adenocarcinoma', 'diagnosis: Maderately differentiated adenocarcinoma', 'diagnosis: Poorly differentiated invasive adenocarcinoma (no surgical specimen available)', 'diagnosis: Low-grade adenocarcinoma with invasion of the perirectal fat', 'diagnosis: Poorly differentiated invasive adenocarcinoma', 'diagnosis: Invasive adenocarcinoma', 'diagnosis: Adenocarcinom, at least intramucosaal (no surgical specimen available)', 'diagnosis: Invasive adenocarcinoma (grade op invasion not to be determined)', 'diagnosis: The major part of the tumor is a tubular villus adenoma, with limited parts of well differantiated intramucosaal invasive adenocarcinoma', 'diagnosis: Tubular adenoma with moderate dysplasia', 'diagnosis: Invasive, moderately differentiated adenocarcinoma', 'diagnosis: Invasive, moderately differentiated adenorcarcinoma, at least intramucosaal', 'diagnosis: Transmural invasive moderately differentiated adenocarcinoma (cilinder cells)', 'diagnosis: invasive, moderately differentiated adenocarcinoma (cilinder cells)', 'diagnosis: Transmural invasive moderately differentiated adenocarcinoma (intestinal type)', 'diagnosis: Invasive well differentiated adenocarcinoma (cilinder cells)', 'diagnosis: Tubulovilleus adenoma with invasion in the submucosa (at least pT1)', 'diagnosis: No residual tumorcells found in ulcus', 'diagnosis: NA', 'diagnosis: adenocarcinoma', 'diagnosis: Adenocarcinoma Tubulare G2', 'diagnosis: 1) Polipo valvola ileo-cecale; 2) Micropolipi colon trasverso; 3) Polipo; 4) Adenocarcinoma moderatamente differenziato (G2)'], 6: ['recurrence: 0', 'recurrence: 1', 'note: Mucosa', 'recurrence: NA'], 7: ['df: 35', 'df: 44', 'df: 63', 'df: 54', 'df: 79', 'df: 16', 'df: 74', 'df: 62', 'df: 58', 'df: 56', 'df: 25', 'df: 20', 'df: 12', 'recurrence: NA', 'df: NA', 'df: 31', 'df: 32', 'df: 24', 'df: 37', 'df: 53', 'df: 55', 'df: 69', 'df: 77', 'df: 26', 'df: 29', 'df: 17', 'df: 13', 'df: 27', 'df: 11', 'df: 4'], 8: ['death: 0', 'death: 1', 'df: NA', 'death: NA'], 9: ['dsf: 35', 'dsf: 44', 'dsf: 63', 'dsf: 54', 'dsf: 79', 'dsf: 16', 'dsf: 74', 'dsf: 62', 'dsf: 58', 'dsf: 56', 'dsf: 36', 'dsf: 27', 'dsf: 13', 'death: NA', 'dsf: NA', 'dsf: 31', 'dsf: 32', 'dsf: 33', 'dsf: 39', 'dsf: 53', 'dsf: 55', 'dsf: 69', 'dsf: 77', 'dsf: 26', 'dsf: 17', 'dsf: 20', 'dsf: 71', 'dsf: 18', 'dsf: 4', 'dsf: 15'], 10: [nan, 'dsf: NA']}\n",
      "Corrected clinical data saved to ../../output/preprocess/Colon_and_Rectal_Cancer/clinical_data/GSE56699.csv\n",
      "Linked data shape: (72, 20212)\n",
      "Data after handling missing values: (0, 1)\n",
      "Quartiles for 'Colon_and_Rectal_Cancer':\n",
      "  25%: nan\n",
      "  50% (Median): nan\n",
      "  75%: nan\n",
      "Min: nan\n",
      "Max: nan\n",
      "The distribution of the feature 'Colon_and_Rectal_Cancer' in this dataset is fine.\n",
      "\n",
      "Abnormality detected in the cohort: GSE56699. Preprocessing failed.\n",
      "Data was determined to be unusable and was not saved\n"
     ]
    }
   ],
   "source": [
    "# 1. Load the normalized gene data \n",
    "gene_data = pd.read_csv(out_gene_data_file, index_col=0)\n",
    "\n",
    "# 2. Re-extract clinical features from the SOFT file to get proper clinical data\n",
    "# Use the actual clinical data from the matrix file properly\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",
    "# 3. Create a correct clinical features dataframe\n",
    "# First inspect what's in the clinical data\n",
    "clinical_data_dict = get_unique_values_by_row(clinical_data)\n",
    "print(\"Clinical data structure:\")\n",
    "print(clinical_data_dict)\n",
    "\n",
    "# Based on the sample characteristics dictionary shown previously, \n",
    "# extract and process clinical features\n",
    "selected_clinical_df = pd.DataFrame()\n",
    "\n",
    "# Process disease state row manually to ensure correct mapping\n",
    "disease_row = clinical_data.iloc[trait_row]\n",
    "samples = [col for col in disease_row.index if col != \"!Sample_geo_accession\"]\n",
    "trait_values = []\n",
    "\n",
    "for sample in samples:\n",
    "    value = disease_row[sample]\n",
    "    if pd.isna(value):\n",
    "        trait_values.append(None)\n",
    "    else:\n",
    "        if \":\" in value:\n",
    "            value = value.split(\":\", 1)[1].strip()\n",
    "        \n",
    "        if \"IBS\" in value:\n",
    "            trait_values.append(1)  # IBS is our target trait\n",
    "        elif \"IBD\" in value:\n",
    "            trait_values.append(0)  # IBD is the control\n",
    "        else:\n",
    "            trait_values.append(None)\n",
    "\n",
    "# Create dataframe with processed values\n",
    "selected_clinical_df[trait] = trait_values\n",
    "selected_clinical_df.index = samples\n",
    "\n",
    "# Save the corrected clinical data\n",
    "os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
    "selected_clinical_df.to_csv(out_clinical_data_file)\n",
    "print(f\"Corrected clinical data saved to {out_clinical_data_file}\")\n",
    "\n",
    "# 4. Link the clinical and genetic data\n",
    "linked_data = pd.DataFrame()\n",
    "# Transpose gene data to have samples as rows and genes as columns\n",
    "gene_data_t = gene_data.T\n",
    "# Verify alignment of sample IDs between clinical and gene data\n",
    "common_samples = list(set(selected_clinical_df.index) & set(gene_data_t.index))\n",
    "if common_samples:\n",
    "    gene_data_filtered = gene_data_t.loc[common_samples]\n",
    "    clinical_data_filtered = selected_clinical_df.loc[common_samples]\n",
    "    # Join the data\n",
    "    linked_data = pd.concat([clinical_data_filtered, gene_data_filtered], axis=1)\n",
    "    print(f\"Linked data shape: {linked_data.shape}\")\n",
    "else:\n",
    "    # Alternative linking approach if sample IDs don't directly match\n",
    "    print(\"No common sample IDs found. Attempting alternative linking...\")\n",
    "    # The GSM ids in gene data columns may correspond to the sample IDs\n",
    "    clinical_data_reset = selected_clinical_df.reset_index()\n",
    "    clinical_data_reset.columns = [\"Sample\"] + list(clinical_data_reset.columns[1:])\n",
    "    gene_data_cols = list(gene_data.columns)\n",
    "    \n",
    "    # Create merged dataframe\n",
    "    data_dict = {trait: []}\n",
    "    # Add trait values\n",
    "    for col in gene_data_cols:\n",
    "        sample_idx = clinical_data_reset.index[clinical_data_reset[\"Sample\"] == col] if \"Sample\" in clinical_data_reset.columns else []\n",
    "        if len(sample_idx) > 0:\n",
    "            data_dict[trait].append(clinical_data_reset.loc[sample_idx[0], trait])\n",
    "        else:\n",
    "            data_dict[trait].append(None)\n",
    "    \n",
    "    # Add gene expression values\n",
    "    for gene in gene_data.index:\n",
    "        data_dict[gene] = list(gene_data.loc[gene])\n",
    "    \n",
    "    linked_data = pd.DataFrame(data_dict, index=gene_data_cols)\n",
    "    print(f\"Alternative linked data shape: {linked_data.shape}\")\n",
    "\n",
    "# 5. Handle missing values in the linked data\n",
    "linked_data = handle_missing_values(linked_data, trait)\n",
    "print(f\"Data after handling missing values: {linked_data.shape}\")\n",
    "\n",
    "# 6. Determine whether the trait and some demographic features are severely biased\n",
    "is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)\n",
    "\n",
    "# 7. Conduct quality check and save the cohort information\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=unbiased_linked_data,\n",
    "    note=\"Dataset contains gene expression data from patients with IBS and IBD, examining effects of relaxation response mind-body intervention.\"\n",
    ")\n",
    "\n",
    "# 8. If the linked data is usable, save it as a CSV file\n",
    "if is_usable:\n",
    "    os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n",
    "    unbiased_linked_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 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
}