File size: 34,863 Bytes
e4183cf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "1d7255ba",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:41:19.638297Z",
     "iopub.status.busy": "2025-03-25T08:41:19.638192Z",
     "iopub.status.idle": "2025-03-25T08:41:19.799754Z",
     "shell.execute_reply": "2025-03-25T08:41:19.799389Z"
    }
   },
   "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 = \"GSE57225\"\n",
    "\n",
    "# Input paths\n",
    "in_trait_dir = \"../../input/GEO/Eczema\"\n",
    "in_cohort_dir = \"../../input/GEO/Eczema/GSE57225\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/Eczema/GSE57225.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/Eczema/gene_data/GSE57225.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/Eczema/clinical_data/GSE57225.csv\"\n",
    "json_path = \"../../output/preprocess/Eczema/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cb945e6f",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "37297bf6",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:41:19.801181Z",
     "iopub.status.busy": "2025-03-25T08:41:19.801042Z",
     "iopub.status.idle": "2025-03-25T08:41:19.982983Z",
     "shell.execute_reply": "2025-03-25T08:41:19.982655Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Background Information:\n",
      "!Series_title\t\"Intra-individual genome expression analysis reveals a specific molecular signature of psoriasis and eczema\"\n",
      "!Series_summary\t\"Comparing molecular signatures of psoriasis and eczema in patients co-affected by both diseases provides a comprehensive understanding of disease pathogenesis as well as a diagnostic tool to differentiate these widespread inflammatory skin diseases.\"\n",
      "!Series_overall_design\t\"In patients affected by both psoriasis and non-atopic or atopic eczema simultaneously (n=24), whole genome expression arrays of psoriasis, eczema, and non-involved skin were performed\"\n",
      "!Series_overall_design\t\"Arrays MQ_35 and MQ_41 did not pass quality control and thus were not normalized and were excluded from this Series.\"\n",
      "Sample Characteristics Dictionary:\n",
      "{0: ['individual: EP', 'individual: KK', 'individual: KP', 'individual: SI', 'individual: MM', 'individual: ZA', 'individual: LA', 'individual: MOF', 'individual: Mattes', 'individual: SS2', 'individual: Klose', 'individual: JB', 'individual: LI', 'individual: HI', 'individual: SM', 'individual: BC', 'individual: BS (31y)', 'individual: VI', 'individual: BA', 'individual: BS (33y)', 'individual: SP', 'individual: MPG', 'individual: WP'], 1: ['disease state: psoriasis', 'disease state: eczema', 'disease state: control (non-involved)'], 2: ['tissue: skin'], 3: ['gender: male', 'gender: female'], 4: ['age: 48y', 'age: 40y', 'age: 65y', 'age: 35y', 'age: 27y', 'age: 72y', 'age: 33y', 'age: 58y', 'age: 56y', 'age: 46y', 'age: 55y', 'age: 53y', 'age: 31y', 'age: 42y', 'age: 43y', 'age: 20y', 'age: 41y']}\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": "4ec2038b",
   "metadata": {},
   "source": [
    "### Step 2: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "23a31134",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:41:19.984261Z",
     "iopub.status.busy": "2025-03-25T08:41:19.984147Z",
     "iopub.status.idle": "2025-03-25T08:41:19.990574Z",
     "shell.execute_reply": "2025-03-25T08:41:19.990258Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Review of Sample Characteristics Dictionary:\n",
      "Key 0: ['individual: EP', 'individual: KK', 'individual: KP', 'individual: SI', 'individual: MM', 'individual: ZA', 'individual: LA', 'individual: MOF', 'individual: Mattes', 'individual: SS2', 'individual: Klose', 'individual: JB', 'individual: LI', 'individual: HI', 'individual: SM', 'individual: BC', 'individual: BS (31y)', 'individual: VI', 'individual: BA', 'individual: BS (33y)', 'individual: SP', 'individual: MPG', 'individual: WP']\n",
      "Key 1: ['disease state: psoriasis', 'disease state: eczema', 'disease state: control (non-involved)']\n",
      "Key 2: ['tissue: skin']\n",
      "Key 3: ['gender: male', 'gender: female']\n",
      "Key 4: ['age: 48y', 'age: 40y', 'age: 65y', 'age: 35y', 'age: 27y', 'age: 72y', 'age: 33y', 'age: 58y', 'age: 56y', 'age: 46y', 'age: 55y', 'age: 53y', 'age: 31y', 'age: 42y', 'age: 43y', 'age: 20y', 'age: 41y']\n",
      "Note: We have identified that trait, age, and gender data are available in the sample characteristics.\n",
      "trait_row = 1, age_row = 4, gender_row = 3\n",
      "However, since we don't have access to the actual clinical data file, we'll skip the data extraction step for now.\n",
      "The sample characteristics provided are metadata about the unique values, not the actual clinical data.\n"
     ]
    }
   ],
   "source": [
    "import pandas as pd\n",
    "import os\n",
    "import json\n",
    "from typing import Optional, Dict, Any, Callable, List\n",
    "import re\n",
    "\n",
    "# Display sample characteristics to understand the dataset\n",
    "sample_characteristics = {0: ['individual: EP', 'individual: KK', 'individual: KP', 'individual: SI', 'individual: MM', 'individual: ZA', 'individual: LA', 'individual: MOF', 'individual: Mattes', 'individual: SS2', 'individual: Klose', 'individual: JB', 'individual: LI', 'individual: HI', 'individual: SM', 'individual: BC', 'individual: BS (31y)', 'individual: VI', 'individual: BA', 'individual: BS (33y)', 'individual: SP', 'individual: MPG', 'individual: WP'], 1: ['disease state: psoriasis', 'disease state: eczema', 'disease state: control (non-involved)'], 2: ['tissue: skin'], 3: ['gender: male', 'gender: female'], 4: ['age: 48y', 'age: 40y', 'age: 65y', 'age: 35y', 'age: 27y', 'age: 72y', 'age: 33y', 'age: 58y', 'age: 56y', 'age: 46y', 'age: 55y', 'age: 53y', 'age: 31y', 'age: 42y', 'age: 43y', 'age: 20y', 'age: 41y']}\n",
    "\n",
    "print(\"Review of Sample Characteristics Dictionary:\")\n",
    "for key, values in sample_characteristics.items():\n",
    "    print(f\"Key {key}: {values}\")\n",
    "\n",
    "# 1. Gene Expression Data Availability\n",
    "# Based on the summary and title, this dataset appears to contain genome expression data\n",
    "is_gene_available = True\n",
    "\n",
    "# 2. Variable Availability and Data Type Conversion\n",
    "# 2.1 Data Availability\n",
    "# From the sample characteristics dictionary:\n",
    "# Key 1 contains disease state which can be used for our trait (Eczema)\n",
    "# Key 4 contains age information\n",
    "# Key 3 contains gender information\n",
    "trait_row = 1  # 'disease state: psoriasis', 'disease state: eczema', 'disease state: control (non-involved)'\n",
    "age_row = 4    # Age information is available\n",
    "gender_row = 3  # Gender information is available\n",
    "\n",
    "# 2.2 Data Type Conversion Functions\n",
    "def convert_trait(value: str) -> Optional[int]:\n",
    "    \"\"\"\n",
    "    Convert trait information to binary format.\n",
    "    1 for eczema, 0 for control, None for psoriasis (as we're focusing on eczema)\n",
    "    \"\"\"\n",
    "    if value is None:\n",
    "        return None\n",
    "    # Extract value after colon\n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip()\n",
    "    \n",
    "    if 'eczema' in value.lower():\n",
    "        return 1  # Case\n",
    "    elif 'control' in value.lower() or 'non-involved' in value.lower():\n",
    "        return 0  # Control\n",
    "    else:\n",
    "        return None  # Other conditions like psoriasis\n",
    "\n",
    "def convert_age(value: str) -> Optional[float]:\n",
    "    \"\"\"\n",
    "    Convert age information to continuous format.\n",
    "    Extract numeric age value from strings like 'age: 48y'\n",
    "    \"\"\"\n",
    "    if value is None:\n",
    "        return None\n",
    "    # Extract value after colon\n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip()\n",
    "    \n",
    "    # Use regex to extract numbers from the age string\n",
    "    age_match = re.search(r'(\\d+)', value)\n",
    "    if age_match:\n",
    "        return float(age_match.group(1))\n",
    "    return None\n",
    "\n",
    "def convert_gender(value: str) -> Optional[int]:\n",
    "    \"\"\"\n",
    "    Convert gender information to binary format.\n",
    "    0 for female, 1 for male\n",
    "    \"\"\"\n",
    "    if value is None:\n",
    "        return None\n",
    "    # Extract value after colon\n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip()\n",
    "    \n",
    "    if 'female' in value.lower():\n",
    "        return 0\n",
    "    elif 'male' in value.lower():\n",
    "        return 1\n",
    "    return None\n",
    "\n",
    "# 3. Save Metadata\n",
    "# Initial filtering on usability - trait data is available if trait_row is not None\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",
    "# Print a message about clinical data extraction\n",
    "print(\"Note: We have identified that trait, age, and gender data are available in the sample characteristics.\")\n",
    "print(f\"trait_row = {trait_row}, age_row = {age_row}, gender_row = {gender_row}\")\n",
    "print(\"However, since we don't have access to the actual clinical data file, we'll skip the data extraction step for now.\")\n",
    "print(\"The sample characteristics provided are metadata about the unique values, not the actual clinical data.\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "32970e1f",
   "metadata": {},
   "source": [
    "### Step 3: Gene Data Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "85a9e393",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:41:19.991752Z",
     "iopub.status.busy": "2025-03-25T08:41:19.991643Z",
     "iopub.status.idle": "2025-03-25T08:41:20.279344Z",
     "shell.execute_reply": "2025-03-25T08:41:20.278975Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Matrix file found: ../../input/GEO/Eczema/GSE57225/GSE57225_series_matrix.txt.gz\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene data shape: (42044, 62)\n",
      "First 20 gene/probe identifiers:\n",
      "Index(['A_19_P00315452', 'A_19_P00315459', 'A_19_P00315469', 'A_19_P00315473',\n",
      "       'A_19_P00315482', 'A_19_P00315490', 'A_19_P00315492', 'A_19_P00315493',\n",
      "       'A_19_P00315499', 'A_19_P00315502', 'A_19_P00315504', 'A_19_P00315506',\n",
      "       'A_19_P00315508', 'A_19_P00315518', 'A_19_P00315519', 'A_19_P00315523',\n",
      "       'A_19_P00315524', 'A_19_P00315526', 'A_19_P00315527', 'A_19_P00315528'],\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": "ccc999c6",
   "metadata": {},
   "source": [
    "### Step 4: Gene Identifier Review"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "1dd1070b",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:41:20.280694Z",
     "iopub.status.busy": "2025-03-25T08:41:20.280577Z",
     "iopub.status.idle": "2025-03-25T08:41:20.282506Z",
     "shell.execute_reply": "2025-03-25T08:41:20.282196Z"
    }
   },
   "outputs": [],
   "source": [
    "# Examining the gene identifiers from the previous step\n",
    "# These identifiers appear to be Agilent microarray probe IDs (starting with A_19_P),\n",
    "# not standard human gene symbols (like ACTB, TP53, etc.)\n",
    "# Therefore, mapping to gene symbols will be required\n",
    "\n",
    "requires_gene_mapping = True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1e202a0e",
   "metadata": {},
   "source": [
    "### Step 5: Gene Annotation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "3f2108c6",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:41:20.283618Z",
     "iopub.status.busy": "2025-03-25T08:41:20.283507Z",
     "iopub.status.idle": "2025-03-25T08:41:24.869191Z",
     "shell.execute_reply": "2025-03-25T08:41:24.868817Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "Gene annotation preview:\n",
      "Columns in gene annotation: ['ID', 'SPOT_ID', 'CONTROL_TYPE', 'REFSEQ', 'GB_ACC', 'GENE', 'GENE_SYMBOL', 'GENE_NAME', 'UNIGENE_ID', 'ENSEMBL_ID', 'TIGR_ID', 'ACCESSION_STRING', 'CHROMOSOMAL_LOCATION', 'CYTOBAND', 'DESCRIPTION', 'GO_ID', 'SEQUENCE']\n",
      "{'ID': ['(+)E1A_r60_1', '(+)E1A_r60_3', '(+)E1A_r60_a104', '(+)E1A_r60_a107', '(+)E1A_r60_a135'], 'SPOT_ID': ['(+)E1A_r60_1', '(+)E1A_r60_3', '(+)E1A_r60_a104', '(+)E1A_r60_a107', '(+)E1A_r60_a135'], 'CONTROL_TYPE': ['pos', 'pos', 'pos', 'pos', 'pos'], 'REFSEQ': [nan, nan, nan, nan, nan], 'GB_ACC': [nan, nan, nan, nan, nan], 'GENE': [nan, nan, nan, nan, nan], 'GENE_SYMBOL': [nan, nan, nan, nan, nan], 'GENE_NAME': [nan, nan, nan, nan, nan], 'UNIGENE_ID': [nan, nan, nan, nan, nan], 'ENSEMBL_ID': [nan, nan, nan, nan, nan], 'TIGR_ID': [nan, nan, nan, nan, nan], 'ACCESSION_STRING': [nan, nan, nan, nan, nan], 'CHROMOSOMAL_LOCATION': [nan, nan, nan, nan, nan], 'CYTOBAND': [nan, nan, nan, nan, nan], 'DESCRIPTION': [nan, nan, nan, nan, nan], 'GO_ID': [nan, nan, nan, nan, nan], 'SEQUENCE': [nan, nan, nan, nan, nan]}\n",
      "\n",
      "Searching for platform information in SOFT file:\n",
      "!Series_platform_id = GPL14550\n",
      "\n",
      "Searching for gene symbol information in SOFT file:\n",
      "Found references to gene symbols:\n",
      "#GENE_SYMBOL = Gene Symbol\n",
      "ID\tSPOT_ID\tCONTROL_TYPE\tREFSEQ\tGB_ACC\tGENE\tGENE_SYMBOL\tGENE_NAME\tUNIGENE_ID\tENSEMBL_ID\tTIGR_ID\tACCESSION_STRING\tCHROMOSOMAL_LOCATION\tCYTOBAND\tDESCRIPTION\tGO_ID\tSEQUENCE\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": "efb3fd1c",
   "metadata": {},
   "source": [
    "### Step 6: Gene Identifier Mapping"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "74cf65d4",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:41:24.870613Z",
     "iopub.status.busy": "2025-03-25T08:41:24.870486Z",
     "iopub.status.idle": "2025-03-25T08:41:25.831867Z",
     "shell.execute_reply": "2025-03-25T08:41:25.831507Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Generated gene mapping dataframe with shape: (30436, 2)\n",
      "Sample of gene mapping data:\n",
      "                ID         Gene\n",
      "21  A_19_P00315502  XLOC_008373\n",
      "25  A_19_P00315518  XLOC_005810\n",
      "26  A_19_P00315519  XLOC_004914\n",
      "28  A_19_P00315524  XLOC_014192\n",
      "31  A_19_P00315528  XLOC_008370\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Converted to gene-level expression data with shape: (19725, 62)\n",
      "Sample of gene expression data:\n",
      "          GSM1377461  GSM1377462  GSM1377463  GSM1377464  GSM1377465  \\\n",
      "Gene                                                                   \n",
      "A1BG       12.977107   13.381272   11.371641   13.209966   12.411935   \n",
      "A1BG-AS1    6.935017    7.078788    7.111287    7.637369    7.016705   \n",
      "A1CF        4.846280    5.042712    4.946058    4.353776    5.875778   \n",
      "A2LD1       8.322505    8.170192    8.379592    8.217080    7.549794   \n",
      "A2M        11.275092   12.710169   12.025984   12.847757   12.482553   \n",
      "\n",
      "          GSM1377466  GSM1377467  GSM1377468  GSM1377469  GSM1377470  ...  \\\n",
      "Gene                                                                  ...   \n",
      "A1BG       13.526912   12.966083   12.651566   13.259562   12.608978  ...   \n",
      "A1BG-AS1    7.483763    7.429407    6.585663    6.524840    6.261774  ...   \n",
      "A1CF        4.998552    5.307923    4.893777    4.880007    4.513105  ...   \n",
      "A2LD1       8.229549    8.247211    7.689971    7.147777    7.747795  ...   \n",
      "A2M        12.976723   12.007616   12.232337   13.135761   12.061959  ...   \n",
      "\n",
      "          GSM1377513  GSM1377514  GSM1377515  GSM1377516  GSM1377517  \\\n",
      "Gene                                                                   \n",
      "A1BG       12.904555   13.239299   14.152031   13.057722   13.466362   \n",
      "A1BG-AS1    6.082960    6.798525    7.392012    6.645857    6.973300   \n",
      "A1CF        5.666027    5.453652    6.042744    5.571033    4.275935   \n",
      "A2LD1       8.431592    7.693956    8.136181    7.384538    7.836907   \n",
      "A2M        12.878337   12.677917   14.821341   11.462099   12.906260   \n",
      "\n",
      "          GSM1377518  GSM1377519  GSM1377520  GSM1377521  GSM1377522  \n",
      "Gene                                                                  \n",
      "A1BG       13.159147   13.026104   13.273054   13.253025   12.128323  \n",
      "A1BG-AS1    7.018946    6.803686    6.649088    7.249076    7.108264  \n",
      "A1CF        5.635575    5.074816    4.825333    4.871838    4.554325  \n",
      "A2LD1       7.620271    7.743741    8.041216    7.938968    8.596695  \n",
      "A2M        11.394855   12.186278   13.044079   13.523840   12.221965  \n",
      "\n",
      "[5 rows x 62 columns]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene expression data saved to: ../../output/preprocess/Eczema/gene_data/GSE57225.csv\n"
     ]
    }
   ],
   "source": [
    "# 1. Determine which columns in the gene annotation contain probe IDs and gene symbols\n",
    "# Based on the gene annotation preview, the relevant columns are:\n",
    "# - 'ID': contains probe IDs like those in gene_data.index (A_19_P...)\n",
    "# - 'GENE_SYMBOL': contains gene symbols\n",
    "\n",
    "# 2. Get a gene mapping dataframe with the two relevant columns\n",
    "gene_mapping = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='GENE_SYMBOL')\n",
    "print(f\"Generated gene mapping dataframe with shape: {gene_mapping.shape}\")\n",
    "print(\"Sample of gene mapping data:\")\n",
    "print(gene_mapping.head())\n",
    "\n",
    "# 3. Apply gene mapping to convert probe-level measurements to gene expression data\n",
    "gene_data = apply_gene_mapping(gene_data, gene_mapping)\n",
    "print(f\"Converted to gene-level expression data with shape: {gene_data.shape}\")\n",
    "print(\"Sample of gene expression data:\")\n",
    "print(gene_data.head())\n",
    "\n",
    "# Save the gene data to 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": "67da6b7e",
   "metadata": {},
   "source": [
    "### Step 7: Data Normalization and Linking"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "aba6a305",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:41:25.833296Z",
     "iopub.status.busy": "2025-03-25T08:41:25.833178Z",
     "iopub.status.idle": "2025-03-25T08:41:34.727691Z",
     "shell.execute_reply": "2025-03-25T08:41:34.727313Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Checking if clinical data extraction is needed...\n",
      "Clinical data file not found. Extracting clinical features from original data...\n",
      "Clinical features extracted and saved to: ../../output/preprocess/Eczema/clinical_data/GSE57225.csv\n",
      "\n",
      "Normalizing gene symbols...\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene data shape after normalization: (19361, 62)\n",
      "Sample of normalized gene symbols: ['A1BG', 'A1BG-AS1', 'A1CF', 'A2M', 'A2ML1', 'A4GALT', 'A4GNT', 'AAA1', 'AAAS', 'AACS']\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Normalized gene data saved to ../../output/preprocess/Eczema/gene_data/GSE57225.csv\n",
      "\n",
      "Linking clinical and genetic data...\n",
      "Linked data shape: (62, 19364)\n",
      "Linked data preview (first 5 rows, 5 columns):\n",
      "            Eczema   Age  Gender       A1BG  A1BG-AS1\n",
      "GSM1377461     NaN  48.0     1.0  12.977107  6.935017\n",
      "GSM1377462     1.0  48.0     1.0  13.381272  7.078788\n",
      "GSM1377463     NaN  40.0     1.0  11.371641  7.111287\n",
      "GSM1377464     1.0  40.0     1.0  13.209966  7.637369\n",
      "GSM1377465     0.0  65.0     1.0  12.411935  7.016705\n",
      "\n",
      "Handling missing values...\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Linked data shape after handling missing values: (40, 19364)\n",
      "\n",
      "Checking for bias in dataset features...\n",
      "For the feature 'Eczema', the least common label is '0.0' with 17 occurrences. This represents 42.50% of the dataset.\n",
      "The distribution of the feature 'Eczema' in this dataset is fine.\n",
      "\n",
      "Quartiles for 'Age':\n",
      "  25%: 34.5\n",
      "  50% (Median): 46.0\n",
      "  75%: 56.0\n",
      "Min: 20.0\n",
      "Max: 72.0\n",
      "The distribution of the feature 'Age' in this dataset is fine.\n",
      "\n",
      "For the feature 'Gender', the least common label is '1.0' with 13 occurrences. This represents 32.50% of the dataset.\n",
      "The distribution of the feature 'Gender' in this dataset is fine.\n",
      "\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Linked data saved to ../../output/preprocess/Eczema/GSE57225.csv\n"
     ]
    }
   ],
   "source": [
    "# 1. Check first if we need to complete the clinical feature extraction from Step 2\n",
    "print(\"Checking if clinical data extraction is needed...\")\n",
    "if not os.path.exists(out_clinical_data_file):\n",
    "    print(\"Clinical data file not found. Extracting clinical features from original data...\")\n",
    "    # Get the matrix file path\n",
    "    _, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
    "    \n",
    "    # Get the clinical data from the matrix file\n",
    "    background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']\n",
    "    clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']\n",
    "    _, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)\n",
    "    \n",
    "    # Define conversion functions from Step 2\n",
    "    def convert_trait(value: str) -> Optional[int]:\n",
    "        if value is None:\n",
    "            return None\n",
    "        if ':' in value:\n",
    "            value = value.split(':', 1)[1].strip()\n",
    "        \n",
    "        if 'eczema' in value.lower():\n",
    "            return 1  # Case\n",
    "        elif 'control' in value.lower() or 'non-involved' in value.lower():\n",
    "            return 0  # Control\n",
    "        else:\n",
    "            return None  # Other conditions like psoriasis\n",
    "\n",
    "    def convert_age(value: str) -> Optional[float]:\n",
    "        if value is None:\n",
    "            return None\n",
    "        if ':' in value:\n",
    "            value = value.split(':', 1)[1].strip()\n",
    "        \n",
    "        age_match = re.search(r'(\\d+)', value)\n",
    "        if age_match:\n",
    "            return float(age_match.group(1))\n",
    "        return None\n",
    "\n",
    "    def convert_gender(value: str) -> Optional[int]:\n",
    "        if value is None:\n",
    "            return None\n",
    "        if ':' in value:\n",
    "            value = value.split(':', 1)[1].strip()\n",
    "        \n",
    "        if 'female' in value.lower():\n",
    "            return 0\n",
    "        elif 'male' in value.lower():\n",
    "            return 1\n",
    "        return None\n",
    "    \n",
    "    # Extract clinical features with identified rows from Step 2\n",
    "    trait_row = 1\n",
    "    age_row = 4\n",
    "    gender_row = 3\n",
    "    \n",
    "    clinical_features = geo_select_clinical_features(\n",
    "        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",
    "    # Save clinical features\n",
    "    os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
    "    clinical_features.to_csv(out_clinical_data_file)\n",
    "    print(f\"Clinical features extracted and saved to: {out_clinical_data_file}\")\n",
    "else:\n",
    "    print(f\"Clinical data file already exists at: {out_clinical_data_file}\")\n",
    "    clinical_features = pd.read_csv(out_clinical_data_file, index_col=0)\n",
    "\n",
    "# Now proceed with Step 7 as originally planned\n",
    "# 1. Normalize gene symbols using NCBI Gene database information\n",
    "print(\"\\nNormalizing 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. Link clinical and genetic data\n",
    "print(\"\\nLinking clinical and genetic data...\")\n",
    "try:\n",
    "    # 3. Link 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
}