File size: 35,519 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
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "d2b26b7c",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:41:36.885459Z",
     "iopub.status.busy": "2025-03-25T08:41:36.885124Z",
     "iopub.status.idle": "2025-03-25T08:41:37.046538Z",
     "shell.execute_reply": "2025-03-25T08:41:37.046116Z"
    }
   },
   "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 = \"Eczema\"\n",
    "cohort = \"GSE63741\"\n",
    "\n",
    "# Input paths\n",
    "in_trait_dir = \"../../input/GEO/Eczema\"\n",
    "in_cohort_dir = \"../../input/GEO/Eczema/GSE63741\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/Eczema/GSE63741.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/Eczema/gene_data/GSE63741.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/Eczema/clinical_data/GSE63741.csv\"\n",
    "json_path = \"../../output/preprocess/Eczema/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7846782c",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "df60fe3c",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:41:37.047928Z",
     "iopub.status.busy": "2025-03-25T08:41:37.047793Z",
     "iopub.status.idle": "2025-03-25T08:41:37.069790Z",
     "shell.execute_reply": "2025-03-25T08:41:37.069417Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Background Information:\n",
      "!Series_title\t\"Gene Expression Analyses of Homo sapiens Inflammatory Skin Diseases\"\n",
      "!Series_summary\t\"Transcriptional profiling of Homo sapiens inflammatory skin diseases (whole skin biospies): Psoriasis (Pso), vs Atopic Dermatitis  (AD) vs Lichen planus (Li), vs Contact Eczema (KE), vs Healthy control (KO)\"\n",
      "!Series_summary\t\"In recent years, different genes and proteins have been highlighted as potential biomarkers for psoriasis, one of the most common inflammatory skin diseases worldwide. However, most of these markers are not psoriasis-specific but also found in other inflammatory disorders.  We performed an unsupervised cluster analysis of gene expression profiles in 150 psoriasis patients and other inflammatory skin diseases (atopic dermatitis, lichen planus, contact eczema, and healthy controls). We identified a cluster of IL-17/TNFα-associated genes specifically expressed in psoriasis, among which IL-36γ was the most outstanding marker. In subsequent immunohistological analyses IL-36γ was confirmed to be expressed in psoriasis lesions only. IL-36γ peripheral blood serum levels were found to be closely associated with disease activity, and they decreased after anti-TNFα-treatment. Furthermore, IL-36γ immunohistochemistry was found to be a helpful marker in the histological differential diagnosis between psoriasis and eczema in diagnostically challenging cases.   These features highlight IL-36γ as a valuable biomarker in psoriasis patients, both for diagnostic purposes and measurement of disease activity during the clinical course. Furthermore, IL-36γ might also provide a future drug target, due to its potential amplifier role in TNFα- and IL-17 pathways in psoriatic skin inflammation.   In recent years, different genes and proteins have been highlighted as potential biomarkers for psoriasis, one of the most common inflammatory skin diseases worldwide. However, most of these markers are not psoriasis-specific but also found in other inflammatory disorders.  We performed an unsupervised cluster analysis of gene expression profiles in 150 psoriasis patients and other inflammatory skin diseases (atopic dermatitis, lichen planus, contact eczema, and healthy controls). We identified a cluster of IL-17/TNFα-associated genes specifically expressed in psoriasis, among which IL-36γ was the most outstanding marker. In subsequent immunohistological analyses IL-36γ was confirmed to be expressed in psoriasis lesions only. IL-36γ peripheral blood serum levels were found to be closely associated with disease activity, and they decreased after anti-TNFα-treatment. Furthermore, IL-36γ immunohistochemistry was found to be a helpful marker in the histological differential diagnosis between psoriasis and eczema in diagnostically challenging cases.   These features highlight IL-36γ as a valuable biomarker in psoriasis patients, both for diagnostic purposes and measurement of disease activity during the clinical course. Furthermore, IL-36γ might also provide a future drug target, due to its potential amplifier role in TNFα- and IL-17 pathways in psoriatic skin inflammation.\"\n",
      "!Series_overall_design\t\"Ex vivo analyses: gene expression analyses (total RNA) of lesional skin versus common skin reference (two channel)\"\n",
      "Sample Characteristics Dictionary:\n",
      "{0: ['tissue: whole skin biopsy'], 1: ['sample type: skin biopsies from pool of 160 patients with skin disorders and healthy donors']}\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": "01532724",
   "metadata": {},
   "source": [
    "### Step 2: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "68f4466b",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:41:37.070782Z",
     "iopub.status.busy": "2025-03-25T08:41:37.070677Z",
     "iopub.status.idle": "2025-03-25T08:41:37.082095Z",
     "shell.execute_reply": "2025-03-25T08:41:37.081752Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Preview of selected clinical features:\n",
      "{'GSM1556392': [0.0], 'GSM1556393': [0.0], 'GSM1556394': [0.0], 'GSM1556395': [0.0], 'GSM1556396': [0.0], 'GSM1556397': [0.0], 'GSM1556398': [0.0], 'GSM1556399': [0.0], 'GSM1556400': [0.0], 'GSM1556401': [0.0], 'GSM1556402': [0.0], 'GSM1556403': [0.0], 'GSM1556404': [0.0], 'GSM1556405': [0.0], 'GSM1556406': [0.0], 'GSM1556407': [0.0], 'GSM1556408': [0.0], 'GSM1556409': [0.0], 'GSM1556410': [0.0], 'GSM1556411': [0.0], 'GSM1556412': [0.0], 'GSM1556413': [0.0], 'GSM1556414': [0.0], 'GSM1556415': [0.0], 'GSM1556416': [0.0], 'GSM1556417': [0.0], 'GSM1556418': [0.0], 'GSM1556419': [0.0], 'GSM1556420': [0.0], 'GSM1556421': [0.0], 'GSM1556422': [0.0], 'GSM1556423': [0.0], 'GSM1556424': [0.0], 'GSM1556425': [0.0], 'GSM1556426': [0.0], 'GSM1556427': [0.0], 'GSM1556428': [0.0], 'GSM1556429': [0.0], 'GSM1556430': [0.0], 'GSM1556431': [0.0], 'GSM1556432': [0.0], 'GSM1556433': [0.0], 'GSM1556434': [0.0], 'GSM1556435': [0.0], 'GSM1556436': [0.0], 'GSM1556437': [0.0], 'GSM1556438': [0.0], 'GSM1556439': [0.0], 'GSM1556440': [0.0], 'GSM1556441': [0.0], 'GSM1556442': [0.0], 'GSM1556443': [0.0], 'GSM1556444': [0.0], 'GSM1556445': [0.0], 'GSM1556446': [0.0], 'GSM1556447': [0.0], 'GSM1556448': [0.0], 'GSM1556449': [0.0], 'GSM1556450': [0.0], 'GSM1556451': [0.0], 'GSM1556452': [0.0], 'GSM1556453': [0.0], 'GSM1556454': [0.0], 'GSM1556455': [0.0], 'GSM1556456': [0.0], 'GSM1556457': [0.0], 'GSM1556458': [0.0], 'GSM1556459': [0.0], 'GSM1556460': [0.0], 'GSM1556461': [0.0], 'GSM1556462': [0.0], 'GSM1556463': [0.0], 'GSM1556464': [0.0], 'GSM1556465': [0.0], 'GSM1556466': [0.0], 'GSM1556467': [0.0], 'GSM1556468': [0.0], 'GSM1556469': [0.0], 'GSM1556470': [0.0], 'GSM1556471': [0.0], 'GSM1556472': [0.0], 'GSM1556473': [0.0], 'GSM1556474': [0.0], 'GSM1556475': [0.0], 'GSM1556476': [0.0], 'GSM1556477': [0.0], 'GSM1556478': [0.0], 'GSM1556479': [0.0], 'GSM1556480': [0.0], 'GSM1556481': [0.0], 'GSM1556482': [0.0], 'GSM1556483': [0.0], 'GSM1556484': [0.0], 'GSM1556485': [0.0], 'GSM1556486': [0.0], 'GSM1556487': [0.0], 'GSM1556488': [0.0], 'GSM1556489': [0.0], 'GSM1556490': [0.0], 'GSM1556491': [0.0], 'GSM1556492': [0.0], 'GSM1556493': [0.0], 'GSM1556494': [0.0], 'GSM1556495': [0.0], 'GSM1556496': [0.0], 'GSM1556497': [0.0], 'GSM1556498': [0.0], 'GSM1556499': [0.0], 'GSM1556500': [0.0], 'GSM1556501': [0.0], 'GSM1556502': [0.0], 'GSM1556503': [0.0], 'GSM1556504': [0.0], 'GSM1556505': [0.0], 'GSM1556506': [0.0], 'GSM1556507': [0.0], 'GSM1556508': [0.0], 'GSM1556509': [0.0], 'GSM1556510': [0.0], 'GSM1556511': [0.0], 'GSM1556512': [0.0], 'GSM1556513': [0.0], 'GSM1556514': [0.0], 'GSM1556515': [0.0], 'GSM1556516': [0.0], 'GSM1556517': [0.0], 'GSM1556518': [0.0], 'GSM1556519': [0.0], 'GSM1556520': [0.0], 'GSM1556521': [0.0], 'GSM1556522': [0.0], 'GSM1556523': [0.0], 'GSM1556524': [0.0], 'GSM1556525': [0.0], 'GSM1556526': [0.0], 'GSM1556527': [0.0], 'GSM1556528': [0.0], 'GSM1556529': [0.0], 'GSM1556530': [0.0], 'GSM1556531': [0.0], 'GSM1556532': [0.0], 'GSM1556533': [0.0], 'GSM1556534': [0.0], 'GSM1556535': [0.0], 'GSM1556536': [0.0], 'GSM1556537': [0.0], 'GSM1556538': [0.0], 'GSM1556539': [0.0], 'GSM1556540': [0.0], 'GSM1556541': [0.0]}\n",
      "Clinical data saved to ../../output/preprocess/Eczema/clinical_data/GSE63741.csv\n"
     ]
    }
   ],
   "source": [
    "# 1. Gene Expression Data Availability\n",
    "# Based on background information, this dataset contains gene expression data\n",
    "is_gene_available = True\n",
    "\n",
    "# 2. Variable Availability and Data Type Conversion\n",
    "\n",
    "# 2.1 Data Availability\n",
    "# From the background information, we can see this is a study comparing different skin conditions\n",
    "# including Atopic Dermatitis (AD) which is a form of Eczema\n",
    "# The dataset contains samples from patients with Eczema (Contact Eczema - KE) and other conditions\n",
    "\n",
    "# For trait (Eczema), we need to infer from 'sample type' information\n",
    "trait_row = 1  # The information about disease status is in row 1\n",
    "\n",
    "# Age is not explicitly mentioned in the sample characteristics\n",
    "age_row = None\n",
    "\n",
    "# Gender is not explicitly mentioned in the sample characteristics\n",
    "gender_row = None\n",
    "\n",
    "# 2.2 Data Type Conversion\n",
    "def convert_trait(value):\n",
    "    \"\"\"\n",
    "    Convert trait value to binary (0 or 1).\n",
    "    1 if the sample is from an Eczema patient (AD - Atopic Dermatitis or KE - Contact Eczema)\n",
    "    0 if the sample is from a non-Eczema patient or healthy control\n",
    "    \"\"\"\n",
    "    if value is None:\n",
    "        return None\n",
    "    \n",
    "    # Extract the value after the colon if present\n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip().lower()\n",
    "    else:\n",
    "        value = value.strip().lower()\n",
    "    \n",
    "    # Check if the value indicates Eczema\n",
    "    if 'atopic dermatitis' in value or 'contact eczema' in value or 'ad' in value or 'ke' in value:\n",
    "        return 1\n",
    "    elif 'healthy' in value or 'control' in value or 'ko' in value or 'psoriasis' in value or 'lichen planus' in value or 'pso' in value or 'li' in value:\n",
    "        return 0\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "# These functions are not needed as age and gender data are not available,\n",
    "# but we'll define them as placeholders\n",
    "def convert_age(value):\n",
    "    return None\n",
    "\n",
    "def convert_gender(value):\n",
    "    return None\n",
    "\n",
    "# 3. Save Metadata\n",
    "# Conduct initial filtering\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\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 dataframe\n",
    "    preview = preview_df(selected_clinical_df)\n",
    "    print(\"Preview of selected clinical features:\")\n",
    "    print(preview)\n",
    "    \n",
    "    # Save to CSV\n",
    "    os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
    "    selected_clinical_df.to_csv(out_clinical_data_file, index=True)\n",
    "    print(f\"Clinical data saved to {out_clinical_data_file}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7349de24",
   "metadata": {},
   "source": [
    "### Step 3: Gene Data Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "e83951f3",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:41:37.083122Z",
     "iopub.status.busy": "2025-03-25T08:41:37.083007Z",
     "iopub.status.idle": "2025-03-25T08:41:37.118278Z",
     "shell.execute_reply": "2025-03-25T08:41:37.117975Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Matrix file found: ../../input/GEO/Eczema/GSE63741/GSE63741_series_matrix.txt.gz\n",
      "Gene data shape: (1542, 150)\n",
      "First 20 gene/probe identifiers:\n",
      "Index(['3', '5', '16', '18', '20', '33', '35', '37', '39', '43', '47', '49',\n",
      "       '55', '57', '59', '61', '67', '71', '73', '81'],\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": "68d97f8a",
   "metadata": {},
   "source": [
    "### Step 4: Gene Identifier Review"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "f7f41dc4",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:41:37.119544Z",
     "iopub.status.busy": "2025-03-25T08:41:37.119433Z",
     "iopub.status.idle": "2025-03-25T08:41:37.121732Z",
     "shell.execute_reply": "2025-03-25T08:41:37.121452Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Based on the observed identifiers which are numeric ('3', '5', '16', etc.), these are not human gene symbols.\n",
      "These appear to be probe IDs that require mapping to standard gene symbols.\n",
      "requires_gene_mapping = True\n"
     ]
    }
   ],
   "source": [
    "# The gene identifiers in the data appear to be numeric identifiers (e.g., '3', '5', '16', etc.)\n",
    "# These are not standard human gene symbols (which would look like BRCA1, TP53, IL6, etc.)\n",
    "# These appear to be probe IDs or some other numeric identifiers that need to be mapped to gene symbols\n",
    "\n",
    "# Therefore, we need to perform gene mapping\n",
    "requires_gene_mapping = True\n",
    "\n",
    "# Print the conclusion for clarity\n",
    "print(f\"Based on the observed identifiers which are numeric ('3', '5', '16', etc.), these are not human gene symbols.\")\n",
    "print(f\"These appear to be probe IDs that require mapping to standard gene symbols.\")\n",
    "print(f\"requires_gene_mapping = {requires_gene_mapping}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1809e337",
   "metadata": {},
   "source": [
    "### Step 5: Gene Annotation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "36057f55",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:41:37.122938Z",
     "iopub.status.busy": "2025-03-25T08:41:37.122830Z",
     "iopub.status.idle": "2025-03-25T08:41:37.423643Z",
     "shell.execute_reply": "2025-03-25T08:41:37.423257Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "Gene annotation preview:\n",
      "Columns in gene annotation: ['ID', 'description', 'uniprot', 'gene ID', 'REFSEQ']\n",
      "{'ID': ['3', '5', '16', '18', '20'], 'description': ['IL1B: (IL1B) INTERLEUKIN-1 BETA PRECURSOR (IL-1 BETA) (CATABOLIN).', 'IL2: (IL2 OR IL-2) INTERLEUKIN-2 PRECURSOR (IL-2) (T-CELL GROWTH FACTOR) (TCGF) (ALDESLEUKIN).', 'IL7: (IL7 OR IL-7) INTERLEUKIN-7 PRECURSOR (IL-7).', 'IL8_HUMAN: (IL8) INTERLEUKIN-8 PRECURSOR (IL-8) (CXCL8) (MONOCYTE-DERIVED NEUTROPHIL CHEMOTACTIC FACTOR) (MDNCF) (T-CELL CHEMOTACTIC FACTOR) (NEUTROPHIL-ACTIVATING PROTEIN 1) (NAP-1) (LYMPHOCYTE-DERIVED NEUTROPHIL-ACTIVATING FACTOR) (LYNAP) (PROTEIN 3-10C) (NEUTROPHIL-ACTIVATING FACTOR) (NAF) (GRANULOCYTE CHEMOTACTIC PROTEIN 1) (GCP-1) (EMOCTAKIN).', 'IL9: (IL9) INTERLEUKIN-9 PRECURSOR (IL-9) (T-CELL GROWTH FACTOR P40) (P40 CYTOKINE).'], 'uniprot': ['sp|P01584,sp|Q96HE5,sp|Q9UCT6,sp|Q7RU01', 'sp|P01585,tr|Q13169,sp|P60568', 'sp|P13232', 'sp|P10145,sp|Q9C077,sp|Q96RG6,sp|Q6FGF6,sp|Q6LAE6', 'sp|P15248'], 'gene ID': ['3553', '3558', '3574', '3576', '3578'], 'REFSEQ': ['NM_000576', 'NM_000586', 'NM_000880', 'NM_000584', 'NM_000590']}\n",
      "\n",
      "Searching for platform information in SOFT file:\n",
      "Platform ID not found in first 100 lines\n",
      "\n",
      "Searching for gene symbol information in SOFT file:\n",
      "No explicit gene symbol references found in first 1000 lines\n",
      "\n",
      "Checking for additional annotation files in the directory:\n",
      "[]\n"
     ]
    }
   ],
   "source": [
    "# 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.\n",
    "gene_annotation = get_gene_annotation(soft_file)\n",
    "\n",
    "# 2. Analyze the gene annotation dataframe to identify which columns contain the gene identifiers and gene symbols\n",
    "print(\"\\nGene annotation preview:\")\n",
    "print(f\"Columns in gene annotation: {gene_annotation.columns.tolist()}\")\n",
    "print(preview_df(gene_annotation, n=5))\n",
    "\n",
    "# Let's look for platform information in the SOFT file to understand the annotation better\n",
    "print(\"\\nSearching for platform information in SOFT file:\")\n",
    "with gzip.open(soft_file, 'rt') as f:\n",
    "    for i, line in enumerate(f):\n",
    "        if '!Series_platform_id' in line:\n",
    "            print(line.strip())\n",
    "            break\n",
    "        if i > 100:  # Limit search to first 100 lines\n",
    "            print(\"Platform ID not found in first 100 lines\")\n",
    "            break\n",
    "\n",
    "# Check if the SOFT file includes any reference to gene symbols\n",
    "print(\"\\nSearching for gene symbol information in SOFT file:\")\n",
    "with gzip.open(soft_file, 'rt') as f:\n",
    "    gene_symbol_lines = []\n",
    "    for i, line in enumerate(f):\n",
    "        if 'GENE_SYMBOL' in line or 'gene_symbol' in line.lower() or 'symbol' in line.lower():\n",
    "            gene_symbol_lines.append(line.strip())\n",
    "        if i > 1000 and len(gene_symbol_lines) > 0:  # Limit search but ensure we found something\n",
    "            break\n",
    "    \n",
    "    if gene_symbol_lines:\n",
    "        print(\"Found references to gene symbols:\")\n",
    "        for line in gene_symbol_lines[:5]:  # Show just first 5 matches\n",
    "            print(line)\n",
    "    else:\n",
    "        print(\"No explicit gene symbol references found in first 1000 lines\")\n",
    "\n",
    "# Look for alternative annotation files or references in the directory\n",
    "print(\"\\nChecking for additional annotation files in the directory:\")\n",
    "all_files = os.listdir(in_cohort_dir)\n",
    "print([f for f in all_files if 'annotation' in f.lower() or 'platform' in f.lower() or 'gpl' in f.lower()])\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0098e116",
   "metadata": {},
   "source": [
    "### Step 6: Gene Identifier Mapping"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "afcc815f",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:41:37.425056Z",
     "iopub.status.busy": "2025-03-25T08:41:37.424932Z",
     "iopub.status.idle": "2025-03-25T08:41:37.669024Z",
     "shell.execute_reply": "2025-03-25T08:41:37.668691Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Starting gene identifier mapping...\n",
      "Sample of extracted gene symbols:\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "   ID Gene_Symbol\n",
      "0   3        IL1B\n",
      "1   5         IL2\n",
      "2  16         IL7\n",
      "3  18   IL8_HUMAN\n",
      "4  20         IL9\n",
      "Creating gene mapping dataframe...\n",
      "Converting probe data to gene expression data...\n",
      "Gene expression data shape after mapping: (1369, 150)\n",
      "First few gene symbols in mapped data:\n",
      "['ABCA12', 'ABI3BP', 'ABME', 'ACADVL', 'ACP5', 'ACPP', 'ACSL3', 'ACTA2', 'ACTB', 'ACTG1']\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene expression data saved to ../../output/preprocess/Eczema/gene_data/GSE63741.csv\n"
     ]
    }
   ],
   "source": [
    "# 1. Identify which columns contain gene IDs and gene symbols\n",
    "# From the preview, the 'ID' column matches the numeric identifiers in gene_data\n",
    "# The 'description' column contains gene symbols at the start (e.g., \"IL1B:\")\n",
    "\n",
    "print(\"Starting gene identifier mapping...\")\n",
    "\n",
    "# Function to extract gene symbols from the description field\n",
    "def extract_gene_symbol(description):\n",
    "    if not isinstance(description, str):\n",
    "        return None\n",
    "    # Extract text before the colon\n",
    "    match = re.match(r'^([^:]+):', description)\n",
    "    if match:\n",
    "        return match.group(1).strip()\n",
    "    return None\n",
    "\n",
    "# Add a column with extracted gene symbols\n",
    "gene_annotation['Gene_Symbol'] = gene_annotation['description'].apply(extract_gene_symbol)\n",
    "\n",
    "# Preview the extracted gene symbols\n",
    "print(\"Sample of extracted gene symbols:\")\n",
    "print(gene_annotation[['ID', 'Gene_Symbol']].head())\n",
    "\n",
    "# 2. Create gene mapping dataframe\n",
    "print(\"Creating gene mapping dataframe...\")\n",
    "mapping_df = gene_annotation[['ID', 'Gene_Symbol']].dropna()\n",
    "mapping_df = mapping_df.rename(columns={'Gene_Symbol': 'Gene'})\n",
    "\n",
    "# 3. Apply gene mapping to convert probe-level data to gene expression data\n",
    "print(\"Converting probe data to gene expression data...\")\n",
    "gene_data = apply_gene_mapping(gene_data, mapping_df)\n",
    "\n",
    "# Print shape and preview of the gene expression data\n",
    "print(f\"Gene expression data shape after mapping: {gene_data.shape}\")\n",
    "print(\"First few gene symbols in mapped data:\")\n",
    "print(gene_data.index[:10].tolist())\n",
    "\n",
    "# Save the gene expression 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\"Gene expression data saved to {out_gene_data_file}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "25a578a8",
   "metadata": {},
   "source": [
    "### Step 7: Data Normalization and Linking"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "eb2ec526",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:41:37.670348Z",
     "iopub.status.busy": "2025-03-25T08:41:37.670231Z",
     "iopub.status.idle": "2025-03-25T08:41:38.077464Z",
     "shell.execute_reply": "2025-03-25T08:41:38.077139Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Normalizing gene symbols...\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene data shape after normalization: (1259, 150)\n",
      "Sample of normalized gene symbols: ['ABCA12', 'ABI1', 'ABI3BP', 'ACADVL', 'ACER1', 'ACER3', 'ACP3', 'ACP5', 'ACSL3', 'ACTA2']\n",
      "Normalized gene data saved to ../../output/preprocess/Eczema/gene_data/GSE63741.csv\n",
      "\n",
      "Loading clinical data...\n",
      "Clinical features shape: (1, 150)\n",
      "Clinical features preview:\n",
      "{'GSM1556392': [0.0], 'GSM1556393': [0.0], 'GSM1556394': [0.0], 'GSM1556395': [0.0], 'GSM1556396': [0.0], 'GSM1556397': [0.0], 'GSM1556398': [0.0], 'GSM1556399': [0.0], 'GSM1556400': [0.0], 'GSM1556401': [0.0], 'GSM1556402': [0.0], 'GSM1556403': [0.0], 'GSM1556404': [0.0], 'GSM1556405': [0.0], 'GSM1556406': [0.0], 'GSM1556407': [0.0], 'GSM1556408': [0.0], 'GSM1556409': [0.0], 'GSM1556410': [0.0], 'GSM1556411': [0.0], 'GSM1556412': [0.0], 'GSM1556413': [0.0], 'GSM1556414': [0.0], 'GSM1556415': [0.0], 'GSM1556416': [0.0], 'GSM1556417': [0.0], 'GSM1556418': [0.0], 'GSM1556419': [0.0], 'GSM1556420': [0.0], 'GSM1556421': [0.0], 'GSM1556422': [0.0], 'GSM1556423': [0.0], 'GSM1556424': [0.0], 'GSM1556425': [0.0], 'GSM1556426': [0.0], 'GSM1556427': [0.0], 'GSM1556428': [0.0], 'GSM1556429': [0.0], 'GSM1556430': [0.0], 'GSM1556431': [0.0], 'GSM1556432': [0.0], 'GSM1556433': [0.0], 'GSM1556434': [0.0], 'GSM1556435': [0.0], 'GSM1556436': [0.0], 'GSM1556437': [0.0], 'GSM1556438': [0.0], 'GSM1556439': [0.0], 'GSM1556440': [0.0], 'GSM1556441': [0.0], 'GSM1556442': [0.0], 'GSM1556443': [0.0], 'GSM1556444': [0.0], 'GSM1556445': [0.0], 'GSM1556446': [0.0], 'GSM1556447': [0.0], 'GSM1556448': [0.0], 'GSM1556449': [0.0], 'GSM1556450': [0.0], 'GSM1556451': [0.0], 'GSM1556452': [0.0], 'GSM1556453': [0.0], 'GSM1556454': [0.0], 'GSM1556455': [0.0], 'GSM1556456': [0.0], 'GSM1556457': [0.0], 'GSM1556458': [0.0], 'GSM1556459': [0.0], 'GSM1556460': [0.0], 'GSM1556461': [0.0], 'GSM1556462': [0.0], 'GSM1556463': [0.0], 'GSM1556464': [0.0], 'GSM1556465': [0.0], 'GSM1556466': [0.0], 'GSM1556467': [0.0], 'GSM1556468': [0.0], 'GSM1556469': [0.0], 'GSM1556470': [0.0], 'GSM1556471': [0.0], 'GSM1556472': [0.0], 'GSM1556473': [0.0], 'GSM1556474': [0.0], 'GSM1556475': [0.0], 'GSM1556476': [0.0], 'GSM1556477': [0.0], 'GSM1556478': [0.0], 'GSM1556479': [0.0], 'GSM1556480': [0.0], 'GSM1556481': [0.0], 'GSM1556482': [0.0], 'GSM1556483': [0.0], 'GSM1556484': [0.0], 'GSM1556485': [0.0], 'GSM1556486': [0.0], 'GSM1556487': [0.0], 'GSM1556488': [0.0], 'GSM1556489': [0.0], 'GSM1556490': [0.0], 'GSM1556491': [0.0], 'GSM1556492': [0.0], 'GSM1556493': [0.0], 'GSM1556494': [0.0], 'GSM1556495': [0.0], 'GSM1556496': [0.0], 'GSM1556497': [0.0], 'GSM1556498': [0.0], 'GSM1556499': [0.0], 'GSM1556500': [0.0], 'GSM1556501': [0.0], 'GSM1556502': [0.0], 'GSM1556503': [0.0], 'GSM1556504': [0.0], 'GSM1556505': [0.0], 'GSM1556506': [0.0], 'GSM1556507': [0.0], 'GSM1556508': [0.0], 'GSM1556509': [0.0], 'GSM1556510': [0.0], 'GSM1556511': [0.0], 'GSM1556512': [0.0], 'GSM1556513': [0.0], 'GSM1556514': [0.0], 'GSM1556515': [0.0], 'GSM1556516': [0.0], 'GSM1556517': [0.0], 'GSM1556518': [0.0], 'GSM1556519': [0.0], 'GSM1556520': [0.0], 'GSM1556521': [0.0], 'GSM1556522': [0.0], 'GSM1556523': [0.0], 'GSM1556524': [0.0], 'GSM1556525': [0.0], 'GSM1556526': [0.0], 'GSM1556527': [0.0], 'GSM1556528': [0.0], 'GSM1556529': [0.0], 'GSM1556530': [0.0], 'GSM1556531': [0.0], 'GSM1556532': [0.0], 'GSM1556533': [0.0], 'GSM1556534': [0.0], 'GSM1556535': [0.0], 'GSM1556536': [0.0], 'GSM1556537': [0.0], 'GSM1556538': [0.0], 'GSM1556539': [0.0], 'GSM1556540': [0.0], 'GSM1556541': [0.0]}\n",
      "\n",
      "Linking clinical and genetic data...\n",
      "Linked data shape: (150, 1260)\n",
      "Linked data preview (first 5 rows, 5 columns):\n",
      "            Eczema  ABCA12    ABI1  ABI3BP  ACADVL\n",
      "GSM1556392     0.0 -0.2239 -0.0303  0.2056 -0.4101\n",
      "GSM1556393     0.0 -0.1982 -0.1678  0.0363 -0.1599\n",
      "GSM1556394     0.0  0.0442 -0.2122 -0.2602 -0.5624\n",
      "GSM1556395     0.0 -0.3612  0.2005 -0.0170 -1.1014\n",
      "GSM1556396     0.0  0.1589  0.0489 -0.3016 -0.2533\n",
      "\n",
      "Handling missing values...\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Linked data shape after handling missing values: (150, 1260)\n",
      "\n",
      "Checking for bias in dataset features...\n",
      "Quartiles for 'Eczema':\n",
      "  25%: 0.0\n",
      "  50% (Median): 0.0\n",
      "  75%: 0.0\n",
      "Min: 0.0\n",
      "Max: 0.0\n",
      "The distribution of the feature 'Eczema' in this dataset is severely biased.\n",
      "\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Dataset deemed not usable for associative studies. Linked data not saved.\n"
     ]
    }
   ],
   "source": [
    "# 1. Normalize gene symbols using NCBI Gene database information\n",
    "print(\"Normalizing gene symbols...\")\n",
    "try:\n",
    "    # Load the gene data if needed\n",
    "    if 'gene_data' not in locals() or gene_data is None:\n",
    "        gene_data = pd.read_csv(out_gene_data_file, index_col=0)\n",
    "        \n",
    "    # Normalize gene symbols\n",
    "    normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n",
    "    print(f\"Gene data shape after normalization: {normalized_gene_data.shape}\")\n",
    "    print(f\"Sample of normalized gene symbols: {normalized_gene_data.index[:10].tolist()}\")\n",
    "    \n",
    "    # Save the normalized gene data\n",
    "    normalized_gene_data.to_csv(out_gene_data_file)\n",
    "    print(f\"Normalized gene data saved to {out_gene_data_file}\")\n",
    "except Exception as e:\n",
    "    print(f\"Error normalizing gene symbols: {e}\")\n",
    "\n",
    "# 2. Load the clinical data that was saved in step 2\n",
    "print(\"\\nLoading clinical data...\")\n",
    "try:\n",
    "    clinical_features = pd.read_csv(out_clinical_data_file, index_col=0)\n",
    "    print(f\"Clinical features shape: {clinical_features.shape}\")\n",
    "    print(\"Clinical features preview:\")\n",
    "    print(preview_df(clinical_features))\n",
    "    \n",
    "    # 3. Link clinical and genetic data\n",
    "    print(\"\\nLinking clinical and genetic data...\")\n",
    "    linked_data = geo_link_clinical_genetic_data(clinical_features, normalized_gene_data)\n",
    "    print(f\"Linked data shape: {linked_data.shape}\")\n",
    "    print(\"Linked data preview (first 5 rows, 5 columns):\")\n",
    "    if linked_data.shape[0] > 0 and linked_data.shape[1] > 5:\n",
    "        print(linked_data.iloc[:5, :5])\n",
    "    else:\n",
    "        print(linked_data)\n",
    "    \n",
    "    # 4. Handle missing values\n",
    "    print(\"\\nHandling missing values...\")\n",
    "    linked_data_clean = handle_missing_values(linked_data, trait)\n",
    "    print(f\"Linked data shape after handling missing values: {linked_data_clean.shape}\")\n",
    "    \n",
    "    # 5. Check for bias in the dataset\n",
    "    print(\"\\nChecking for bias in dataset features...\")\n",
    "    is_biased, linked_data_clean = judge_and_remove_biased_features(linked_data_clean, trait)\n",
    "    \n",
    "    # 6. Conduct final quality validation\n",
    "    note = \"Dataset contains gene expression data from skin biopsies comparing different skin conditions including eczema (atopic dermatitis and contact eczema) against other conditions like psoriasis and healthy controls.\"\n",
    "    is_usable = validate_and_save_cohort_info(\n",
    "        is_final=True,\n",
    "        cohort=cohort,\n",
    "        info_path=json_path,\n",
    "        is_gene_available=True,\n",
    "        is_trait_available=True,\n",
    "        is_biased=is_biased,\n",
    "        df=linked_data_clean,\n",
    "        note=note\n",
    "    )\n",
    "    \n",
    "    # 7. Save the linked data if it's usable\n",
    "    if is_usable:\n",
    "        os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n",
    "        linked_data_clean.to_csv(out_data_file, index=True)\n",
    "        print(f\"Linked data saved to {out_data_file}\")\n",
    "    else:\n",
    "        print(\"Dataset deemed not usable for associative studies. Linked data not saved.\")\n",
    "        \n",
    "except Exception as e:\n",
    "    print(f\"Error processing data: {e}\")\n",
    "    # If processing fails, we should still validate the dataset status\n",
    "    is_usable = validate_and_save_cohort_info(\n",
    "        is_final=True,\n",
    "        cohort=cohort,\n",
    "        info_path=json_path,\n",
    "        is_gene_available=True,\n",
    "        is_trait_available=True,  # We know trait data is available from step 2\n",
    "        is_biased=True,  # Set to True to ensure it's not marked usable\n",
    "        df=pd.DataFrame(),  # Empty dataframe since processing failed\n",
    "        note=f\"Failed to process data: {e}\"\n",
    "    )\n",
    "    print(\"Dataset validation completed with error status.\")"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.16"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}