File size: 75,897 Bytes
32677ff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "8c19fb93",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:24:09.586060Z",
     "iopub.status.busy": "2025-03-25T08:24:09.585875Z",
     "iopub.status.idle": "2025-03-25T08:24:09.753428Z",
     "shell.execute_reply": "2025-03-25T08:24:09.753026Z"
    }
   },
   "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 = \"GSE46517\"\n",
    "\n",
    "# Input paths\n",
    "in_trait_dir = \"../../input/GEO/Colon_and_Rectal_Cancer\"\n",
    "in_cohort_dir = \"../../input/GEO/Colon_and_Rectal_Cancer/GSE46517\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/Colon_and_Rectal_Cancer/GSE46517.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/Colon_and_Rectal_Cancer/gene_data/GSE46517.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/Colon_and_Rectal_Cancer/clinical_data/GSE46517.csv\"\n",
    "json_path = \"../../output/preprocess/Colon_and_Rectal_Cancer/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "df6c35b3",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "c83c1dca",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:24:09.754795Z",
     "iopub.status.busy": "2025-03-25T08:24:09.754648Z",
     "iopub.status.idle": "2025-03-25T08:24:09.941832Z",
     "shell.execute_reply": "2025-03-25T08:24:09.941245Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Background Information:\n",
      "!Series_title\t\"Human melanoma samples comparing nevi and primary and metastatic melanoma\"\n",
      "!Series_summary\t\"We sought to identify genes and gene signatures which correlate with progression by sampling human melanomas from nevi, primary, and metastatic tumors. The large number of samples also permits analysis within groups.\"\n",
      "!Series_overall_design\t\"Human melanoma samples were isolated from historical frozen patient specimens. RNA was extracted and run on the human Affymetrix U133A microarray chip.\"\n",
      "Sample Characteristics Dictionary:\n",
      "{0: ['tissue type: Metastatic Melanoma', 'tissue type: Primary Melanoma', 'tissue type: Nevus', 'tissue type: Normal Skin', 'tissue type: Normal Epithelial Melanocytes'], 1: [nan, 'patient id: 35', 'patient id: 23', 'patient id: 13', 'patient id: 6', 'patient id: 40', 'patient id: 26', 'patient id: 1', 'patient id: 22', 'patient id: 4', 'patient id: 30', 'patient id: 5', 'patient id: 15', 'patient id: 20', 'patient id: 17', 'patient id: 38', 'patient id: 37', 'patient id: 36', 'patient id: 25', 'patient id: 39', 'patient id: 29', 'patient id: 7', 'patient id: 18', 'patient id: 16', 'patient id: 3', 'patient id: 31', 'patient id: 32', 'patient id: 8', 'patient id: 10', 'patient id: 21'], 2: [nan, '% melanoma cells: 95', '% melanoma cells: 85', '% melanoma cells: 90', '% melanoma cells: 75', '% melanoma cells: 20', '% melanoma cells: 40', '% melanoma cells: 80', '% melanoma cells: 70', '% melanoma cells: 100', '% melanoma cells: 5', '% melanoma cells: 25', '% melanoma cells: 60', '% melanoma cells: 45', '% melanoma cells: 97', '% inflammatory cells: 40', '% inflammatory cells: 50', '% inflammatory cells: 25', '% inflammatory cells: 0', '% inflammatory cells: 35', '% inflammatory cells: 5', '% inflammatory cells: 45', '% inflammatory cells: 55', '% inflammatory cells: 60', '% inflammatory cells: 30', '% inflammatory cells: 20', '% inflammatory cells: 10', '% inflammatory cells: 80', '% melanocytes: 85', '% melanocytes: 75'], 3: [nan, '% inflammatory cells: 0', '% inflammatory cells: 5', '% inflammatory cells: 10', '% inflammatory cells: 7', '% inflammatory cells: 77', '% inflammatory cells: 60', '% inflammatory cells: 17', '% inflammatory cells: 15', '% inflammatory cells: 25', '% inflammatory cells: 80', '% inflammatory cells: 95', '% inflammatory cells: 75', '% inflammatory cells: 40', '% inflammatory cells: 50', '% inflammatory cells: 3', '% other cells: 15', '% other cells: 25', '% other cells: 10', '% other cells: 35', '% other cells: 5', '% other cells: 30', '% other cells: 40', '% other cells: 20', '% other cells: 0', '% other cells: 50', '% keratinocytes: 96', '% keratinocytes: 64'], 4: [nan, '% other cells: 5', '% other cells: 10', '% other cells: 0', '% other cells: 3', '% other cells: 20', '% other cells: 15', '% other cells: <1%', 'necrosis (% of total area): 0', '% keratinocytes: 15', '% keratinocytes: 25', '% keratinocytes: 12', '% keratinocytes: 90', '% keratinocytes: 80', '% keratinocytes: 5', 'body-site: right forearm', 'body-site: breast'], 5: [nan, 'other cell types: Muscle', 'other cell types: Skin', 'necrosis (% of total area): 0', 'necrosis (% of total area): 20', 'necrosis (% of total area): 50', 'necrosis (% of total area): 30', 'necrosis (% of total area): 10', 'necrosis (% of total area): 5', 'necrosis (% of total area): 3', 'other cell types: Few Fibrous strands', 'necrosis (% of total area): 25', 'other cell types: Epidermis/skin', 'necrosis (% of total area): 15', 'necrosis (% of total area): 2', 'other cell types: Epidermis', 'body-site: backside', 'body-site: left food', 'body-site: left thigh', 'body-site: right forearm', 'body-site: right lower leg', 'body-site: neck', 'body-site: abdomen', 'body-site: left lower leg', 'body-site: left upper arm', 'body-site: scalp', 'body-site: right shoulder', 'body-site: chest', 'body-site: right food', 'diagnosis: melanocytic nevus, compound-type'], 6: [nan, 'necrosis (% of total area): 10', 'necrosis (% of total area): 0', 'body-site: left thigh', 'body-site: left axilla', 'necrosis (% of total area): 3', 'body-site: left lower leg', 'body-site: abdominal', 'necrosis (% of total area): 30', 'body-site: neck', 'body-site: right inguinal', 'body-site: right axilla', 'body-site: left inguinal', 'body-site: right lower leg', 'body-site: abdomen', 'body-site: chest', 'location: mesenterial', 'body-site: suprascapulär li B', 'necrosis (% of total area): 40', 'body-site: right thigh', 'body-site: colon', 'body-site: backside', 'date of resection: Mar-96', 'date of resection: Jul-97', 'date of resection: Feb-95', 'date of resection: Oct-96', 'date of resection: Aug-97', 'date of resection: Jan-96', 'date of resection: May-95', 'date of resection: May-90'], 7: [nan, 'body-site: right lower leg', 'body-site: left knee', 'body-site: abdomen', 'location: cutaneous/subcutaneous', 'location: cutaneous', 'body-site: chest', 'body-site: backside', 'location: subcutaneous', 'body-site: facial', 'location: Lymph Node', 'organ: mesenterial', 'body-site: neck', 'body-site: left lower leg', 'body-site: left axilla', 'location: colon/peritoneal', 'body-site: right cervical', 'body-site: left thigh', 'body-site: right inguinal', 'age at time of resection: 72y 4m', 'age at time of resection: 52y 1m', 'age at time of resection: 87y 9m', 'age at time of resection: 55y 8m', 'age at time of resection: 84y 9m', 'age at time of resection: 72y 5m', 'age at time of resection: 73y 4m', 'age at time of resection: 78y 2m', 'age at time of resection: 66y 6m', 'age at time of resection: 81y 4m', 'age at time of resection: 59y 6m'], 8: [nan, 'location: cutaneous', 'organ: skin', 'location: cutaneous/subcutaneous', 'location: subcutaneous', 'organ: Lymph Node', 'date of resection: Feb-93', 'organ: colon/peritoneal', 'location: Lymph Node', 'gender: male', 'gender: female'], 9: [nan, 'organ: skin', 'date of resection: May-96', 'date of resection: Apr-93', 'date of resection: Dec-96', 'date of resection: Aug-90', 'date of resection: Apr-94', 'date of resection: Jun-93', 'date of resection: Mar-95', 'date of resection: Jul-95', 'date of resection: Jul-93', 'date of resection: Aug-91', 'date of resection: Feb-95', 'date of resection: May-93', 'age at time of resection: 30y 6m', 'date of resection: Jan-95', 'date of resection: Sep-95', 'date of resection: Jun-95', 'date of resection: Oct-95', 'date of resection: May-92', 'date of resection: Sep-96', 'date of resection: Apr-96', 'date of resection: Jan-96', 'date of resection: Feb-93', 'organ: Lymph Node', 'date of resection: Apr-89', 'date of resection: Oct-96', 'race: caucasian'], 10: [nan, 'date of resection: Sep-93', 'date of resection: Mar-97', 'date of resection: Aug-96', 'age at time of resection: 69y 9m', 'age at time of resection: 60y 5m', 'date of resection: Apr-95', 'date of resection: Oct-95', 'date of resection: Jan-97', 'age at time of resection: 68y 9m', 'date of resection: Jul-97', 'date of resection: Jan-96', 'date of resection: Jul-90', 'age at time of resection: 41y', 'date of resection: Nov-89', 'date of resection: Sep-95', 'age at time of resection: 34y 2m', 'age at time of resection: 54y 11m', 'age at time of resection: 62y 11m', 'age at time of resection: 52y 6m', 'age at time of resection: 28y 4m', 'age at time of resection: 53y 1m', 'age at time of resection: 57y 5m', 'age at time of resection: 31y 8m', 'date of resection: May-93', 'gender: male', 'age at time of resection: 56y 9m', 'date of resection: Jan-95', 'age at time of resection: 28y', 'age at time of resection: 59y 7m'], 11: [nan, 'age at time of resection: 57y 11m', 'age at time of resection: 59y 7m', 'age at time of resection: 70y', 'gender: male', 'age at time of resection: 58y 4m', 'age at time of resection: 56y 4m', 'age at time of resection: 68y 10m', 'age at time of resection: 73y 4m', 'age at time of resection: 68y 8m', 'age at time of resection: 30y 2m', 'age at time of resection: 66y 5m', 'age at time of resection: 66y', 'gender: female', 'age at time of resection: 60y 5m', 'race: caucasian', 'age at time of resection: 79y 1m', 'age at time of resection: 83y 6m', 'age at time of resection: 34y 2m', 'age at time of resection: 69y 6m', 'age at time of resection: 57y 5m', 'age at time of resection: 85y 5 m', 'age at time of resection: 72y 10m', 'age at time of resection: 60y 8m', 'age at time of resection: 82y 11m', 'age at time of resection: 71y 1m', 'tnm status: pT3N0M0', 'tnm status: pT2N0M0', 'tnm status: pT4N0M0', 'tnm status: pT3N1M1a'], 12: [nan, 'gender: female', 'gender: male', 'race: caucasian', 'clinical stage: 4 new AJCC', 'prior ctx, rtx, itx: no'], 13: [nan, 'race: caucasian', 'clinical stage: 4 new AJCC', 'clinical stage: 3 C new AJCC', 'clinical stage: 4 C new AJCC', 'tnm status: pT4aN3bM1c', 'clinical stage: 3 B new AJCC', 'clinical stage: no further clinical data', 'subsequent metastasis: no', 'subsequent metastasis: 8/01 LNN retrojugular, retroclavicular, retrosternal, pretracheal', 'subsequent metastasis: yes, progressive disease', 'subsequent metastasis: 10/98 LNN left inguinal, 3/99 brain, suspected lung mets', 'subsequent metastasis: 8/97 LNN left inguinal; 8/98 liver; 12/98 brain', 'subsequent metastasis: 9/99 satellite mets , 7/01 LNN left cervical/supraclavicular, 10/01 LNN right cervical/axilla, 2/02 LNN left cervical, s.c. left cervical and supraclavicular, 7/02 colon, coecum, liver; 8/02 lungs', 'subsequent metastasis: 4/94 liver', 'subsequent metastasis: 7/95 cutis; 8/97 cutis; 9/97 LNN; 12/97 LNN [recurrence]; 5/98 skin; 7/98 LNN [recurrence] + skin; 7/98 liver, lung; 11/98 LNN [recurrence]', 'subsequent metastasis: 02/01 + 04/01 neck; 07/01 LNN mediast.; 07/01 liver; 10/01 cutis; 12/01 liver, spleen; 2/02 lungs.', 'subsequent metastasis: 6/96 lung, LNN', 'subsequent metastasis: 6/92 liver, LNN', 'subsequent metastasis: 12/99 LNN ing. left; 9/00 LNN cervical left; 1/02 LNN right axilla; 4/02 brain'], 14: [nan, 'clinical stage: 3 C new AJCC', 'clinical stage: 4 new AJCC', 'tnm status: pT4N1M1', 'tnm status: pT1N2M1b', 'tnm status: pT4N0M1b', 'tnm status: pT1N3M1c', 'clinical stage: 3 B new AJCC', 'tnm status: pT2N3M1c', 'tnm status: pT3bN3bM1c', 'tnm status: pT3N3M0', 'tnm status: pT3N3M1c', 'tnm status: pT3bN3bM1b', 'tnm status: pT3aN0M1c', 'tnm status: pT4N3M1c', 'corresponding primary tumor thickness: Breslow index, mm: [4,7]', 'tnm status: pT4aN2bcM0', 'tnm status: pT4aN3bM1c', 'tnm status: pT1aN1bM0', 'tnm status: pT1N3M0', 'tnm status: no further clinical data', 'tnm status: pT2aN2bM0', 'tnm status: pT2N3M0', 'tnm status: pT2aN2bM1a', 'tnm status: pT3aN1bM1b', 'tnm status: pT4N3M0', 'first instance [fi] or recurrance [r]: FI'], 15: [nan, 'tnm status: pT4bN3M0', 'tnm status: pT3aN1bM1b', 'tnm status: pT4N1M1', 'corresponding primary tumor thickness: Breslow index, mm: [>5]', 'corresponding primary tumor thickness: Breslow index, mm: [0,4]', 'tnm status: pT3N1M1a', 'tnm status: pT2N2M1c', 'tnm status: pT4N0M1b', 'corresponding primary tumor thickness: Breslow index, mm: [4,4]', 'tnm status: pT4N2M1b', 'tnm status: pT1N2M1b', 'tnm status: pT4N3M1c', 'corresponding primary tumor thickness: Breslow index, mm: [0,75]', 'tnm status: pT4aN1bM0', 'tnm status: pT3NxM1c', 'corresponding primary tumor thickness: Breslow index, mm: [1,4]', 'corresponding primary tumor thickness: Breslow index, mm: [>3,0]', 'corresponding primary tumor thickness: Breslow index, mm: [3,1]', 'corresponding primary tumor thickness: Breslow index, mm: [1,8]', 'corresponding primary tumor thickness: Breslow index, mm: [1,5]', 'corresponding primary tumor thickness: Breslow index, mm: [2,6]', 'corresponding primary tumor thickness: Breslow index, mm: [>25,0]', \"corresponding primary tumor thickness: Clark's level: [IV]\", 'corresponding primary tumor thickness: Breslow index, mm: [8]', 'tnm status: pTxN3M1c', 'corresponding primary tumor thickness: Breslow index, mm: [0,618]', 'tnm status: pT4N0M1c', 'tnm status: pT2N3M1c', 'tnm status: pT4N3M0'], 16: [nan, 'corresponding primary tumor thickness: Breslow index, mm: [4,5]', 'corresponding primary tumor thickness: Breslow index, mm: [2,75]', 'corresponding primary tumor thickness: Breslow index, mm: [>5]', \"corresponding primary tumor thickness: Clark's level: [IV]\", \"corresponding primary tumor thickness: Clark's level: [II]\", 'corresponding primary tumor thickness: Breslow index, mm: [2,3]', 'corresponding primary tumor thickness: Breslow index, mm: [?]', 'corresponding primary tumor thickness: Breslow index, mm: [4,4]', 'corresponding primary tumor thickness: Breslow index, mm: [5,0]', 'corresponding primary tumor thickness: Breslow index, mm: [0,75]', 'corresponding primary tumor thickness: Breslow index, mm: [4]', 'corresponding primary tumor thickness: Breslow index, mm: [3,5]', \"corresponding primary tumor thickness: Clark's level: [V]\", 'corresponding primary tumor thickness: Breslow index, mm: [0,4]', 'corresponding primary tumor: Histologic Type: [SSM, sec.nod.]', 'corresponding primary tumor thickness: Breslow index, mm: n.a.', 'corresponding primary tumor thickness: Breslow index, mm: [8,0]', 'corresponding primary tumor thickness: Breslow index, mm: [1,4]', 'corresponding primary tumor thickness: Breslow index, mm: [6,5]', 'corresponding primary tumor thickness: Breslow index, mm: [2,6]', \"corresponding primary tumor thickness: Clark's level: [III]\", \"corresponding primary tumor thickness: Clark's level: no further clinical data\", 'corresponding primary tumor thickness: Breslow index, mm: [7,5]', 'corresponding primary tumor thickness: Breslow index, mm: [2,5]', 'past malignant tumors?: no', 'past malignant tumors?: liposarcoma', 'past malignant tumors?: adrenal adenoma'], 17: [nan, \"corresponding primary tumor thickness: Clark's level: [IV]\", 'corresponding primary tumor: Histologic Type: [SSM]', \"corresponding primary tumor thickness: Clark's level: [III]\", 'prior ctx, rtx, itx: no', \"corresponding primary tumor thickness: Clark's level: [V]\", 'corresponding primary tumor: Histologic Type: [NMM]', \"corresponding primary tumor thickness: Clark's level: [II]\", 'prior ctx, rtx, itx: 1-6/94: 6x immunochemotherapy (DTIC+IL2+INFa); 3/96 radiation therapy head; 11/96 radiation therapy spine; 8/94-3/95 8x polychemotherapy (DTIC + Vindesine + Carboplatin)', \"corresponding primary tumor thickness: Clark's level: n.a.\", 'corresponding primary tumor: Histologic Type: [MM]', 'corresponding primary tumor: Histologic Type: no further clinical data', 'corresponding primary tumor: Histologic Type: [ALM]', 'corresponding primary tumor: Histologic Type: [SSM, sec.nod.]', 'corresponding primary tumor: Histologic Type: NMM', 'last clinical status: Sep 03, alive, NED', 'last clinical status: Feb 03, alive, NED', 'last clinical status: Aug 00, death, MM-unrelated', 'last clinical status: Okt 02, death, MM-unrelated', 'last clinical status: Mai 02, alive, NED', 'last clinical status: Nov 01, death, MM-unrelated', 'last clinical status: Okt 01, death, MM-related', 'last clinical status: 1999, death, MM-related', 'last clinical status: Aug 02, alive, NED', 'last clinical status: Jun 96, alive, NED', 'last clinical status: Nov 01, alive, NED', 'last clinical status: Mai 01, death, MM-related', 'last clinical status: Jan 03, alive, NED', 'last clinical status: Okt 02, death, MM-related', 'last clinical status: Jun 01, alive, NED'], 18: [nan, 'corresponding primary tumor: Histologic Type: [MM]', 'corresponding primary tumor: Histologic Type: [NMM]', 'corresponding primary tumor: Histologic Type: [SSM]', 'prior ctx, rtx, itx: no', 'prior ctx, rtx, itx: 2-9/99 3x3 Mio IE Interferon/week + 7 cycles chemotherapy DTIC.', 'prior ctx, rtx, itx: 1 cycle of polychemotherapy (Temodal + Vindesine + Carboplatin) 12/00', 'subsequent metastasis: 2/02 lung, soft tissue, GI', 'prior ctx, rtx, itx: 3 cycles of immunochemotherapy (DTIC, Intron A, Proleukin)', 'corresponding primary tumor: Histologic Type: [ALM]', 'prior ctx, rtx, itx: 1 cycle of immunochemotherapy (DTIC, Proleukin, Intron A)', 'prior ctx, rtx, itx: 10/95-1/96 3 x polychemotherapy (DTIC + Vindesine + Carboplatin)', 'prior ctx, rtx, itx: 1 cycle of polychemotherapy (DTIC, Cisplatin, Vindesine)', 'prior ctx, rtx, itx: 4/93-7/93 3 x immunochemotherapy (DTIC + INF-a + IL-2); 6/94 embolisation of liver mets [Cisplatin]; 11/96-7/97 polychemotherapy (DTIC + Vindesine + Carboplatin); 8/97 radiation therapy brain [30 Gy]', 'prior ctx, rtx, itx: 3 cycles of polychemotherapy (DVP-regimen)', 'subsequent metastasis: 1/98 progression liver and bone, 4/99 lung', 'prior ctx, rtx, itx: 6/88 Interferon beta, 05/89 Interferon alpha, hyperthermic limb perfusion (Melphalan)', 'corresponding primary tumor: Histologic Type: [uvea]', 'prior ctx, rtx, itx: 11x immunochemotherapy (DTIC+IL2+INFa);  adjuvant immunotherapy INF-a', 'prior ctx, rtx, itx: 12 x polychemotherapy (DTIC + Vindesine + Carboplatin)', 'corresponding primary tumor: Histologic Type: [SSM, sec.nod.]', 'prior ctx, rtx, itx: no further clinical data', 'prior ctx, rtx, itx: 1-6/94: 6x immunochemotherapy (DTIC+IL2+INFa); 3/96 radiation therapy head; 11/96 radiation therapy spine; 8/94-3/95 8x polychemotherapy (DTIC + Vindesine + Carboplatin)', 'prior ctx, rtx, itx: since 4/00 polychemotherapy (DTIC + Vindesine + Carboplatin)', 'prior ctx, rtx, itx: 1/97 INF-a s.c.; 2/98 hyperthermic limb perfusion (Melphalan); 3/99-11/99 chemotherapy Vindesine', 'corresponding primary tumor: Histologic Type: [SSM, sec.nod]', 'type: SSM, sec. nodular', 'type: SSM', 'type: Acral Lentiginous', 'ulceration: Yes'], 19: [nan, 'prior ctx, rtx, itx: no', 'prior ctx, rtx, itx: 1/97 INF-a s.c.; 2/98 hyperthermic limb perfusion (Melphalan); 3/99-11/99 chemotherapy Vindesine', 'prior ctx, rtx, itx: 1 cycle of immunochemotherapy (DTIC, Intron A)', 'subsequent metastasis: 7/00 cutis, spleen; 9/01 cutis, liver.', 'subsequent metastasis: 8/97 brain, progression of pulmonal mets, progression of LNN mets axillar and mediastinal, suspected adrenal mets, suspected liver mets, progression of cutaneous mets', 'prior ctx, rtx, itx: 2 cycles polychemotherapy (DTIC, Cisplatin, Vindesine)', 'subsequent metastasis: 9/99 brain, LNN', 'subsequent metastasis: 2/02 lung, soft tissue, GI', 'first instance [fi] or recurrance [r]: FI', 'prior ctx, rtx, itx: from 8/99 4 cycles of polychemotherapy (Vindesine + Cisplatin), radiation therapy (Lnn left axilla) 12/99', 'prior ctx, rtx, itx: no further clinical data', 'subsequent metastasis: 10/94: lungs', 'prior ctx, rtx, itx: 10 cycles of polychemotherapy (DTIC + Vindesine + Carboplatin), 3 cycles of polychemotherapy (Taxol+Tamoxifen+Cisplatin), radiation therapy brain (30 Gy)', 'subsequent metastasis: 7/98: lungs, intraabdominal, s.c., brain', 'subsequent metastasis: 7/97: Lnn right inguinal, right kidney, left suprarenal gland; 3/98: brain, lung, liver, kidney, cutis', 'subsequent metastasis: no further clinical data', 'subsequent metastasis: 8/99: lungs, intraabdominal, spleen, liver', 'subsequent metastasis: progression of mets: lung, liver, spleen, brain, LNN', 'subsequent metastasis: 9/95 lung; 10/95 LNN right inguinal; 8/96 LNN right axilla; 3/97 LNN right inguinal; 7/97: Lnn right inguinal, right kidney, left suprarenal gland; 3/98 brain, lung, liver, kidney, cutis', 'subsequent metastasis: 8/97 s.c. left scapula, right cheek, left upper leg; 8/97 brain', 'subsequent metastasis: progression of known mets (s.c., lungs, liver, peritoneum, mediastinum)', 'subsequent metastasis: recurrent s.c. mets left leg', 'subsequent metastasis: no (complete remission since 4/00)', 'subsequent metastasis: 9/01 Lnn cervical right; 3/02 brain (single lesion) g-knife; 11/02 progression of brain met: chemotherapy Temodal', 'prior ctx, rtx, itx: 1 cycle of immunochemotherapy (DTIC, Proleukin, Intron A)', 'prior ctx, rtx, itx: 4/93-7/93 3 x immunochemotherapy (DTIC + INF-a + IL-2); 6/94 embolisation of liver mets [Cisplatin]; 11/96-7/97 polychemotherapy (DTIC + Vindesine + Carboplatin); 8/97 radiation therapy brain [30 Gy]', 'subsequent metastasis: 9/00 left chest, 2/02: s.c. mets thoracal left', 'subsequent metastasis: 8/96 + 4/97 + 5/97: Lnn right inguinal; 7/97 brain', 'subsequent metastasis: 1/98 progression liver and bone, 4/99 lung'], 20: [nan, 'subsequent metastasis: 8/00: Lnn, lungs', 'subsequent metastasis: 1/02 lungs, pleura (subsequent polychemotherapy Temodal, Vindesine, Carboplatin; complete remission)', 'subsequent metastasis: 7/00 cutis, spleen; 9/01 cutis, liver.', 'first instance [fi] or recurrance [r]: FI', 'subsequent metastasis: 5/99 brain, meningeosis carcinomatosa; 6/99 cutis.', 'other concurrent malignant tumors?: no', 'subsequent metastasis: 7/01 scull (bone); lungs, Lnn, cutis', 'subsequent metastasis: no at 3/2000', 'subsequent metastasis: no further clinical data', 'first instance [fi] or recurrance [r]: R', 'subsequent metastasis: 5/95 local recurrance, 9/95 LNN,', 'subsequent metastasis: progression of known mets', 'subsequent metastasis: 8/97 brain, progression of pulmonal mets, progression of LNN mets axillar and mediastinal, suspected adrenal mets, suspected liver mets, progression of cutaneous mets', 'subsequent metastasis: n.a.', 'subsequent metastasis: 7/98: lungs, intraabdominal, s.c., brain', 'subsequent metastasis: no', 'subsequent metastasis: 8/97 s.c. left scapula, right cheek, left upper leg; 8/97 brain', 'subsequent metastasis: 6/92 liver, LN', 'subsequent metastasis: 9/00 liver, lung, heart, spleen, cutis, LNN', 'subsequent metastasis: 8/97 cutis; 9/97 LN; 12/97 LN [recurrence]; 5/98 cutis; 7/98 LN [recurrence] + cutis; 7/98 liver, lung; 11/98 LN [recurrence]', 'subsequent metastasis: 9/01: cutaneous mets right leg, 5/02 cutaneous mets abdomen, mets lungs, mets intraabdominal', 'other concurrent malignant tumors?: no further clinical data', \"clark's: IV\", \"clark's: III\", \"clark's: V\", \"clark's: II\", \"clark's: III/IV\", 'breslow thickness: 2.750'], 21: [nan, 'first instance [fi] or recurrance [r]: FI', 'other concurrent malignant tumors?: no', 'past malignant tumors?: no', 'other concurrent malignant tumors?: suspected rectal carcinoma', 'other concurrent malignant tumors?: no further clinical data', 'first instance [fi] or recurrance [r]: R', 'past malignant tumors?: no further clinical data', 'breslow thickness: 3.500', 'breslow thickness: 0.400', 'breslow thickness: 4.500', 'breslow thickness: 3.000', 'breslow thickness: 2.000', 'breslow thickness: 2.510', 'breslow thickness: 0.600', 'breslow thickness: 0.450', 'breslow thickness: 6.500', 'breslow thickness: 1.000', 'breslow thickness: 0.350', 'breslow thickness: 0.925', 'breslow thickness: 1.200', 'breslow thickness: 1.130', 'breslow thickness: 4.000', 'breslow thickness: 2.500', 'breslow thickness: 1.625', 'breslow thickness: 6.000', 'breslow thickness: 1.100', 'breslow thickness: 0.375', 'breslow thickness: 0.975', 'breslow thickness: 2.800'], 22: [nan, 'other concurrent malignant tumors?: no', 'past malignant tumors?: no', 'last clinical status: Feb 01, death, MM-related', 'other concurrent malignant tumors?: no further clinical data', 'last clinical status: Mai 99, death, MM-related', 'past malignant tumors?: no further clinical data', 'last clinical status: no further clinical data', 'ulceration size: 2', 'ulceration size: -', 'ulceration size: 5', 'ulceration size: 6', 'ulceration size: 3', 'rgp: Yes', 'vgp: Yes'], 23: [nan, 'past malignant tumors?: no', 'last clinical status: Dez 01, death, MM-related', 'last clinical status: Okt 97, death, MM-related', 'last clinical status: 2000, death, MM-related', 'last clinical status: Feb 01, death, MM-related', 'past malignant tumors?: no further clinical data', 'last clinical status: 1996, death, MM-related', 'last clinical status: Feb 99, death, MM-related', 'last clinical status: Jun 99, alive with disease', 'last clinical status: 1999, death, MM-related', 'last clinical status: Sep 97, death, MM-related', 'last clinical status: Nov 97, death, MM-related', 'last clinical status: Aug 99, death, MM-related', 'last clinical status: Feb 03, alive, NED', 'last clinical status: Jan 03, alive, NED', 'last clinical status: 1997, death, MM-unrelated', 'last clinical status: Nov 99, death, MM-related', 'last clinical status: Dez 02, alive, NED', 'last clinical status: 1998, death, MM-related', 'last clinical status: Mai 99, death, MM-related', 'rgp: Yes', 'vgp: Yes', 'vgp type: Epithelioid', 'rgp: No'], 24: [nan, 'last clinical status: Jan 01, alive with disease', 'last clinical status: Jan 03, alive, NED', 'last clinical status: Dez 01, death, MM-related', 'last clinical status: Sep 99, death, MM-related', 'last clinical status: Okt 02, death, MM-related', 'last clinical status: 2000, death, MM-related', 'last clinical status: no further clinical data', 'last clinical status: Apr 97, death, MM-related', 'last clinical status: Dez 99, death, MM-related', 'last clinical status: Okt 97, death, MM-related', 'last clinical status: Feb 99, death, MM-related', 'last clinical status: Dez 95, death, MM-related', 'last clinical status: Nov 97, death, MM-related', 'last clinical status: Jul 92, death, MM-related', 'comments: /extensive necrosis in adjacent areas', 'last clinical status: Dez 00, death, MM-related', 'last clinical status: Jun 02, death, MM-related', 'vgp: Yes', 'vgp: No', 'vgp type: Epithelioid and Spindled', 'precursor: No'], 25: [nan, 'comments: tumor cell number, is this an inflammatory infiltrate?', 'comments: 2 cell types in met (spindle/epitheloid)', 'comments: 2 cell types in met', 'comments: looks like lymphoma', 'vgp type: Epithelioid', 'precursor: No', 'vgp type: Epithelioid and Spindled', 'vgp type: Spindled', 'vgp type: RGP:Epithelioid', 'vgp type: RGP: Epithelioid', 'mitotic rate: 2'], 26: [nan, 'precursor: No', 'precursor: DN', 'precursor: CCN', 'mitotic rate: N/A', 'mitotic rate: 45', 'precursor: DN FOC', 'precursor: LCDN', 'tils: Absent'], 27: [nan, 'mitotic rate: 8', 'mitotic rate: Cannot Evaluate', 'mitotic rate: 6', 'mitotic rate: 4', 'mitotic rate: 7', 'mitotic rate: 0', 'mitotic rate: 1', 'tils: Non-brisk', 'mitotic rate: 10', 'mitotic rate: 3', 'mitotic rate: 33', 'mitotic rate: N/A', 'neural invasion: No', 'mitotic rate: 2'], 28: [nan, 'tils: Non-brisk', 'tils: Cannot Evaluate', 'tils: Absent', 'neural invasion: No', 'tils: N/A', 'vascular: No'], 29: [nan, 'neural invasion: No', 'vascular: No', 'neural invasion: N/A', 'regression: No'], 30: [nan, 'vascular: No', 'vascular: Yes', 'regression: No', 'regression: Yes', 'vascular: N/A', 'microsatellites: No'], 31: [nan, 'regression: No', 'regression: Yes', 'microsatellites: No', 'regression: Partial', 'comments: type: nodular vs. superficial spreading'], 32: [nan, 'microsatellites: No', 'comments: no further clinical data available', 'microsatellites: N/A'], 33: [nan, 'comments: tumor cells could be high as 50%', 'comments: metastatic disease at first diagnosis', 'comments: 50% melanoma cells, 50% nevus cells', 'comments: Breslow: 1,2 vs. 3,0']}\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": "207f84e1",
   "metadata": {},
   "source": [
    "### Step 2: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "1237b495",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:24:09.943710Z",
     "iopub.status.busy": "2025-03-25T08:24:09.943558Z",
     "iopub.status.idle": "2025-03-25T08:24:09.949225Z",
     "shell.execute_reply": "2025-03-25T08:24:09.948745Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Initial validation complete. Trait availability: True, Gene availability: True\n",
      "Note: This appears to be a melanoma dataset rather than Colon_and_Rectal_Cancer.\n"
     ]
    }
   ],
   "source": [
    "# 1. Gene Expression Data Availability\n",
    "# The background information mentions Affymetrix U133A microarray chip, which is used for gene expression analysis\n",
    "is_gene_available = True\n",
    "\n",
    "# 2. Variable Availability and Data Type Conversion\n",
    "# 2.1 Data Availability\n",
    "\n",
    "# For trait data (Melanoma vs. other tissue types)\n",
    "trait_row = 0  # \"tissue type\" contains information about the Melanoma status\n",
    "\n",
    "# For age data\n",
    "age_row = 7  # \"age at time of resection\" contains age information\n",
    "\n",
    "# For gender data\n",
    "gender_row = 8  # \"gender\" contains gender information\n",
    "\n",
    "# 2.2 Data Type Conversion\n",
    "\n",
    "# Convert trait data (Melanoma vs. normal)\n",
    "def convert_trait(value):\n",
    "    if pd.isna(value):\n",
    "        return None\n",
    "    \n",
    "    # Extract value after colon\n",
    "    if \":\" in value:\n",
    "        value = value.split(\":\", 1)[1].strip()\n",
    "    \n",
    "    # Binary classification: 1 for melanoma (primary or metastatic), 0 for non-melanoma (nevus, normal skin, normal melanocytes)\n",
    "    if \"Metastatic Melanoma\" in value or \"Primary Melanoma\" in value:\n",
    "        return 1\n",
    "    elif \"Nevus\" in value or \"Normal\" in value:\n",
    "        return 0\n",
    "    return None\n",
    "\n",
    "# Convert age data to numeric values\n",
    "def convert_age(value):\n",
    "    if pd.isna(value):\n",
    "        return None\n",
    "    \n",
    "    # Extract value after colon\n",
    "    if \":\" in value:\n",
    "        value = value.split(\":\", 1)[1].strip()\n",
    "    \n",
    "    # Extract age in years from format like \"72y 4m\"\n",
    "    if \"y\" in value:\n",
    "        try:\n",
    "            years = float(value.split(\"y\")[0])\n",
    "            return years\n",
    "        except ValueError:\n",
    "            return None\n",
    "    return None\n",
    "\n",
    "# Convert gender data to binary (0 for female, 1 for male)\n",
    "def convert_gender(value):\n",
    "    if pd.isna(value):\n",
    "        return None\n",
    "    \n",
    "    # Extract value after colon\n",
    "    if \":\" in value:\n",
    "        value = value.split(\":\", 1)[1].strip().lower()\n",
    "    \n",
    "    if value == \"female\":\n",
    "        return 0\n",
    "    elif value == \"male\":\n",
    "        return 1\n",
    "    return None\n",
    "\n",
    "# 3. Save Metadata\n",
    "# Determine trait data availability\n",
    "is_trait_available = trait_row is not None\n",
    "\n",
    "# Save metadata using the provided function\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",
    "# Note: This dataset appears to be a melanoma dataset, not Colon_and_Rectal_Cancer.\n",
    "# We'll proceed with initial validation and skip clinical feature extraction\n",
    "# since the expected clinical_data.csv file does not exist.\n",
    "\n",
    "print(f\"Initial validation complete. Trait availability: {is_trait_available}, Gene availability: {is_gene_available}\")\n",
    "print(f\"Note: This appears to be a melanoma dataset rather than {trait}.\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d99f96f3",
   "metadata": {},
   "source": [
    "### Step 3: Gene Data Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "8080d2ce",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:24:09.950830Z",
     "iopub.status.busy": "2025-03-25T08:24:09.950710Z",
     "iopub.status.idle": "2025-03-25T08:24:10.280542Z",
     "shell.execute_reply": "2025-03-25T08:24:10.279883Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Found data marker at line 92\n",
      "Header line: \"ID_REF\"\t\"GSM1131566\"\t\"GSM1131567\"\t\"GSM1131568\"\t\"GSM1131569\"\t\"GSM1131570\"\t\"GSM1131571\"\t\"GSM1131572\"\t\"GSM1131573\"\t\"GSM1131574\"\t\"GSM1131575\"\t\"GSM1131576\"\t\"GSM1131577\"\t\"GSM1131578\"\t\"GSM1131579\"\t\"GSM1131580\"\t\"GSM1131581\"\t\"GSM1131582\"\t\"GSM1131583\"\t\"GSM1131584\"\t\"GSM1131585\"\t\"GSM1131586\"\t\"GSM1131587\"\t\"GSM1131588\"\t\"GSM1131589\"\t\"GSM1131590\"\t\"GSM1131591\"\t\"GSM1131592\"\t\"GSM1131593\"\t\"GSM1131594\"\t\"GSM1131595\"\t\"GSM1131596\"\t\"GSM1131597\"\t\"GSM1131598\"\t\"GSM1131599\"\t\"GSM1131600\"\t\"GSM1131601\"\t\"GSM1131602\"\t\"GSM1131603\"\t\"GSM1131604\"\t\"GSM1131605\"\t\"GSM1131606\"\t\"GSM1131607\"\t\"GSM1131608\"\t\"GSM1131609\"\t\"GSM1131610\"\t\"GSM1131611\"\t\"GSM1131612\"\t\"GSM1131613\"\t\"GSM1131614\"\t\"GSM1131615\"\t\"GSM1131616\"\t\"GSM1131617\"\t\"GSM1131618\"\t\"GSM1131619\"\t\"GSM1131620\"\t\"GSM1131621\"\t\"GSM1131622\"\t\"GSM1131623\"\t\"GSM1131624\"\t\"GSM1131625\"\t\"GSM1131626\"\t\"GSM1131627\"\t\"GSM1131628\"\t\"GSM1131629\"\t\"GSM1131630\"\t\"GSM1131631\"\t\"GSM1131632\"\t\"GSM1131633\"\t\"GSM1131634\"\t\"GSM1131635\"\t\"GSM1131636\"\t\"GSM1131637\"\t\"GSM1131638\"\t\"GSM1131639\"\t\"GSM1131640\"\t\"GSM1131641\"\t\"GSM1131642\"\t\"GSM1131643\"\t\"GSM1131644\"\t\"GSM1131645\"\t\"GSM1131646\"\t\"GSM1131647\"\t\"GSM1131648\"\t\"GSM1131649\"\t\"GSM1131650\"\t\"GSM1131651\"\t\"GSM1131652\"\t\"GSM1131653\"\t\"GSM1131654\"\t\"GSM1131655\"\t\"GSM1131656\"\t\"GSM1131657\"\t\"GSM1131658\"\t\"GSM1131659\"\t\"GSM1131660\"\t\"GSM1131661\"\t\"GSM1131662\"\t\"GSM1131663\"\t\"GSM1131664\"\t\"GSM1131665\"\t\"GSM1131666\"\t\"GSM1131667\"\t\"GSM1131668\"\t\"GSM1131669\"\t\"GSM1131670\"\t\"GSM1131671\"\t\"GSM1131672\"\t\"GSM1131673\"\t\"GSM1131674\"\t\"GSM1131675\"\t\"GSM1131676\"\t\"GSM1131677\"\t\"GSM1131678\"\t\"GSM1131679\"\t\"GSM1131680\"\t\"GSM1131681\"\t\"GSM1131682\"\t\"GSM1131683\"\t\"GSM1131684\"\t\"GSM1131685\"\t\"GSM1131686\"\n",
      "First data line: \"1007_s_at\"\t190.8515442\t213.2920265\t190.7908308\t347.7253153\t651.3708589\t256.2708397\t345.4084068\t548.8546002\t265.8518713\t245.6122929\t186.8757804\t490.2549522\t527.8685673\t769.4666604\t377.5487916\t314.7115917\t839.5629527\t986.248516\t849.0611291\t722.761388\t158.4976912\t513.9841698\t765.3808903\t518.2010565\t505.3698157\t1009.678681\t615.7703799\t651.7344925\t658.9181835\t1535.828806\t890.2075188\t370.4767988\t927.1042337\t469.8667562\t334.5146902\t712.6929604\t859.8468113\t429.3961573\t511.2780001\t232.3263264\t1043.017134\t352.5587217\t140.3723579\t800.7991556\t162.7007325\t875.7329087\t224.1461637\t344.3204999\t174.9629\t313.1715783\t287.3384977\t571.4520459\t186.2374667\t552.0237186\t410.6163652\t138.7101404\t209.7377735\t1153.752645\t212.5578713\t204.154081\t394.3908341\t182.8304465\t263.8934972\t585.1488997\t690.915668\t271.8838307\t623.7072068\t1198.926061\t558.3213203\t489.9844103\t827.615316\t673.0766951\t428.9831376\t447.0136225\t451.532014\t499.1368911\t506.0840471\t557.4059345\t611.8939911\t411.0381439\t850.7480532\t675.9571137\t424.6597771\t466.6531444\t441.7537454\t1183.531487\t698.3658341\t419.7848276\t589.6294092\t631.3845117\t907.4674867\t511.6468647\t561.0949612\t417.8417321\t423.1234616\t712.5021757\t440.4598564\t747.8270537\t553.4215178\t723.2996303\t684.1214638\t536.5456525\t580.6010723\t968.911426\t654.238344\t1066.514904\t858.1353499\t1204.16852\t846.4547372\t909.2428986\t665.6016164\t1302.500707\t867.6718718\t1529.273113\t1314.390089\t911.6509804\t1328.06822\t1203.447534\t781.17848\t233.5105722\t1001.356172\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Index(['1007_s_at', '1053_at', '117_at', '121_at', '1255_g_at', '1294_at',\n",
      "       '1316_at', '1320_at', '1405_i_at', '1431_at', '1438_at', '1487_at',\n",
      "       '1494_f_at', '1598_g_at', '160020_at', '1729_at', '1773_at', '177_at',\n",
      "       '179_at', '1861_at'],\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": "e8cf0498",
   "metadata": {},
   "source": [
    "### Step 4: Gene Identifier Review"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "e9e1e67b",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:24:10.282416Z",
     "iopub.status.busy": "2025-03-25T08:24:10.282257Z",
     "iopub.status.idle": "2025-03-25T08:24:10.284822Z",
     "shell.execute_reply": "2025-03-25T08:24:10.284377Z"
    }
   },
   "outputs": [],
   "source": [
    "# Looking at the gene identifiers provided in the data, these appear to be probe IDs\n",
    "# rather than standard human gene symbols. Specifically, these look like Affymetrix\n",
    "# probe identifiers (e.g., \"1007_s_at\", \"1053_at\") which need to be mapped to \n",
    "# official gene symbols.\n",
    "\n",
    "# Affymetrix probe IDs typically have formats like \"####_at\", \"####_s_at\", etc.\n",
    "# and require mapping to convert to standard gene symbols (like BRCA1, TP53, etc.)\n",
    "\n",
    "requires_gene_mapping = True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3d226ca7",
   "metadata": {},
   "source": [
    "### Step 5: Gene Annotation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "10a90712",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:24:10.286392Z",
     "iopub.status.busy": "2025-03-25T08:24:10.286280Z",
     "iopub.status.idle": "2025-03-25T08:24:14.615877Z",
     "shell.execute_reply": "2025-03-25T08:24:14.615318Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene annotation preview:\n",
      "{'ID': ['1007_s_at', '1053_at', '117_at', '121_at', '1255_g_at'], 'GB_ACC': ['U48705', 'M87338', 'X51757', 'X69699', 'L36861'], 'SPOT_ID': [nan, nan, nan, nan, nan], 'Species Scientific Name': ['Homo sapiens', 'Homo sapiens', 'Homo sapiens', 'Homo sapiens', 'Homo sapiens'], 'Annotation Date': ['Oct 6, 2014', 'Oct 6, 2014', 'Oct 6, 2014', 'Oct 6, 2014', 'Oct 6, 2014'], 'Sequence Type': ['Exemplar sequence', 'Exemplar sequence', 'Exemplar sequence', 'Exemplar sequence', 'Exemplar sequence'], 'Sequence Source': ['Affymetrix Proprietary Database', 'GenBank', '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\", 'X69699 /FEATURE= /DEFINITION=HSPAX8A H.sapiens Pax8 mRNA', 'L36861 /FEATURE=expanded_cds /DEFINITION=HUMGCAPB Homo sapiens guanylate cyclase activating protein (GCAP) gene exons 1-4, complete cds'], 'Representative Public ID': ['U48705', 'M87338', 'X51757', 'X69699', 'L36861'], 'Gene Title': ['discoidin domain receptor tyrosine kinase 1 /// microRNA 4640', 'replication factor C (activator 1) 2, 40kDa', \"heat shock 70kDa protein 6 (HSP70B')\", 'paired box 8', 'guanylate cyclase activator 1A (retina)'], 'Gene Symbol': ['DDR1 /// MIR4640', 'RFC2', 'HSPA6', 'PAX8', 'GUCA1A'], 'ENTREZ_GENE_ID': ['780 /// 100616237', '5982', '3310', '7849', '2978'], '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', 'NM_003466 /// NM_013951 /// NM_013952 /// NM_013953 /// NM_013992', 'NM_000409 /// XM_006715073'], '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', '0001655 // urogenital system development // inferred from sequence or structural similarity /// 0001656 // metanephros development // inferred from electronic annotation /// 0001658 // branching involved in ureteric bud morphogenesis // inferred from expression pattern /// 0001822 // kidney development // inferred from expression pattern /// 0001823 // mesonephros development // inferred from sequence or structural similarity /// 0003337 // mesenchymal to epithelial transition involved in metanephros morphogenesis // inferred from expression pattern /// 0006351 // transcription, DNA-templated // inferred from direct assay /// 0006355 // regulation of transcription, DNA-templated // inferred from electronic annotation /// 0007275 // multicellular organismal development // inferred from electronic annotation /// 0007417 // central nervous system development // inferred from expression pattern /// 0009653 // anatomical structure morphogenesis // traceable author statement /// 0030154 // cell differentiation // inferred from electronic annotation /// 0030878 // thyroid gland development // inferred from expression pattern /// 0030878 // thyroid gland development // inferred from mutant phenotype /// 0038194 // thyroid-stimulating hormone signaling pathway // traceable author statement /// 0039003 // pronephric field specification // inferred from sequence or structural similarity /// 0042472 // inner ear morphogenesis // inferred from sequence or structural similarity /// 0042981 // regulation of apoptotic process // inferred from sequence or structural similarity /// 0045893 // positive regulation of transcription, DNA-templated // inferred from direct assay /// 0045893 // positive regulation of transcription, DNA-templated // inferred from sequence or structural similarity /// 0045944 // positive regulation of transcription from RNA polymerase II promoter // inferred from direct assay /// 0048793 // pronephros development // inferred from sequence or structural similarity /// 0071371 // cellular response to gonadotropin stimulus // inferred from direct assay /// 0071599 // otic vesicle development // inferred from expression pattern /// 0072050 // S-shaped body morphogenesis // inferred from electronic annotation /// 0072073 // kidney epithelium development // inferred from electronic annotation /// 0072108 // positive regulation of mesenchymal to epithelial transition involved in metanephros morphogenesis // inferred from sequence or structural similarity /// 0072164 // mesonephric tubule development // inferred from electronic annotation /// 0072207 // metanephric epithelium development // inferred from expression pattern /// 0072221 // metanephric distal convoluted tubule development // inferred from sequence or structural similarity /// 0072278 // metanephric comma-shaped body morphogenesis // inferred from expression pattern /// 0072284 // metanephric S-shaped body morphogenesis // inferred from expression pattern /// 0072289 // metanephric nephron tubule formation // inferred from sequence or structural similarity /// 0072305 // negative regulation of mesenchymal cell apoptotic process involved in metanephric nephron morphogenesis // inferred from sequence or structural similarity /// 0072307 // regulation of metanephric nephron tubule epithelial cell differentiation // inferred from sequence or structural similarity /// 0090190 // positive regulation of branching involved in ureteric bud morphogenesis // inferred from sequence or structural similarity /// 1900212 // negative regulation of mesenchymal cell apoptotic process involved in metanephros development // inferred from sequence or structural similarity /// 1900215 // negative regulation of apoptotic process involved in metanephric collecting duct development // inferred from sequence or structural similarity /// 1900218 // negative regulation of apoptotic process involved in metanephric nephron tubule development // inferred from sequence or structural similarity /// 2000594 // positive regulation of metanephric DCT cell differentiation // inferred from sequence or structural similarity /// 2000611 // positive regulation of thyroid hormone generation // inferred from mutant phenotype /// 2000612 // regulation of thyroid-stimulating hormone secretion // inferred from mutant phenotype', '0007165 // signal transduction // non-traceable author statement /// 0007601 // visual perception // inferred from electronic annotation /// 0007602 // phototransduction // inferred from electronic annotation /// 0007603 // phototransduction, visible light // traceable author statement /// 0016056 // rhodopsin mediated signaling pathway // traceable author statement /// 0022400 // regulation of rhodopsin mediated signaling pathway // traceable author statement /// 0030828 // positive regulation of cGMP biosynthetic process // inferred from electronic annotation /// 0031282 // regulation of guanylate cyclase activity // inferred from electronic annotation /// 0031284 // positive regulation of guanylate cyclase activity // inferred from electronic annotation /// 0050896 // response to stimulus // inferred from electronic annotation'], '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', '0005634 // nucleus // inferred from direct assay /// 0005654 // nucleoplasm // inferred from sequence or structural similarity /// 0005730 // nucleolus // inferred from direct assay', '0001750 // photoreceptor outer segment // inferred from electronic annotation /// 0001917 // photoreceptor inner segment // inferred from electronic annotation /// 0005578 // proteinaceous extracellular matrix // inferred from electronic annotation /// 0005886 // plasma membrane // inferred from direct assay /// 0016020 // membrane // inferred from electronic annotation /// 0097381 // photoreceptor disc membrane // traceable author statement'], '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', '0000979 // RNA polymerase II core promoter sequence-specific DNA binding // inferred from direct assay /// 0003677 // DNA binding // inferred from direct assay /// 0003677 // DNA binding // inferred from mutant phenotype /// 0003700 // sequence-specific DNA binding transcription factor activity // inferred from direct assay /// 0004996 // thyroid-stimulating hormone receptor activity // traceable author statement /// 0005515 // protein binding // inferred from physical interaction /// 0044212 // transcription regulatory region DNA binding // inferred from direct assay', '0005509 // calcium ion binding // inferred from electronic annotation /// 0008048 // calcium sensitive guanylate cyclase activator activity // inferred from electronic annotation /// 0030249 // guanylate cyclase regulator activity // inferred from electronic annotation /// 0046872 // metal ion binding // inferred from electronic annotation']}\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": "cc139c12",
   "metadata": {},
   "source": [
    "### Step 6: Gene Identifier Mapping"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "572262dd",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:24:14.617748Z",
     "iopub.status.busy": "2025-03-25T08:24:14.617585Z",
     "iopub.status.idle": "2025-03-25T08:24:14.840472Z",
     "shell.execute_reply": "2025-03-25T08:24:14.839780Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene data shape: (13830, 121)\n",
      "First few genes with their expression values:\n",
      "        GSM1131566   GSM1131567   GSM1131568   GSM1131569  GSM1131570  \\\n",
      "Gene                                                                    \n",
      "A1CF    144.908113   119.080971   114.282289   118.952864  118.819808   \n",
      "A2M     445.552804  1715.715807  3180.960949  2705.682868  680.621470   \n",
      "A4GALT   93.274356    60.266460    31.331144    75.625633   50.981658   \n",
      "A4GNT   201.909554   196.655163   133.220356   276.103770  144.675771   \n",
      "AAAS    200.259891   203.574159   155.812455   203.366706  175.886595   \n",
      "\n",
      "        GSM1131571   GSM1131572  GSM1131573  GSM1131574  GSM1131575  ...  \\\n",
      "Gene                                                                 ...   \n",
      "A1CF    110.742702   138.952519  156.039543  131.423745  175.564547  ...   \n",
      "A2M     970.836927  1145.824529  793.454716  223.795857  369.923699  ...   \n",
      "A4GALT   22.568745   136.231870  131.918490   22.343044   91.924361  ...   \n",
      "A4GNT   160.380270   187.058991  221.374316  182.794574  288.421672  ...   \n",
      "AAAS    193.774165   186.920488  193.829899  181.813716  175.097119  ...   \n",
      "\n",
      "         GSM1131677  GSM1131678   GSM1131679   GSM1131680  GSM1131681  \\\n",
      "Gene                                                                    \n",
      "A1CF     119.010955   91.561092   107.642880    69.969254  107.181636   \n",
      "A2M     1046.764473  919.362105  1332.209859  1069.040941  720.373582   \n",
      "A4GALT    98.780434   34.763718   291.288878    29.391811   74.275588   \n",
      "A4GNT     94.693768  175.940563   201.348700   142.056978  132.090781   \n",
      "AAAS     165.318223  171.599169   195.196615   154.136555  153.442997   \n",
      "\n",
      "        GSM1131682  GSM1131683  GSM1131684  GSM1131685  GSM1131686  \n",
      "Gene                                                                \n",
      "A1CF    103.549345   92.145215   98.195240  102.539858   76.449388  \n",
      "A2M     856.182442  960.609752  821.828430  633.030286  894.948884  \n",
      "A4GALT   91.382194  158.172164  246.992946   18.376081  140.555502  \n",
      "A4GNT   118.330636  125.632759  111.611433   84.458939  101.339276  \n",
      "AAAS    171.434674  216.025418  192.912016  213.613126  196.170304  \n",
      "\n",
      "[5 rows x 121 columns]\n"
     ]
    }
   ],
   "source": [
    "# 1. Identify the columns in the gene annotation dataframe that contain probe IDs and gene symbols\n",
    "probe_col = 'ID'  # Column containing probe IDs like \"1007_s_at\"\n",
    "gene_col = 'Gene Symbol'  # Column containing gene symbols like \"DDR1 /// MIR4640\"\n",
    "\n",
    "# 2. Get a mapping dataframe using the function from the library\n",
    "mapping_df = get_gene_mapping(gene_annotation, probe_col, gene_col)\n",
    "\n",
    "# 3. Apply the gene mapping to convert probe-level measurements to gene expression data\n",
    "gene_data = apply_gene_mapping(gene_data, mapping_df)\n",
    "\n",
    "# Print the shape of the resulting gene expression dataframe and preview a few rows\n",
    "print(f\"Gene data shape: {gene_data.shape}\")\n",
    "print(\"First few genes with their expression values:\")\n",
    "print(gene_data.head())\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "05a47a9c",
   "metadata": {},
   "source": [
    "### Step 7: Data Normalization and Linking"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "e14ea34e",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:24:14.842346Z",
     "iopub.status.busy": "2025-03-25T08:24:14.842216Z",
     "iopub.status.idle": "2025-03-25T08:24:23.755727Z",
     "shell.execute_reply": "2025-03-25T08:24:23.755030Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Normalized gene data shape: (13542, 121)\n",
      "First few genes with their expression values after normalization:\n",
      "        GSM1131566   GSM1131567   GSM1131568   GSM1131569  GSM1131570  \\\n",
      "Gene                                                                    \n",
      "A1CF    144.908113   119.080971   114.282289   118.952864  118.819808   \n",
      "A2M     445.552804  1715.715807  3180.960949  2705.682868  680.621470   \n",
      "A4GALT   93.274356    60.266460    31.331144    75.625633   50.981658   \n",
      "A4GNT   201.909554   196.655163   133.220356   276.103770  144.675771   \n",
      "AAAS    200.259891   203.574159   155.812455   203.366706  175.886595   \n",
      "\n",
      "        GSM1131571   GSM1131572  GSM1131573  GSM1131574  GSM1131575  ...  \\\n",
      "Gene                                                                 ...   \n",
      "A1CF    110.742702   138.952519  156.039543  131.423745  175.564547  ...   \n",
      "A2M     970.836927  1145.824529  793.454716  223.795857  369.923699  ...   \n",
      "A4GALT   22.568745   136.231870  131.918490   22.343044   91.924361  ...   \n",
      "A4GNT   160.380270   187.058991  221.374316  182.794574  288.421672  ...   \n",
      "AAAS    193.774165   186.920488  193.829899  181.813716  175.097119  ...   \n",
      "\n",
      "         GSM1131677  GSM1131678   GSM1131679   GSM1131680  GSM1131681  \\\n",
      "Gene                                                                    \n",
      "A1CF     119.010955   91.561092   107.642880    69.969254  107.181636   \n",
      "A2M     1046.764473  919.362105  1332.209859  1069.040941  720.373582   \n",
      "A4GALT    98.780434   34.763718   291.288878    29.391811   74.275588   \n",
      "A4GNT     94.693768  175.940563   201.348700   142.056978  132.090781   \n",
      "AAAS     165.318223  171.599169   195.196615   154.136555  153.442997   \n",
      "\n",
      "        GSM1131682  GSM1131683  GSM1131684  GSM1131685  GSM1131686  \n",
      "Gene                                                                \n",
      "A1CF    103.549345   92.145215   98.195240  102.539858   76.449388  \n",
      "A2M     856.182442  960.609752  821.828430  633.030286  894.948884  \n",
      "A4GALT   91.382194  158.172164  246.992946   18.376081  140.555502  \n",
      "A4GNT   118.330636  125.632759  111.611433   84.458939  101.339276  \n",
      "AAAS    171.434674  216.025418  192.912016  213.613126  196.170304  \n",
      "\n",
      "[5 rows x 121 columns]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Normalized gene data saved to ../../output/preprocess/Colon_and_Rectal_Cancer/gene_data/GSE46517.csv\n",
      "Clinical data saved to ../../output/preprocess/Colon_and_Rectal_Cancer/clinical_data/GSE46517.csv\n",
      "Clinical data preview:\n",
      "{'GSM1131566': [1.0, nan, nan], 'GSM1131567': [1.0, nan, nan], 'GSM1131568': [1.0, nan, nan], 'GSM1131569': [1.0, nan, nan], 'GSM1131570': [1.0, nan, nan], 'GSM1131571': [1.0, nan, nan], 'GSM1131572': [1.0, nan, nan], 'GSM1131573': [1.0, nan, nan], 'GSM1131574': [1.0, nan, nan], 'GSM1131575': [1.0, nan, nan], 'GSM1131576': [1.0, nan, nan], 'GSM1131577': [1.0, nan, nan], 'GSM1131578': [1.0, nan, nan], 'GSM1131579': [1.0, nan, nan], 'GSM1131580': [1.0, nan, nan], 'GSM1131581': [1.0, nan, nan], 'GSM1131582': [1.0, nan, nan], 'GSM1131583': [1.0, nan, nan], 'GSM1131584': [1.0, nan, nan], 'GSM1131585': [1.0, nan, nan], 'GSM1131586': [1.0, nan, nan], 'GSM1131587': [1.0, nan, nan], 'GSM1131588': [1.0, nan, nan], 'GSM1131589': [1.0, nan, nan], 'GSM1131590': [1.0, nan, nan], 'GSM1131591': [1.0, nan, nan], 'GSM1131592': [1.0, nan, nan], 'GSM1131593': [1.0, nan, nan], 'GSM1131594': [1.0, nan, nan], 'GSM1131595': [1.0, nan, nan], 'GSM1131596': [1.0, nan, nan], 'GSM1131597': [1.0, nan, nan], 'GSM1131598': [1.0, nan, nan], 'GSM1131599': [1.0, nan, nan], 'GSM1131600': [1.0, nan, nan], 'GSM1131601': [1.0, nan, nan], 'GSM1131602': [1.0, nan, nan], 'GSM1131603': [1.0, nan, nan], 'GSM1131604': [1.0, nan, nan], 'GSM1131605': [1.0, nan, nan], 'GSM1131606': [1.0, nan, nan], 'GSM1131607': [1.0, nan, nan], 'GSM1131608': [1.0, nan, nan], 'GSM1131609': [1.0, nan, nan], 'GSM1131610': [1.0, nan, nan], 'GSM1131611': [1.0, nan, nan], 'GSM1131612': [1.0, nan, nan], 'GSM1131613': [1.0, nan, nan], 'GSM1131614': [1.0, nan, nan], 'GSM1131615': [1.0, nan, nan], 'GSM1131616': [1.0, nan, nan], 'GSM1131617': [1.0, nan, nan], 'GSM1131618': [1.0, nan, nan], 'GSM1131619': [1.0, nan, nan], 'GSM1131620': [1.0, nan, nan], 'GSM1131621': [1.0, nan, nan], 'GSM1131622': [1.0, nan, nan], 'GSM1131623': [1.0, nan, nan], 'GSM1131624': [1.0, nan, nan], 'GSM1131625': [1.0, nan, nan], 'GSM1131626': [1.0, nan, nan], 'GSM1131627': [1.0, nan, nan], 'GSM1131628': [1.0, nan, nan], 'GSM1131629': [1.0, nan, nan], 'GSM1131630': [1.0, nan, nan], 'GSM1131631': [1.0, nan, nan], 'GSM1131632': [1.0, nan, nan], 'GSM1131633': [1.0, nan, nan], 'GSM1131634': [1.0, nan, nan], 'GSM1131635': [1.0, nan, nan], 'GSM1131636': [1.0, nan, nan], 'GSM1131637': [1.0, nan, nan], 'GSM1131638': [1.0, nan, nan], 'GSM1131639': [1.0, 72.0, 1.0], 'GSM1131640': [1.0, 52.0, 0.0], 'GSM1131641': [1.0, 87.0, 0.0], 'GSM1131642': [1.0, 55.0, 0.0], 'GSM1131643': [1.0, 84.0, 1.0], 'GSM1131644': [1.0, 72.0, 1.0], 'GSM1131645': [1.0, 73.0, 0.0], 'GSM1131646': [1.0, 72.0, 1.0], 'GSM1131647': [1.0, 78.0, 1.0], 'GSM1131648': [1.0, 66.0, 0.0], 'GSM1131649': [1.0, 81.0, 1.0], 'GSM1131650': [1.0, 59.0, 0.0], 'GSM1131651': [1.0, 64.0, 1.0], 'GSM1131652': [1.0, 29.0, 1.0], 'GSM1131653': [1.0, 31.0, 1.0], 'GSM1131654': [1.0, 43.0, 1.0], 'GSM1131655': [1.0, 57.0, 1.0], 'GSM1131656': [1.0, 64.0, 0.0], 'GSM1131657': [1.0, 52.0, 1.0], 'GSM1131658': [1.0, 55.0, 1.0], 'GSM1131659': [1.0, 77.0, 0.0], 'GSM1131660': [1.0, 38.0, 1.0], 'GSM1131661': [1.0, 52.0, 1.0], 'GSM1131662': [1.0, 59.0, 0.0], 'GSM1131663': [1.0, 56.0, 1.0], 'GSM1131664': [1.0, 68.0, 1.0], 'GSM1131665': [1.0, 75.0, 0.0], 'GSM1131666': [1.0, 85.0, 0.0], 'GSM1131667': [1.0, 46.0, 0.0], 'GSM1131668': [1.0, 63.0, 0.0], 'GSM1131669': [1.0, 46.0, 0.0], 'GSM1131670': [0.0, nan, nan], 'GSM1131671': [0.0, nan, nan], 'GSM1131672': [0.0, nan, nan], 'GSM1131673': [0.0, nan, nan], 'GSM1131674': [0.0, nan, nan], 'GSM1131675': [0.0, nan, nan], 'GSM1131676': [0.0, nan, nan], 'GSM1131677': [0.0, nan, nan], 'GSM1131678': [0.0, nan, nan], 'GSM1131679': [0.0, nan, nan], 'GSM1131680': [0.0, nan, nan], 'GSM1131681': [0.0, nan, nan], 'GSM1131682': [0.0, nan, nan], 'GSM1131683': [0.0, nan, nan], 'GSM1131684': [0.0, nan, nan], 'GSM1131685': [0.0, nan, nan], 'GSM1131686': [0.0, nan, nan]}\n",
      "Linked data shape (before handling missing values): (121, 13545)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Data after handling missing values: (121, 13545)\n",
      "For the feature 'Melanoma', the least common label is '0.0' with 17 occurrences. This represents 14.05% of the dataset.\n",
      "The distribution of the feature 'Melanoma' in this dataset is fine.\n",
      "\n",
      "Quartiles for 'Age':\n",
      "  25%: 61.645161290322584\n",
      "  50% (Median): 61.645161290322584\n",
      "  75%: 61.645161290322584\n",
      "Min: 29.0\n",
      "Max: 87.0\n",
      "The distribution of the feature 'Age' in this dataset is fine.\n",
      "\n",
      "For the feature 'Gender', the least common label is '0.0' with 14 occurrences. This represents 11.57% of the dataset.\n",
      "The distribution of the feature 'Gender' in this dataset is fine.\n",
      "\n",
      "A new JSON file was created at: ../../output/preprocess/Colon_and_Rectal_Cancer/cohort_info.json\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Linked data saved to ../../output/preprocess/Colon_and_Rectal_Cancer/GSE46517.csv\n"
     ]
    }
   ],
   "source": [
    "# 1. Normalize gene symbols in the gene expression data\n",
    "normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n",
    "print(f\"Normalized gene data shape: {normalized_gene_data.shape}\")\n",
    "print(\"First few genes with their expression values after normalization:\")\n",
    "print(normalized_gene_data.head())\n",
    "\n",
    "# Save the normalized gene data\n",
    "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
    "normalized_gene_data.to_csv(out_gene_data_file)\n",
    "print(f\"Normalized gene data saved to {out_gene_data_file}\")\n",
    "\n",
    "# 2. Extract clinical features using the functions defined in step 2\n",
    "# First, let's load the clinical data again to ensure we have the latest version\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 using melanoma vs normal tissue as the binary trait\n",
    "selected_clinical_df = geo_select_clinical_features(\n",
    "    clinical_data, \n",
    "    trait=\"Melanoma\", \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",
    "# Save the 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\"Clinical data saved to {out_clinical_data_file}\")\n",
    "print(\"Clinical data preview:\")\n",
    "print(preview_df(selected_clinical_df))\n",
    "\n",
    "# 3. Link the clinical and genetic data\n",
    "# Transpose normalized gene data for linking\n",
    "gene_data_t = normalized_gene_data.T\n",
    "\n",
    "# Link the clinical and genetic data\n",
    "linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)\n",
    "print(f\"Linked data shape (before handling missing values): {linked_data.shape}\")\n",
    "\n",
    "# 4. Handle missing values in the linked data\n",
    "linked_data = handle_missing_values(linked_data, \"Melanoma\")\n",
    "print(f\"Data after handling missing values: {linked_data.shape}\")\n",
    "\n",
    "# 5. Determine whether the trait and demographic features are biased\n",
    "is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, \"Melanoma\")\n",
    "\n",
    "# 6. Conduct final quality validation and save 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 comparing melanoma (primary and metastatic) with normal tissue/nevi.\"\n",
    ")\n",
    "\n",
    "# 7. If the linked data is usable, save it\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
}