File size: 37,747 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
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "8485cb4f",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:32:06.499146Z",
     "iopub.status.busy": "2025-03-25T08:32:06.498785Z",
     "iopub.status.idle": "2025-03-25T08:32:06.666657Z",
     "shell.execute_reply": "2025-03-25T08:32:06.666312Z"
    }
   },
   "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 = \"GSE123088\"\n",
    "\n",
    "# Input paths\n",
    "in_trait_dir = \"../../input/GEO/Crohns_Disease\"\n",
    "in_cohort_dir = \"../../input/GEO/Crohns_Disease/GSE123088\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/Crohns_Disease/GSE123088.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/Crohns_Disease/gene_data/GSE123088.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/Crohns_Disease/clinical_data/GSE123088.csv\"\n",
    "json_path = \"../../output/preprocess/Crohns_Disease/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "97dd5573",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "ea92ea77",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:32:06.668092Z",
     "iopub.status.busy": "2025-03-25T08:32:06.667946Z",
     "iopub.status.idle": "2025-03-25T08:32:06.944372Z",
     "shell.execute_reply": "2025-03-25T08:32:06.944010Z"
    }
   },
   "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\"\n",
      "!Series_summary\t\"This SuperSeries is composed of the SubSeries listed below.\"\n",
      "!Series_overall_design\t\"Refer to individual Series\"\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', 'primary diagnosis: Breast cancer', 'primary diagnosis: Control'], 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": "348fa83c",
   "metadata": {},
   "source": [
    "### Step 2: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "c306f14c",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:32:06.945685Z",
     "iopub.status.busy": "2025-03-25T08:32:06.945566Z",
     "iopub.status.idle": "2025-03-25T08:32:06.972002Z",
     "shell.execute_reply": "2025-03-25T08:32:06.971702Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Preview of clinical data:\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], 'GSM3495050': [nan, 62.0, 0.0], 'GSM3495051': [nan, 74.0, 0.0], 'GSM3495052': [0.0, 57.0, 0.0], 'GSM3495053': [0.0, 47.0, 0.0], 'GSM3495054': [nan, 70.0, 0.0], 'GSM3495055': [nan, 50.0, 0.0], 'GSM3495056': [0.0, 52.0, 0.0], 'GSM3495057': [nan, 43.0, 0.0], 'GSM3495058': [0.0, 57.0, 0.0], 'GSM3495059': [nan, 53.0, 0.0], 'GSM3495060': [nan, 70.0, 0.0], 'GSM3495061': [0.0, 41.0, 0.0], 'GSM3495062': [nan, 61.0, 0.0], 'GSM3495063': [0.0, 39.0, 0.0], 'GSM3495064': [0.0, 58.0, 0.0], 'GSM3495065': [nan, 55.0, 0.0], 'GSM3495066': [nan, 63.0, 0.0], 'GSM3495067': [0.0, 60.0, 0.0], 'GSM3495068': [nan, 43.0, 0.0], 'GSM3495069': [nan, 68.0, 0.0], 'GSM3495070': [nan, 67.0, 0.0], 'GSM3495071': [nan, 50.0, 0.0], 'GSM3495072': [nan, 67.0, 0.0], 'GSM3495073': [0.0, 51.0, 0.0], 'GSM3495074': [0.0, 59.0, 0.0], 'GSM3495075': [0.0, 44.0, 0.0], 'GSM3495076': [nan, 35.0, 0.0], 'GSM3495077': [nan, 83.0, 0.0], 'GSM3495078': [nan, 78.0, 0.0], 'GSM3495079': [nan, 88.0, 0.0], 'GSM3495080': [nan, 41.0, 0.0], 'GSM3495081': [0.0, 60.0, 0.0], 'GSM3495082': [nan, 72.0, 0.0], 'GSM3495083': [nan, 53.0, 0.0]}\n",
      "Clinical data saved to ../../output/preprocess/Crohns_Disease/clinical_data/GSE123088.csv\n"
     ]
    }
   ],
   "source": [
    "# 1. Gene Expression Data Availability\n",
    "# Based on the background information, this dataset likely contains gene expression data, so:\n",
    "is_gene_available = True\n",
    "\n",
    "# 2. Variable Availability and Data Type Conversion\n",
    "# 2.1 Data Availability\n",
    "# Trait: Locate Crohn's Disease data in sample characteristics dictionary\n",
    "trait_row = 1  # Primary diagnosis is in row 1, which includes \"CROHN_DISEASE\"\n",
    "\n",
    "# Age: Age information is available in row 3 and 4\n",
    "age_row = 3  # Using row 3 as the main source for age data\n",
    "\n",
    "# Gender: Gender information is in row 2 and 3 (labeled as \"Sex\")\n",
    "gender_row = 2  # Using row 2 as the main source for gender data\n",
    "\n",
    "# 2.2 Data Type Conversion\n",
    "def convert_trait(value):\n",
    "    \"\"\"Convert trait values to binary (1 for Crohn's Disease, 0 for Control)\"\"\"\n",
    "    if isinstance(value, str):\n",
    "        value = value.strip().lower()\n",
    "        if ':' in value:\n",
    "            value = value.split(':', 1)[1].strip()\n",
    "        \n",
    "        if 'crohn' in value or 'crohn_disease' in value:\n",
    "            return 1\n",
    "        elif 'control' in value or 'healthy_control' in value:\n",
    "            return 0\n",
    "    return None\n",
    "\n",
    "def convert_age(value):\n",
    "    \"\"\"Convert age values to continuous numeric values\"\"\"\n",
    "    if isinstance(value, str):\n",
    "        value = value.strip()\n",
    "        if ':' in value:\n",
    "            value = value.split(':', 1)[1].strip()\n",
    "        \n",
    "        try:\n",
    "            return float(value)\n",
    "        except ValueError:\n",
    "            pass\n",
    "    return None\n",
    "\n",
    "def convert_gender(value):\n",
    "    \"\"\"Convert gender values to binary (0 for Female, 1 for Male)\"\"\"\n",
    "    if isinstance(value, str):\n",
    "        value = value.strip().lower()\n",
    "        if ':' in value:\n",
    "            value = value.split(':', 1)[1].strip()\n",
    "        \n",
    "        if 'female' in value:\n",
    "            return 0\n",
    "        elif 'male' in value:\n",
    "            return 1\n",
    "    return None\n",
    "\n",
    "# 3. Save Metadata\n",
    "# Initial filtering on usability\n",
    "is_trait_available = trait_row is not None\n",
    "initial_validation = 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\n",
    "    clinical_selected = 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_selected)\n",
    "    print(\"Preview of clinical data:\")\n",
    "    print(preview)\n",
    "    \n",
    "    # Save clinical data to CSV\n",
    "    os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
    "    clinical_selected.to_csv(out_clinical_data_file, index=True)\n",
    "    print(f\"Clinical data saved to {out_clinical_data_file}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "560141d1",
   "metadata": {},
   "source": [
    "### Step 3: Gene Data Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "82351f47",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:32:06.973196Z",
     "iopub.status.busy": "2025-03-25T08:32:06.973090Z",
     "iopub.status.idle": "2025-03-25T08:32:07.491225Z",
     "shell.execute_reply": "2025-03-25T08:32:07.490840Z"
    }
   },
   "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: 24166 genes × 204 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": "b66390f1",
   "metadata": {},
   "source": [
    "### Step 4: Gene Identifier Review"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "3630afeb",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:32:07.492620Z",
     "iopub.status.busy": "2025-03-25T08:32:07.492499Z",
     "iopub.status.idle": "2025-03-25T08:32:07.494449Z",
     "shell.execute_reply": "2025-03-25T08:32:07.494154Z"
    }
   },
   "outputs": [],
   "source": [
    "# Examining the gene identifiers\n",
    "# These appear to be integer/numeric identifiers rather than standard HGNC gene symbols\n",
    "# Human gene symbols are typically alphanumeric (like \"TP53\", \"BRCA1\", \"IL6\")\n",
    "# The identifiers shown are simple numbers which likely need mapping to gene symbols\n",
    "\n",
    "requires_gene_mapping = True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cbc89361",
   "metadata": {},
   "source": [
    "### Step 5: Gene Annotation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "40247968",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:32:07.495710Z",
     "iopub.status.busy": "2025-03-25T08:32:07.495601Z",
     "iopub.status.idle": "2025-03-25T08:32:11.926403Z",
     "shell.execute_reply": "2025-03-25T08:32:11.925945Z"
    }
   },
   "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": "13a5c0e2",
   "metadata": {},
   "source": [
    "### Step 6: Gene Identifier Mapping"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "301c359b",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:32:11.927890Z",
     "iopub.status.busy": "2025-03-25T08:32:11.927767Z",
     "iopub.status.idle": "2025-03-25T08:32:20.401799Z",
     "shell.execute_reply": "2025-03-25T08:32:20.401238Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Number of probes with mappings: 4740924\n",
      "Sample of mapping data:\n",
      "   ID Gene\n",
      "0   1    1\n",
      "1   2    2\n",
      "2   3    3\n",
      "3   9    9\n",
      "4  10   10\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "After mapping, gene data dimensions: (0, 204)\n",
      "First 10 mapped gene symbols (if any):\n",
      "No genes were successfully mapped. This might indicate an issue with the gene annotation format.\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "Using original probe data: 24166 probes × 204 samples\n"
     ]
    }
   ],
   "source": [
    "# 1. Observe the gene identifiers in both datasets\n",
    "# From previous outputs:\n",
    "# - Gene expression data: identifiers are numeric strings like '1', '2', '3'\n",
    "# - Gene annotation data: has columns 'ID', 'ENTREZ_GENE_ID', 'SPOT_ID'\n",
    "\n",
    "# The 'ID' column in gene annotation matches the identifiers in gene expression data\n",
    "# The 'ENTREZ_GENE_ID' column appears to contain Entrez Gene IDs which we need to map to gene symbols\n",
    "\n",
    "# 2. Create gene mapping dataframe\n",
    "mapping_df = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='ENTREZ_GENE_ID')\n",
    "\n",
    "# Print information about the mapping\n",
    "print(f\"Number of probes with mappings: {len(mapping_df)}\")\n",
    "print(f\"Sample of mapping data:\")\n",
    "print(mapping_df.head())\n",
    "\n",
    "# 3. Apply gene mapping to convert probe-level measurements to gene expression data\n",
    "gene_data = apply_gene_mapping(gene_data, mapping_df)\n",
    "\n",
    "# Print information about the mapped gene data\n",
    "print(\"\\nAfter mapping, gene data dimensions:\", gene_data.shape)\n",
    "print(\"First 10 mapped gene symbols (if any):\")\n",
    "if len(gene_data) > 0:\n",
    "    print(gene_data.index[:10])\n",
    "else:\n",
    "    print(\"No genes were successfully mapped. This might indicate an issue with the gene annotation format.\")\n",
    "    \n",
    "    # Save original probe data as gene data for downstream processes\n",
    "    # This is a fallback to allow the pipeline to continue\n",
    "    gene_data = get_genetic_data(matrix_file)\n",
    "    gene_data.index.name = 'Gene'\n",
    "    print(f\"\\nUsing original probe data: {gene_data.shape[0]} probes × {gene_data.shape[1]} samples\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6b205378",
   "metadata": {},
   "source": [
    "### Step 7: Data Normalization and Linking"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "bc757bc5",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:32:20.403429Z",
     "iopub.status.busy": "2025-03-25T08:32:20.403303Z",
     "iopub.status.idle": "2025-03-25T08:32:21.008844Z",
     "shell.execute_reply": "2025-03-25T08:32:21.008320Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Original probe data dimensions: (24166, 204)\n",
      "Normalizing gene symbols...\n",
      "Gene data shape after normalization: 0 genes × 204 samples\n",
      "Gene expression data saved to ../../output/preprocess/Crohns_Disease/gene_data/GSE123088.csv\n",
      "Loading clinical features...\n",
      "Loading clinical features from ../../output/preprocess/Crohns_Disease/clinical_data/GSE123088.csv\n",
      "Clinical data preview:\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], 'GSM3495050': [nan, 62.0, 0.0], 'GSM3495051': [nan, 74.0, 0.0], 'GSM3495052': [0.0, 57.0, 0.0], 'GSM3495053': [0.0, 47.0, 0.0], 'GSM3495054': [nan, 70.0, 0.0], 'GSM3495055': [nan, 50.0, 0.0], 'GSM3495056': [0.0, 52.0, 0.0], 'GSM3495057': [nan, 43.0, 0.0], 'GSM3495058': [0.0, 57.0, 0.0], 'GSM3495059': [nan, 53.0, 0.0], 'GSM3495060': [nan, 70.0, 0.0], 'GSM3495061': [0.0, 41.0, 0.0], 'GSM3495062': [nan, 61.0, 0.0], 'GSM3495063': [0.0, 39.0, 0.0], 'GSM3495064': [0.0, 58.0, 0.0], 'GSM3495065': [nan, 55.0, 0.0], 'GSM3495066': [nan, 63.0, 0.0], 'GSM3495067': [0.0, 60.0, 0.0], 'GSM3495068': [nan, 43.0, 0.0], 'GSM3495069': [nan, 68.0, 0.0], 'GSM3495070': [nan, 67.0, 0.0], 'GSM3495071': [nan, 50.0, 0.0], 'GSM3495072': [nan, 67.0, 0.0], 'GSM3495073': [0.0, 51.0, 0.0], 'GSM3495074': [0.0, 59.0, 0.0], 'GSM3495075': [0.0, 44.0, 0.0], 'GSM3495076': [nan, 35.0, 0.0], 'GSM3495077': [nan, 83.0, 0.0], 'GSM3495078': [nan, 78.0, 0.0], 'GSM3495079': [nan, 88.0, 0.0], 'GSM3495080': [nan, 41.0, 0.0], 'GSM3495081': [0.0, 60.0, 0.0], 'GSM3495082': [nan, 72.0, 0.0], 'GSM3495083': [nan, 53.0, 0.0]}\n",
      "Clinical data shape: (3, 204)\n",
      "Linking clinical and genetic data...\n",
      "Linked data shape: (204, 3)\n",
      "Error: Linked data is missing trait data or gene expression data.\n",
      "Abnormality detected in the cohort: GSE123088. Preprocessing failed.\n",
      "Dataset deemed not usable due to incomplete data.\n"
     ]
    }
   ],
   "source": [
    "# 1. Make sure we have the original gene_data before any mapping attempts\n",
    "original_gene_data = get_genetic_data(matrix_file)\n",
    "print(f\"Original probe data dimensions: {original_gene_data.shape}\")\n",
    "\n",
    "# Handle the case where gene data is empty after mapping\n",
    "if gene_data.shape[0] == 0:\n",
    "    print(\"Warning: No genes were successfully mapped to symbols. Using probe IDs as features instead.\")\n",
    "    # Use the original probe-level data instead of the empty mapped data\n",
    "    gene_data_normalized = original_gene_data\n",
    "    print(f\"Using original probe data as features: {gene_data_normalized.shape[0]} probes × {gene_data_normalized.shape[1]} samples\")\n",
    "else:\n",
    "    # If we have mapped gene data, proceed with normalization\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 gene data (normalized or probe-based)\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\"Gene expression data saved to {out_gene_data_file}\")\n",
    "\n",
    "# Load clinical data\n",
    "print(\"Loading clinical features...\")\n",
    "# Check if the clinical data file exists\n",
    "if os.path.exists(out_clinical_data_file):\n",
    "    print(f\"Loading clinical features from {out_clinical_data_file}\")\n",
    "    clinical_data = pd.read_csv(out_clinical_data_file, index_col=0)\n",
    "else:\n",
    "    # Extract clinical features from the original source\n",
    "    print(\"Extracting clinical features from the original source...\")\n",
    "    # Get background information and clinical data\n",
    "    background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']\n",
    "    clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']\n",
    "    background_info, clinical_raw = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)\n",
    "    \n",
    "    # Extract clinical features\n",
    "    clinical_data = geo_select_clinical_features(\n",
    "        clinical_df=clinical_raw,\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",
    "    # Save the extracted clinical features\n",
    "    os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
    "    clinical_data.to_csv(out_clinical_data_file)\n",
    "\n",
    "print(\"Clinical data preview:\")\n",
    "print(preview_df(clinical_data))\n",
    "print(f\"Clinical data shape: {clinical_data.shape}\")\n",
    "\n",
    "# Link clinical and genetic data\n",
    "print(\"Linking clinical and genetic data...\")\n",
    "linked_data = geo_link_clinical_genetic_data(clinical_data, gene_data_normalized)\n",
    "print(f\"Linked data shape: {linked_data.shape}\")\n",
    "\n",
    "# Verify we have both trait and gene data in the linked dataset\n",
    "has_trait_data = trait in linked_data.columns\n",
    "has_genetic_data = len(linked_data.columns) > 3  # More than just trait, age, and gender columns\n",
    "\n",
    "if not has_trait_data or not has_genetic_data:\n",
    "    print(\"Error: Linked data is missing trait data or 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=has_genetic_data,\n",
    "        is_trait_available=has_trait_data,\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 incomplete data.\")\n",
    "else:\n",
    "    # Handle missing values\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",
    "    # If we have samples after missing value handling\n",
    "    if linked_data_clean.shape[0] > 0:\n",
    "        # Check for bias in features\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",
    "        # Final quality validation\n",
    "        note = \"Dataset contains gene expression data (using probe IDs) for Crohn's Disease patients.\"\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=note\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.\")\n",
    "    else:\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.\")"
   ]
  }
 ],
 "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
}