File size: 32,468 Bytes
6bc7e45
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "5da2182e",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:40:38.239927Z",
     "iopub.status.busy": "2025-03-25T06:40:38.239692Z",
     "iopub.status.idle": "2025-03-25T06:40:38.408616Z",
     "shell.execute_reply": "2025-03-25T06:40:38.408161Z"
    }
   },
   "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 = \"Asthma\"\n",
    "cohort = \"GSE182798\"\n",
    "\n",
    "# Input paths\n",
    "in_trait_dir = \"../../input/GEO/Asthma\"\n",
    "in_cohort_dir = \"../../input/GEO/Asthma/GSE182798\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/Asthma/GSE182798.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/Asthma/gene_data/GSE182798.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/Asthma/clinical_data/GSE182798.csv\"\n",
    "json_path = \"../../output/preprocess/Asthma/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f621fdc7",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "3c832158",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:40:38.410119Z",
     "iopub.status.busy": "2025-03-25T06:40:38.409961Z",
     "iopub.status.idle": "2025-03-25T06:40:38.680414Z",
     "shell.execute_reply": "2025-03-25T06:40:38.679927Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Background Information:\n",
      "!Series_title\t\"Transcriptomic profiling of adult-onset asthma related to damp and moldy buildings and idiopathic environmental intolerance\"\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: ['diagnosis: adult-onset asthma', 'diagnosis: IEI', 'diagnosis: healthy'], 1: ['gender: Female'], 2: ['age: 33.42', 'age: 46.08', 'age: 45.58', 'age: 28', 'age: 25.75', 'age: 59.83', 'age: 41.17', 'age: 47.58', 'age: 50.75', 'age: 42.58', 'age: 52.75', 'age: 51.75', 'age: 18.42', 'age: 47', 'age: 38.33', 'age: 58.58', 'age: 56.17', 'age: 40.67', 'age: 47.5', 'age: 54.67', 'age: 48.83', 'age: 64.67', 'age: 54.83', 'age: 57.67', 'age: 39.17', 'age: 38.08', 'age: 28.42', 'age: 40.75', 'age: 43.17', 'age: 43.08'], 3: ['cell type: PBMC', 'tissue: Nasal biopsy'], 4: [nan, 'subject: 605', 'subject: 611', 'subject: 621', 'subject: 35', 'subject: 11', 'subject: 1', 'subject: 601', 'subject: 54', 'subject: 68_A', 'subject: 55', 'subject: 44', 'subject: 603_A', 'subject: 63', 'subject: 39', 'subject: 13', 'subject: 3', 'subject: 619', 'subject: 58', 'subject: 79', 'subject: 77', 'subject: 41', 'subject: 624', 'subject: 37_A', 'subject: 61', 'subject: 31', 'subject: 25', 'subject: 617', 'subject: 65', 'subject: 81']}\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": "afe4d5ca",
   "metadata": {},
   "source": [
    "### Step 2: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "abb1abcc",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:40:38.681686Z",
     "iopub.status.busy": "2025-03-25T06:40:38.681567Z",
     "iopub.status.idle": "2025-03-25T06:40:38.708352Z",
     "shell.execute_reply": "2025-03-25T06:40:38.707876Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Preview of selected clinical features:\n",
      "{'GSM5530417': [1.0, 33.42, 0.0], 'GSM5530418': [1.0, 46.08, 0.0], 'GSM5530419': [nan, 45.58, 0.0], 'GSM5530420': [0.0, 28.0, 0.0], 'GSM5530421': [0.0, 25.75, 0.0], 'GSM5530422': [1.0, 59.83, 0.0], 'GSM5530423': [0.0, 41.17, 0.0], 'GSM5530424': [1.0, 47.58, 0.0], 'GSM5530425': [1.0, 50.75, 0.0], 'GSM5530426': [0.0, 42.58, 0.0], 'GSM5530427': [1.0, 52.75, 0.0], 'GSM5530428': [1.0, 51.75, 0.0], 'GSM5530429': [0.0, 18.42, 0.0], 'GSM5530430': [0.0, 47.0, 0.0], 'GSM5530431': [0.0, 38.33, 0.0], 'GSM5530432': [1.0, 58.58, 0.0], 'GSM5530433': [1.0, 56.17, 0.0], 'GSM5530434': [1.0, 52.75, 0.0], 'GSM5530435': [nan, 40.67, 0.0], 'GSM5530436': [1.0, 47.5, 0.0], 'GSM5530437': [1.0, 54.67, 0.0], 'GSM5530438': [0.0, 48.83, 0.0], 'GSM5530439': [0.0, 25.75, 0.0], 'GSM5530440': [1.0, 64.67, 0.0], 'GSM5530441': [1.0, 54.83, 0.0], 'GSM5530442': [nan, 57.67, 0.0], 'GSM5530443': [nan, 39.17, 0.0], 'GSM5530444': [0.0, 38.08, 0.0], 'GSM5530445': [1.0, 28.42, 0.0], 'GSM5530446': [1.0, 40.75, 0.0], 'GSM5530447': [1.0, 43.17, 0.0], 'GSM5530448': [0.0, 43.08, 0.0], 'GSM5530449': [1.0, 48.83, 0.0], 'GSM5530450': [0.0, 58.83, 0.0], 'GSM5530451': [0.0, 26.58, 0.0], 'GSM5530452': [0.0, 42.5, 0.0], 'GSM5530453': [nan, 48.25, 0.0], 'GSM5530454': [1.0, 39.25, 0.0], 'GSM5530455': [1.0, 55.33, 0.0], 'GSM5530456': [0.0, 47.0, 0.0], 'GSM5530457': [1.0, 55.75, 0.0], 'GSM5530458': [1.0, 47.08, 0.0], 'GSM5530459': [nan, 47.5, 0.0], 'GSM5530460': [1.0, 53.58, 0.0], 'GSM5530461': [1.0, 60.17, 0.0], 'GSM5530462': [0.0, 40.58, 0.0], 'GSM5530463': [1.0, 50.5, 0.0], 'GSM5530464': [1.0, 46.17, 0.0], 'GSM5530465': [1.0, 51.33, 0.0], 'GSM5530466': [nan, 56.67, 0.0], 'GSM5530467': [0.0, 37.5, 0.0], 'GSM5530468': [0.0, 48.83, 0.0], 'GSM5530469': [1.0, 38.08, 0.0], 'GSM5530470': [1.0, 52.58, 0.0], 'GSM5530471': [0.0, 52.67, 0.0], 'GSM5530472': [1.0, 59.58, 0.0], 'GSM5530473': [1.0, 56.25, 0.0], 'GSM5530474': [nan, 46.42, 0.0], 'GSM5530475': [0.0, 47.08, 0.0], 'GSM5530476': [0.0, 52.67, 0.0], 'GSM5530477': [1.0, 60.08, 0.0], 'GSM5530478': [1.0, 44.67, 0.0], 'GSM5530479': [nan, 57.58, 0.0], 'GSM5530480': [0.0, 26.58, 0.0], 'GSM5530481': [nan, 53.5, 0.0], 'GSM5530482': [0.0, 58.83, 0.0], 'GSM5530483': [0.0, 41.5, 0.0], 'GSM5530484': [1.0, 47.17, 0.0], 'GSM5530485': [1.0, 51.25, 0.0], 'GSM5530486': [1.0, 33.08, 0.0], 'GSM5530487': [nan, 50.33, 0.0], 'GSM5530488': [nan, 60.17, 0.0], 'GSM5530489': [0.0, 19.17, 0.0], 'GSM5530490': [1.0, 40.67, 0.0], 'GSM5530491': [1.0, 24.25, 0.0], 'GSM5530492': [0.0, 43.08, 0.0], 'GSM5530493': [0.0, 51.75, 0.0], 'GSM5530494': [1.0, 41.17, 0.0], 'GSM5530495': [1.0, 30.83, 0.0], 'GSM5530496': [0.0, 40.58, 0.0], 'GSM5530497': [0.0, 42.58, 0.0], 'GSM5530498': [1.0, 52.75, 0.0], 'GSM5530499': [nan, 43.17, 0.0], 'GSM5530500': [1.0, 24.75, 0.0], 'GSM5530501': [0.0, 51.75, 0.0], 'GSM5530502': [1.0, 24.5, 0.0], 'GSM5530503': [1.0, 44.5, 0.0], 'GSM5530504': [nan, 53.17, 0.0], 'GSM5530505': [0.0, 38.08, 0.0], 'GSM5530506': [0.0, 37.83, 0.0], 'GSM5530507': [nan, 41.33, 0.0], 'GSM5530508': [1.0, 47.67, 0.0], 'GSM5530509': [1.0, 57.75, 0.0], 'GSM5530510': [0.0, 37.5, 0.0], 'GSM5530511': [0.0, 41.5, 0.0], 'GSM5530512': [1.0, 44.25, 0.0], 'GSM5530513': [nan, 53.58, 0.0], 'GSM5530514': [1.0, 45.58, 0.0], 'GSM5530515': [0.0, 19.17, 0.0], 'GSM5530516': [0.0, 18.42, 0.0], 'GSM5530517': [1.0, 57.08, 0.0], 'GSM5530518': [1.0, 60.67, 0.0], 'GSM5537157': [0.0, 38.33, 0.0], 'GSM5537158': [0.0, 38.08, 0.0], 'GSM5537159': [0.0, 48.83, 0.0], 'GSM5537160': [1.0, 33.42, 0.0], 'GSM5537161': [1.0, 46.08, 0.0], 'GSM5537162': [nan, 45.58, 0.0], 'GSM5537163': [0.0, 28.0, 0.0], 'GSM5537164': [1.0, 30.83, 0.0], 'GSM5537165': [1.0, 39.25, 0.0], 'GSM5537166': [nan, 60.17, 0.0], 'GSM5537167': [1.0, 52.75, 0.0], 'GSM5537168': [0.0, 25.75, 0.0], 'GSM5537169': [1.0, 60.67, 0.0], 'GSM5537170': [1.0, 64.67, 0.0], 'GSM5537171': [1.0, 54.83, 0.0], 'GSM5537172': [nan, 57.67, 0.0], 'GSM5537173': [0.0, 47.0, 0.0], 'GSM5537174': [1.0, 47.5, 0.0], 'GSM5537175': [1.0, 24.25, 0.0], 'GSM5537176': [1.0, 47.67, 0.0], 'GSM5537177': [1.0, 47.58, 0.0], 'GSM5537178': [0.0, 18.42, 0.0], 'GSM5537179': [nan, 41.33, 0.0], 'GSM5537180': [1.0, 24.5, 0.0], 'GSM5537181': [1.0, 47.08, 0.0], 'GSM5537182': [nan, 47.5, 0.0], 'GSM5537183': [0.0, 41.17, 0.0], 'GSM5537184': [1.0, 48.83, 0.0], 'GSM5537185': [1.0, 47.17, 0.0], 'GSM5537186': [1.0, 59.83, 0.0], 'GSM5537187': [0.0, 42.58, 0.0], 'GSM5537188': [nan, 56.67, 0.0], 'GSM5537189': [0.0, 37.5, 0.0], 'GSM5537190': [1.0, 58.58, 0.0], 'GSM5537191': [1.0, 24.75, 0.0], 'GSM5537192': [1.0, 52.75, 0.0], 'GSM5537193': [1.0, 55.33, 0.0], 'GSM5537194': [1.0, 56.17, 0.0], 'GSM5537195': [1.0, 52.75, 0.0], 'GSM5537196': [nan, 40.67, 0.0], 'GSM5537197': [0.0, 19.17, 0.0], 'GSM5537198': [0.0, 42.5, 0.0], 'GSM5537199': [1.0, 57.08, 0.0], 'GSM5537200': [0.0, 40.58, 0.0], 'GSM5537201': [1.0, 40.67, 0.0], 'GSM5537202': [1.0, 55.75, 0.0], 'GSM5537203': [1.0, 43.17, 0.0], 'GSM5537204': [1.0, 59.58, 0.0], 'GSM5537205': [1.0, 56.25, 0.0], 'GSM5537206': [nan, 46.42, 0.0], 'GSM5537207': [0.0, 47.08, 0.0], 'GSM5537208': [0.0, 51.75, 0.0], 'GSM5537209': [nan, 53.5, 0.0], 'GSM5537210': [1.0, 52.58, 0.0], 'GSM5537211': [nan, 52.25, 0.0], 'GSM5537212': [1.0, 45.58, 0.0], 'GSM5537213': [0.0, 52.67, 0.0], 'GSM5537214': [1.0, 50.5, 0.0], 'GSM5537215': [1.0, 60.08, 0.0], 'GSM5537216': [1.0, 44.67, 0.0], 'GSM5537217': [nan, 57.58, 0.0], 'GSM5537218': [nan, 53.17, 0.0], 'GSM5537219': [1.0, 51.33, 0.0], 'GSM5537220': [1.0, 46.17, 0.0], 'GSM5537221': [0.0, 26.58, 0.0], 'GSM5537222': [1.0, 60.17, 0.0], 'GSM5537223': [1.0, 54.67, 0.0], 'GSM5537224': [1.0, 57.75, 0.0], 'GSM5537225': [1.0, 28.42, 0.0], 'GSM5537226': [1.0, 33.08, 0.0], 'GSM5537227': [nan, 50.33, 0.0], 'GSM5537228': [0.0, 37.83, 0.0], 'GSM5537229': [1.0, 44.25, 0.0], 'GSM5537230': [0.0, 58.83, 0.0], 'GSM5537231': [nan, 48.25, 0.0], 'GSM5537232': [0.0, 43.08, 0.0], 'GSM5537233': [1.0, 41.17, 0.0], 'GSM5537234': [1.0, 51.75, 0.0], 'GSM5537235': [1.0, 53.58, 0.0], 'GSM5537236': [0.0, 41.5, 0.0]}\n",
      "Clinical data saved to ../../output/preprocess/Asthma/clinical_data/GSE182798.csv\n"
     ]
    }
   ],
   "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "import os\n",
    "from typing import Optional, Callable, Any, Dict\n",
    "\n",
    "# 1. Gene Expression Data Availability\n",
    "# Based on the background information, this dataset seems to contain transcriptomic profiling\n",
    "# which suggests gene expression data is available\n",
    "is_gene_available = True\n",
    "\n",
    "# 2. Variable Availability and Data Type Conversion\n",
    "# 2.1 Identify keys for trait, age, and gender\n",
    "trait_row = 0  # diagnosis information is in row 0\n",
    "age_row = 2    # age information is in row 2\n",
    "gender_row = 1 # gender information is in row 1\n",
    "\n",
    "# 2.2 Define conversion functions\n",
    "def convert_trait(value: str) -> Optional[int]:\n",
    "    \"\"\"Convert trait values to binary (0 for control, 1 for Asthma).\"\"\"\n",
    "    if pd.isna(value):\n",
    "        return None\n",
    "    \n",
    "    # Extract value after colon\n",
    "    if \":\" in value:\n",
    "        value = value.split(\":\", 1)[1].strip()\n",
    "    \n",
    "    # Convert to binary\n",
    "    if \"adult-onset asthma\" in value.lower():\n",
    "        return 1  # Asthma\n",
    "    elif \"healthy\" in value.lower():\n",
    "        return 0  # Control\n",
    "    else:\n",
    "        return None  # IEI or other conditions\n",
    "\n",
    "def convert_age(value: str) -> Optional[float]:\n",
    "    \"\"\"Convert age values to float.\"\"\"\n",
    "    if pd.isna(value):\n",
    "        return None\n",
    "    \n",
    "    # Extract value after colon\n",
    "    if \":\" in value:\n",
    "        value = value.split(\":\", 1)[1].strip()\n",
    "    \n",
    "    try:\n",
    "        return float(value)\n",
    "    except ValueError:\n",
    "        return None\n",
    "\n",
    "def convert_gender(value: str) -> Optional[int]:\n",
    "    \"\"\"Convert gender values to binary (0 for female, 1 for male).\"\"\"\n",
    "    if pd.isna(value):\n",
    "        return None\n",
    "    \n",
    "    # Extract value after colon\n",
    "    if \":\" in value:\n",
    "        value = value.split(\":\", 1)[1].strip().lower()\n",
    "    \n",
    "    if \"female\" in value:\n",
    "        return 0\n",
    "    elif \"male\" in value:\n",
    "        return 1\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "# 3. Save Metadata\n",
    "# Determine trait availability\n",
    "is_trait_available = trait_row is not None\n",
    "\n",
    "# Initial filtering validation\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",
    "    try:\n",
    "        # Assuming clinical_data was loaded in a previous step\n",
    "        # If not, we need to load it\n",
    "        if 'clinical_data' not in locals() and 'clinical_data' not in globals():\n",
    "            # Define the expected path for clinical data\n",
    "            clinical_data_path = os.path.join(in_cohort_dir, f\"{cohort}_sample_characteristics.csv\")\n",
    "            if os.path.exists(clinical_data_path):\n",
    "                clinical_data = pd.read_csv(clinical_data_path)\n",
    "            else:\n",
    "                print(f\"Clinical data file not found at {clinical_data_path}\")\n",
    "                # Consider alternative loading methods if needed\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",
    "        # Preview the processed data\n",
    "        preview = preview_df(selected_clinical_df)\n",
    "        print(\"Preview of selected clinical features:\")\n",
    "        print(preview)\n",
    "        \n",
    "        # Create directory if it doesn't exist\n",
    "        os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
    "        \n",
    "        # Save to CSV\n",
    "        selected_clinical_df.to_csv(out_clinical_data_file, index=False)\n",
    "        print(f\"Clinical data saved to {out_clinical_data_file}\")\n",
    "    except Exception as e:\n",
    "        print(f\"Error in clinical feature extraction: {e}\")\n",
    "else:\n",
    "    print(\"Clinical data not available, skipping clinical feature extraction.\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4db7a299",
   "metadata": {},
   "source": [
    "### Step 3: Gene Data Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "9d5f1e11",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:40:38.709578Z",
     "iopub.status.busy": "2025-03-25T06:40:38.709462Z",
     "iopub.status.idle": "2025-03-25T06:40:39.230312Z",
     "shell.execute_reply": "2025-03-25T06:40:39.229585Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Matrix file found: ../../input/GEO/Asthma/GSE182798/GSE182798_series_matrix.txt.gz\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene data shape: (39341, 182)\n",
      "First 20 gene/probe identifiers:\n",
      "Index(['A_19_P00315452', 'A_19_P00315492', 'A_19_P00315493', 'A_19_P00315502',\n",
      "       'A_19_P00315506', 'A_19_P00315518', 'A_19_P00315529', 'A_19_P00315543',\n",
      "       'A_19_P00315551', 'A_19_P00315581', 'A_19_P00315584', 'A_19_P00315593',\n",
      "       'A_19_P00315603', 'A_19_P00315627', 'A_19_P00315631', 'A_19_P00315641',\n",
      "       'A_19_P00315647', 'A_19_P00315649', 'A_19_P00315668', 'A_19_P00315691'],\n",
      "      dtype='object', name='ID')\n"
     ]
    }
   ],
   "source": [
    "# 1. Get the SOFT and matrix file paths again \n",
    "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
    "print(f\"Matrix file found: {matrix_file}\")\n",
    "\n",
    "# 2. Use the get_genetic_data function from the library to get the gene_data\n",
    "try:\n",
    "    gene_data = get_genetic_data(matrix_file)\n",
    "    print(f\"Gene data shape: {gene_data.shape}\")\n",
    "    \n",
    "    # 3. Print the first 20 row IDs (gene or probe identifiers)\n",
    "    print(\"First 20 gene/probe identifiers:\")\n",
    "    print(gene_data.index[:20])\n",
    "except Exception as e:\n",
    "    print(f\"Error extracting gene data: {e}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4b397369",
   "metadata": {},
   "source": [
    "### Step 4: Gene Identifier Review"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "1bf20cd0",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:40:39.231682Z",
     "iopub.status.busy": "2025-03-25T06:40:39.231561Z",
     "iopub.status.idle": "2025-03-25T06:40:39.234113Z",
     "shell.execute_reply": "2025-03-25T06:40:39.233663Z"
    }
   },
   "outputs": [],
   "source": [
    "# The identifiers in the gene expression data do not appear to be standard human gene symbols.\n",
    "# They appear to be Agilent microarray probe IDs (starting with \"A_19_P\"), which are platform-specific\n",
    "# identifiers that need to be mapped to standard gene symbols.\n",
    "# These probe IDs typically need mapping to official gene symbols for downstream analysis.\n",
    "\n",
    "requires_gene_mapping = True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "32f9ceda",
   "metadata": {},
   "source": [
    "### Step 5: Gene Annotation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "891ba95e",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:40:39.235305Z",
     "iopub.status.busy": "2025-03-25T06:40:39.235194Z",
     "iopub.status.idle": "2025-03-25T06:40:48.520112Z",
     "shell.execute_reply": "2025-03-25T06:40:48.519461Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene annotation preview:\n",
      "{'ID': ['GE_BrightCorner', 'DarkCorner', 'A_21_P0014386', 'A_33_P3396872', 'A_33_P3267760'], 'CONTROL_TYPE': ['pos', 'pos', 'FALSE', 'FALSE', 'FALSE'], 'REFSEQ': [nan, nan, nan, 'NM_001105533', nan], 'GB_ACC': [nan, nan, nan, 'NM_001105533', nan], 'LOCUSLINK_ID': [nan, nan, nan, 79974.0, 54880.0], 'GENE_SYMBOL': [nan, nan, nan, 'CPED1', 'BCOR'], 'GENE_NAME': [nan, nan, nan, 'cadherin-like and PC-esterase domain containing 1', 'BCL6 corepressor'], 'UNIGENE_ID': [nan, nan, nan, 'Hs.189652', nan], 'ENSEMBL_ID': [nan, nan, nan, nan, 'ENST00000378463'], 'ACCESSION_STRING': [nan, nan, nan, 'ref|NM_001105533|gb|AK025639|gb|BC030538|tc|THC2601673', 'ens|ENST00000378463'], 'CHROMOSOMAL_LOCATION': [nan, nan, 'unmapped', 'chr7:120901888-120901947', 'chrX:39909128-39909069'], 'CYTOBAND': [nan, nan, nan, 'hs|7q31.31', 'hs|Xp11.4'], 'DESCRIPTION': [nan, nan, nan, 'Homo sapiens cadherin-like and PC-esterase domain containing 1 (CPED1), transcript variant 2, mRNA [NM_001105533]', 'BCL6 corepressor [Source:HGNC Symbol;Acc:HGNC:20893] [ENST00000378463]'], 'GO_ID': [nan, nan, nan, 'GO:0005783(endoplasmic reticulum)', 'GO:0000122(negative regulation of transcription from RNA polymerase II promoter)|GO:0000415(negative regulation of histone H3-K36 methylation)|GO:0003714(transcription corepressor activity)|GO:0004842(ubiquitin-protein ligase activity)|GO:0005515(protein binding)|GO:0005634(nucleus)|GO:0006351(transcription, DNA-dependent)|GO:0007507(heart development)|GO:0008134(transcription factor binding)|GO:0030502(negative regulation of bone mineralization)|GO:0031072(heat shock protein binding)|GO:0031519(PcG protein complex)|GO:0035518(histone H2A monoubiquitination)|GO:0042476(odontogenesis)|GO:0042826(histone deacetylase binding)|GO:0044212(transcription regulatory region DNA binding)|GO:0045892(negative regulation of transcription, DNA-dependent)|GO:0051572(negative regulation of histone H3-K4 methylation)|GO:0060021(palate development)|GO:0065001(specification of axis polarity)|GO:0070171(negative regulation of tooth mineralization)'], 'SEQUENCE': [nan, nan, 'AATACATGTTTTGGTAAACACTCGGTCAGAGCACCCTCTTTCTGTGGAATCAGACTGGCA', 'GCTTATCTCACCTAATACAGGGACTATGCAACCAAGAAACTGGAAATAAAAACAAAGATA', 'CATCAAAGCTACGAGAGATCCTACACACCCAGATTTAAAAAATAATAAAAACTTAAGGGC'], 'SPOT_ID': ['GE_BrightCorner', 'DarkCorner', 'A_21_P0014386', 'A_33_P3396872', 'A_33_P3267760']}\n"
     ]
    }
   ],
   "source": [
    "# 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.\n",
    "gene_annotation = get_gene_annotation(soft_file)\n",
    "\n",
    "# 2. Use the 'preview_df' function from the library to preview the data and print out the results.\n",
    "print(\"Gene annotation preview:\")\n",
    "print(preview_df(gene_annotation))\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b0601c77",
   "metadata": {},
   "source": [
    "### Step 6: Gene Identifier Mapping"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "fbd8b415",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:40:48.521610Z",
     "iopub.status.busy": "2025-03-25T06:40:48.521474Z",
     "iopub.status.idle": "2025-03-25T06:40:51.041792Z",
     "shell.execute_reply": "2025-03-25T06:40:51.041154Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene mapping shape: (48862, 2)\n",
      "Sample of gene mapping:\n",
      "{'ID': ['A_33_P3396872', 'A_33_P3267760', 'A_32_P194264', 'A_23_P153745', 'A_21_P0014180'], 'Gene': ['CPED1', 'BCOR', 'CHAC2', 'IFI30', 'GPR146']}\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene expression data shape after mapping: (22196, 182)\n",
      "First few gene symbols after mapping:\n",
      "['A1BG', 'A1BG-AS1', 'A1CF-3', 'A2M', 'A2M-1', 'A2M-AS1', 'A2ML1', 'A2MP1', 'A4GALT', 'AAAS']\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene expression data saved to ../../output/preprocess/Asthma/gene_data/GSE182798.csv\n"
     ]
    }
   ],
   "source": [
    "# From inspecting previous outputs, I can see:\n",
    "# - Gene expression data has identifiers like 'A_19_P00315452'\n",
    "# - Gene annotation data has 'ID' column with values like 'A_21_P0014386', 'A_33_P3396872', etc.\n",
    "# - The gene symbols are in the 'GENE_SYMBOL' column\n",
    "\n",
    "# 1. Determine which columns to use for mapping\n",
    "# The ID column in gene_annotation contains microarray probe IDs similar to gene expression indices\n",
    "# The GENE_SYMBOL column contains the human gene symbols we want to map to\n",
    "id_column = 'ID'\n",
    "gene_symbol_column = 'GENE_SYMBOL'\n",
    "\n",
    "# 2. Get gene mapping dataframe by extracting relevant columns\n",
    "gene_mapping = get_gene_mapping(gene_annotation, id_column, gene_symbol_column)\n",
    "print(f\"Gene mapping shape: {gene_mapping.shape}\")\n",
    "print(\"Sample of gene mapping:\")\n",
    "print(preview_df(gene_mapping))\n",
    "\n",
    "# 3. Apply gene mapping to convert probe-level data to gene-level expression data\n",
    "gene_data = apply_gene_mapping(gene_data, gene_mapping)\n",
    "print(f\"Gene expression data shape after mapping: {gene_data.shape}\")\n",
    "print(\"First few gene symbols after mapping:\")\n",
    "print(list(gene_data.index[:10]))\n",
    "\n",
    "# Save the gene expression data to a CSV file\n",
    "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
    "gene_data.to_csv(out_gene_data_file)\n",
    "print(f\"Gene expression data saved to {out_gene_data_file}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e9e8434a",
   "metadata": {},
   "source": [
    "### Step 7: Data Normalization and Linking"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "34b10624",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:40:51.043279Z",
     "iopub.status.busy": "2025-03-25T06:40:51.043147Z",
     "iopub.status.idle": "2025-03-25T06:41:07.096835Z",
     "shell.execute_reply": "2025-03-25T06:41:07.096154Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Normalized gene data saved to ../../output/preprocess/Asthma/gene_data/GSE182798.csv\n",
      "Clinical data saved to ../../output/preprocess/Asthma/clinical_data/GSE182798.csv\n",
      "Linked data shape: (182, 18157)\n",
      "Linked data preview (first 5 rows, 5 columns):\n",
      "            Asthma    Age  Gender     A1BG  A1BG-AS1\n",
      "GSM5530417     1.0  33.42     0.0  9.58489   6.85151\n",
      "GSM5530418     1.0  46.08     0.0  9.65673   6.74284\n",
      "GSM5530419     NaN  45.58     0.0  9.55825   6.47113\n",
      "GSM5530420     0.0  28.00     0.0  9.71055   6.90045\n",
      "GSM5530421     0.0  25.75     0.0  9.22204   6.75952\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Data shape after handling missing values: (152, 18157)\n",
      "For the feature 'Asthma', the least common label is '0.0' with 57 occurrences. This represents 37.50% of the dataset.\n",
      "The distribution of the feature 'Asthma' in this dataset is fine.\n",
      "\n",
      "Quartiles for 'Age':\n",
      "  25%: 38.33\n",
      "  50% (Median): 47.0\n",
      "  75%: 52.75\n",
      "Min: 18.42\n",
      "Max: 64.67\n",
      "The distribution of the feature 'Age' in this dataset is fine.\n",
      "\n",
      "For the feature 'Gender', the least common label is '0.0' with 152 occurrences. This represents 100.00% of the dataset.\n",
      "The distribution of the feature 'Gender' in this dataset is severely biased.\n",
      "\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Linked data saved to ../../output/preprocess/Asthma/GSE182798.csv\n"
     ]
    }
   ],
   "source": [
    "# 1. Normalize gene symbols in the gene expression data\n",
    "gene_data = normalize_gene_symbols_in_index(gene_data)\n",
    "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
    "gene_data.to_csv(out_gene_data_file)\n",
    "print(f\"Normalized gene data saved to {out_gene_data_file}\")\n",
    "\n",
    "# Define the correct convert_trait function as established in Step 2\n",
    "def convert_trait(value: str) -> Optional[int]:\n",
    "    \"\"\"Convert trait values to binary (0 for control, 1 for Asthma).\"\"\"\n",
    "    if pd.isna(value):\n",
    "        return None\n",
    "    \n",
    "    # Extract value after colon\n",
    "    if \":\" in value:\n",
    "        value = value.split(\":\", 1)[1].strip()\n",
    "    \n",
    "    # Convert to binary\n",
    "    if \"adult-onset asthma\" in value.lower():\n",
    "        return 1  # Asthma\n",
    "    elif \"healthy\" in value.lower():\n",
    "        return 0  # Control\n",
    "    else:\n",
    "        return None  # IEI or other conditions\n",
    "\n",
    "def convert_age(value: str) -> Optional[float]:\n",
    "    \"\"\"Convert age values to float.\"\"\"\n",
    "    if pd.isna(value):\n",
    "        return None\n",
    "    \n",
    "    # Extract value after colon\n",
    "    if \":\" in value:\n",
    "        value = value.split(\":\", 1)[1].strip()\n",
    "    \n",
    "    try:\n",
    "        return float(value)\n",
    "    except ValueError:\n",
    "        return None\n",
    "\n",
    "def convert_gender(value: str) -> Optional[int]:\n",
    "    \"\"\"Convert gender values to binary (0 for female, 1 for male).\"\"\"\n",
    "    if pd.isna(value):\n",
    "        return None\n",
    "    \n",
    "    # Extract value after colon\n",
    "    if \":\" in value:\n",
    "        value = value.split(\":\", 1)[1].strip().lower()\n",
    "    \n",
    "    if \"female\" in value:\n",
    "        return 0\n",
    "    elif \"male\" in value:\n",
    "        return 1\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "# Re-extract clinical features using the appropriate conversion functions\n",
    "selected_clinical_df = geo_select_clinical_features(\n",
    "    clinical_df=clinical_data,\n",
    "    trait=trait,\n",
    "    trait_row=0,  # Correct trait row from Step 2\n",
    "    convert_trait=convert_trait,\n",
    "    age_row=2,     # Age row from Step 2\n",
    "    convert_age=convert_age,\n",
    "    gender_row=1,  # Gender row from Step 2\n",
    "    convert_gender=convert_gender\n",
    ")\n",
    "\n",
    "# Save the processed clinical data\n",
    "os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
    "selected_clinical_df.to_csv(out_clinical_data_file)\n",
    "print(f\"Clinical data saved to {out_clinical_data_file}\")\n",
    "\n",
    "# 2. Link clinical and genetic data\n",
    "linked_data = geo_link_clinical_genetic_data(selected_clinical_df, gene_data)\n",
    "print(f\"Linked data shape: {linked_data.shape}\")\n",
    "print(\"Linked data preview (first 5 rows, 5 columns):\")\n",
    "print(linked_data.iloc[:5, :5] if not linked_data.empty else \"Linked data is empty\")\n",
    "\n",
    "# 3. Handle missing values\n",
    "linked_data = handle_missing_values(linked_data, trait)\n",
    "print(f\"Data shape after handling missing values: {linked_data.shape}\")\n",
    "\n",
    "# 4. Check for bias in features\n",
    "is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n",
    "\n",
    "# 5. Validate and save cohort information\n",
    "is_usable = validate_and_save_cohort_info(\n",
    "    is_final=True,\n",
    "    cohort=cohort,\n",
    "    info_path=json_path,\n",
    "    is_gene_available=True,\n",
    "    is_trait_available=True,\n",
    "    is_biased=is_biased,\n",
    "    df=linked_data,\n",
    "    note=\"Dataset contains gene expression data from adult patients with asthma related to damp/moldy buildings and controls.\"\n",
    ")\n",
    "\n",
    "# 6. Save the linked data if usable\n",
    "if is_usable:\n",
    "    os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n",
    "    linked_data.to_csv(out_data_file)\n",
    "    print(f\"Linked data saved to {out_data_file}\")\n",
    "else:\n",
    "    print(\"Dataset is not usable for analysis. No linked data file 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
}