File size: 39,588 Bytes
32677ff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "d66a6f7d",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:32:21.930922Z",
     "iopub.status.busy": "2025-03-25T08:32:21.930437Z",
     "iopub.status.idle": "2025-03-25T08:32:22.100818Z",
     "shell.execute_reply": "2025-03-25T08:32:22.100463Z"
    }
   },
   "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 = \"GSE169568\"\n",
    "\n",
    "# Input paths\n",
    "in_trait_dir = \"../../input/GEO/Crohns_Disease\"\n",
    "in_cohort_dir = \"../../input/GEO/Crohns_Disease/GSE169568\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/Crohns_Disease/GSE169568.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/Crohns_Disease/gene_data/GSE169568.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/Crohns_Disease/clinical_data/GSE169568.csv\"\n",
    "json_path = \"../../output/preprocess/Crohns_Disease/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "80cee7d9",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "bd213c76",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:32:22.102315Z",
     "iopub.status.busy": "2025-03-25T08:32:22.102163Z",
     "iopub.status.idle": "2025-03-25T08:32:22.313769Z",
     "shell.execute_reply": "2025-03-25T08:32:22.313438Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Background Information:\n",
      "!Series_title\t\"BeadChip microarray data of peripheral blood obtained from treatment-näive IBD patients and control individuals\"\n",
      "!Series_summary\t\"Comperhensive analysis of blood transcriptomes obtained from treatment-näive IBD patients.\"\n",
      "!Series_overall_design\t\"Total RNA extracted from peripheral blood samples (n = 205) was reverse transcribed and biotin-labeled using the TargetAmp-Nano Labeling Kit for Illumina Expression BeadChip (Epicentre) according to the manufacturer’s protocol. The labeled antisense RNA was hybridized to Human HT-12 v4 BeadChip array (Illumina) following the standard producer’s hybridization protocol. The array imaging was performed on an iScan system (Illumina) according to the standard manufacturer’s protocol.\"\n",
      "Sample Characteristics Dictionary:\n",
      "{0: ['Sex: female', 'Sex: male'], 1: ['age: 20', 'age: 39', 'age: 56', 'age: 31', 'age: 22', 'age: 32', 'age: 30', 'age: 18', 'age: 60', 'age: 33', 'age: 27', 'age: 34', 'age: 57', 'age: 72', 'age: 35', 'age: 24', 'age: 21', 'age: 62', 'age: 41', 'age: 29', 'age: 46', 'age: 49', 'age: 76', 'age: 23', 'age: 37', 'age: 64', 'age: 26', 'age: 19', 'age: 17', 'age: 48'], 2: ['diagnosis: Symptomatic control', 'diagnosis: Ulcerative colitis', \"diagnosis: Crohn's disease\", 'diagnosis: Healthy control'], 3: ['annotation file: HumanHT-12_V4_0_R2_15002873_B.bgx']}\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": "213435cf",
   "metadata": {},
   "source": [
    "### Step 2: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "75f34f93",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:32:22.315062Z",
     "iopub.status.busy": "2025-03-25T08:32:22.314936Z",
     "iopub.status.idle": "2025-03-25T08:32:22.338382Z",
     "shell.execute_reply": "2025-03-25T08:32:22.338069Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Clinical Data Preview:\n",
      "{'GSM5209429': [0.0, 20.0, 0.0], 'GSM5209430': [0.0, 39.0, 1.0], 'GSM5209431': [0.0, 56.0, 0.0], 'GSM5209432': [0.0, 31.0, 0.0], 'GSM5209433': [1.0, 22.0, 1.0], 'GSM5209434': [0.0, 32.0, 1.0], 'GSM5209435': [0.0, 32.0, 0.0], 'GSM5209436': [0.0, 30.0, 0.0], 'GSM5209437': [0.0, 30.0, 1.0], 'GSM5209438': [0.0, 18.0, 0.0], 'GSM5209439': [0.0, 60.0, 0.0], 'GSM5209440': [0.0, 33.0, 1.0], 'GSM5209441': [0.0, 27.0, 0.0], 'GSM5209442': [0.0, 30.0, 1.0], 'GSM5209443': [0.0, 34.0, 0.0], 'GSM5209444': [0.0, 57.0, 1.0], 'GSM5209445': [0.0, 27.0, 1.0], 'GSM5209446': [0.0, 20.0, 0.0], 'GSM5209447': [0.0, 30.0, 0.0], 'GSM5209448': [1.0, 27.0, 1.0], 'GSM5209449': [0.0, 32.0, 1.0], 'GSM5209450': [0.0, 72.0, 0.0], 'GSM5209451': [1.0, 35.0, 0.0], 'GSM5209452': [0.0, 24.0, 0.0], 'GSM5209453': [1.0, 21.0, 1.0], 'GSM5209454': [0.0, 62.0, 1.0], 'GSM5209455': [1.0, 41.0, 0.0], 'GSM5209456': [0.0, 22.0, 0.0], 'GSM5209457': [0.0, 18.0, 0.0], 'GSM5209458': [0.0, 20.0, 1.0], 'GSM5209459': [1.0, 29.0, 0.0], 'GSM5209460': [0.0, 46.0, 1.0], 'GSM5209461': [0.0, 31.0, 1.0], 'GSM5209462': [0.0, 34.0, 0.0], 'GSM5209463': [0.0, 32.0, 1.0], 'GSM5209464': [0.0, 49.0, 0.0], 'GSM5209465': [1.0, 76.0, 1.0], 'GSM5209466': [1.0, 23.0, 0.0], 'GSM5209467': [0.0, 37.0, 1.0], 'GSM5209468': [0.0, 30.0, 1.0], 'GSM5209469': [0.0, 64.0, 1.0], 'GSM5209470': [0.0, 23.0, 1.0], 'GSM5209471': [0.0, 24.0, 0.0], 'GSM5209472': [0.0, 26.0, 1.0], 'GSM5209473': [1.0, 19.0, 1.0], 'GSM5209474': [0.0, 60.0, 0.0], 'GSM5209475': [1.0, 17.0, 0.0], 'GSM5209476': [1.0, 41.0, 0.0], 'GSM5209477': [1.0, 48.0, 0.0], 'GSM5209478': [0.0, 26.0, 0.0], 'GSM5209479': [0.0, 35.0, 1.0], 'GSM5209480': [0.0, 22.0, 0.0], 'GSM5209481': [0.0, 73.0, 0.0], 'GSM5209482': [1.0, 69.0, 1.0], 'GSM5209483': [0.0, 57.0, 1.0], 'GSM5209484': [0.0, 50.0, 0.0], 'GSM5209485': [0.0, 27.0, 1.0], 'GSM5209486': [0.0, 69.0, 1.0], 'GSM5209487': [0.0, 28.0, 1.0], 'GSM5209488': [0.0, 51.0, 0.0], 'GSM5209489': [0.0, 64.0, 1.0], 'GSM5209490': [0.0, 52.0, 1.0], 'GSM5209491': [0.0, 55.0, 1.0], 'GSM5209492': [0.0, 47.0, 1.0], 'GSM5209493': [0.0, 61.0, 0.0], 'GSM5209494': [0.0, 29.0, 0.0], 'GSM5209495': [0.0, 36.0, 0.0], 'GSM5209496': [0.0, 24.0, 0.0], 'GSM5209497': [0.0, 24.0, 0.0], 'GSM5209498': [0.0, 21.0, 0.0], 'GSM5209499': [0.0, 54.0, 0.0], 'GSM5209500': [0.0, 24.0, 0.0], 'GSM5209501': [0.0, 78.0, 0.0], 'GSM5209502': [0.0, 23.0, 1.0], 'GSM5209503': [0.0, 27.0, 0.0], 'GSM5209504': [0.0, 21.0, 1.0], 'GSM5209505': [0.0, 34.0, 1.0], 'GSM5209506': [0.0, 51.0, 1.0], 'GSM5209507': [1.0, 31.0, 0.0], 'GSM5209508': [1.0, 40.0, 0.0], 'GSM5209509': [1.0, 24.0, 0.0], 'GSM5209510': [1.0, 24.0, 1.0], 'GSM5209511': [0.0, 23.0, 0.0], 'GSM5209512': [0.0, 33.0, 1.0], 'GSM5209513': [0.0, 25.0, 0.0], 'GSM5209514': [0.0, 23.0, 0.0], 'GSM5209515': [0.0, 41.0, 1.0], 'GSM5209516': [0.0, 32.0, 1.0], 'GSM5209517': [1.0, 23.0, 0.0], 'GSM5209518': [0.0, 36.0, 1.0], 'GSM5209519': [1.0, 26.0, 1.0], 'GSM5209520': [1.0, 23.0, 0.0], 'GSM5209521': [1.0, 36.0, 1.0], 'GSM5209522': [1.0, 40.0, 0.0], 'GSM5209523': [1.0, 26.0, 0.0], 'GSM5209524': [1.0, 18.0, 0.0], 'GSM5209525': [0.0, 35.0, 0.0], 'GSM5209526': [0.0, 24.0, 0.0], 'GSM5209527': [0.0, 32.0, 1.0], 'GSM5209528': [0.0, 61.0, 0.0], 'GSM5209529': [0.0, 34.0, 0.0], 'GSM5209530': [0.0, 54.0, 0.0], 'GSM5209531': [1.0, 21.0, 0.0], 'GSM5209532': [0.0, 28.0, 1.0], 'GSM5209533': [1.0, 38.0, 0.0], 'GSM5209534': [1.0, 69.0, 1.0], 'GSM5209535': [0.0, 28.0, 0.0], 'GSM5209536': [0.0, 27.0, 1.0], 'GSM5209537': [0.0, 33.0, 1.0], 'GSM5209538': [0.0, 24.0, 1.0], 'GSM5209539': [0.0, 19.0, 1.0], 'GSM5209540': [1.0, 32.0, 1.0], 'GSM5209541': [0.0, 40.0, 1.0], 'GSM5209542': [0.0, 39.0, 0.0], 'GSM5209543': [1.0, 29.0, 0.0], 'GSM5209544': [1.0, 26.0, 1.0], 'GSM5209545': [1.0, 26.0, 1.0], 'GSM5209546': [0.0, 18.0, 0.0], 'GSM5209547': [0.0, 38.0, 1.0], 'GSM5209548': [0.0, 59.0, 1.0], 'GSM5209549': [1.0, 53.0, 1.0], 'GSM5209550': [0.0, 41.0, 1.0], 'GSM5209551': [1.0, 24.0, 0.0], 'GSM5209552': [1.0, 28.0, 0.0], 'GSM5209553': [1.0, 30.0, 1.0], 'GSM5209554': [0.0, 31.0, 1.0], 'GSM5209555': [0.0, 47.0, 0.0], 'GSM5209556': [0.0, 76.0, 0.0], 'GSM5209557': [0.0, 27.0, 1.0], 'GSM5209558': [0.0, 36.0, 1.0], 'GSM5209559': [0.0, 19.0, 0.0], 'GSM5209560': [0.0, 38.0, 1.0], 'GSM5209561': [1.0, 24.0, 1.0], 'GSM5209562': [0.0, 33.0, 1.0], 'GSM5209563': [0.0, 23.0, 0.0], 'GSM5209564': [0.0, 20.0, 0.0], 'GSM5209565': [1.0, 38.0, 1.0], 'GSM5209566': [0.0, 68.0, 0.0], 'GSM5209567': [0.0, 23.0, 1.0], 'GSM5209568': [1.0, 39.0, 1.0], 'GSM5209569': [1.0, 23.0, 1.0], 'GSM5209570': [1.0, 23.0, 0.0], 'GSM5209571': [0.0, 39.0, 1.0], 'GSM5209572': [0.0, 38.0, 0.0], 'GSM5209573': [0.0, 20.0, 0.0], 'GSM5209574': [1.0, 54.0, 1.0], 'GSM5209575': [0.0, 41.0, 1.0], 'GSM5209576': [0.0, 48.0, 0.0], 'GSM5209577': [0.0, 74.0, 1.0], 'GSM5209578': [0.0, 69.0, 0.0], 'GSM5209579': [0.0, 42.0, 0.0], 'GSM5209580': [1.0, 25.0, 1.0], 'GSM5209581': [0.0, 35.0, 1.0], 'GSM5209582': [1.0, 30.0, 1.0], 'GSM5209583': [1.0, 23.0, 0.0], 'GSM5209584': [0.0, 36.0, 0.0], 'GSM5209585': [0.0, 61.0, 1.0], 'GSM5209586': [0.0, 37.0, 1.0], 'GSM5209587': [0.0, 50.0, 1.0], 'GSM5209588': [0.0, 46.0, 0.0], 'GSM5209589': [0.0, 22.0, 1.0], 'GSM5209590': [0.0, 21.0, 0.0], 'GSM5209591': [0.0, 44.0, 0.0], 'GSM5209592': [0.0, 24.0, 0.0], 'GSM5209593': [0.0, 24.0, 1.0], 'GSM5209594': [0.0, 23.0, 0.0], 'GSM5209595': [0.0, 47.0, 0.0], 'GSM5209596': [0.0, 21.0, 0.0], 'GSM5209597': [0.0, 19.0, 0.0], 'GSM5209598': [0.0, 56.0, 0.0], 'GSM5209599': [0.0, 25.0, 1.0], 'GSM5209600': [0.0, 54.0, 1.0], 'GSM5209601': [0.0, 51.0, 1.0], 'GSM5209602': [0.0, 43.0, 0.0], 'GSM5209603': [0.0, 53.0, 0.0], 'GSM5209604': [0.0, 66.0, 1.0], 'GSM5209605': [0.0, 69.0, 1.0], 'GSM5209606': [0.0, 22.0, 0.0], 'GSM5209607': [0.0, 56.0, 0.0], 'GSM5209608': [0.0, 51.0, 1.0], 'GSM5209609': [0.0, 69.0, 1.0], 'GSM5209610': [0.0, 53.0, 0.0], 'GSM5209611': [0.0, 61.0, 1.0], 'GSM5209612': [0.0, 52.0, 1.0], 'GSM5209613': [0.0, 42.0, 0.0], 'GSM5209614': [0.0, 56.0, 1.0], 'GSM5209615': [1.0, 58.0, 0.0], 'GSM5209616': [1.0, 20.0, 0.0], 'GSM5209617': [1.0, 17.0, 1.0], 'GSM5209618': [0.0, 40.0, 0.0], 'GSM5209619': [1.0, 44.0, 1.0], 'GSM5209620': [0.0, 45.0, 0.0], 'GSM5209621': [1.0, 19.0, 1.0], 'GSM5209622': [0.0, 28.0, 0.0], 'GSM5209623': [0.0, 57.0, 0.0], 'GSM5209624': [1.0, 41.0, 0.0], 'GSM5209625': [0.0, 34.0, 0.0], 'GSM5209626': [0.0, 54.0, 0.0], 'GSM5209627': [1.0, 59.0, 1.0], 'GSM5209628': [0.0, 20.0, 1.0]}\n",
      "Clinical data saved to ../../output/preprocess/Crohns_Disease/clinical_data/GSE169568.csv\n"
     ]
    }
   ],
   "source": [
    "# 1. Check if this dataset likely contains gene expression data\n",
    "# Based on the background information, this dataset contains BeadChip microarray data (Illumina Human HT-12 v4), \n",
    "# which is indeed gene expression data. So we set is_gene_available to True.\n",
    "is_gene_available = True\n",
    "\n",
    "# 2. Identify keys and conversion functions for trait, age, and gender data\n",
    "# 2.1 Data Availability\n",
    "\n",
    "# Trait - Crohn's Disease (key 2 contains diagnostic information)\n",
    "trait_row = 2\n",
    "\n",
    "# Age data (key 1 contains age information)\n",
    "age_row = 1\n",
    "\n",
    "# Gender data (key 0 contains sex information)\n",
    "gender_row = 0\n",
    "\n",
    "# 2.2 Data Type Conversion\n",
    "\n",
    "def convert_trait(value):\n",
    "    \"\"\"\n",
    "    Convert trait values to binary format:\n",
    "    1 for Crohn's disease, 0 for controls (healthy or symptomatic)\n",
    "    \"\"\"\n",
    "    if value is None:\n",
    "        return None\n",
    "    \n",
    "    # Extract the value after colon\n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip()\n",
    "    \n",
    "    # Convert to binary based on diagnosis\n",
    "    if \"Crohn's disease\" in value:\n",
    "        return 1\n",
    "    elif \"Healthy control\" in value or \"Symptomatic control\" in value or \"Ulcerative colitis\" in value:\n",
    "        return 0\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "def convert_age(value):\n",
    "    \"\"\"\n",
    "    Convert age values to continuous format\n",
    "    \"\"\"\n",
    "    if value is None:\n",
    "        return None\n",
    "    \n",
    "    # Extract the value after colon\n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip()\n",
    "    \n",
    "    try:\n",
    "        return float(value)\n",
    "    except:\n",
    "        return None\n",
    "\n",
    "def convert_gender(value):\n",
    "    \"\"\"\n",
    "    Convert gender values to binary format:\n",
    "    0 for female, 1 for male\n",
    "    \"\"\"\n",
    "    if value is None:\n",
    "        return None\n",
    "    \n",
    "    # Extract the value after colon\n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip().lower()\n",
    "    \n",
    "    if \"female\" in value:\n",
    "        return 0\n",
    "    elif \"male\" in value:\n",
    "        return 1\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "# 3. Determine trait data availability and save metadata\n",
    "is_trait_available = trait_row is not None\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",
    "if trait_row is not None:\n",
    "    # Extract clinical features using the provided library function\n",
    "    clinical_df = geo_select_clinical_features(\n",
    "        clinical_df=clinical_data,\n",
    "        trait=trait,\n",
    "        trait_row=trait_row,\n",
    "        convert_trait=convert_trait,\n",
    "        age_row=age_row,\n",
    "        convert_age=convert_age,\n",
    "        gender_row=gender_row,\n",
    "        convert_gender=convert_gender\n",
    "    )\n",
    "    \n",
    "    # Preview the extracted clinical data\n",
    "    preview = preview_df(clinical_df)\n",
    "    print(\"Clinical Data Preview:\")\n",
    "    print(preview)\n",
    "    \n",
    "    # Save the clinical data to the specified path\n",
    "    os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
    "    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": "1db3cd6c",
   "metadata": {},
   "source": [
    "### Step 3: Gene Data Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "6e43c924",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:32:22.339554Z",
     "iopub.status.busy": "2025-03-25T08:32:22.339439Z",
     "iopub.status.idle": "2025-03-25T08:32:22.699990Z",
     "shell.execute_reply": "2025-03-25T08:32:22.699537Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "First 20 gene/probe identifiers:\n",
      "Index(['ILMN_1651209', 'ILMN_1651229', 'ILMN_1651254', 'ILMN_1651262',\n",
      "       'ILMN_1651278', 'ILMN_1651282', 'ILMN_1651285', 'ILMN_1651315',\n",
      "       'ILMN_1651336', 'ILMN_1651341', 'ILMN_1651343', 'ILMN_1651347',\n",
      "       'ILMN_1651354', 'ILMN_1651358', 'ILMN_1651373', 'ILMN_1651378',\n",
      "       'ILMN_1651385', 'ILMN_1651405', 'ILMN_1651415', 'ILMN_1651429'],\n",
      "      dtype='object', name='ID')\n",
      "\n",
      "Gene data dimensions: 11727 genes × 205 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": "9bfd468e",
   "metadata": {},
   "source": [
    "### Step 4: Gene Identifier Review"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "0c93598b",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:32:22.701393Z",
     "iopub.status.busy": "2025-03-25T08:32:22.701261Z",
     "iopub.status.idle": "2025-03-25T08:32:22.703303Z",
     "shell.execute_reply": "2025-03-25T08:32:22.702987Z"
    }
   },
   "outputs": [],
   "source": [
    "# Looking at the gene identifiers, I can see they use the format ILMN_XXXXXXX\n",
    "# These are Illumina BeadArray probe IDs, not human gene symbols\n",
    "# Illumina probe IDs need to be mapped to human gene symbols for biological interpretation\n",
    "\n",
    "requires_gene_mapping = True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "757f43ca",
   "metadata": {},
   "source": [
    "### Step 5: Gene Annotation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "0cd84a88",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:32:22.704495Z",
     "iopub.status.busy": "2025-03-25T08:32:22.704380Z",
     "iopub.status.idle": "2025-03-25T08:32:28.328415Z",
     "shell.execute_reply": "2025-03-25T08:32:28.328019Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene annotation dataframe column names:\n",
      "Index(['ID', 'Species', 'Source', 'Search_Key', 'Transcript', 'ILMN_Gene',\n",
      "       'Source_Reference_ID', 'RefSeq_ID', 'Unigene_ID', 'Entrez_Gene_ID',\n",
      "       'GI', 'Accession', 'Symbol', 'Protein_Product', 'Probe_Id',\n",
      "       'Array_Address_Id', 'Probe_Type', 'Probe_Start', 'SEQUENCE',\n",
      "       'Chromosome', 'Probe_Chr_Orientation', 'Probe_Coordinates', 'Cytoband',\n",
      "       'Definition', 'Ontology_Component', 'Ontology_Process',\n",
      "       'Ontology_Function', 'Synonyms', 'Obsolete_Probe_Id', 'GB_ACC'],\n",
      "      dtype='object')\n",
      "\n",
      "Preview of gene annotation data:\n",
      "{'ID': ['ILMN_1343048', 'ILMN_1343049', 'ILMN_1343050'], 'Species': [nan, nan, nan], 'Source': [nan, nan, nan], 'Search_Key': [nan, nan, nan], 'Transcript': [nan, nan, nan], 'ILMN_Gene': [nan, nan, nan], 'Source_Reference_ID': [nan, nan, nan], 'RefSeq_ID': [nan, nan, nan], 'Unigene_ID': [nan, nan, nan], 'Entrez_Gene_ID': [nan, nan, nan], 'GI': [nan, nan, nan], 'Accession': [nan, nan, nan], 'Symbol': ['phage_lambda_genome', 'phage_lambda_genome', 'phage_lambda_genome:low'], 'Protein_Product': [nan, nan, nan], 'Probe_Id': [nan, nan, nan], 'Array_Address_Id': [5090180.0, 6510136.0, 7560739.0], 'Probe_Type': [nan, nan, nan], 'Probe_Start': [nan, nan, nan], 'SEQUENCE': ['GAATAAAGAACAATCTGCTGATGATCCCTCCGTGGATCTGATTCGTGTAA', 'CCATGTGATACGAGGGCGCGTAGTTTGCATTATCGTTTTTATCGTTTCAA', 'CCGACAGATGTATGTAAGGCCAACGTGCTCAAATCTTCATACAGAAAGAT'], 'Chromosome': [nan, nan, nan], 'Probe_Chr_Orientation': [nan, nan, nan], 'Probe_Coordinates': [nan, nan, nan], 'Cytoband': [nan, nan, nan], 'Definition': [nan, nan, nan], 'Ontology_Component': [nan, nan, nan], 'Ontology_Process': [nan, nan, nan], 'Ontology_Function': [nan, nan, nan], 'Synonyms': [nan, nan, nan], 'Obsolete_Probe_Id': [nan, nan, nan], 'GB_ACC': [nan, nan, nan]}\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": "30f653d6",
   "metadata": {},
   "source": [
    "### Step 6: Gene Identifier Mapping"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "f187ccba",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:32:28.329823Z",
     "iopub.status.busy": "2025-03-25T08:32:28.329690Z",
     "iopub.status.idle": "2025-03-25T08:32:28.529372Z",
     "shell.execute_reply": "2025-03-25T08:32:28.529019Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "Mapped gene data dimensions: 11148 genes × 205 samples\n",
      "\n",
      "First 10 gene symbols after mapping:\n",
      "Index(['A2BP1', 'A2LD1', 'A4GNT', 'AAAS', 'AACS', 'AADACL1', 'AADACL4',\n",
      "       'AAGAB', 'AAK1', 'AAMP'],\n",
      "      dtype='object', name='Gene')\n"
     ]
    }
   ],
   "source": [
    "# 1. Identify the appropriate columns in the gene annotation dataframe\n",
    "# The 'ID' column in gene_annotation contains probe IDs that match gene_data.index\n",
    "# The 'Symbol' column contains gene symbols that we want to map to\n",
    "\n",
    "# 2. Get gene mapping dataframe\n",
    "gene_mapping = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='Symbol')\n",
    "\n",
    "# Ensure no empty gene symbols\n",
    "gene_mapping = gene_mapping.dropna(subset=['Gene'])\n",
    "\n",
    "# 3. Apply gene mapping to convert probe-level measurements to gene expression data\n",
    "gene_data = apply_gene_mapping(gene_data, gene_mapping)\n",
    "\n",
    "# Print dimensions of the processed gene expression data\n",
    "print(f\"\\nMapped gene data dimensions: {gene_data.shape[0]} genes × {gene_data.shape[1]} samples\")\n",
    "\n",
    "# Preview the first few gene symbols after mapping\n",
    "print(\"\\nFirst 10 gene symbols after mapping:\")\n",
    "print(gene_data.index[:10])\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "767e30fc",
   "metadata": {},
   "source": [
    "### Step 7: Data Normalization and Linking"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "5a08b637",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:32:28.530833Z",
     "iopub.status.busy": "2025-03-25T08:32:28.530713Z",
     "iopub.status.idle": "2025-03-25T08:32:38.607836Z",
     "shell.execute_reply": "2025-03-25T08:32:38.607384Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Normalizing gene symbols...\n",
      "Gene data shape after normalization: 11039 genes × 205 samples\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Normalized gene expression data saved to ../../output/preprocess/Crohns_Disease/gene_data/GSE169568.csv\n",
      "Extracting clinical features from the original source...\n",
      "Extracted clinical features preview:\n",
      "{'GSM5209429': [0.0, 20.0, 0.0], 'GSM5209430': [0.0, 39.0, 1.0], 'GSM5209431': [0.0, 56.0, 0.0], 'GSM5209432': [0.0, 31.0, 0.0], 'GSM5209433': [1.0, 22.0, 1.0], 'GSM5209434': [0.0, 32.0, 1.0], 'GSM5209435': [0.0, 32.0, 0.0], 'GSM5209436': [0.0, 30.0, 0.0], 'GSM5209437': [0.0, 30.0, 1.0], 'GSM5209438': [0.0, 18.0, 0.0], 'GSM5209439': [0.0, 60.0, 0.0], 'GSM5209440': [0.0, 33.0, 1.0], 'GSM5209441': [0.0, 27.0, 0.0], 'GSM5209442': [0.0, 30.0, 1.0], 'GSM5209443': [0.0, 34.0, 0.0], 'GSM5209444': [0.0, 57.0, 1.0], 'GSM5209445': [0.0, 27.0, 1.0], 'GSM5209446': [0.0, 20.0, 0.0], 'GSM5209447': [0.0, 30.0, 0.0], 'GSM5209448': [1.0, 27.0, 1.0], 'GSM5209449': [0.0, 32.0, 1.0], 'GSM5209450': [0.0, 72.0, 0.0], 'GSM5209451': [1.0, 35.0, 0.0], 'GSM5209452': [0.0, 24.0, 0.0], 'GSM5209453': [1.0, 21.0, 1.0], 'GSM5209454': [0.0, 62.0, 1.0], 'GSM5209455': [1.0, 41.0, 0.0], 'GSM5209456': [0.0, 22.0, 0.0], 'GSM5209457': [0.0, 18.0, 0.0], 'GSM5209458': [0.0, 20.0, 1.0], 'GSM5209459': [1.0, 29.0, 0.0], 'GSM5209460': [0.0, 46.0, 1.0], 'GSM5209461': [0.0, 31.0, 1.0], 'GSM5209462': [0.0, 34.0, 0.0], 'GSM5209463': [0.0, 32.0, 1.0], 'GSM5209464': [0.0, 49.0, 0.0], 'GSM5209465': [1.0, 76.0, 1.0], 'GSM5209466': [1.0, 23.0, 0.0], 'GSM5209467': [0.0, 37.0, 1.0], 'GSM5209468': [0.0, 30.0, 1.0], 'GSM5209469': [0.0, 64.0, 1.0], 'GSM5209470': [0.0, 23.0, 1.0], 'GSM5209471': [0.0, 24.0, 0.0], 'GSM5209472': [0.0, 26.0, 1.0], 'GSM5209473': [1.0, 19.0, 1.0], 'GSM5209474': [0.0, 60.0, 0.0], 'GSM5209475': [1.0, 17.0, 0.0], 'GSM5209476': [1.0, 41.0, 0.0], 'GSM5209477': [1.0, 48.0, 0.0], 'GSM5209478': [0.0, 26.0, 0.0], 'GSM5209479': [0.0, 35.0, 1.0], 'GSM5209480': [0.0, 22.0, 0.0], 'GSM5209481': [0.0, 73.0, 0.0], 'GSM5209482': [1.0, 69.0, 1.0], 'GSM5209483': [0.0, 57.0, 1.0], 'GSM5209484': [0.0, 50.0, 0.0], 'GSM5209485': [0.0, 27.0, 1.0], 'GSM5209486': [0.0, 69.0, 1.0], 'GSM5209487': [0.0, 28.0, 1.0], 'GSM5209488': [0.0, 51.0, 0.0], 'GSM5209489': [0.0, 64.0, 1.0], 'GSM5209490': [0.0, 52.0, 1.0], 'GSM5209491': [0.0, 55.0, 1.0], 'GSM5209492': [0.0, 47.0, 1.0], 'GSM5209493': [0.0, 61.0, 0.0], 'GSM5209494': [0.0, 29.0, 0.0], 'GSM5209495': [0.0, 36.0, 0.0], 'GSM5209496': [0.0, 24.0, 0.0], 'GSM5209497': [0.0, 24.0, 0.0], 'GSM5209498': [0.0, 21.0, 0.0], 'GSM5209499': [0.0, 54.0, 0.0], 'GSM5209500': [0.0, 24.0, 0.0], 'GSM5209501': [0.0, 78.0, 0.0], 'GSM5209502': [0.0, 23.0, 1.0], 'GSM5209503': [0.0, 27.0, 0.0], 'GSM5209504': [0.0, 21.0, 1.0], 'GSM5209505': [0.0, 34.0, 1.0], 'GSM5209506': [0.0, 51.0, 1.0], 'GSM5209507': [1.0, 31.0, 0.0], 'GSM5209508': [1.0, 40.0, 0.0], 'GSM5209509': [1.0, 24.0, 0.0], 'GSM5209510': [1.0, 24.0, 1.0], 'GSM5209511': [0.0, 23.0, 0.0], 'GSM5209512': [0.0, 33.0, 1.0], 'GSM5209513': [0.0, 25.0, 0.0], 'GSM5209514': [0.0, 23.0, 0.0], 'GSM5209515': [0.0, 41.0, 1.0], 'GSM5209516': [0.0, 32.0, 1.0], 'GSM5209517': [1.0, 23.0, 0.0], 'GSM5209518': [0.0, 36.0, 1.0], 'GSM5209519': [1.0, 26.0, 1.0], 'GSM5209520': [1.0, 23.0, 0.0], 'GSM5209521': [1.0, 36.0, 1.0], 'GSM5209522': [1.0, 40.0, 0.0], 'GSM5209523': [1.0, 26.0, 0.0], 'GSM5209524': [1.0, 18.0, 0.0], 'GSM5209525': [0.0, 35.0, 0.0], 'GSM5209526': [0.0, 24.0, 0.0], 'GSM5209527': [0.0, 32.0, 1.0], 'GSM5209528': [0.0, 61.0, 0.0], 'GSM5209529': [0.0, 34.0, 0.0], 'GSM5209530': [0.0, 54.0, 0.0], 'GSM5209531': [1.0, 21.0, 0.0], 'GSM5209532': [0.0, 28.0, 1.0], 'GSM5209533': [1.0, 38.0, 0.0], 'GSM5209534': [1.0, 69.0, 1.0], 'GSM5209535': [0.0, 28.0, 0.0], 'GSM5209536': [0.0, 27.0, 1.0], 'GSM5209537': [0.0, 33.0, 1.0], 'GSM5209538': [0.0, 24.0, 1.0], 'GSM5209539': [0.0, 19.0, 1.0], 'GSM5209540': [1.0, 32.0, 1.0], 'GSM5209541': [0.0, 40.0, 1.0], 'GSM5209542': [0.0, 39.0, 0.0], 'GSM5209543': [1.0, 29.0, 0.0], 'GSM5209544': [1.0, 26.0, 1.0], 'GSM5209545': [1.0, 26.0, 1.0], 'GSM5209546': [0.0, 18.0, 0.0], 'GSM5209547': [0.0, 38.0, 1.0], 'GSM5209548': [0.0, 59.0, 1.0], 'GSM5209549': [1.0, 53.0, 1.0], 'GSM5209550': [0.0, 41.0, 1.0], 'GSM5209551': [1.0, 24.0, 0.0], 'GSM5209552': [1.0, 28.0, 0.0], 'GSM5209553': [1.0, 30.0, 1.0], 'GSM5209554': [0.0, 31.0, 1.0], 'GSM5209555': [0.0, 47.0, 0.0], 'GSM5209556': [0.0, 76.0, 0.0], 'GSM5209557': [0.0, 27.0, 1.0], 'GSM5209558': [0.0, 36.0, 1.0], 'GSM5209559': [0.0, 19.0, 0.0], 'GSM5209560': [0.0, 38.0, 1.0], 'GSM5209561': [1.0, 24.0, 1.0], 'GSM5209562': [0.0, 33.0, 1.0], 'GSM5209563': [0.0, 23.0, 0.0], 'GSM5209564': [0.0, 20.0, 0.0], 'GSM5209565': [1.0, 38.0, 1.0], 'GSM5209566': [0.0, 68.0, 0.0], 'GSM5209567': [0.0, 23.0, 1.0], 'GSM5209568': [1.0, 39.0, 1.0], 'GSM5209569': [1.0, 23.0, 1.0], 'GSM5209570': [1.0, 23.0, 0.0], 'GSM5209571': [0.0, 39.0, 1.0], 'GSM5209572': [0.0, 38.0, 0.0], 'GSM5209573': [0.0, 20.0, 0.0], 'GSM5209574': [1.0, 54.0, 1.0], 'GSM5209575': [0.0, 41.0, 1.0], 'GSM5209576': [0.0, 48.0, 0.0], 'GSM5209577': [0.0, 74.0, 1.0], 'GSM5209578': [0.0, 69.0, 0.0], 'GSM5209579': [0.0, 42.0, 0.0], 'GSM5209580': [1.0, 25.0, 1.0], 'GSM5209581': [0.0, 35.0, 1.0], 'GSM5209582': [1.0, 30.0, 1.0], 'GSM5209583': [1.0, 23.0, 0.0], 'GSM5209584': [0.0, 36.0, 0.0], 'GSM5209585': [0.0, 61.0, 1.0], 'GSM5209586': [0.0, 37.0, 1.0], 'GSM5209587': [0.0, 50.0, 1.0], 'GSM5209588': [0.0, 46.0, 0.0], 'GSM5209589': [0.0, 22.0, 1.0], 'GSM5209590': [0.0, 21.0, 0.0], 'GSM5209591': [0.0, 44.0, 0.0], 'GSM5209592': [0.0, 24.0, 0.0], 'GSM5209593': [0.0, 24.0, 1.0], 'GSM5209594': [0.0, 23.0, 0.0], 'GSM5209595': [0.0, 47.0, 0.0], 'GSM5209596': [0.0, 21.0, 0.0], 'GSM5209597': [0.0, 19.0, 0.0], 'GSM5209598': [0.0, 56.0, 0.0], 'GSM5209599': [0.0, 25.0, 1.0], 'GSM5209600': [0.0, 54.0, 1.0], 'GSM5209601': [0.0, 51.0, 1.0], 'GSM5209602': [0.0, 43.0, 0.0], 'GSM5209603': [0.0, 53.0, 0.0], 'GSM5209604': [0.0, 66.0, 1.0], 'GSM5209605': [0.0, 69.0, 1.0], 'GSM5209606': [0.0, 22.0, 0.0], 'GSM5209607': [0.0, 56.0, 0.0], 'GSM5209608': [0.0, 51.0, 1.0], 'GSM5209609': [0.0, 69.0, 1.0], 'GSM5209610': [0.0, 53.0, 0.0], 'GSM5209611': [0.0, 61.0, 1.0], 'GSM5209612': [0.0, 52.0, 1.0], 'GSM5209613': [0.0, 42.0, 0.0], 'GSM5209614': [0.0, 56.0, 1.0], 'GSM5209615': [1.0, 58.0, 0.0], 'GSM5209616': [1.0, 20.0, 0.0], 'GSM5209617': [1.0, 17.0, 1.0], 'GSM5209618': [0.0, 40.0, 0.0], 'GSM5209619': [1.0, 44.0, 1.0], 'GSM5209620': [0.0, 45.0, 0.0], 'GSM5209621': [1.0, 19.0, 1.0], 'GSM5209622': [0.0, 28.0, 0.0], 'GSM5209623': [0.0, 57.0, 0.0], 'GSM5209624': [1.0, 41.0, 0.0], 'GSM5209625': [0.0, 34.0, 0.0], 'GSM5209626': [0.0, 54.0, 0.0], 'GSM5209627': [1.0, 59.0, 1.0], 'GSM5209628': [0.0, 20.0, 1.0]}\n",
      "Clinical data shape: (3, 205)\n",
      "Clinical features saved to ../../output/preprocess/Crohns_Disease/clinical_data/GSE169568.csv\n",
      "Linking clinical and genetic data...\n",
      "Linked data shape: (205, 11042)\n",
      "Handling missing values...\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Data shape after handling missing values: (205, 11042)\n",
      "\n",
      "Checking for bias in feature variables:\n",
      "For the feature 'Crohns_Disease', the least common label is '1.0' with 52 occurrences. This represents 25.37% of the dataset.\n",
      "The distribution of the feature 'Crohns_Disease' in this dataset is fine.\n",
      "\n",
      "Quartiles for 'Age':\n",
      "  25%: 24.0\n",
      "  50% (Median): 34.0\n",
      "  75%: 51.0\n",
      "Min: 17.0\n",
      "Max: 78.0\n",
      "The distribution of the feature 'Age' in this dataset is fine.\n",
      "\n",
      "For the feature 'Gender', the least common label is '1.0' with 98 occurrences. This represents 47.80% of the dataset.\n",
      "The distribution of the feature 'Gender' in this dataset is fine.\n",
      "\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Linked data saved to ../../output/preprocess/Crohns_Disease/GSE169568.csv\n",
      "Final dataset shape: (205, 11042)\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
}