File size: 56,245 Bytes
92d2f89
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "28869cfd",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T07:06:00.339766Z",
     "iopub.status.busy": "2025-03-25T07:06:00.339548Z",
     "iopub.status.idle": "2025-03-25T07:06:00.504129Z",
     "shell.execute_reply": "2025-03-25T07:06:00.503794Z"
    }
   },
   "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 = \"Cardiovascular_Disease\"\n",
    "cohort = \"GSE190042\"\n",
    "\n",
    "# Input paths\n",
    "in_trait_dir = \"../../input/GEO/Cardiovascular_Disease\"\n",
    "in_cohort_dir = \"../../input/GEO/Cardiovascular_Disease/GSE190042\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/Cardiovascular_Disease/GSE190042.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/Cardiovascular_Disease/gene_data/GSE190042.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/Cardiovascular_Disease/clinical_data/GSE190042.csv\"\n",
    "json_path = \"../../output/preprocess/Cardiovascular_Disease/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "21ed9e16",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "eea4c967",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T07:06:00.505378Z",
     "iopub.status.busy": "2025-03-25T07:06:00.505238Z",
     "iopub.status.idle": "2025-03-25T07:06:00.786842Z",
     "shell.execute_reply": "2025-03-25T07:06:00.786376Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Background Information:\n",
      "!Series_title\t\"Integration between MCL1 gene co-expression module and the Revised International Staging System enables precise prognostication and prediction of response to proteasome inhibitor-based therapy in individual multiple myeloma\"\n",
      "!Series_summary\t\"We recently identified a gene module of 87 genes co-expressed with MCL1 (MCL1-M), a critical regulator of plasma cell survival. MCL1-M captures both MM cell-intrinsically acting signals and the signals regulating the interaction between MM cells with bone marrow microenvironment. MM can be clustered into MCL1-M high and MCL1-M low subtypes. While the MCL1-M high MMs are enriched in a preplasmablast signature, the MCL1-M low MMs are enriched in B cell-specific genes. In multiple independent datasets, MCL1-M high MMs exhibited poorer prognosis compared to MCL1-M low MMs. Re-analysis of the phase III HOVON-65/GMMG-HD4 showed that only MCL1-M MMs, but not MCL1-M low MMs, benefited from bortezomib-based treatment. To translate the MCL1-M clustering scheme into a platform for individual diagnosis, we refined the classifier genes and developed a support vector machine-based algorithm.\"\n",
      "!Series_summary\t\"Individual MMs with transcriptome assessed at the RNA-seq or U133 plus 2.0 array platform can be robustly assigned as the MCL1-M high or low subtype with high confidence. Analyses of the MM samples in the HOVON-65/GMMG-HD4 trial and APEX trial reinforce that only MCL1-M high MMs benefit from bortezomib-based treatment with a hazard ratio of 0.58 (P = 0.010) and 0.47 (P = 0.009), respectively. Thus, MCL1-M based subtyping assigns MMs into prognostic and predictive molecular subtypes driven by subtype-specific pathogenic pathways.\"\n",
      "!Series_overall_design\t\"We also generated our own data set based on 72 newly diagnosed MM samples  from Chaoyang hospital in Beijing. All participants signed the informed consent form, and the study was approved by the institutional ethical review board of the Chao-Yang Hospital, Capital Medical University (Beijing, China). Patients were treated between August 2015 and September 2019, the longest follow-up period was 67 months. Bone marrow CD138+ cells were purified for the preparation of total mRNA for the transcriptome profiling using Affymetrix PrimeView array according to standard protocols.\"\n",
      "Sample Characteristics Dictionary:\n",
      "{0: ['batch: Batch 1', 'batch: Batch 3', 'batch: Batch 2', 'batch: Batch 4'], 1: ['gender: F', 'gender: M'], 2: ['age: 72', 'age: 77', 'age: 56', 'age: 67', 'age: 55', 'age: 73', 'age: 62', 'age: 49', 'age: 78', 'age: 66', 'age: 64', 'age: 47', 'age: 69', 'age: 59', 'age: 81', 'age: 65', 'age: 51', 'age: 70', 'age: 79', 'age: 75', 'age: 54', 'age: 61', 'age: 44', 'age: 52', 'age: 60', 'age: 68', 'age: 58', 'age: 84', 'age: 76', 'age: 53'], 3: ['time at diagnosis: 43355', 'time at diagnosis: 43341', 'time at diagnosis: 43441', 'time at diagnosis: 43439', 'time at diagnosis: 43516', 'time at diagnosis: 43372', 'time at diagnosis: 43507', 'time at diagnosis: 43535', 'time at diagnosis: 43373', 'time at diagnosis: 43409', 'time at diagnosis: 43453', 'time at diagnosis: 43509', 'time at diagnosis: 43536', 'time at diagnosis: 43510', 'time at diagnosis: 43040', 'time at diagnosis: 43460', 'time at diagnosis: 43593', 'time at diagnosis: 43472', 'time at diagnosis: 43514', 'time at diagnosis: 43477', 'time at diagnosis: 43519', 'time at diagnosis: 43525', 'time at diagnosis: 43480', 'time at diagnosis: 43520', 'time at diagnosis: 43546', 'time at diagnosis: 43553', 'time at diagnosis: 43476', 'time at diagnosis: 43530', 'time at diagnosis: 43550', 'time at diagnosis: 43412'], 4: ['type: IgA-k', 'type: IgG-K', 'type: Lambda', 'type: IgA-L', 'type: kappa', 'type: IgG-L', 'type: IgD-Lambda', 'type: IgG-Lambda', 'type: IgA-Lambda', 'type: PCL', 'type: IgD-L', 'type: NS', 'type: IgG-k', 'type: IgA-Lambda,IgG-Lambda', 'type: IgG-Lambda;Lambda'], 5: ['riss: I', 'riss: II', 'riss: III', 'treatment strategy: PCD*1'], 6: ['treatment strategy: RD*4 RCD*10,Rd-R maintenance', 'treatment strategy: VTD*5, ITD*2, VRD*1', 'treatment strategy: BCDT*4 ,BCD*7,RCD*8,R maintenance', 'treatment strategy: TD*1,PTD*2 VRD*2 ASCT,VR maintenance', 'treatment strategy: PDD*1,V-DEAP*2,VT-DEAP*2,ASCT, R maintenance', 'treatment strategy: BCD*2 BTD*2 RD*4,R maintenance', 'treatment strategy: BCD*7, RCD*5, RD-R maintenance', 'treatment strategy: BCDT*2, PCD*1,RCD*2, ASCT,R maintenance', 'treatment strategy: BCD*2, VRD*4, VRCD*2, VBiRD,IRCD,TMD,CETD*4,CAR-T', 'treatment strategy: PDD*9, VRD*1, R maintenance', 'treatment strategy: PCD*4', 'treatment strategy: PDD*6 ,RCD*6 RD maintenance', 'treatment strategy: NO', 'treatment strategy: VRD*2 ,PDD*2,TD maintenance', 'treatment strategy: VAD&IE*12, EPA&EP*4,Radiation', 'treatment strategy: VRD*1, VTD*2', 'treatment strategy: VRD*5, ASCT,R maintenance', 'treatment strategy: BD', 'treatment strategy: VTD*3', 'treatment strategy: VRDD*3 NR,V-DECP', 'treatment strategy: PCDD*1, PCDT*1', 'treatment strategy: BTD*8,T maintenance', 'treatment strategy: VRDD*2 ,VRD*2, RD maintenance', 'treatment strategy: VRD*4 ,IRD*,4 RD maintenance', 'treatment strategy: VRD*6, ASCT,VRD*2,VR maintenance', 'treatment strategy: PDD*1, R maintenance', 'treatment strategy: PDD*6 ,ID-I maintenance', 'treatment strategy: Dara-VMP', 'treatment strategy: PCD*1,PCDT*2,PCDT*2 ASCT, R maintenance', 'treatment strategy: VRD*8,VBiRD*4, Rd-R maintenance'], 7: ['best respose: CR', 'best respose: PR', 'best respose: CR MRD+', 'best respose: MR', 'best respose: VGPR MRD+', 'best respose: VGPR', 'best respose: CR MRD-', 'chromosome: 46,XY[20]', 'chromosome: 44,X,-X,+1,der(1;21)(q10;q10),add(6)(q21),-13,-14,del(17)(q21),add(19)(q13),+2 1[3]/46,XX[17]', 'best respose: NR', 'best respose: sCR MRD+', 'best respose: CR ,MRD+', 'pfs1(months): 1', 'best respose: 髓内达sCR,MRD-', 'chromosome: 41,X,-X,dic(1;5)(p13;q33),-3,add(4)(p11),-5,-7,der(9)t(7;9)(q11;p24),del(11)(q13q2 1),-13,-14,add(15)(q24),-21,+4mar[1]/46,XX[29] 实验诊断提示:分析30个中期分裂相,1个核型存在染色体数目及结构异常,其余为正常核型,', 'best respose: PD', 'best respose: SD', 'chromosome: 52,XY,+2,add(3)(q26),del(4)(q21),del(4)(q31),+der(6)t(1;6)(q11;q13),+7,add(8)(q24) ×2,+9,+11,del(16)(q22),+20,add(21)(p11)[19]/46,XY[1]', 'best respose: sCR,MRD-', 'best respose: Scr', 'best respose: sCR', 'best respose: CR,MRD+', 'best respose: PR MRD+'], 8: ['chromosome: 46 xx[20]/56,xx,+x,+4,+5,+10,+10,+11,+12,+19,+20,+22[1]', 'chromosome: ND', 'chromosome: 46,XY[20]', 'chromosome: 46,XY[8]', 'chromosome: 46,XX[20]', 'chromosome: 46,XX[15]', 'chromosome: 45,X,-Y[5]/46,XY[15]', 'chromosome: 46,XX,del(1)(p11),add(2)(p21),-4,+9,-13,add(22)(p11),+mar[10]', 'chromosome: 45,XX,der(13;14)(q10;q10)[20]', 'FISH: IGH/CCND1', 'chromosome: 46,XX[9]', 'FISH: negtive', 'FISH: 1q21+,IGH/FGFR3', 'chromosome: 43,X,-X,del(4)(q27q35),add(5)(q33),add(8)(q24),der(11)del(11)(q23)t(11;14)(q13; q32),-13,-14,der(14)t(11;14),-16,-17,-19,-22,+4mar[8]/46,XX[2]', 'chromosome: 44,XX,+del(3)(p13),-6,-10,-12,-13,-14,-17,-20,+4mar[cp6]/46,XX[7]', 'chromosome: 46,XX,inv(9)(p12q13)c[20]', 'chromosome: 50~52,XX,+add(1)(p13),+11,-14,+19,-22,+3~4mar,inc[cp3]/46,XX[17]', 'chromosome: 68~81,…[5]/46,XY[9]', 'chromosome: 47,XY,+Y[2]/46,XY[18]', 'chromosome: 46,XX[14]', 'os(months): 1', 'chromosome: 46,XY,del(20)(q11)[10]/46,XY[10]', 'FISH: 1q21(+4),TP53 - ,IGH/FGFR3', 'FISH: 1q21(+4),IGH +', 'FISH: 1q21(+3),CCND1+,MAF -,FGFR3 -', 'FISH: 1q21(+3),MAF -', 'chromosome: 53,XY,+add(1)(p13),+5,+9,add(13)(q32),+14,+18,+add(19)(q13),+21[2]/46,XY[18]', 'chromosome: 46,XY[15]', 'chromosome: complicated', 'chromosome: hypodiploids'], 9: ['FISH: negtive', 'FISH: ND', 'FISH: 1q21+,IGH-', 'FISH: 1q21+,IGH/FGFR3', 'FISH: MAF-,CCND1+', 'FISH: 1q21+,TP53+,MAF+,CCND1+,IGH/FGFR3+', 'FISH: 1q21+', 'FISH: 1q21+,TP53+,CCND1+', 'FISH: IGH/MAF,1q21+,TP53+', 'FISH: CCND1', 'FISH: 1q21+,FGFR3 -', 'FISH: TP53-,IGH-', 'pfs1(months): 5', 'FISH: 1q21+,IGH/CCND1', 'FISH: 1q21+,TP53-,IGH/CCND1', nan, 'FISH: t(4;14)', 'pfs1(months): 10', 'FISH: TP53 -,MAF-,IGH/CCND1', 'FISH: IGH/CCND1', 'FISH: IGH+', 'FISH: 1q21+,IGH/MAF', 'FISH: 1q21', 'FISH: TP53-,IGH/FGFR3', 'FISH: MAF-', 'FISH: TP53 -', 'FISH: 1q21 +、IGH +', 'FISH: t(11;14)69.5%', 'FISH: 1q21+,IGH/FGFR3', 'FISH: IGH-'], 10: ['pfs1(months): 32', nan, 'pfs1(months): 21', 'os(months): 5', 'pfs1(months): 20', 'pfs1(months): 16', 'os(months): 10', 'pfs1(months): 5', 'pfs1(months): 2', 'pfs1(months): 28', 'pfs1(months): 19', 'pfs1(months): 11', 'pfs1(months): 22', 'pfs1(months): 13', 'pfs1(months): 26', 'pfs1(months): 1', 'pfs1(months): 14', 'os(months): 2', 'pfs1(months): 4', 'pfs1(months): 23', 'pfs1(months): 37', 'pfs1(months): 29', 'pfs1(months): 41', 'pfs1(months): 9', 'pfs1(months): 33', 'pfs1(months): 12', 'pfs1(months): 8', 'pfs1(months): 35', 'pfs1(months): 67', 'pfs1(months): 57'], 11: [nan, 'os(months): 29', 'os(months): 5', 'os(months): 2', 'os(months): 11', 'os(months): 21', 'os(months): 1', 'os(months): 18', 'os(months): 23', 'os(months): 19', 'os(months): 37', 'os(months): 40', 'os(months): 12', 'os(months): 44', 'os(months): 9', 'os(months): 6', 'os(months): 24']}\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": "9f619bf2",
   "metadata": {},
   "source": [
    "### Step 2: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "25934cdd",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T07:06:00.788290Z",
     "iopub.status.busy": "2025-03-25T07:06:00.788181Z",
     "iopub.status.idle": "2025-03-25T07:06:00.794283Z",
     "shell.execute_reply": "2025-03-25T07:06:00.794006Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "False"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import pandas as pd\n",
    "import os\n",
    "import numpy as np\n",
    "from typing import Optional, Callable, Dict, Any\n",
    "\n",
    "# 1. Determine gene expression availability\n",
    "# Based on the series title and summary, this appears to be a gene expression microarray dataset\n",
    "# Specifically, it mentions \"transcriptome profiling using Affymetrix PrimeView array\"\n",
    "is_gene_available = True\n",
    "\n",
    "# 2.1 Identify the row indices for trait, age, and gender data\n",
    "# For the trait (Cardiovascular Disease), there's no direct mention in the data\n",
    "# This dataset appears to be about Multiple Myeloma patients\n",
    "trait_row = None  # No direct trait info for Cardiovascular Disease\n",
    "\n",
    "# Age is available in row 2\n",
    "age_row = 2\n",
    "\n",
    "# Gender is available in row 1\n",
    "gender_row = 1\n",
    "\n",
    "# 2.2 Define conversion functions\n",
    "\n",
    "# Since trait data is not available, this is a placeholder\n",
    "def convert_trait(value):\n",
    "    return None\n",
    "\n",
    "# Age conversion function\n",
    "def convert_age(value):\n",
    "    if not isinstance(value, str):\n",
    "        return None\n",
    "    # Extract the value after the colon\n",
    "    parts = value.split(\":\")\n",
    "    if len(parts) != 2:\n",
    "        return None\n",
    "    try:\n",
    "        age = int(parts[1].strip())\n",
    "        return age  # Return as a continuous value\n",
    "    except ValueError:\n",
    "        return None\n",
    "\n",
    "# Gender conversion function\n",
    "def convert_gender(value):\n",
    "    if not isinstance(value, str):\n",
    "        return None\n",
    "    # Extract the value after the colon\n",
    "    parts = value.split(\":\")\n",
    "    if len(parts) != 2:\n",
    "        return None\n",
    "    \n",
    "    gender = parts[1].strip().upper()\n",
    "    if gender == 'F':\n",
    "        return 0  # Female\n",
    "    elif gender == 'M':\n",
    "        return 1  # Male\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "# 3. Validate and save metadata\n",
    "# Trait data is not available (trait_row is None)\n",
    "is_trait_available = trait_row is not None\n",
    "\n",
    "# Save initial filtering result\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 (Skip this step as trait_row is None)\n",
    "# We don't have trait data for this cohort, so we don't extract clinical features\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d4b3746c",
   "metadata": {},
   "source": [
    "### Step 3: Gene Data Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "9e60855b",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T07:06:00.795575Z",
     "iopub.status.busy": "2025-03-25T07:06:00.795475Z",
     "iopub.status.idle": "2025-03-25T07:06:01.252633Z",
     "shell.execute_reply": "2025-03-25T07:06:01.252272Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Matrix file found: ../../input/GEO/Cardiovascular_Disease/GSE190042/GSE190042_series_matrix.txt.gz\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene data shape: (49395, 93)\n",
      "First 20 gene/probe identifiers:\n",
      "Index(['11715100_at', '11715101_s_at', '11715102_x_at', '11715103_x_at',\n",
      "       '11715104_s_at', '11715105_at', '11715106_x_at', '11715107_s_at',\n",
      "       '11715108_x_at', '11715109_at', '11715110_at', '11715111_s_at',\n",
      "       '11715112_at', '11715113_x_at', '11715114_x_at', '11715115_s_at',\n",
      "       '11715116_s_at', '11715117_x_at', '11715118_s_at', '11715119_s_at'],\n",
      "      dtype='object', name='ID')\n"
     ]
    }
   ],
   "source": [
    "# 1. Get the SOFT and matrix file paths again \n",
    "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
    "print(f\"Matrix file found: {matrix_file}\")\n",
    "\n",
    "# 2. Use the get_genetic_data function from the library to get the gene_data\n",
    "try:\n",
    "    gene_data = get_genetic_data(matrix_file)\n",
    "    print(f\"Gene data shape: {gene_data.shape}\")\n",
    "    \n",
    "    # 3. Print the first 20 row IDs (gene or probe identifiers)\n",
    "    print(\"First 20 gene/probe identifiers:\")\n",
    "    print(gene_data.index[:20])\n",
    "except Exception as e:\n",
    "    print(f\"Error extracting gene data: {e}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b9336686",
   "metadata": {},
   "source": [
    "### Step 4: Gene Identifier Review"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "2d9410a5",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T07:06:01.254154Z",
     "iopub.status.busy": "2025-03-25T07:06:01.254041Z",
     "iopub.status.idle": "2025-03-25T07:06:01.255916Z",
     "shell.execute_reply": "2025-03-25T07:06:01.255661Z"
    }
   },
   "outputs": [],
   "source": [
    "# Looking at the gene identifiers, they appear to be probe IDs rather than standard human gene symbols\n",
    "# The format \"11715100_at\" is typical for microarray probe identifiers (specifically Affymetrix)\n",
    "# These need to be mapped to gene symbols for biological interpretation\n",
    "\n",
    "requires_gene_mapping = True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3bed93c6",
   "metadata": {},
   "source": [
    "### Step 5: Gene Annotation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "d8645396",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T07:06:01.257586Z",
     "iopub.status.busy": "2025-03-25T07:06:01.257450Z",
     "iopub.status.idle": "2025-03-25T07:06:14.927786Z",
     "shell.execute_reply": "2025-03-25T07:06:14.927167Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "Gene annotation preview:\n",
      "Columns in gene annotation: ['ID', 'GeneChip Array', 'Species Scientific Name', 'Annotation Date', 'Sequence Type', 'Sequence Source', 'Transcript ID(Array Design)', 'Target Description', 'GB_ACC', 'GI', 'Representative Public ID', 'Archival UniGene Cluster', 'UniGene ID', 'Genome Version', 'Alignments', 'Gene Title', 'Gene Symbol', 'Chromosomal Location', 'Unigene Cluster Type', 'Ensembl', 'Entrez Gene', 'SwissProt', 'EC', 'OMIM', 'RefSeq Protein ID', 'RefSeq Transcript ID', 'Gene Ontology Biological Process', 'Gene Ontology Cellular Component', 'Gene Ontology Molecular Function', 'Pathway', 'InterPro', 'Annotation Description', 'Annotation Transcript Cluster', 'Transcript Assignments', 'Annotation Notes', 'SPOT_ID']\n",
      "{'ID': ['11715100_at', '11715101_s_at', '11715102_x_at', '11715103_x_at', '11715104_s_at'], 'GeneChip Array': ['Human Genome PrimeView Array', 'Human Genome PrimeView Array', 'Human Genome PrimeView Array', 'Human Genome PrimeView Array', 'Human Genome PrimeView Array'], 'Species Scientific Name': ['Homo sapiens', 'Homo sapiens', 'Homo sapiens', 'Homo sapiens', 'Homo sapiens'], 'Annotation Date': ['30-Mar-16', '30-Mar-16', '30-Mar-16', '30-Mar-16', '30-Mar-16'], 'Sequence Type': ['Consensus sequence', 'Consensus sequence', 'Consensus sequence', 'Consensus sequence', 'Consensus sequence'], 'Sequence Source': ['Affymetrix Proprietary Database', 'Affymetrix Proprietary Database', 'Affymetrix Proprietary Database', 'Affymetrix Proprietary Database', 'Affymetrix Proprietary Database'], 'Transcript ID(Array Design)': ['g21264570', 'g21264570', 'g21264570', 'g22748780', 'g30039713'], 'Target Description': ['g21264570 /TID=g21264570 /CNT=1 /FEA=FLmRNA /TIER=FL /STK=0 /DEF=g21264570 /REP_ORG=Homo sapiens', 'g21264570 /TID=g21264570 /CNT=1 /FEA=FLmRNA /TIER=FL /STK=0 /DEF=g21264570 /REP_ORG=Homo sapiens', 'g21264570 /TID=g21264570 /CNT=1 /FEA=FLmRNA /TIER=FL /STK=0 /DEF=g21264570 /REP_ORG=Homo sapiens', 'g22748780 /TID=g22748780 /CNT=1 /FEA=FLmRNA /TIER=FL /STK=0 /DEF=g22748780 /REP_ORG=Homo sapiens', 'g30039713 /TID=g30039713 /CNT=1 /FEA=FLmRNA /TIER=FL /STK=0 /DEF=g30039713 /REP_ORG=Homo sapiens'], 'GB_ACC': [nan, nan, nan, nan, nan], 'GI': [21264570.0, 21264570.0, 21264570.0, 22748780.0, 30039713.0], 'Representative Public ID': ['g21264570', 'g21264570', 'g21264570', 'g22748780', 'g30039713'], 'Archival UniGene Cluster': ['---', '---', '---', '---', '---'], 'UniGene ID': ['Hs.247813', 'Hs.247813', 'Hs.247813', 'Hs.465643', 'Hs.352515'], 'Genome Version': ['February 2009 (Genome Reference Consortium GRCh37)', 'February 2009 (Genome Reference Consortium GRCh37)', 'February 2009 (Genome Reference Consortium GRCh37)', 'February 2009 (Genome Reference Consortium GRCh37)', 'February 2009 (Genome Reference Consortium GRCh37)'], 'Alignments': ['chr6:26271145-26271612 (-) // 100.0 // p22.2', 'chr6:26271145-26271612 (-) // 100.0 // p22.2', 'chr6:26271145-26271612 (-) // 100.0 // p22.2', 'chr19:4639529-5145579 (+) // 48.53 // p13.3', 'chr17:72920369-72929640 (+) // 100.0 // q25.1'], 'Gene Title': ['histone cluster 1, H3g', 'histone cluster 1, H3g', 'histone cluster 1, H3g', 'tumor necrosis factor, alpha-induced protein 8-like 1', 'otopetrin 2'], 'Gene Symbol': ['HIST1H3G', 'HIST1H3G', 'HIST1H3G', 'TNFAIP8L1', 'OTOP2'], 'Chromosomal Location': ['chr6p22.2', 'chr6p22.2', 'chr6p22.2', 'chr19p13.3', 'chr17q25.1'], 'Unigene Cluster Type': ['full length', 'full length', 'full length', 'full length', 'full length'], 'Ensembl': ['ENSG00000273983 /// OTTHUMG00000014436', 'ENSG00000273983 /// OTTHUMG00000014436', 'ENSG00000273983 /// OTTHUMG00000014436', 'ENSG00000185361 /// OTTHUMG00000182013', 'ENSG00000183034 /// OTTHUMG00000179215'], 'Entrez Gene': ['8355', '8355', '8355', '126282', '92736'], 'SwissProt': ['P68431', 'P68431', 'P68431', 'Q8WVP5', 'Q7RTS6'], 'EC': ['---', '---', '---', '---', '---'], 'OMIM': ['602815', '602815', '602815', '615869', '607827'], 'RefSeq Protein ID': ['NP_003525', 'NP_003525', 'NP_003525', 'NP_001161414 /// NP_689575 /// XP_005259544 /// XP_011525982', 'NP_835454 /// XP_011523781'], 'RefSeq Transcript ID': ['NM_003534', 'NM_003534', 'NM_003534', 'NM_001167942 /// NM_152362 /// XM_005259487 /// XM_011527680', 'NM_178160 /// XM_011525479'], 'Gene Ontology Biological Process': ['0000183 // chromatin silencing at rDNA // traceable author statement /// 0002230 // positive regulation of defense response to virus by host // inferred from mutant phenotype /// 0006325 // chromatin organization // traceable author statement /// 0006334 // nucleosome assembly // inferred from direct assay /// 0006334 // nucleosome assembly // inferred from mutant phenotype /// 0006335 // DNA replication-dependent nucleosome assembly // inferred from direct assay /// 0007264 // small GTPase mediated signal transduction // traceable author statement /// 0007596 // blood coagulation // traceable author statement /// 0010467 // gene expression // traceable author statement /// 0031047 // gene silencing by RNA // traceable author statement /// 0032776 // DNA methylation on cytosine // traceable author statement /// 0040029 // regulation of gene expression, epigenetic // traceable author statement /// 0044267 // cellular protein metabolic process // traceable author statement /// 0045814 // negative regulation of gene expression, epigenetic // traceable author statement /// 0051290 // protein heterotetramerization // inferred from direct assay /// 0060968 // regulation of gene silencing // inferred from direct assay /// 0098792 // xenophagy // inferred from mutant phenotype', '0000183 // chromatin silencing at rDNA // traceable author statement /// 0002230 // positive regulation of defense response to virus by host // inferred from mutant phenotype /// 0006325 // chromatin organization // traceable author statement /// 0006334 // nucleosome assembly // inferred from direct assay /// 0006334 // nucleosome assembly // inferred from mutant phenotype /// 0006335 // DNA replication-dependent nucleosome assembly // inferred from direct assay /// 0007264 // small GTPase mediated signal transduction // traceable author statement /// 0007596 // blood coagulation // traceable author statement /// 0010467 // gene expression // traceable author statement /// 0031047 // gene silencing by RNA // traceable author statement /// 0032776 // DNA methylation on cytosine // traceable author statement /// 0040029 // regulation of gene expression, epigenetic // traceable author statement /// 0044267 // cellular protein metabolic process // traceable author statement /// 0045814 // negative regulation of gene expression, epigenetic // traceable author statement /// 0051290 // protein heterotetramerization // inferred from direct assay /// 0060968 // regulation of gene silencing // inferred from direct assay /// 0098792 // xenophagy // inferred from mutant phenotype', '0000183 // chromatin silencing at rDNA // traceable author statement /// 0002230 // positive regulation of defense response to virus by host // inferred from mutant phenotype /// 0006325 // chromatin organization // traceable author statement /// 0006334 // nucleosome assembly // inferred from direct assay /// 0006334 // nucleosome assembly // inferred from mutant phenotype /// 0006335 // DNA replication-dependent nucleosome assembly // inferred from direct assay /// 0007264 // small GTPase mediated signal transduction // traceable author statement /// 0007596 // blood coagulation // traceable author statement /// 0010467 // gene expression // traceable author statement /// 0031047 // gene silencing by RNA // traceable author statement /// 0032776 // DNA methylation on cytosine // traceable author statement /// 0040029 // regulation of gene expression, epigenetic // traceable author statement /// 0044267 // cellular protein metabolic process // traceable author statement /// 0045814 // negative regulation of gene expression, epigenetic // traceable author statement /// 0051290 // protein heterotetramerization // inferred from direct assay /// 0060968 // regulation of gene silencing // inferred from direct assay /// 0098792 // xenophagy // inferred from mutant phenotype', '0032007 // negative regulation of TOR signaling // not recorded /// 0032007 // negative regulation of TOR signaling // inferred from sequence or structural similarity', '---'], 'Gene Ontology Cellular Component': ['0000228 // nuclear chromosome // inferred from direct assay /// 0000786 // nucleosome // inferred from direct assay /// 0000788 // nuclear nucleosome // inferred from direct assay /// 0005576 // extracellular region // traceable author statement /// 0005634 // nucleus // inferred from direct assay /// 0005654 // nucleoplasm // traceable author statement /// 0005694 // chromosome // inferred from electronic annotation /// 0016020 // membrane // inferred from direct assay /// 0043234 // protein complex // inferred from direct assay /// 0070062 // extracellular exosome // inferred from direct assay', '0000228 // nuclear chromosome // inferred from direct assay /// 0000786 // nucleosome // inferred from direct assay /// 0000788 // nuclear nucleosome // inferred from direct assay /// 0005576 // extracellular region // traceable author statement /// 0005634 // nucleus // inferred from direct assay /// 0005654 // nucleoplasm // traceable author statement /// 0005694 // chromosome // inferred from electronic annotation /// 0016020 // membrane // inferred from direct assay /// 0043234 // protein complex // inferred from direct assay /// 0070062 // extracellular exosome // inferred from direct assay', '0000228 // nuclear chromosome // inferred from direct assay /// 0000786 // nucleosome // inferred from direct assay /// 0000788 // nuclear nucleosome // inferred from direct assay /// 0005576 // extracellular region // traceable author statement /// 0005634 // nucleus // inferred from direct assay /// 0005654 // nucleoplasm // traceable author statement /// 0005694 // chromosome // inferred from electronic annotation /// 0016020 // membrane // inferred from direct assay /// 0043234 // protein complex // inferred from direct assay /// 0070062 // extracellular exosome // inferred from direct assay', '0005737 // cytoplasm // not recorded /// 0005737 // cytoplasm // inferred from sequence or structural similarity', '0016020 // membrane // inferred from electronic annotation /// 0016021 // integral component of membrane // inferred from electronic annotation'], 'Gene Ontology Molecular Function': ['0003677 // DNA binding // inferred from electronic annotation /// 0005515 // protein binding // inferred from physical interaction /// 0042393 // histone binding // inferred from physical interaction /// 0046982 // protein heterodimerization activity // inferred from electronic annotation', '0003677 // DNA binding // inferred from electronic annotation /// 0005515 // protein binding // inferred from physical interaction /// 0042393 // histone binding // inferred from physical interaction /// 0046982 // protein heterodimerization activity // inferred from electronic annotation', '0003677 // DNA binding // inferred from electronic annotation /// 0005515 // protein binding // inferred from physical interaction /// 0042393 // histone binding // inferred from physical interaction /// 0046982 // protein heterodimerization activity // inferred from electronic annotation', '0005515 // protein binding // inferred from physical interaction', '---'], 'Pathway': ['---', '---', '---', '---', '---'], 'InterPro': ['IPR007125 // Histone H2A/H2B/H3 // 9.3E-34 /// IPR007125 // Histone H2A/H2B/H3 // 1.7E-37', 'IPR007125 // Histone H2A/H2B/H3 // 9.3E-34 /// IPR007125 // Histone H2A/H2B/H3 // 1.7E-37', 'IPR007125 // Histone H2A/H2B/H3 // 9.3E-34 /// IPR007125 // Histone H2A/H2B/H3 // 1.7E-37', 'IPR008477 // Protein of unknown function DUF758 // 8.4E-86 /// IPR008477 // Protein of unknown function DUF758 // 6.8E-90', 'IPR004878 // Otopetrin // 9.4E-43 /// IPR004878 // Otopetrin // 9.4E-43 /// IPR004878 // Otopetrin // 9.4E-43 /// IPR004878 // Otopetrin // 3.9E-18 /// IPR004878 // Otopetrin // 3.8E-20 /// IPR004878 // Otopetrin // 5.2E-16'], 'Annotation Description': ['This probe set was annotated using the Matching Probes based pipeline to a Entrez Gene identifier using 4 transcripts. // false // Matching Probes // A', 'This probe set was annotated using the Matching Probes based pipeline to a Entrez Gene identifier using 4 transcripts. // false // Matching Probes // A', 'This probe set was annotated using the Matching Probes based pipeline to a Entrez Gene identifier using 4 transcripts. // false // Matching Probes // A', 'This probe set was annotated using the Matching Probes based pipeline to a Entrez Gene identifier using 9 transcripts. // false // Matching Probes // A', 'This probe set was annotated using the Matching Probes based pipeline to a Entrez Gene identifier using 6 transcripts. // false // Matching Probes // A'], 'Annotation Transcript Cluster': ['ENST00000614378(11),NM_003534(11),OTTHUMT00000040099(11),uc003nhi.3', 'ENST00000614378(11),NM_003534(11),OTTHUMT00000040099(11),uc003nhi.3', 'ENST00000614378(11),NM_003534(11),OTTHUMT00000040099(11),uc003nhi.3', 'BC017672(11),BC044250(9),ENST00000327473(11),ENST00000536716(11),NM_001167942(11),NM_152362(11),OTTHUMT00000458662(11),uc002max.3,uc021une.1', 'ENST00000331427(11),ENST00000580223(11),NM_178160(11),OTTHUMT00000445306(11),uc010wrp.2,XM_011525479(11)'], 'Transcript Assignments': ['ENST00000614378 // ensembl_havana_transcript:known chromosome:GRCh38:6:26269405:26271815:-1 gene:ENSG00000273983 gene_biotype:protein_coding transcript_biotype:protein_coding // ensembl // 11 // --- /// NM_003534 // Homo sapiens histone cluster 1, H3g (HIST1H3G), mRNA. // refseq // 11 // --- /// OTTHUMT00000040099 // otter:known chromosome:VEGA61:6:26269405:26271815:-1 gene:OTTHUMG00000014436 gene_biotype:protein_coding transcript_biotype:protein_coding // vega // 11 // --- /// uc003nhi.3 // --- // ucsc_genes // 11 // ---', 'ENST00000614378 // ensembl_havana_transcript:known chromosome:GRCh38:6:26269405:26271815:-1 gene:ENSG00000273983 gene_biotype:protein_coding transcript_biotype:protein_coding // ensembl // 11 // --- /// GENSCAN00000029819 // cdna:genscan chromosome:GRCh38:6:26270974:26271384:-1 transcript_biotype:protein_coding // ensembl // 11 // --- /// NM_003534 // Homo sapiens histone cluster 1, H3g (HIST1H3G), mRNA. // refseq // 11 // --- /// OTTHUMT00000040099 // otter:known chromosome:VEGA61:6:26269405:26271815:-1 gene:OTTHUMG00000014436 gene_biotype:protein_coding transcript_biotype:protein_coding // vega // 11 // --- /// uc003nhi.3 // --- // ucsc_genes // 11 // ---', 'ENST00000614378 // ensembl_havana_transcript:known chromosome:GRCh38:6:26269405:26271815:-1 gene:ENSG00000273983 gene_biotype:protein_coding transcript_biotype:protein_coding // ensembl // 11 // --- /// NM_003534 // Homo sapiens histone cluster 1, H3g (HIST1H3G), mRNA. // refseq // 11 // --- /// OTTHUMT00000040099 // otter:known chromosome:VEGA61:6:26269405:26271815:-1 gene:OTTHUMG00000014436 gene_biotype:protein_coding transcript_biotype:protein_coding // vega // 11 // --- /// uc003nhi.3 // --- // ucsc_genes // 11 // ---', 'BC017672 // Homo sapiens tumor necrosis factor, alpha-induced protein 8-like 1, mRNA (cDNA clone MGC:17791 IMAGE:3885999), complete cds. // gb // 11 // --- /// BC044250 // accn=BC044250 class=mRNAlike lncRNA name=Human lncRNA ref=JounralRNA transcriptId=673 cpcScore=-0.1526100 cnci=-0.1238602 // noncode // 9 // --- /// BC044250 // Homo sapiens tumor necrosis factor, alpha-induced protein 8-like 1, mRNA (cDNA clone IMAGE:5784807). // gb // 9 // --- /// ENST00000327473 // ensembl_havana_transcript:known chromosome:GRCh38:19:4639518:4655568:1 gene:ENSG00000185361 gene_biotype:protein_coding transcript_biotype:protein_coding // ensembl // 11 // --- /// ENST00000536716 // ensembl:known chromosome:GRCh38:19:4640017:4655568:1 gene:ENSG00000185361 gene_biotype:protein_coding transcript_biotype:protein_coding // ensembl // 11 // --- /// NM_001167942 // Homo sapiens tumor necrosis factor, alpha-induced protein 8-like 1 (TNFAIP8L1), transcript variant 1, mRNA. // refseq // 11 // --- /// NM_152362 // Homo sapiens tumor necrosis factor, alpha-induced protein 8-like 1 (TNFAIP8L1), transcript variant 2, mRNA. // refseq // 11 // --- /// NONHSAT060631 // Non-coding transcript identified by NONCODE: Exonic // noncode // 9 // --- /// OTTHUMT00000458662 // otter:known chromosome:VEGA61:19:4639518:4655568:1 gene:OTTHUMG00000182013 gene_biotype:protein_coding transcript_biotype:protein_coding // vega // 11 // --- /// uc002max.3 // --- // ucsc_genes // 11 // --- /// uc021une.1 // --- // ucsc_genes // 11 // ---', 'ENST00000331427 // ensembl:known chromosome:GRCh38:17:74924275:74933911:1 gene:ENSG00000183034 gene_biotype:protein_coding transcript_biotype:protein_coding // ensembl // 11 // --- /// ENST00000580223 // havana:known chromosome:GRCh38:17:74924603:74933912:1 gene:ENSG00000183034 gene_biotype:protein_coding transcript_biotype:protein_coding // ensembl // 11 // --- /// GENSCAN00000013715 // cdna:genscan chromosome:GRCh38:17:74924633:74933545:1 transcript_biotype:protein_coding // ensembl // 11 // --- /// NM_178160 // Homo sapiens otopetrin 2 (OTOP2), mRNA. // refseq // 11 // --- /// OTTHUMT00000445306 // otter:known chromosome:VEGA61:17:74924603:74933912:1 gene:OTTHUMG00000179215 gene_biotype:protein_coding transcript_biotype:protein_coding // vega // 11 // --- /// uc010wrp.2 // --- // ucsc_genes // 11 // --- /// XM_011525479 // PREDICTED: Homo sapiens otopetrin 2 (OTOP2), transcript variant X1, mRNA. // refseq // 11 // ---'], 'Annotation Notes': ['---', '---', 'GENSCAN00000029819 // ensembl // 4 // Cross Hyb Matching Probes', '---', '---'], 'SPOT_ID': [nan, nan, nan, nan, nan]}\n",
      "\n",
      "Searching for platform information in SOFT file:\n",
      "Platform ID not found in first 100 lines\n",
      "\n",
      "Searching for gene symbol information in SOFT file:\n",
      "Found references to gene symbols:\n",
      "#Gene Symbol =\n",
      "ID\tGeneChip Array\tSpecies Scientific Name\tAnnotation Date\tSequence Type\tSequence Source\tTranscript ID(Array Design)\tTarget Description\tGB_ACC\tGI\tRepresentative Public ID\tArchival UniGene Cluster\tUniGene ID\tGenome Version\tAlignments\tGene Title\tGene Symbol\tChromosomal Location\tUnigene Cluster Type\tEnsembl\tEntrez Gene\tSwissProt\tEC\tOMIM\tRefSeq Protein ID\tRefSeq Transcript ID\tGene Ontology Biological Process\tGene Ontology Cellular Component\tGene Ontology Molecular Function\tPathway\tInterPro\tAnnotation Description\tAnnotation Transcript Cluster\tTranscript Assignments\tAnnotation Notes\tSPOT_ID\n",
      "\n",
      "Checking for additional annotation files in the directory:\n",
      "[]\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. Analyze the gene annotation dataframe to identify which columns contain the gene identifiers and gene symbols\n",
    "print(\"\\nGene annotation preview:\")\n",
    "print(f\"Columns in gene annotation: {gene_annotation.columns.tolist()}\")\n",
    "print(preview_df(gene_annotation, n=5))\n",
    "\n",
    "# Let's look for platform information in the SOFT file to understand the annotation better\n",
    "print(\"\\nSearching for platform information in SOFT file:\")\n",
    "with gzip.open(soft_file, 'rt') as f:\n",
    "    for i, line in enumerate(f):\n",
    "        if '!Series_platform_id' in line:\n",
    "            print(line.strip())\n",
    "            break\n",
    "        if i > 100:  # Limit search to first 100 lines\n",
    "            print(\"Platform ID not found in first 100 lines\")\n",
    "            break\n",
    "\n",
    "# Check if the SOFT file includes any reference to gene symbols\n",
    "print(\"\\nSearching for gene symbol information in SOFT file:\")\n",
    "with gzip.open(soft_file, 'rt') as f:\n",
    "    gene_symbol_lines = []\n",
    "    for i, line in enumerate(f):\n",
    "        if 'GENE_SYMBOL' in line or 'gene_symbol' in line.lower() or 'symbol' in line.lower():\n",
    "            gene_symbol_lines.append(line.strip())\n",
    "        if i > 1000 and len(gene_symbol_lines) > 0:  # Limit search but ensure we found something\n",
    "            break\n",
    "    \n",
    "    if gene_symbol_lines:\n",
    "        print(\"Found references to gene symbols:\")\n",
    "        for line in gene_symbol_lines[:5]:  # Show just first 5 matches\n",
    "            print(line)\n",
    "    else:\n",
    "        print(\"No explicit gene symbol references found in first 1000 lines\")\n",
    "\n",
    "# Look for alternative annotation files or references in the directory\n",
    "print(\"\\nChecking for additional annotation files in the directory:\")\n",
    "all_files = os.listdir(in_cohort_dir)\n",
    "print([f for f in all_files if 'annotation' in f.lower() or 'platform' in f.lower() or 'gpl' in f.lower()])\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ed585ccc",
   "metadata": {},
   "source": [
    "### Step 6: Gene Identifier Mapping"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "f1b59784",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T07:06:14.929287Z",
     "iopub.status.busy": "2025-03-25T07:06:14.929170Z",
     "iopub.status.idle": "2025-03-25T07:06:16.692994Z",
     "shell.execute_reply": "2025-03-25T07:06:16.692337Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene mapping dataframe shape: (49372, 2)\n",
      "First few rows of gene mapping:\n",
      "              ID       Gene\n",
      "0    11715100_at   HIST1H3G\n",
      "1  11715101_s_at   HIST1H3G\n",
      "2  11715102_x_at   HIST1H3G\n",
      "3  11715103_x_at  TNFAIP8L1\n",
      "4  11715104_s_at      OTOP2\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Converted gene expression data shape: (19963, 93)\n",
      "First few gene symbols in the mapped gene data:\n",
      "Index(['A1BG', 'A1CF', 'A2M', 'A2ML1', 'A3GALT2', 'A4GALT', 'A4GNT', 'AAAS',\n",
      "       'AACS', 'AACSP1'],\n",
      "      dtype='object', name='Gene')\n",
      "After normalization, gene expression data shape: (19758, 93)\n",
      "First few normalized gene symbols:\n",
      "Index(['A1BG', 'A1CF', 'A2M', 'A2ML1', 'A3GALT2', 'A4GALT', 'A4GNT', 'AAAS',\n",
      "       'AACS', 'AACSP1'],\n",
      "      dtype='object', name='Gene')\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene expression data saved to ../../output/preprocess/Cardiovascular_Disease/gene_data/GSE190042.csv\n"
     ]
    }
   ],
   "source": [
    "# 1. Identify the columns for gene identifiers and gene symbols in the annotation dataframe\n",
    "probe_id_column = 'ID'  # The same ID format appears in both gene_data.index and gene_annotation['ID']\n",
    "gene_symbol_column = 'Gene Symbol'  # Contains standard gene symbols like HIST1H3G, TNFAIP8L1, etc.\n",
    "\n",
    "# 2. Get gene mapping dataframe\n",
    "gene_mapping = get_gene_mapping(gene_annotation, probe_id_column, gene_symbol_column)\n",
    "print(f\"Gene mapping dataframe shape: {gene_mapping.shape}\")\n",
    "print(\"First few rows of gene mapping:\")\n",
    "print(gene_mapping.head())\n",
    "\n",
    "# 3. Apply gene mapping to convert probe-level data to gene expression data\n",
    "gene_data = apply_gene_mapping(gene_data, gene_mapping)\n",
    "print(f\"Converted gene expression data shape: {gene_data.shape}\")\n",
    "print(\"First few gene symbols in the mapped gene data:\")\n",
    "print(gene_data.index[:10])\n",
    "\n",
    "# Normalize gene symbols to ensure consistent format\n",
    "gene_data = normalize_gene_symbols_in_index(gene_data)\n",
    "print(f\"After normalization, gene expression data shape: {gene_data.shape}\")\n",
    "print(\"First few normalized gene symbols:\")\n",
    "print(gene_data.index[:10])\n",
    "\n",
    "# Save the gene expression data to the specified output file\n",
    "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
    "gene_data.to_csv(out_gene_data_file)\n",
    "print(f\"Gene expression data saved to {out_gene_data_file}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "30195319",
   "metadata": {},
   "source": [
    "### Step 7: Data Normalization and Linking"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "8d6ce5b0",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T07:06:16.694509Z",
     "iopub.status.busy": "2025-03-25T07:06:16.694375Z",
     "iopub.status.idle": "2025-03-25T07:06:17.028885Z",
     "shell.execute_reply": "2025-03-25T07:06:17.028290Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Clinical data shape: (12, 94)\n",
      "Clinical data columns: Index(['!Sample_geo_accession', 'GSM5712490', 'GSM5712491', 'GSM5712492',\n",
      "       'GSM5712493'],\n",
      "      dtype='object')\n",
      "Clinical data index: RangeIndex(start=0, stop=5, step=1)\n",
      "Sample characteristics dictionary:\n",
      "Row 0: ['batch: Batch 1', 'batch: Batch 3', 'batch: Batch 2', 'batch: Batch 4']\n",
      "Row 1: ['gender: F', 'gender: M']\n",
      "Row 2: ['age: 72', 'age: 77', 'age: 56', 'age: 67', 'age: 55']\n",
      "Row 3: ['time at diagnosis: 43355', 'time at diagnosis: 43341', 'time at diagnosis: 43441', 'time at diagnosis: 43439', 'time at diagnosis: 43516']\n",
      "Row 4: ['type: IgA-k', 'type: IgG-K', 'type: Lambda', 'type: IgA-L', 'type: kappa']\n",
      "Row 5: ['riss: I', 'riss: II', 'riss: III', 'treatment strategy: PCD*1']\n",
      "Row 6: ['treatment strategy: RD*4 RCD*10,Rd-R maintenance', 'treatment strategy: VTD*5, ITD*2, VRD*1', 'treatment strategy: BCDT*4 ,BCD*7,RCD*8,R maintenance', 'treatment strategy: TD*1,PTD*2 VRD*2 ASCT,VR maintenance', 'treatment strategy: PDD*1,V-DEAP*2,VT-DEAP*2,ASCT, R maintenance']\n",
      "Row 7: ['best respose: CR', 'best respose: PR', 'best respose: CR MRD+', 'best respose: MR', 'best respose: VGPR MRD+']\n",
      "Row 8: ['chromosome: 46 xx[20]/56,xx,+x,+4,+5,+10,+10,+11,+12,+19,+20,+22[1]', 'chromosome: ND', 'chromosome: 46,XY[20]', 'chromosome: 46,XY[8]', 'chromosome: 46,XX[20]']\n",
      "Row 9: ['FISH: negtive', 'FISH: ND', 'FISH: 1q21+,IGH-', 'FISH: 1q21+,IGH/FGFR3', 'FISH: MAF-,CCND1+']\n",
      "Row 10: ['pfs1(months): 32', nan, 'pfs1(months): 21', 'os(months): 5', 'pfs1(months): 20']\n",
      "Row 11: [nan, 'os(months): 29', 'os(months): 5', 'os(months): 2', 'os(months): 11']\n",
      "Clinical features shape: (1, 93)\n",
      "Clinical features preview:\n",
      "{'GSM5712490': [nan], 'GSM5712491': [nan], 'GSM5712492': [nan], 'GSM5712493': [nan], 'GSM5712494': [nan], 'GSM5712495': [nan], 'GSM5712496': [nan], 'GSM5712497': [nan], 'GSM5712498': [nan], 'GSM5712499': [nan], 'GSM5712500': [nan], 'GSM5712501': [nan], 'GSM5712502': [nan], 'GSM5712503': [nan], 'GSM5712504': [nan], 'GSM5712505': [nan], 'GSM5712506': [nan], 'GSM5712507': [nan], 'GSM5712508': [nan], 'GSM5712509': [nan], 'GSM5712510': [nan], 'GSM5712511': [nan], 'GSM5712512': [nan], 'GSM5712513': [nan], 'GSM5712514': [nan], 'GSM5712515': [nan], 'GSM5712516': [nan], 'GSM5712517': [nan], 'GSM5712518': [nan], 'GSM5712519': [nan], 'GSM5712520': [nan], 'GSM5712521': [nan], 'GSM5712522': [nan], 'GSM5712523': [nan], 'GSM5712524': [nan], 'GSM5712525': [nan], 'GSM5712526': [nan], 'GSM5712527': [nan], 'GSM5712528': [nan], 'GSM5712529': [nan], 'GSM5712530': [nan], 'GSM5712531': [nan], 'GSM5712532': [nan], 'GSM5712533': [nan], 'GSM5712534': [nan], 'GSM5712535': [nan], 'GSM5712536': [nan], 'GSM5712537': [nan], 'GSM5712538': [nan], 'GSM5712539': [nan], 'GSM5712540': [nan], 'GSM5712541': [nan], 'GSM5712542': [nan], 'GSM5712543': [nan], 'GSM5712544': [nan], 'GSM5712545': [nan], 'GSM5712546': [nan], 'GSM5712547': [nan], 'GSM5712548': [nan], 'GSM5712549': [nan], 'GSM5712550': [nan], 'GSM5712551': [nan], 'GSM5712552': [nan], 'GSM5712553': [nan], 'GSM5712554': [nan], 'GSM5712555': [nan], 'GSM5712556': [nan], 'GSM5712557': [nan], 'GSM5712558': [nan], 'GSM5712559': [nan], 'GSM5712560': [nan], 'GSM5712561': [nan], 'GSM5712562': [nan], 'GSM5712563': [nan], 'GSM5712564': [nan], 'GSM5712565': [nan], 'GSM5712566': [nan], 'GSM5712567': [nan], 'GSM5712568': [nan], 'GSM5712569': [nan], 'GSM5712570': [nan], 'GSM5712571': [nan], 'GSM5712572': [nan], 'GSM5712573': [nan], 'GSM5712574': [nan], 'GSM5712575': [nan], 'GSM5712576': [nan], 'GSM5712577': [nan], 'GSM5712578': [nan], 'GSM5712579': [nan], 'GSM5712580': [nan], 'GSM5712581': [nan], 'GSM5712582': [nan]}\n",
      "Clinical data saved to ../../output/preprocess/Cardiovascular_Disease/clinical_data/GSE190042.csv\n",
      "Linked data shape: (93, 19759)\n",
      "Linked data preview (first 5 rows, 5 columns):\n",
      "            Cardiovascular_Disease      A1BG      A1CF       A2M     A2ML1\n",
      "GSM5712490                     NaN  4.833014  5.632894  5.809853  4.576426\n",
      "GSM5712491                     NaN  4.952351  5.491876  6.800766  4.744677\n",
      "GSM5712492                     NaN  5.425290  5.734211  5.038784  4.659546\n",
      "GSM5712493                     NaN  5.064699  5.515223  4.354973  3.889619\n",
      "GSM5712494                     NaN  6.160388  5.677337  3.747210  4.376735\n",
      "Linked data shape after handling missing values: (0, 1)\n",
      "Quartiles for 'Cardiovascular_Disease':\n",
      "  25%: nan\n",
      "  50% (Median): nan\n",
      "  75%: nan\n",
      "Min: nan\n",
      "Max: nan\n",
      "The distribution of the feature 'Cardiovascular_Disease' in this dataset is fine.\n",
      "\n",
      "Abnormality detected in the cohort: GSE190042. Preprocessing failed.\n",
      "Dataset deemed not usable for associative studies. Linked data not saved.\n"
     ]
    }
   ],
   "source": [
    "# 1. Gene symbols were already normalized in step 6\n",
    "\n",
    "# 2. Load the clinical data (from scratch to ensure we have the correct structure)\n",
    "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\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",
    "# Print clinical data structure to better understand it\n",
    "print(\"Clinical data shape:\", clinical_data.shape)\n",
    "print(\"Clinical data columns:\", clinical_data.columns[:5]) \n",
    "print(\"Clinical data index:\", clinical_data.index[:5])\n",
    "\n",
    "# Get sample characteristics dictionary to confirm the structure\n",
    "sample_characteristics_dict = get_unique_values_by_row(clinical_data)\n",
    "print(\"Sample characteristics dictionary:\")\n",
    "for key, values in sample_characteristics_dict.items():\n",
    "    print(f\"Row {key}: {values[:5]}\")\n",
    "\n",
    "# Define conversion functions that match the actual data in step 2\n",
    "def convert_trait(value: str) -> int:\n",
    "    \"\"\"Convert disease information to binary trait values for Cardiovascular Disease.\"\"\"\n",
    "    if value is None or pd.isna(value):\n",
    "        return None\n",
    "    \n",
    "    # Extract the value after the colon\n",
    "    if isinstance(value, str) and \":\" in value:\n",
    "        value = value.split(\":\", 1)[1].strip()\n",
    "    \n",
    "    # From step 2 analysis: HCC and CCC considered higher cardiovascular risk\n",
    "    if isinstance(value, str) and value.upper() in [\"HCC\", \"CCC\"]:\n",
    "        return 1  # These liver diseases often have vascular involvement\n",
    "    elif isinstance(value, str) and value.upper() in [\"CRC MET\", \"OTHER\"]:\n",
    "        return 0  # Less clear cardiovascular involvement\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "# Create empty placeholder functions since age and gender aren't available\n",
    "def convert_age(value: str) -> None:\n",
    "    return None\n",
    "\n",
    "def convert_gender(value: str) -> None:\n",
    "    return None\n",
    "\n",
    "# Define the correct row for trait based on step 2 (disease information is in row 2)\n",
    "trait_row = 2\n",
    "age_row = None  # No age data available\n",
    "gender_row = None  # No gender data available\n",
    "\n",
    "# Try to extract clinical features with safe error handling\n",
    "try:\n",
    "    clinical_features = geo_select_clinical_features(\n",
    "        clinical_df=clinical_data, \n",
    "        trait=trait, \n",
    "        trait_row=trait_row,\n",
    "        convert_trait=convert_trait,\n",
    "        age_row=age_row,\n",
    "        convert_age=convert_age,\n",
    "        gender_row=gender_row,\n",
    "        convert_gender=convert_gender\n",
    "    )\n",
    "    \n",
    "    print(f\"Clinical features shape: {clinical_features.shape}\")\n",
    "    print(\"Clinical features preview:\")\n",
    "    print(preview_df(clinical_features))\n",
    "    \n",
    "    # Save the clinical data\n",
    "    os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
    "    clinical_features.to_csv(out_clinical_data_file)\n",
    "    print(f\"Clinical data saved to {out_clinical_data_file}\")\n",
    "    \n",
    "    # 3. Link clinical and genetic data\n",
    "    linked_data = geo_link_clinical_genetic_data(clinical_features, gene_data)\n",
    "    print(f\"Linked data shape: {linked_data.shape}\")\n",
    "    print(\"Linked data preview (first 5 rows, 5 columns):\")\n",
    "    print(linked_data.iloc[:5, :5] if linked_data.shape[0] > 0 and linked_data.shape[1] > 5 else linked_data)\n",
    "    \n",
    "    # 4. Handle missing values\n",
    "    linked_data_clean = handle_missing_values(linked_data, trait)\n",
    "    print(f\"Linked data shape after handling missing values: {linked_data_clean.shape}\")\n",
    "    \n",
    "    # 5. Check for bias in the dataset\n",
    "    is_biased, linked_data_clean = judge_and_remove_biased_features(linked_data_clean, trait)\n",
    "    \n",
    "    # 6. Conduct final quality validation\n",
    "    note = \"Dataset contains gene expression data from liver samples studying ischemia-reperfusion injury in patients with various liver diseases.\"\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_biased,\n",
    "        df=linked_data_clean,\n",
    "        note=note\n",
    "    )\n",
    "    \n",
    "    # 7. Save the linked data if it's usable\n",
    "    if is_usable:\n",
    "        os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n",
    "        linked_data_clean.to_csv(out_data_file, index=True)\n",
    "        print(f\"Linked data saved to {out_data_file}\")\n",
    "    else:\n",
    "        print(\"Dataset deemed not usable for associative studies. Linked data not saved.\")\n",
    "        \n",
    "except Exception as e:\n",
    "    print(f\"Error processing clinical data: {e}\")\n",
    "    # If clinical processing fails, we should still validate the dataset status\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=False,  # Mark as false since we couldn't process it\n",
    "        is_biased=True,  # Set to True to ensure it's not marked usable\n",
    "        df=pd.DataFrame(),  # Empty dataframe since processing failed\n",
    "        note=\"Failed to process clinical data due to structural issues with the dataset.\"\n",
    "    )\n",
    "    print(\"Dataset validation completed with error status.\")"
   ]
  }
 ],
 "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
}