File size: 24,403 Bytes
9fe78b4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "9b91109b",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T03:38:02.392609Z",
     "iopub.status.busy": "2025-03-25T03:38:02.392264Z",
     "iopub.status.idle": "2025-03-25T03:38:02.563808Z",
     "shell.execute_reply": "2025-03-25T03:38:02.563404Z"
    }
   },
   "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 = \"Psoriasis\"\n",
    "cohort = \"GSE123088\"\n",
    "\n",
    "# Input paths\n",
    "in_trait_dir = \"../../input/GEO/Psoriasis\"\n",
    "in_cohort_dir = \"../../input/GEO/Psoriasis/GSE123088\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/Psoriasis/GSE123088.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/Psoriasis/gene_data/GSE123088.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/Psoriasis/clinical_data/GSE123088.csv\"\n",
    "json_path = \"../../output/preprocess/Psoriasis/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2d510be4",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "9b45d31b",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T03:38:02.565059Z",
     "iopub.status.busy": "2025-03-25T03:38:02.564902Z",
     "iopub.status.idle": "2025-03-25T03:38:02.845352Z",
     "shell.execute_reply": "2025-03-25T03:38:02.844972Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Background Information:\n",
      "!Series_title\t\"A validated single-cell-based strategy to identify diagnostic and therapeutic targets in complex diseases\"\n",
      "!Series_summary\t\"This SuperSeries is composed of the SubSeries listed below.\"\n",
      "!Series_overall_design\t\"Refer to individual Series\"\n",
      "Sample Characteristics Dictionary:\n",
      "{0: ['cell type: CD4+ T cells'], 1: ['primary diagnosis: ASTHMA', 'primary diagnosis: ATHEROSCLEROSIS', 'primary diagnosis: BREAST_CANCER', 'primary diagnosis: CHRONIC_LYMPHOCYTIC_LEUKEMIA', 'primary diagnosis: CROHN_DISEASE', 'primary diagnosis: ATOPIC_ECZEMA', 'primary diagnosis: HEALTHY_CONTROL', 'primary diagnosis: INFLUENZA', 'primary diagnosis: OBESITY', 'primary diagnosis: PSORIASIS', 'primary diagnosis: SEASONAL_ALLERGIC_RHINITIS', 'primary diagnosis: TYPE_1_DIABETES', 'primary diagnosis: ACUTE_TONSILLITIS', 'primary diagnosis: ULCERATIVE_COLITIS', 'primary diagnosis: Breast cancer', 'primary diagnosis: Control'], 2: ['Sex: Male', 'diagnosis2: ATOPIC_ECZEMA', 'Sex: Female', 'diagnosis2: ATHEROSCLEROSIS', 'diagnosis2: ASTHMA_OBESITY', 'diagnosis2: ASTHMA', 'diagnosis2: ASTMHA_SEASONAL_ALLERGIC_RHINITIS', 'diagnosis2: OBESITY'], 3: ['age: 56', 'Sex: Male', 'age: 20', 'age: 51', 'age: 37', 'age: 61', 'age: 31', 'age: 41', 'age: 80', 'age: 53', 'age: 73', 'age: 60', 'age: 76', 'age: 77', 'age: 74', 'age: 69', 'age: 81', 'age: 70', 'age: 82', 'age: 67', 'age: 78', 'age: 72', 'age: 66', 'age: 36', 'age: 45', 'age: 65', 'age: 48', 'age: 50', 'age: 24', 'age: 42'], 4: [nan, 'age: 63', 'age: 74', 'age: 49', 'age: 60', 'age: 68', 'age: 38', 'age: 16', 'age: 12', 'age: 27']}\n"
     ]
    }
   ],
   "source": [
    "from tools.preprocess import *\n",
    "# 1. Identify the paths to the SOFT file and the matrix file\n",
    "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
    "\n",
    "# 2. Read the matrix file to obtain background information and sample characteristics data\n",
    "background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']\n",
    "clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']\n",
    "background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)\n",
    "\n",
    "# 3. Obtain the sample characteristics dictionary from the clinical dataframe\n",
    "sample_characteristics_dict = get_unique_values_by_row(clinical_data)\n",
    "\n",
    "# 4. Explicitly print out all the background information and the sample characteristics dictionary\n",
    "print(\"Background Information:\")\n",
    "print(background_info)\n",
    "print(\"Sample Characteristics Dictionary:\")\n",
    "print(sample_characteristics_dict)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ae2c270d",
   "metadata": {},
   "source": [
    "### Step 2: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "467addbb",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T03:38:02.846612Z",
     "iopub.status.busy": "2025-03-25T03:38:02.846505Z",
     "iopub.status.idle": "2025-03-25T03:38:02.860267Z",
     "shell.execute_reply": "2025-03-25T03:38:02.859926Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Preview of selected clinical features:\n",
      "{0: [0.0, 56.0, 1.0], 1: [0.0, nan, nan], 2: [0.0, 20.0, 0.0], 3: [0.0, 51.0, nan], 4: [0.0, 37.0, nan], 5: [0.0, 61.0, nan], 6: [0.0, 31.0, nan], 7: [0.0, 41.0, nan], 8: [0.0, 80.0, nan], 9: [1.0, 53.0, nan], 10: [0.0, 73.0, nan], 11: [0.0, 60.0, nan], 12: [0.0, 76.0, nan], 13: [0.0, 77.0, nan], 14: [0.0, 74.0, nan], 15: [0.0, 69.0, nan], 16: [nan, 81.0, nan], 17: [nan, 70.0, nan], 18: [nan, 82.0, nan], 19: [nan, 67.0, nan], 20: [nan, 78.0, nan], 21: [nan, 72.0, nan], 22: [nan, 66.0, nan], 23: [nan, 36.0, nan], 24: [nan, 45.0, nan], 25: [nan, 65.0, nan], 26: [nan, 48.0, nan], 27: [nan, 50.0, nan], 28: [nan, 24.0, nan], 29: [nan, 42.0, nan]}\n",
      "Clinical data saved to ../../output/preprocess/Psoriasis/clinical_data/GSE123088.csv\n"
     ]
    }
   ],
   "source": [
    "import pandas as pd\n",
    "from typing import Optional, Callable\n",
    "import numpy as np\n",
    "import os\n",
    "import json\n",
    "\n",
    "# 1. Gene Expression Data Availability\n",
    "# From the background information, this appears to be a SuperSeries with multiple datasets\n",
    "# containing gene expression data from CD4+ T cells, so gene data is likely available\n",
    "is_gene_available = True\n",
    "\n",
    "# 2.1 Data Availability\n",
    "# For trait (Psoriasis), look at row 1 which contains primary diagnosis\n",
    "trait_row = 1\n",
    "\n",
    "# For age, look at rows 3 and 4 which contain age information\n",
    "age_row = 3  # We'll use row 3 as the primary age row\n",
    "\n",
    "# For gender, look at rows 2 and 3 which contain sex information\n",
    "gender_row = 2  # Row 2 appears to have more gender information\n",
    "\n",
    "# 2.2 Data Type Conversion\n",
    "def convert_trait(value):\n",
    "    \"\"\"Convert trait data to binary format (1 for Psoriasis, 0 for others)\"\"\"\n",
    "    if pd.isna(value):\n",
    "        return None\n",
    "    # Extract value after colon\n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip()\n",
    "    # Check if value matches Psoriasis\n",
    "    if value.upper() == 'PSORIASIS':\n",
    "        return 1\n",
    "    else:\n",
    "        return 0\n",
    "\n",
    "def convert_age(value):\n",
    "    \"\"\"Convert age data to continuous format\"\"\"\n",
    "    if pd.isna(value):\n",
    "        return None\n",
    "    # Extract value after colon\n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip()\n",
    "    try:\n",
    "        return float(value)\n",
    "    except (ValueError, TypeError):\n",
    "        return None\n",
    "\n",
    "def convert_gender(value):\n",
    "    \"\"\"Convert gender data to binary format (0 for female, 1 for male)\"\"\"\n",
    "    if pd.isna(value):\n",
    "        return None\n",
    "    # Extract value after colon\n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip()\n",
    "    # Check if value matches male or female\n",
    "    if value.upper() == 'MALE':\n",
    "        return 1\n",
    "    elif value.upper() == 'FEMALE':\n",
    "        return 0\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "# 3. Save Metadata\n",
    "# Determine trait data availability\n",
    "is_trait_available = trait_row is not None\n",
    "validate_and_save_cohort_info(is_final=False, cohort=cohort, info_path=json_path, \n",
    "                              is_gene_available=is_gene_available, \n",
    "                              is_trait_available=is_trait_available)\n",
    "\n",
    "# 4. Clinical Feature Extraction (only if trait_row is not None)\n",
    "if trait_row is not None:\n",
    "    # Since we don't have direct access to the clinical_data.csv file,\n",
    "    # we'll use the sample characteristics dictionary from the previous step\n",
    "    # Create a sample characteristic dictionary based on the provided information\n",
    "    sample_char_dict = {\n",
    "        0: ['cell type: CD4+ T cells'], \n",
    "        1: ['primary diagnosis: ASTHMA', 'primary diagnosis: ATHEROSCLEROSIS', 'primary diagnosis: BREAST_CANCER', \n",
    "            'primary diagnosis: CHRONIC_LYMPHOCYTIC_LEUKEMIA', 'primary diagnosis: CROHN_DISEASE', \n",
    "            'primary diagnosis: ATOPIC_ECZEMA', 'primary diagnosis: HEALTHY_CONTROL', 'primary diagnosis: INFLUENZA', \n",
    "            'primary diagnosis: OBESITY', 'primary diagnosis: PSORIASIS', 'primary diagnosis: SEASONAL_ALLERGIC_RHINITIS', \n",
    "            'primary diagnosis: TYPE_1_DIABETES', 'primary diagnosis: ACUTE_TONSILLITIS', \n",
    "            'primary diagnosis: ULCERATIVE_COLITIS', 'primary diagnosis: Breast cancer', 'primary diagnosis: Control'], \n",
    "        2: ['Sex: Male', 'diagnosis2: ATOPIC_ECZEMA', 'Sex: Female', 'diagnosis2: ATHEROSCLEROSIS', \n",
    "            'diagnosis2: ASTHMA_OBESITY', 'diagnosis2: ASTHMA', 'diagnosis2: ASTMHA_SEASONAL_ALLERGIC_RHINITIS', \n",
    "            'diagnosis2: OBESITY'], \n",
    "        3: ['age: 56', 'Sex: Male', 'age: 20', 'age: 51', 'age: 37', 'age: 61', 'age: 31', 'age: 41', 'age: 80', \n",
    "            'age: 53', 'age: 73', 'age: 60', 'age: 76', 'age: 77', 'age: 74', 'age: 69', 'age: 81', 'age: 70', \n",
    "            'age: 82', 'age: 67', 'age: 78', 'age: 72', 'age: 66', 'age: 36', 'age: 45', 'age: 65', 'age: 48', \n",
    "            'age: 50', 'age: 24', 'age: 42'], \n",
    "        4: [np.nan, 'age: 63', 'age: 74', 'age: 49', 'age: 60', 'age: 68', 'age: 38', 'age: 16', 'age: 12', 'age: 27']\n",
    "    }\n",
    "    \n",
    "    # Convert sample_char_dict to a DataFrame format that geo_select_clinical_features can use\n",
    "    clinical_data = pd.DataFrame.from_dict(sample_char_dict, orient='index')\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 data\n",
    "    preview = preview_df(selected_clinical_df)\n",
    "    print(\"Preview of selected clinical features:\")\n",
    "    print(preview)\n",
    "    \n",
    "    # Create the directory if it doesn't exist\n",
    "    os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
    "    \n",
    "    # Save the clinical data\n",
    "    selected_clinical_df.to_csv(out_clinical_data_file, index=False)\n",
    "    print(f\"Clinical data saved to {out_clinical_data_file}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fd4d0ef2",
   "metadata": {},
   "source": [
    "### Step 3: Gene Data Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "c49bb7a6",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T03:38:02.861359Z",
     "iopub.status.busy": "2025-03-25T03:38:02.861250Z",
     "iopub.status.idle": "2025-03-25T03:38:03.353630Z",
     "shell.execute_reply": "2025-03-25T03:38:03.353257Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "First 20 gene/probe identifiers:\n",
      "Index(['1', '2', '3', '9', '10', '12', '13', '14', '15', '16', '18', '19',\n",
      "       '20', '21', '22', '23', '24', '25', '26', '27'],\n",
      "      dtype='object', name='ID')\n",
      "\n",
      "Gene data dimensions: 24166 genes × 204 samples\n"
     ]
    }
   ],
   "source": [
    "# 1. Re-identify the SOFT and matrix files to ensure we have the correct paths\n",
    "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
    "\n",
    "# 2. Extract the gene expression data from the matrix file\n",
    "gene_data = get_genetic_data(matrix_file)\n",
    "\n",
    "# 3. Print the first 20 row IDs (gene or probe identifiers)\n",
    "print(\"\\nFirst 20 gene/probe identifiers:\")\n",
    "print(gene_data.index[:20])\n",
    "\n",
    "# 4. Print the dimensions of the gene expression data\n",
    "print(f\"\\nGene data dimensions: {gene_data.shape[0]} genes × {gene_data.shape[1]} samples\")\n",
    "\n",
    "# Note: we keep is_gene_available as True since we successfully extracted gene expression data\n",
    "is_gene_available = True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cc98d14d",
   "metadata": {},
   "source": [
    "### Step 4: Gene Identifier Review"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "499fa7d0",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T03:38:03.354931Z",
     "iopub.status.busy": "2025-03-25T03:38:03.354824Z",
     "iopub.status.idle": "2025-03-25T03:38:03.356825Z",
     "shell.execute_reply": "2025-03-25T03:38:03.356524Z"
    }
   },
   "outputs": [],
   "source": [
    "# Review the gene identifiers\n",
    "# These appear to be numeric IDs (1, 2, 3, etc.) which are not human gene symbols\n",
    "# They are likely probe or feature identifiers from the microarray platform\n",
    "# These would require mapping to official gene symbols for biological interpretation\n",
    "\n",
    "requires_gene_mapping = True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "48c76426",
   "metadata": {},
   "source": [
    "### Step 5: Gene Annotation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "d958f1cd",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T03:38:03.357914Z",
     "iopub.status.busy": "2025-03-25T03:38:03.357818Z",
     "iopub.status.idle": "2025-03-25T03:38:07.608803Z",
     "shell.execute_reply": "2025-03-25T03:38:07.608428Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene annotation dataframe:\n",
      "Shape: (4740924, 3)\n",
      "Columns: ['ID', 'ENTREZ_GENE_ID', 'SPOT_ID']\n",
      "\n",
      "Gene annotation preview as dictionary:\n",
      "{'ID': ['1', '2', '3', '9', '10'], 'ENTREZ_GENE_ID': ['1', '2', '3', '9', '10'], 'SPOT_ID': [1.0, 2.0, 3.0, 9.0, 10.0]}\n",
      "\n",
      "Searching for platform annotation section in SOFT file...\n",
      "^PLATFORM = GPL25864\n",
      "!platform_table_begin\n",
      "ID\tENTREZ_GENE_ID\tSPOT_ID\n",
      "1\t1\t1\n",
      "2\t2\t2\n",
      "3\t3\t3\n",
      "9\t9\t9\n",
      "10\t10\t10\n",
      "12\t12\t12\n",
      "13\t13\t13\n",
      "14\t14\t14\n",
      "15\t15\t15\n"
     ]
    }
   ],
   "source": [
    "# 1. First get the file paths using geo_get_relevant_filepaths function\n",
    "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
    "\n",
    "# 2. Extract gene annotation data from the SOFT file\n",
    "gene_annotation = get_gene_annotation(soft_file)\n",
    "print(\"Gene annotation dataframe:\")\n",
    "print(f\"Shape: {gene_annotation.shape}\")\n",
    "print(f\"Columns: {gene_annotation.columns.tolist()}\")\n",
    "\n",
    "# 3. Preview the gene annotation dataframe as a Python dictionary\n",
    "gene_annotation_preview = {col: gene_annotation[col].head(5).tolist() for col in gene_annotation.columns}\n",
    "print(\"\\nGene annotation preview as dictionary:\")\n",
    "print(gene_annotation_preview)\n",
    "\n",
    "# 4. Also check platform annotation section for additional context\n",
    "print(\"\\nSearching for platform annotation section in SOFT file...\")\n",
    "with gzip.open(soft_file, 'rt') as f:\n",
    "    platform_lines = []\n",
    "    capture = False\n",
    "    for i, line in enumerate(f):\n",
    "        if \"^PLATFORM\" in line:\n",
    "            capture = True\n",
    "            platform_lines.append(line.strip())\n",
    "        elif capture and line.startswith(\"!platform_table_begin\"):\n",
    "            platform_lines.append(line.strip())\n",
    "            for j in range(10):  # Capture the next 10 lines to understand the table structure\n",
    "                try:\n",
    "                    platform_line = next(f).strip()\n",
    "                    platform_lines.append(platform_line)\n",
    "                except StopIteration:\n",
    "                    break\n",
    "            break\n",
    "    \n",
    "    print(\"\\n\".join(platform_lines))\n",
    "\n",
    "# Maintain gene availability status as True based on previous steps\n",
    "is_gene_available = True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "03c0910b",
   "metadata": {},
   "source": [
    "### Step 6: Gene Identifier Mapping"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "6112e8b9",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T03:38:07.610168Z",
     "iopub.status.busy": "2025-03-25T03:38:07.610051Z",
     "iopub.status.idle": "2025-03-25T03:41:32.492846Z",
     "shell.execute_reply": "2025-03-25T03:41:32.492285Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "First few rows of gene_data:\n",
      "    GSM3494884  GSM3494885  GSM3494886  GSM3494887  GSM3494888  GSM3494889  \\\n",
      "ID                                                                           \n",
      "1     6.948572    6.783931    6.780049    7.159348    7.311038    8.522366   \n",
      "2     4.267766    3.692029    3.649207    4.331090    3.903376    4.191000   \n",
      "3     4.334513    3.981417    3.922257    4.549893    4.140639    4.013236   \n",
      "9     7.140005    7.411580    6.722240    7.117540    6.874786    7.020385   \n",
      "10    4.486670    4.615900    3.966261    4.543677    4.150289    4.216883   \n",
      "\n",
      "    GSM3494890  GSM3494891  GSM3494892  GSM3494893  ...  GSM3495078  \\\n",
      "ID                                                  ...               \n",
      "1     7.208509    7.339519    7.292977    7.244630  ...    6.510166   \n",
      "2     3.771017    4.293601    3.963668    4.104845  ...    3.160329   \n",
      "3     3.996610    4.933703    3.735861    3.992670  ...    3.477307   \n",
      "9     7.031787    6.980904    7.003364    6.794992  ...    6.126888   \n",
      "10    4.736946    4.296770    4.462828    4.089816  ...    3.120966   \n",
      "\n",
      "    GSM3495079  GSM3495080  GSM3495081  GSM3495082  GSM3495083  GSM3495084  \\\n",
      "ID                                                                           \n",
      "1     6.400521    6.841084    6.689765    6.490229    6.342661    6.818770   \n",
      "2     4.067687    3.930320    3.714828    3.607567    3.732946    4.127519   \n",
      "3     3.450851    3.267643    3.997723    3.814572    3.530067    3.563020   \n",
      "9     6.361985    6.455366    6.666864    6.562479    6.537970    6.501036   \n",
      "10    3.934066    3.350455    3.268122    2.986117    4.154208    3.520550   \n",
      "\n",
      "    GSM3495085  GSM3495086  GSM3495087  \n",
      "ID                                      \n",
      "1     6.749511    5.702573    6.220784  \n",
      "2     3.685672    4.603592    4.182425  \n",
      "3     3.383465    4.885039    4.028309  \n",
      "9     6.373249    6.597989    6.264610  \n",
      "10    3.593129    3.834457    3.562929  \n",
      "\n",
      "[5 rows x 204 columns]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Entrez mapping sample:\n",
      "   ID Gene\n",
      "0   1    1\n",
      "1   2    2\n",
      "2   3    3\n",
      "3   9    9\n",
      "4  10   10\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene expression data after direct mapping: 4740720 genes × 204 samples\n",
      "First few gene identifiers:\n",
      "Index(['1', '6.948572124', '6.783931247', '6.780049494', '7.159347576',\n",
      "       '7.31103756', '8.522365778', '7.208509095', '7.339519183',\n",
      "       '7.292977237'],\n",
      "      dtype='object', name='Gene')\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Final gene data after aggregation: 1584674 genes × 204 samples\n",
      "First few gene symbols in final data:\n",
      "Index(['-0.001001579', '-0.010425045', '-0.045320336', '-0.046967808',\n",
      "       '-0.069891929', '-0.081080626', '-0.093186199', '-0.098238043',\n",
      "       '-0.103844598', '-0.126973525'],\n",
      "      dtype='object', name='Gene')\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene expression data saved to ../../output/preprocess/Psoriasis/gene_data/GSE123088.csv\n"
     ]
    }
   ],
   "source": [
    "# 1. Analyzing the structure of the data to understand why mapping isn't working\n",
    "print(\"First few rows of gene_data:\")\n",
    "print(gene_data.head())\n",
    "\n",
    "# 2. Let's check the gene mapping process more carefully\n",
    "# Create a simplified mapping approach using the Entrez Gene IDs directly\n",
    "entrez_mapping = gene_annotation[['ID', 'ENTREZ_GENE_ID']].dropna().astype({'ID': 'str'})\n",
    "entrez_mapping = entrez_mapping.rename(columns={'ENTREZ_GENE_ID': 'Gene'})\n",
    "\n",
    "print(\"Entrez mapping sample:\")\n",
    "print(entrez_mapping.head())\n",
    "\n",
    "# 3. Apply a direct mapping approach - merge the gene expression data with the mapping\n",
    "gene_data_with_entrez = gene_data.reset_index()\n",
    "gene_data_with_entrez = pd.merge(gene_data_with_entrez, entrez_mapping, on='ID', how='inner')\n",
    "gene_data_with_entrez.set_index('Gene', inplace=True)\n",
    "gene_data_with_entrez.drop('ID', axis=1, inplace=True)\n",
    "\n",
    "print(f\"Gene expression data after direct mapping: {gene_data_with_entrez.shape[0]} genes × {gene_data_with_entrez.shape[1]} samples\")\n",
    "print(\"First few gene identifiers:\")\n",
    "print(gene_data_with_entrez.index[:10])\n",
    "\n",
    "# 4. Group by gene ID to handle cases where multiple probes map to the same gene\n",
    "gene_data = gene_data_with_entrez.groupby(level=0).mean()\n",
    "\n",
    "print(f\"Final gene data after aggregation: {gene_data.shape[0]} genes × {gene_data.shape[1]} samples\")\n",
    "print(\"First few gene symbols in final data:\")\n",
    "print(gene_data.index[:10])\n",
    "\n",
    "# 5. Save 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}\")"
   ]
  }
 ],
 "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
}