File size: 33,944 Bytes
e4183cf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "5d925014",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:31:53.915251Z",
     "iopub.status.busy": "2025-03-25T08:31:53.914941Z",
     "iopub.status.idle": "2025-03-25T08:31:54.083683Z",
     "shell.execute_reply": "2025-03-25T08:31:54.083335Z"
    }
   },
   "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 = \"Crohns_Disease\"\n",
    "cohort = \"GSE123086\"\n",
    "\n",
    "# Input paths\n",
    "in_trait_dir = \"../../input/GEO/Crohns_Disease\"\n",
    "in_cohort_dir = \"../../input/GEO/Crohns_Disease/GSE123086\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/Crohns_Disease/GSE123086.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/Crohns_Disease/gene_data/GSE123086.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/Crohns_Disease/clinical_data/GSE123086.csv\"\n",
    "json_path = \"../../output/preprocess/Crohns_Disease/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b178ae1b",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "da850c1f",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:31:54.085116Z",
     "iopub.status.busy": "2025-03-25T08:31:54.084957Z",
     "iopub.status.idle": "2025-03-25T08:31:54.313403Z",
     "shell.execute_reply": "2025-03-25T08:31:54.312963Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Background Information:\n",
      "!Series_title\t\"A validated single-cell-based strategy to identify diagnostic and therapeutic targets in complex diseases [study of 13 diseases]\"\n",
      "!Series_summary\t\"We conducted prospective clinical studies to validate the importance of CD4+ T cells in 13 diseases from the following ICD-10-CM chapters: Neoplasms (breast cancer, chronic lymphocytic leukemia); endocrine, nutritional and metabolic diseases (type I diabetes, obesity); diseases of the circulatory system (atherosclerosis); diseases of the respiratory system (acute tonsillitis, influenza, seasonal allergic rhinitis, asthma); diseases of the digestive system (Crohn’s disease [CD], ulcerative colitis [UC]); and diseases of the skin and subcutaneous tissue (atopic eczema, psoriatic diseases).\"\n",
      "!Series_summary\t\"Study participants were recruited by clinical specialists based on diagnostic criteria defined by organizations representing each specialist’s discipline. Age and gender matched healthy controls (n = 127 and 39, respectively) were recruited in the Southeast region of Sweden from outpatient clinics at the University Hospital, Linköping; Ryhov County Hospital, Jönköping, a primary health care center in Jönköping; and a medical specialist unit for children in Värnamo. Study participants represented both urban and rural populations with an age range of 8–94 years. Patients with type I diabetes and obesity had an age range of 8–18 years. 12 patients had more than one diagnosis.\"\n",
      "!Series_overall_design\t\"Total RNA was extracted using the AllPrep DNA/RNA Micro kit (Qiagen, Hilden, Germany; cat. no. 80284) according to the manufacturer’s instructions. RNA concentration and integrity were evaluated using the Agilent RNA 6000 Nano Kit (Agilent Technologies, Santa Clara, California, USA; cat. no. 5067-1511) on an Agilent 2100 Bioanalyzer (Agilent Technologies, Santa Clara, California, USA). Microarrays were then further computationally processed as described in One-Color Microarray-Based Gene Expression Analysis Low Input Quick Amp Labeling protocol (Agilent Technologies, Santa Clara, California, USA).\"\n",
      "Sample Characteristics Dictionary:\n",
      "{0: ['cell type: CD4+ T cells'], 1: ['primary diagnosis: ASTHMA', 'primary diagnosis: ATHEROSCLEROSIS', 'primary diagnosis: BREAST_CANCER', 'primary diagnosis: CHRONIC_LYMPHOCYTIC_LEUKEMIA', 'primary diagnosis: CROHN_DISEASE', 'primary diagnosis: ATOPIC_ECZEMA', 'primary diagnosis: HEALTHY_CONTROL', 'primary diagnosis: INFLUENZA', 'primary diagnosis: OBESITY', 'primary diagnosis: PSORIASIS', 'primary diagnosis: SEASONAL_ALLERGIC_RHINITIS', 'primary diagnosis: TYPE_1_DIABETES', 'primary diagnosis: ACUTE_TONSILLITIS', 'primary diagnosis: ULCERATIVE_COLITIS'], 2: ['Sex: Male', 'diagnosis2: ATOPIC_ECZEMA', 'Sex: Female', 'diagnosis2: ATHEROSCLEROSIS', 'diagnosis2: ASTHMA_OBESITY', 'diagnosis2: ASTHMA', 'diagnosis2: ASTMHA_SEASONAL_ALLERGIC_RHINITIS', 'diagnosis2: OBESITY'], 3: ['age: 56', 'Sex: Male', 'age: 20', 'age: 51', 'age: 37', 'age: 61', 'age: 31', 'age: 41', 'age: 80', 'age: 53', 'age: 73', 'age: 60', 'age: 76', 'age: 77', 'age: 74', 'age: 69', 'age: 81', 'age: 70', 'age: 82', 'age: 67', 'age: 78', 'age: 72', 'age: 66', 'age: 36', 'age: 45', 'age: 65', 'age: 48', 'age: 50', 'age: 24', 'age: 42'], 4: [nan, 'age: 63', 'age: 74', 'age: 49', 'age: 60', 'age: 68', 'age: 38', 'age: 16', 'age: 12', 'age: 27']}\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": "e5154371",
   "metadata": {},
   "source": [
    "### Step 2: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "e7bb312b",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:31:54.314843Z",
     "iopub.status.busy": "2025-03-25T08:31:54.314732Z",
     "iopub.status.idle": "2025-03-25T08:31:54.337797Z",
     "shell.execute_reply": "2025-03-25T08:31:54.337511Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Preview of selected clinical features:\n",
      "{'GSM3494884': [nan, 56.0, 1.0], 'GSM3494885': [nan, nan, nan], 'GSM3494886': [nan, 20.0, 0.0], 'GSM3494887': [nan, 51.0, 0.0], 'GSM3494888': [nan, 37.0, 1.0], 'GSM3494889': [nan, 61.0, 1.0], 'GSM3494890': [nan, nan, nan], 'GSM3494891': [nan, 31.0, 1.0], 'GSM3494892': [nan, 56.0, 0.0], 'GSM3494893': [nan, 41.0, 0.0], 'GSM3494894': [nan, 61.0, 0.0], 'GSM3494895': [nan, nan, nan], 'GSM3494896': [nan, 80.0, 1.0], 'GSM3494897': [nan, 53.0, 1.0], 'GSM3494898': [nan, 61.0, 1.0], 'GSM3494899': [nan, 73.0, 1.0], 'GSM3494900': [nan, 60.0, 1.0], 'GSM3494901': [nan, 76.0, 1.0], 'GSM3494902': [nan, 77.0, 0.0], 'GSM3494903': [nan, 74.0, 0.0], 'GSM3494904': [nan, 69.0, 1.0], 'GSM3494905': [nan, 77.0, 0.0], 'GSM3494906': [nan, 81.0, 0.0], 'GSM3494907': [nan, 70.0, 0.0], 'GSM3494908': [nan, 82.0, 0.0], 'GSM3494909': [nan, 69.0, 0.0], 'GSM3494910': [nan, 82.0, 0.0], 'GSM3494911': [nan, 67.0, 0.0], 'GSM3494912': [nan, 67.0, 0.0], 'GSM3494913': [nan, 78.0, 0.0], 'GSM3494914': [nan, 67.0, 0.0], 'GSM3494915': [nan, 74.0, 1.0], 'GSM3494916': [nan, nan, nan], 'GSM3494917': [nan, 51.0, 1.0], 'GSM3494918': [nan, 72.0, 1.0], 'GSM3494919': [nan, 66.0, 1.0], 'GSM3494920': [nan, 80.0, 0.0], 'GSM3494921': [1.0, 36.0, 1.0], 'GSM3494922': [1.0, 67.0, 0.0], 'GSM3494923': [1.0, 31.0, 0.0], 'GSM3494924': [1.0, 31.0, 0.0], 'GSM3494925': [1.0, 45.0, 0.0], 'GSM3494926': [1.0, 56.0, 0.0], 'GSM3494927': [1.0, 65.0, 0.0], 'GSM3494928': [1.0, 53.0, 0.0], 'GSM3494929': [1.0, 48.0, 0.0], 'GSM3494930': [1.0, 50.0, 0.0], 'GSM3494931': [1.0, 76.0, 1.0], 'GSM3494932': [nan, nan, nan], 'GSM3494933': [nan, 24.0, 0.0], 'GSM3494934': [nan, 42.0, 0.0], 'GSM3494935': [nan, 76.0, 1.0], 'GSM3494936': [nan, 22.0, 1.0], 'GSM3494937': [nan, nan, nan], 'GSM3494938': [nan, 23.0, 0.0], 'GSM3494939': [0.0, 34.0, 1.0], 'GSM3494940': [0.0, 43.0, 1.0], 'GSM3494941': [0.0, 47.0, 1.0], 'GSM3494942': [0.0, 24.0, 0.0], 'GSM3494943': [0.0, 55.0, 1.0], 'GSM3494944': [0.0, 48.0, 1.0], 'GSM3494945': [0.0, 58.0, 1.0], 'GSM3494946': [0.0, 30.0, 0.0], 'GSM3494947': [0.0, 28.0, 1.0], 'GSM3494948': [0.0, 41.0, 0.0], 'GSM3494949': [0.0, 63.0, 1.0], 'GSM3494950': [0.0, 55.0, 0.0], 'GSM3494951': [0.0, 55.0, 0.0], 'GSM3494952': [0.0, 67.0, 1.0], 'GSM3494953': [0.0, 47.0, 0.0], 'GSM3494954': [0.0, 46.0, 0.0], 'GSM3494955': [0.0, 49.0, 1.0], 'GSM3494956': [0.0, 23.0, 1.0], 'GSM3494957': [0.0, 68.0, 1.0], 'GSM3494958': [0.0, 39.0, 1.0], 'GSM3494959': [0.0, 24.0, 1.0], 'GSM3494960': [0.0, 36.0, 0.0], 'GSM3494961': [0.0, 58.0, 0.0], 'GSM3494962': [0.0, 38.0, 0.0], 'GSM3494963': [0.0, 27.0, 0.0], 'GSM3494964': [0.0, 67.0, 0.0], 'GSM3494965': [0.0, 61.0, 1.0], 'GSM3494966': [0.0, 69.0, 1.0], 'GSM3494967': [0.0, 63.0, 1.0], 'GSM3494968': [0.0, 60.0, 0.0], 'GSM3494969': [0.0, 17.0, 1.0], 'GSM3494970': [0.0, 10.0, 0.0], 'GSM3494971': [0.0, 9.0, 1.0], 'GSM3494972': [0.0, 13.0, 0.0], 'GSM3494973': [0.0, 10.0, 1.0], 'GSM3494974': [0.0, 13.0, 0.0], 'GSM3494975': [0.0, 15.0, 1.0], 'GSM3494976': [0.0, 12.0, 1.0], 'GSM3494977': [0.0, 13.0, 1.0], 'GSM3494978': [nan, 81.0, 0.0], 'GSM3494979': [nan, 94.0, 0.0], 'GSM3494980': [nan, 51.0, 1.0], 'GSM3494981': [nan, 40.0, 1.0], 'GSM3494982': [nan, nan, nan], 'GSM3494983': [nan, 97.0, 1.0], 'GSM3494984': [nan, 23.0, 1.0], 'GSM3494985': [nan, 93.0, 0.0], 'GSM3494986': [nan, 58.0, 1.0], 'GSM3494987': [nan, 28.0, 0.0], 'GSM3494988': [nan, 54.0, 1.0], 'GSM3494989': [nan, 15.0, 1.0], 'GSM3494990': [nan, 8.0, 1.0], 'GSM3494991': [nan, 11.0, 1.0], 'GSM3494992': [nan, 12.0, 1.0], 'GSM3494993': [nan, 8.0, 0.0], 'GSM3494994': [nan, 14.0, 1.0], 'GSM3494995': [nan, 8.0, 0.0], 'GSM3494996': [nan, 10.0, 1.0], 'GSM3494997': [nan, 14.0, 1.0], 'GSM3494998': [nan, 13.0, 1.0], 'GSM3494999': [nan, 40.0, 0.0], 'GSM3495000': [nan, 52.0, 0.0], 'GSM3495001': [nan, 42.0, 0.0], 'GSM3495002': [nan, 29.0, 0.0], 'GSM3495003': [nan, 43.0, 0.0], 'GSM3495004': [nan, 41.0, 0.0], 'GSM3495005': [nan, 54.0, 1.0], 'GSM3495006': [nan, 42.0, 1.0], 'GSM3495007': [nan, 49.0, 1.0], 'GSM3495008': [nan, 45.0, 0.0], 'GSM3495009': [nan, 56.0, 1.0], 'GSM3495010': [nan, 64.0, 0.0], 'GSM3495011': [nan, 71.0, 0.0], 'GSM3495012': [nan, 48.0, 0.0], 'GSM3495013': [nan, 20.0, 1.0], 'GSM3495014': [nan, 53.0, 0.0], 'GSM3495015': [nan, 32.0, 0.0], 'GSM3495016': [nan, 26.0, 0.0], 'GSM3495017': [nan, 28.0, 0.0], 'GSM3495018': [nan, 47.0, 0.0], 'GSM3495019': [nan, 24.0, 0.0], 'GSM3495020': [nan, 48.0, 0.0], 'GSM3495021': [nan, nan, nan], 'GSM3495022': [nan, 19.0, 0.0], 'GSM3495023': [nan, 41.0, 0.0], 'GSM3495024': [nan, 38.0, 0.0], 'GSM3495025': [nan, nan, nan], 'GSM3495026': [nan, 15.0, 0.0], 'GSM3495027': [nan, 12.0, 1.0], 'GSM3495028': [nan, 13.0, 0.0], 'GSM3495029': [nan, nan, nan], 'GSM3495030': [nan, 11.0, 1.0], 'GSM3495031': [nan, nan, nan], 'GSM3495032': [nan, 16.0, 1.0], 'GSM3495033': [nan, 11.0, 1.0], 'GSM3495034': [nan, nan, nan], 'GSM3495035': [nan, 35.0, 0.0], 'GSM3495036': [nan, 26.0, 0.0], 'GSM3495037': [nan, 39.0, 0.0], 'GSM3495038': [nan, 46.0, 0.0], 'GSM3495039': [nan, 42.0, 0.0], 'GSM3495040': [nan, 20.0, 1.0], 'GSM3495041': [nan, 69.0, 1.0], 'GSM3495042': [nan, 69.0, 0.0], 'GSM3495043': [nan, 47.0, 1.0], 'GSM3495044': [nan, 47.0, 1.0], 'GSM3495045': [nan, 56.0, 0.0], 'GSM3495046': [nan, 54.0, 0.0], 'GSM3495047': [nan, 53.0, 0.0], 'GSM3495048': [nan, 50.0, 0.0], 'GSM3495049': [nan, 22.0, 1.0]}\n",
      "Clinical data saved to ../../output/preprocess/Crohns_Disease/clinical_data/GSE123086.csv\n"
     ]
    }
   ],
   "source": [
    "# 1. Gene Expression Data Availability\n",
    "# Based on the Series_overall_design, this dataset contains microarray data from CD4+ T cells\n",
    "# which would provide gene expression data, not just miRNA or methylation\n",
    "is_gene_available = True\n",
    "\n",
    "# 2. Variable Availability and Data Type Conversion\n",
    "# 2.1 Data Availability\n",
    "# For trait - Crohn's disease appears in row 1 under \"primary diagnosis\"\n",
    "trait_row = 1\n",
    "\n",
    "# For gender - appears in rows 2 and 3, but row 2 seems to be more complete\n",
    "gender_row = 2 \n",
    "\n",
    "# For age - appears in rows 3 and 4\n",
    "age_row = 3\n",
    "\n",
    "# 2.2 Data Type Conversion\n",
    "def convert_trait(value):\n",
    "    if not isinstance(value, str):\n",
    "        return None\n",
    "    # Extract value after colon if present\n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip()\n",
    "    \n",
    "    # Matching trait (Crohn's Disease)\n",
    "    if \"CROHN\" in value.upper():\n",
    "        return 1\n",
    "    # Healthy controls should be 0\n",
    "    elif \"HEALTHY\" in value.upper() or \"CONTROL\" in value.upper():\n",
    "        return 0\n",
    "    # Other diseases are not relevant for our binary classification\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "def convert_gender(value):\n",
    "    if not isinstance(value, str):\n",
    "        return None\n",
    "    # Extract value after colon if present\n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip()\n",
    "    \n",
    "    # Female is 0, Male is 1\n",
    "    if value.upper() == \"FEMALE\":\n",
    "        return 0\n",
    "    elif value.upper() == \"MALE\":\n",
    "        return 1\n",
    "    # If it's a diagnosis2 field, return None as it's not gender data\n",
    "    elif \"DIAGNOSIS2\" in value.upper():\n",
    "        return None\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "def convert_age(value):\n",
    "    if not isinstance(value, str):\n",
    "        return None\n",
    "    # Extract value after colon if present\n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip()\n",
    "    \n",
    "    # Try to convert to float for continuous age\n",
    "    try:\n",
    "        return float(value)\n",
    "    except:\n",
    "        return None\n",
    "\n",
    "# 3. Save Metadata\n",
    "# Determine trait data availability\n",
    "is_trait_available = trait_row is not None\n",
    "\n",
    "# Initial filtering using validate_and_save_cohort_info\n",
    "validate_and_save_cohort_info(\n",
    "    is_final=False, \n",
    "    cohort=cohort, \n",
    "    info_path=json_path, \n",
    "    is_gene_available=is_gene_available, \n",
    "    is_trait_available=is_trait_available\n",
    ")\n",
    "\n",
    "# 4. Clinical Feature Extraction\n",
    "# Since trait_row is not None, we proceed with clinical feature extraction\n",
    "if trait_row is not None:\n",
    "    # Extract clinical features using the geo_select_clinical_features function\n",
    "    selected_clinical_df = geo_select_clinical_features(\n",
    "        clinical_df=clinical_data,\n",
    "        trait=trait,\n",
    "        trait_row=trait_row,\n",
    "        convert_trait=convert_trait,\n",
    "        age_row=age_row,\n",
    "        convert_age=convert_age,\n",
    "        gender_row=gender_row,\n",
    "        convert_gender=convert_gender\n",
    "    )\n",
    "    \n",
    "    # Preview the extracted features\n",
    "    preview = preview_df(selected_clinical_df)\n",
    "    print(\"Preview of selected clinical features:\")\n",
    "    print(preview)\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, index=False)\n",
    "    print(f\"Clinical data saved to {out_clinical_data_file}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d1038144",
   "metadata": {},
   "source": [
    "### Step 3: Gene Data Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "608edba3",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:31:54.339030Z",
     "iopub.status.busy": "2025-03-25T08:31:54.338825Z",
     "iopub.status.idle": "2025-03-25T08:31:54.748049Z",
     "shell.execute_reply": "2025-03-25T08:31:54.747652Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "First 20 gene/probe identifiers:\n",
      "Index(['1', '2', '3', '9', '10', '12', '13', '14', '15', '16', '18', '19',\n",
      "       '20', '21', '22', '23', '24', '25', '26', '27'],\n",
      "      dtype='object', name='ID')\n",
      "\n",
      "Gene data dimensions: 22881 genes × 166 samples\n"
     ]
    }
   ],
   "source": [
    "# 1. Re-identify the SOFT and matrix files to ensure we have the correct paths\n",
    "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
    "\n",
    "# 2. Extract the gene expression data from the matrix file\n",
    "gene_data = get_genetic_data(matrix_file)\n",
    "\n",
    "# 3. Print the first 20 row IDs (gene or probe identifiers)\n",
    "print(\"\\nFirst 20 gene/probe identifiers:\")\n",
    "print(gene_data.index[:20])\n",
    "\n",
    "# 4. Print the dimensions of the gene expression data\n",
    "print(f\"\\nGene data dimensions: {gene_data.shape[0]} genes × {gene_data.shape[1]} samples\")\n",
    "\n",
    "# Note: we keep is_gene_available as True since we successfully extracted gene expression data\n",
    "is_gene_available = True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "68513421",
   "metadata": {},
   "source": [
    "### Step 4: Gene Identifier Review"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "b17de00e",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:31:54.749415Z",
     "iopub.status.busy": "2025-03-25T08:31:54.749292Z",
     "iopub.status.idle": "2025-03-25T08:31:54.751231Z",
     "shell.execute_reply": "2025-03-25T08:31:54.750951Z"
    }
   },
   "outputs": [],
   "source": [
    "# Examining the gene identifiers\n",
    "# The identifiers appear to be numerical values (1, 2, 3, etc.)\n",
    "# These are not standard human gene symbols, which are typically alphanumeric \n",
    "# (like BRCA1, TP53, etc.)\n",
    "# These appear to be probe IDs or some other form of identifiers that would\n",
    "# need to be mapped to standard gene symbols\n",
    "\n",
    "requires_gene_mapping = True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8d4e6390",
   "metadata": {},
   "source": [
    "### Step 5: Gene Annotation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "5b49e7b5",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:31:54.752424Z",
     "iopub.status.busy": "2025-03-25T08:31:54.752318Z",
     "iopub.status.idle": "2025-03-25T08:31:58.331994Z",
     "shell.execute_reply": "2025-03-25T08:31:58.331624Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene annotation dataframe column names:\n",
      "Index(['ID', 'ENTREZ_GENE_ID', 'SPOT_ID'], dtype='object')\n",
      "\n",
      "Preview of gene annotation data:\n",
      "{'ID': ['1', '2', '3'], 'ENTREZ_GENE_ID': ['1', '2', '3'], 'SPOT_ID': [1.0, 2.0, 3.0]}\n"
     ]
    }
   ],
   "source": [
    "# 1. First get the file paths using geo_get_relevant_filepaths function\n",
    "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
    "\n",
    "# 2. Extract gene annotation data from the SOFT file\n",
    "gene_annotation = get_gene_annotation(soft_file)\n",
    "\n",
    "# 3. Preview the gene annotation dataframe\n",
    "print(\"Gene annotation dataframe column names:\")\n",
    "print(gene_annotation.columns)\n",
    "\n",
    "# Preview the first few rows to understand the data structure\n",
    "print(\"\\nPreview of gene annotation data:\")\n",
    "annotation_preview = preview_df(gene_annotation, n=3)\n",
    "print(annotation_preview)\n",
    "\n",
    "# Maintain gene availability status as True based on previous steps\n",
    "is_gene_available = True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "88933adc",
   "metadata": {},
   "source": [
    "### Step 6: Gene Identifier Mapping"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "79475a3d",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:31:58.333245Z",
     "iopub.status.busy": "2025-03-25T08:31:58.333119Z",
     "iopub.status.idle": "2025-03-25T08:32:05.569628Z",
     "shell.execute_reply": "2025-03-25T08:32:05.569287Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene annotation first few rows:\n",
      "   ID ENTREZ_GENE_ID  SPOT_ID\n",
      "0   1              1      1.0\n",
      "1   2              2      2.0\n",
      "2   3              3      3.0\n",
      "3   9              9      9.0\n",
      "4  10             10     10.0\n",
      "\n",
      "Sample values in ENTREZ_GENE_ID column:\n",
      "0     1\n",
      "1     2\n",
      "2     3\n",
      "3     9\n",
      "4    10\n",
      "5    12\n",
      "6    13\n",
      "7    14\n",
      "8    15\n",
      "9    16\n",
      "Name: ENTREZ_GENE_ID, dtype: object\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "Check if gene symbols are available in the SOFT file:\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "Cleaned gene mapping:\n",
      "   ID Gene\n",
      "0   1    1\n",
      "1   2    2\n",
      "2   3    3\n",
      "3   9    9\n",
      "4  10   10\n",
      "Mapping shape after cleaning: (3822578, 2)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "Gene expression data after mapping:\n",
      "Number of genes: 0\n",
      "Number of samples: 166\n",
      "No genes were mapped successfully.\n"
     ]
    }
   ],
   "source": [
    "# Let's examine the gene_annotation data more carefully to understand the structure\n",
    "print(\"Gene annotation first few rows:\")\n",
    "print(gene_annotation.head())\n",
    "\n",
    "# Check what's in the ENTREZ_GENE_ID column - we need actual gene identifiers\n",
    "print(\"\\nSample values in ENTREZ_GENE_ID column:\")\n",
    "print(gene_annotation['ENTREZ_GENE_ID'].head(10))\n",
    "\n",
    "# The issue is that we need proper gene symbols, not just Entrez IDs\n",
    "# Let's check if we have access to proper gene symbols by fetching the platform annotation\n",
    "# from the SOFT file\n",
    "\n",
    "# Parse the SOFT file to get platform information including gene symbols\n",
    "with gzip.open(soft_file, 'rt') as f:\n",
    "    soft_content = f.read()\n",
    "\n",
    "# Look for sections containing gene symbol information\n",
    "print(\"\\nCheck if gene symbols are available in the SOFT file:\")\n",
    "gene_symbol_lines = [line for line in soft_content.split('\\n') if 'gene_symbol' in line.lower()][:5]\n",
    "print(gene_symbol_lines)\n",
    "\n",
    "# If we don't find gene symbols directly, we'll use the Entrez Gene IDs as identifiers\n",
    "# since they can be mapped to gene symbols later\n",
    "\n",
    "# Create a mapping dataframe with ID and Entrez Gene ID\n",
    "gene_mapping = gene_annotation[['ID', 'ENTREZ_GENE_ID']].copy()\n",
    "gene_mapping.rename(columns={'ENTREZ_GENE_ID': 'Gene'}, inplace=True)\n",
    "\n",
    "# Filter out any rows with missing values\n",
    "gene_mapping = gene_mapping.dropna()\n",
    "\n",
    "# Print a preview of the cleaned mapping\n",
    "print(\"\\nCleaned gene mapping:\")\n",
    "print(gene_mapping.head())\n",
    "print(f\"Mapping shape after cleaning: {gene_mapping.shape}\")\n",
    "\n",
    "# Apply the gene mapping to convert probe-level measurements to gene expression data\n",
    "# We'll use the standard function but make sure our Gene column has proper values\n",
    "gene_data = apply_gene_mapping(gene_data, gene_mapping)\n",
    "\n",
    "# Print statistics about the resulting gene data\n",
    "print(f\"\\nGene expression data after mapping:\")\n",
    "print(f\"Number of genes: {gene_data.shape[0]}\")\n",
    "print(f\"Number of samples: {gene_data.shape[1]}\")\n",
    "\n",
    "# Check the first few gene identifiers - they should be Entrez IDs\n",
    "if gene_data.shape[0] > 0:\n",
    "    print(\"First 5 gene identifiers:\")\n",
    "    print(gene_data.index[:5])\n",
    "else:\n",
    "    print(\"No genes were mapped successfully.\")\n",
    "\n",
    "# For this dataset, since we don't have access to proper gene symbols, \n",
    "# we'll treat the Entrez Gene IDs as our gene identifiers\n",
    "# Later normalization can map these to standard gene symbols if needed\n",
    "\n",
    "# Verify we have non-empty gene expression data\n",
    "is_gene_available = gene_data.shape[0] > 0\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fc4c1efa",
   "metadata": {},
   "source": [
    "### Step 7: Data Normalization and Linking"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "2e150f28",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:32:05.571074Z",
     "iopub.status.busy": "2025-03-25T08:32:05.570955Z",
     "iopub.status.idle": "2025-03-25T08:32:05.577791Z",
     "shell.execute_reply": "2025-03-25T08:32:05.577484Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Error: Gene expression matrix is empty after mapping.\n",
      "Abnormality detected in the cohort: GSE123086. Preprocessing failed.\n",
      "A new JSON file was created at: ../../output/preprocess/Crohns_Disease/cohort_info.json\n",
      "Dataset deemed not usable due to lack of gene expression data.\n"
     ]
    }
   ],
   "source": [
    "# 1. Check if gene data is available after mapping\n",
    "if gene_data.shape[0] == 0:\n",
    "    print(\"Error: Gene expression matrix is empty after mapping.\")\n",
    "    # Mark the dataset as not usable due to lack of gene expression data\n",
    "    is_usable = validate_and_save_cohort_info(\n",
    "        is_final=True,\n",
    "        cohort=cohort,\n",
    "        info_path=json_path,\n",
    "        is_gene_available=False,  # No usable gene data\n",
    "        is_trait_available=True,\n",
    "        is_biased=True,\n",
    "        df=pd.DataFrame(),\n",
    "        note=\"Failed to map probe IDs to gene symbols. The annotation format may not be compatible with the extraction methods.\"\n",
    "    )\n",
    "    print(\"Dataset deemed not usable due to lack of gene expression data.\")\n",
    "else:\n",
    "    # Only proceed with normalization if we have gene data\n",
    "    print(\"Normalizing gene symbols...\")\n",
    "    gene_data_normalized = normalize_gene_symbols_in_index(gene_data)\n",
    "    print(f\"Gene data shape after normalization: {gene_data_normalized.shape[0]} genes × {gene_data_normalized.shape[1]} samples\")\n",
    "\n",
    "    # Save the normalized gene data\n",
    "    os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
    "    gene_data_normalized.to_csv(out_gene_data_file)\n",
    "    print(f\"Normalized gene expression data saved to {out_gene_data_file}\")\n",
    "    \n",
    "    # Extract clinical features from the original data source\n",
    "    print(\"Extracting clinical features from the original source...\")\n",
    "    # Get background information and clinical data again\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",
    "    # Extract clinical features\n",
    "    selected_clinical_df = geo_select_clinical_features(\n",
    "        clinical_df=clinical_data,\n",
    "        trait=trait,\n",
    "        trait_row=trait_row,\n",
    "        convert_trait=convert_trait,\n",
    "        age_row=age_row,\n",
    "        convert_age=convert_age,\n",
    "        gender_row=gender_row,\n",
    "        convert_gender=convert_gender\n",
    "    )\n",
    "    \n",
    "    print(\"Extracted clinical features preview:\")\n",
    "    print(preview_df(selected_clinical_df))\n",
    "    print(f\"Clinical data shape: {selected_clinical_df.shape}\")\n",
    "    \n",
    "    # Save the extracted clinical features\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 features saved to {out_clinical_data_file}\")\n",
    "    \n",
    "    # Link clinical and genetic data\n",
    "    print(\"Linking clinical and genetic data...\")\n",
    "    linked_data = geo_link_clinical_genetic_data(selected_clinical_df, gene_data_normalized)\n",
    "    print(f\"Linked data shape: {linked_data.shape}\")\n",
    "    \n",
    "    # Check if the linked data has adequate data\n",
    "    if linked_data.shape[0] == 0 or linked_data.shape[1] <= 4:  # 4 is an arbitrary small number\n",
    "        print(\"Error: Linked data has insufficient samples or features.\")\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=True,\n",
    "            df=linked_data,\n",
    "            note=\"Failed to properly link gene expression data with clinical features.\"\n",
    "        )\n",
    "        print(\"Dataset deemed not usable due to linking failure.\")\n",
    "    else:\n",
    "        # Handle missing values systematically\n",
    "        print(\"Handling missing values...\")\n",
    "        linked_data_clean = handle_missing_values(linked_data, trait_col=trait)\n",
    "        print(f\"Data shape after handling missing values: {linked_data_clean.shape}\")\n",
    "        \n",
    "        # Check if there are still samples after missing value handling\n",
    "        if linked_data_clean.shape[0] == 0:\n",
    "            print(\"Error: No samples remain after handling missing values.\")\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=True,\n",
    "                df=pd.DataFrame(),\n",
    "                note=\"All samples were removed during missing value handling.\"\n",
    "            )\n",
    "            print(\"Dataset deemed not usable as all samples were filtered out.\")\n",
    "        else:\n",
    "            # Check if the dataset is biased\n",
    "            print(\"\\nChecking for bias in feature variables:\")\n",
    "            is_biased, linked_data_final = judge_and_remove_biased_features(linked_data_clean, trait)\n",
    "            \n",
    "            # Conduct final quality validation\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_final,\n",
    "                note=\"Dataset contains gene expression data for Crohn's Disease patients, examining response to Infliximab treatment.\"\n",
    "            )\n",
    "            \n",
    "            # Save linked data if usable\n",
    "            if is_usable:\n",
    "                os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n",
    "                linked_data_final.to_csv(out_data_file)\n",
    "                print(f\"Linked data saved to {out_data_file}\")\n",
    "                print(f\"Final dataset shape: {linked_data_final.shape}\")\n",
    "            else:\n",
    "                print(\"Dataset deemed not usable for trait association studies, linked data 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
}