File size: 42,854 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
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "0e12b627",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:30:57.804937Z",
     "iopub.status.busy": "2025-03-25T08:30:57.804641Z",
     "iopub.status.idle": "2025-03-25T08:30:57.970947Z",
     "shell.execute_reply": "2025-03-25T08:30:57.970579Z"
    }
   },
   "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 = \"COVID-19\"\n",
    "cohort = \"GSE212866\"\n",
    "\n",
    "# Input paths\n",
    "in_trait_dir = \"../../input/GEO/COVID-19\"\n",
    "in_cohort_dir = \"../../input/GEO/COVID-19/GSE212866\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/COVID-19/GSE212866.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/COVID-19/gene_data/GSE212866.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/COVID-19/clinical_data/GSE212866.csv\"\n",
    "json_path = \"../../output/preprocess/COVID-19/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a218e494",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "3b5ec58d",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:30:57.972440Z",
     "iopub.status.busy": "2025-03-25T08:30:57.972290Z",
     "iopub.status.idle": "2025-03-25T08:30:58.299882Z",
     "shell.execute_reply": "2025-03-25T08:30:58.299544Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Background Information:\n",
      "!Series_title\t\"Dynamics of gene expression profiling by microarrays and identification of high-risk patients for severe COVID-19\"\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: ['disease state: Control', 'disease state: Covid19', 'disease state: Covid19_SDRA'], 1: ['time: NA', 'time: D0', 'time: D7'], 2: ['tissue: peripheral blood']}\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": "0ec76a0c",
   "metadata": {},
   "source": [
    "### Step 2: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "506622fa",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:30:58.301156Z",
     "iopub.status.busy": "2025-03-25T08:30:58.301032Z",
     "iopub.status.idle": "2025-03-25T08:30:58.306444Z",
     "shell.execute_reply": "2025-03-25T08:30:58.306119Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Clinical data file not found at ../../input/GEO/COVID-19/GSE212866/clinical_data.csv\n",
      "This is a SuperSeries (GSE212866) that may not have standalone clinical data files at this directory level.\n",
      "Clinical feature extraction will be skipped.\n"
     ]
    }
   ],
   "source": [
    "import pandas as pd\n",
    "import os\n",
    "import json\n",
    "from typing import Optional, Callable, Dict, Any\n",
    "\n",
    "# 1. Gene Expression Data Availability\n",
    "# Based on the Series title, this appears to be microarray gene expression data\n",
    "is_gene_available = True\n",
    "\n",
    "# 2. Variable Availability and Data Type Conversion\n",
    "\n",
    "# 2.1 Data Availability\n",
    "# Trait - The disease state is in row 0\n",
    "trait_row = 0\n",
    "\n",
    "# Age - Not available in the sample characteristics\n",
    "age_row = None\n",
    "\n",
    "# Gender - Not available in the sample characteristics\n",
    "gender_row = None\n",
    "\n",
    "# 2.2 Data Type Conversion\n",
    "def convert_trait(value):\n",
    "    \"\"\"Convert COVID-19 disease state to binary (0: Control, 1: COVID-19)\"\"\"\n",
    "    if value is None:\n",
    "        return None\n",
    "    \n",
    "    # Extract the value after the colon\n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip()\n",
    "    \n",
    "    if value.lower() == 'control':\n",
    "        return 0\n",
    "    elif value.lower() in ['covid19', 'covid19_sdra']:\n",
    "        return 1\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "def convert_age(value):\n",
    "    \"\"\"Convert age to a continuous value\"\"\"\n",
    "    # Not used in this dataset\n",
    "    return None\n",
    "\n",
    "def convert_gender(value):\n",
    "    \"\"\"Convert gender to binary (0: Female, 1: Male)\"\"\"\n",
    "    # Not used in this dataset\n",
    "    return None\n",
    "\n",
    "# 3. Save Metadata\n",
    "# Determine if trait data is available\n",
    "is_trait_available = trait_row is not None\n",
    "\n",
    "# Validate and save cohort info\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",
    "    # Check if clinical data file exists\n",
    "    clinical_data_path = os.path.join(in_cohort_dir, \"clinical_data.csv\")\n",
    "    \n",
    "    if os.path.exists(clinical_data_path):\n",
    "        # Load clinical data\n",
    "        clinical_data = pd.read_csv(clinical_data_path)\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 selected clinical features\n",
    "        preview = preview_df(selected_clinical_df)\n",
    "        print(\"Preview of selected clinical features:\")\n",
    "        print(preview)\n",
    "        \n",
    "        # Save the selected clinical features\n",
    "        os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
    "        selected_clinical_df.to_csv(out_clinical_data_file, index=False)\n",
    "        print(f\"Clinical data saved to {out_clinical_data_file}\")\n",
    "    else:\n",
    "        print(f\"Clinical data file not found at {clinical_data_path}\")\n",
    "        print(f\"This is a SuperSeries (GSE212866) that may not have standalone clinical data files at this directory level.\")\n",
    "        print(f\"Clinical feature extraction will be skipped.\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6b4c1148",
   "metadata": {},
   "source": [
    "### Step 3: Gene Data Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "31716a75",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:30:58.307686Z",
     "iopub.status.busy": "2025-03-25T08:30:58.307566Z",
     "iopub.status.idle": "2025-03-25T08:30:58.848861Z",
     "shell.execute_reply": "2025-03-25T08:30:58.848474Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "SOFT file: ../../input/GEO/COVID-19/GSE212866/GSE212866_family.soft.gz\n",
      "Matrix file: ../../input/GEO/COVID-19/GSE212866/GSE212866-GPL23159_series_matrix.txt.gz\n",
      "Found the matrix table marker at line 59\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene data shape: (27189, 137)\n",
      "First 20 gene/probe identifiers:\n",
      "['23064070', '23064071', '23064072', '23064073', '23064074', '23064075', '23064076', '23064077', '23064078', '23064079', '23064080', '23064081', '23064083', '23064084', '23064085', '23064086', '23064087', '23064088', '23064089', '23064090']\n"
     ]
    }
   ],
   "source": [
    "# 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",
    "print(f\"SOFT file: {soft_file}\")\n",
    "print(f\"Matrix file: {matrix_file}\")\n",
    "\n",
    "# Set gene availability flag\n",
    "is_gene_available = True  # Initially assume gene data is available\n",
    "\n",
    "# First check if the matrix file contains the expected marker\n",
    "found_marker = False\n",
    "marker_row = None\n",
    "try:\n",
    "    with gzip.open(matrix_file, 'rt') as file:\n",
    "        for i, line in enumerate(file):\n",
    "            if \"!series_matrix_table_begin\" in line:\n",
    "                found_marker = True\n",
    "                marker_row = i\n",
    "                print(f\"Found the matrix table marker at line {i}\")\n",
    "                break\n",
    "    \n",
    "    if not found_marker:\n",
    "        print(\"Warning: Could not find '!series_matrix_table_begin' marker in the file.\")\n",
    "        is_gene_available = False\n",
    "        \n",
    "    # If marker was found, try to extract gene data\n",
    "    if is_gene_available:\n",
    "        try:\n",
    "            # Try using the library function\n",
    "            gene_data = get_genetic_data(matrix_file)\n",
    "            \n",
    "            if gene_data.shape[0] == 0:\n",
    "                print(\"Warning: Extracted gene data has 0 rows.\")\n",
    "                is_gene_available = False\n",
    "            else:\n",
    "                print(f\"Gene data shape: {gene_data.shape}\")\n",
    "                # Print the first 20 gene/probe identifiers\n",
    "                print(\"First 20 gene/probe identifiers:\")\n",
    "                print(gene_data.index[:20].tolist())\n",
    "        except Exception as e:\n",
    "            print(f\"Error extracting gene data with get_genetic_data(): {e}\")\n",
    "            is_gene_available = False\n",
    "    \n",
    "    # If gene data extraction failed, examine file content to diagnose\n",
    "    if not is_gene_available:\n",
    "        print(\"Examining file content to diagnose the issue:\")\n",
    "        try:\n",
    "            with gzip.open(matrix_file, 'rt') as file:\n",
    "                # Print lines around the marker if found\n",
    "                if marker_row is not None:\n",
    "                    for i, line in enumerate(file):\n",
    "                        if i >= marker_row - 2 and i <= marker_row + 10:\n",
    "                            print(f\"Line {i}: {line.strip()[:100]}...\")\n",
    "                        if i > marker_row + 10:\n",
    "                            break\n",
    "                else:\n",
    "                    # If marker not found, print first 10 lines\n",
    "                    for i, line in enumerate(file):\n",
    "                        if i < 10:\n",
    "                            print(f\"Line {i}: {line.strip()[:100]}...\")\n",
    "                        else:\n",
    "                            break\n",
    "        except Exception as e2:\n",
    "            print(f\"Error examining file: {e2}\")\n",
    "        \n",
    "except Exception as e:\n",
    "    print(f\"Error processing file: {e}\")\n",
    "    is_gene_available = False\n",
    "\n",
    "# Update validation information if gene data extraction failed\n",
    "if not is_gene_available:\n",
    "    print(\"Gene expression data could not be successfully extracted from this dataset.\")\n",
    "    # Update the validation record since gene data isn't available\n",
    "    is_trait_available = False  # We already determined trait data isn't available in step 2\n",
    "    validate_and_save_cohort_info(is_final=False, cohort=cohort, info_path=json_path,\n",
    "                                 is_gene_available=is_gene_available, is_trait_available=is_trait_available)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cec3f6ca",
   "metadata": {},
   "source": [
    "### Step 4: Gene Identifier Review"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "9f889e92",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:30:58.850303Z",
     "iopub.status.busy": "2025-03-25T08:30:58.850166Z",
     "iopub.status.idle": "2025-03-25T08:30:58.852226Z",
     "shell.execute_reply": "2025-03-25T08:30:58.851882Z"
    }
   },
   "outputs": [],
   "source": [
    "# These appear to be probe IDs from a microarray platform (GPL23159)\n",
    "# They are not standard human gene symbols like BRCA1, TP53, etc.\n",
    "# These are numeric identifiers that need to be mapped to actual gene symbols\n",
    "\n",
    "requires_gene_mapping = True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ba7f7124",
   "metadata": {},
   "source": [
    "### Step 5: Gene Annotation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "4e694970",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:30:58.853482Z",
     "iopub.status.busy": "2025-03-25T08:30:58.853360Z",
     "iopub.status.idle": "2025-03-25T08:31:05.887630Z",
     "shell.execute_reply": "2025-03-25T08:31:05.887103Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "Gene annotation preview:\n",
      "Columns in gene annotation: ['ID', 'probeset_id', 'seqname', 'strand', 'start', 'stop', 'total_probes', 'category', 'SPOT_ID', 'SPOT_ID.1']\n",
      "{'ID': ['TC0100006437.hg.1', 'TC0100006476.hg.1', 'TC0100006479.hg.1'], 'probeset_id': ['TC0100006437.hg.1', 'TC0100006476.hg.1', 'TC0100006479.hg.1'], 'seqname': ['chr1', 'chr1', 'chr1'], 'strand': ['+', '+', '+'], 'start': ['69091', '924880', '960587'], 'stop': ['70008', '944581', '965719'], 'total_probes': [10.0, 10.0, 10.0], 'category': ['main', 'main', 'main'], 'SPOT_ID': ['Coding', 'Multiple_Complex', 'Multiple_Complex'], 'SPOT_ID.1': ['NM_001005484 // RefSeq // Homo sapiens olfactory receptor, family 4, subfamily F, member 5 (OR4F5), mRNA. // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000335137 // ENSEMBL // olfactory receptor, family 4, subfamily F, member 5 [gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// OTTHUMT00000003223 // Havana transcript // olfactory receptor, family 4, subfamily F, member 5[gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// uc001aal.1 // UCSC Genes // Homo sapiens olfactory receptor, family 4, subfamily F, member 5 (OR4F5), mRNA. // chr1 // 100 // 100 // 0 // --- // 0 /// CCDS30547.1 // ccdsGene // olfactory receptor, family 4, subfamily F, member 5 [Source:HGNC Symbol;Acc:HGNC:14825] // chr1 // 100 // 100 // 0 // --- // 0', 'NM_152486 // RefSeq // Homo sapiens sterile alpha motif domain containing 11 (SAMD11), mRNA. // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000341065 // ENSEMBL // sterile alpha motif domain containing 11 [gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000342066 // ENSEMBL // sterile alpha motif domain containing 11 [gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000420190 // ENSEMBL // sterile alpha motif domain containing 11 [gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000437963 // ENSEMBL // sterile alpha motif domain containing 11 [gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000455979 // ENSEMBL // sterile alpha motif domain containing 11 [gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000464948 // ENSEMBL // sterile alpha motif domain containing 11 [gene_biotype:protein_coding transcript_biotype:retained_intron] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000466827 // ENSEMBL // sterile alpha motif domain containing 11 [gene_biotype:protein_coding transcript_biotype:retained_intron] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000474461 // ENSEMBL // sterile alpha motif domain containing 11 [gene_biotype:protein_coding transcript_biotype:retained_intron] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000478729 // ENSEMBL // sterile alpha motif domain containing 11 [gene_biotype:protein_coding transcript_biotype:processed_transcript] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000616016 // ENSEMBL // sterile alpha motif domain containing 11 [gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000616125 // ENSEMBL // sterile alpha motif domain containing 11 [gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000617307 // ENSEMBL // sterile alpha motif domain containing 11 [gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000618181 // ENSEMBL // sterile alpha motif domain containing 11 [gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000618323 // ENSEMBL // sterile alpha motif domain containing 11 [gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000618779 // ENSEMBL // sterile alpha motif domain containing 11 [gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000620200 // ENSEMBL // sterile alpha motif domain containing 11 [gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000622503 // ENSEMBL // sterile alpha motif domain containing 11 [gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// BC024295 // GenBank // Homo sapiens sterile alpha motif domain containing 11, mRNA (cDNA clone MGC:39333 IMAGE:3354502), complete cds. // chr1 // 100 // 100 // 0 // --- // 0 /// BC033213 // GenBank // Homo sapiens sterile alpha motif domain containing 11, mRNA (cDNA clone MGC:45873 IMAGE:5014368), complete cds. // chr1 // 100 // 100 // 0 // --- // 0 /// OTTHUMT00000097860 // Havana transcript // sterile alpha motif domain containing 11[gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// OTTHUMT00000097862 // Havana transcript // sterile alpha motif domain containing 11[gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// OTTHUMT00000097863 // Havana transcript // sterile alpha motif domain containing 11[gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// OTTHUMT00000097865 // Havana transcript // sterile alpha motif domain containing 11[gene_biotype:protein_coding transcript_biotype:processed_transcript] // chr1 // 100 // 100 // 0 // --- // 0 /// OTTHUMT00000097866 // Havana transcript // sterile alpha motif domain containing 11[gene_biotype:protein_coding transcript_biotype:retained_intron] // chr1 // 100 // 100 // 0 // --- // 0 /// OTTHUMT00000097867 // Havana transcript // sterile alpha motif domain containing 11[gene_biotype:protein_coding transcript_biotype:retained_intron] // chr1 // 100 // 100 // 0 // --- // 0 /// OTTHUMT00000097868 // Havana transcript // sterile alpha motif domain containing 11[gene_biotype:protein_coding transcript_biotype:retained_intron] // chr1 // 100 // 100 // 0 // --- // 0 /// OTTHUMT00000276866 // Havana transcript // sterile alpha motif domain containing 11[gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// OTTHUMT00000316521 // Havana transcript // sterile alpha motif domain containing 11[gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// CCDS2.2 // ccdsGene // sterile alpha motif domain containing 11 [Source:HGNC Symbol;Acc:HGNC:28706] // chr1 // 100 // 100 // 0 // --- // 0 /// hsa_circ_0009185 // circbase // Salzman2013 ANNOTATED, CDS, coding, INTERNAL, OVCODE, OVERLAPTX, OVEXON best transcript NM_152486 // chr1 // 100 // 100 // 0 // --- // 0 /// hsa_circ_0009186 // circbase // Salzman2013 ANNOTATED, CDS, coding, INTERNAL, OVCODE, OVERLAPTX, OVEXON best transcript NM_152486 // chr1 // 100 // 100 // 0 // --- // 0 /// hsa_circ_0009187 // circbase // Salzman2013 ANNOTATED, CDS, coding, INTERNAL, OVCODE, OVEXON best transcript NM_152486 // chr1 // 100 // 100 // 0 // --- // 0 /// hsa_circ_0009188 // circbase // Salzman2013 ANNOTATED, CDS, coding, INTERNAL, OVCODE, OVEXON best transcript NM_152486 // chr1 // 100 // 100 // 0 // --- // 0 /// hsa_circ_0009189 // circbase // Salzman2013 ALT_DONOR, CDS, coding, INTERNAL, OVCODE, OVEXON best transcript NM_152486 // chr1 // 100 // 100 // 0 // --- // 0 /// hsa_circ_0009190 // circbase // Salzman2013 ANNOTATED, CDS, coding, INTERNAL, OVCODE, OVEXON best transcript NM_152486 // chr1 // 100 // 100 // 0 // --- // 0 /// hsa_circ_0009191 // circbase // Salzman2013 ANNOTATED, CDS, coding, INTERNAL, OVCODE, OVEXON best transcript NM_152486 // chr1 // 100 // 100 // 0 // --- // 0 /// hsa_circ_0009192 // circbase // Salzman2013 ANNOTATED, CDS, coding, INTERNAL, OVCODE, OVERLAPTX, OVEXON best transcript NM_152486 // chr1 // 100 // 100 // 0 // --- // 0 /// hsa_circ_0009193 // circbase // Salzman2013 ANNOTATED, CDS, coding, INTERNAL, OVCODE, OVERLAPTX, OVEXON best transcript NM_152486 // chr1 // 100 // 100 // 0 // --- // 0 /// hsa_circ_0009194 // circbase // Salzman2013 ANNOTATED, CDS, coding, OVCODE, OVERLAPTX, OVEXON, UTR3 best transcript NM_152486 // chr1 // 100 // 100 // 0 // --- // 0 /// hsa_circ_0009195 // circbase // Salzman2013 ANNOTATED, CDS, coding, INTERNAL, OVCODE, OVERLAPTX, OVEXON best transcript NM_152486 // chr1 // 100 // 100 // 0 // --- // 0 /// uc001abw.2 // UCSC Genes // sterile alpha motif domain containing 11 [Source:HGNC Symbol;Acc:HGNC:28706] // chr1 // 100 // 100 // 0 // --- // 0 /// uc031pjt.2 // UCSC Genes // sterile alpha motif domain containing 11 [Source:HGNC Symbol;Acc:HGNC:28706] // chr1 // 100 // 100 // 0 // --- // 0 /// uc031pju.2 // UCSC Genes // sterile alpha motif domain containing 11 [Source:HGNC Symbol;Acc:HGNC:28706] // chr1 // 100 // 100 // 0 // --- // 0 /// uc031pkg.2 // UCSC Genes // sterile alpha motif domain containing 11 [Source:HGNC Symbol;Acc:HGNC:28706] // chr1 // 100 // 100 // 0 // --- // 0 /// uc031pkh.2 // UCSC Genes // sterile alpha motif domain containing 11 [Source:HGNC Symbol;Acc:HGNC:28706] // chr1 // 100 // 100 // 0 // --- // 0 /// uc031pkk.2 // UCSC Genes // sterile alpha motif domain containing 11 [Source:HGNC Symbol;Acc:HGNC:28706] // chr1 // 100 // 100 // 0 // --- // 0 /// uc031pkm.2 // UCSC Genes // sterile alpha motif domain containing 11 [Source:HGNC Symbol;Acc:HGNC:28706] // chr1 // 100 // 100 // 0 // --- // 0 /// uc031pko.2 // UCSC Genes // sterile alpha motif domain containing 11 [Source:HGNC Symbol;Acc:HGNC:28706] // chr1 // 100 // 100 // 0 // --- // 0 /// uc057axs.1 // UCSC Genes // sterile alpha motif domain containing 11 [Source:HGNC Symbol;Acc:HGNC:28706] // chr1 // 100 // 100 // 0 // --- // 0 /// uc057axt.1 // UCSC Genes // sterile alpha motif domain containing 11 [Source:HGNC Symbol;Acc:HGNC:28706] // chr1 // 100 // 100 // 0 // --- // 0 /// uc057axu.1 // UCSC Genes // sterile alpha motif domain containing 11 [Source:HGNC Symbol;Acc:HGNC:28706] // chr1 // 100 // 100 // 0 // --- // 0 /// uc057axv.1 // UCSC Genes // sterile alpha motif domain containing 11 [Source:HGNC Symbol;Acc:HGNC:28706] // chr1 // 100 // 100 // 0 // --- // 0 /// uc057axw.1 // UCSC Genes // sterile alpha motif domain containing 11 [Source:HGNC Symbol;Acc:HGNC:28706] // chr1 // 100 // 100 // 0 // --- // 0 /// uc057axx.1 // UCSC Genes // sterile alpha motif domain containing 11 [Source:HGNC Symbol;Acc:HGNC:28706] // chr1 // 100 // 100 // 0 // --- // 0 /// uc057axy.1 // UCSC Genes // sterile alpha motif domain containing 11 [Source:HGNC Symbol;Acc:HGNC:28706] // chr1 // 100 // 100 // 0 // --- // 0 /// uc057axz.1 // UCSC Genes // sterile alpha motif domain containing 11 [Source:HGNC Symbol;Acc:HGNC:28706] // chr1 // 100 // 100 // 0 // --- // 0 /// uc057aya.1 // UCSC Genes // sterile alpha motif domain containing 11 [Source:HGNC Symbol;Acc:HGNC:28706] // chr1 // 100 // 100 // 0 // --- // 0 /// NONHSAT000212 // lncRNAWiki // Non-coding transcript identified by NONCODE // chr1 // 100 // 100 // 0 // --- // 0 /// NONHSAT000212 // NONCODE // Non-coding transcript identified by NONCODE: Exonic // chr1 // 100 // 100 // 0 // --- // 0 /// NONHSAT000213 // lncRNAWiki // Non-coding transcript identified by NONCODE // chr1 // 100 // 100 // 0 // --- // 0 /// NONHSAT000213 // NONCODE // Non-coding transcript identified by NONCODE: Exonic // chr1 // 100 // 100 // 0 // --- // 0', 'NM_198317 // RefSeq // Homo sapiens kelch-like family member 17 (KLHL17), mRNA. // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000338591 // ENSEMBL // kelch-like family member 17 [gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000463212 // ENSEMBL // kelch-like family member 17 [gene_biotype:protein_coding transcript_biotype:retained_intron] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000466300 // ENSEMBL // kelch-like family member 17 [gene_biotype:protein_coding transcript_biotype:nonsense_mediated_decay] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000481067 // ENSEMBL // kelch-like family member 17 [gene_biotype:protein_coding transcript_biotype:retained_intron] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000622660 // ENSEMBL // kelch-like family member 17 [gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// OTTHUMT00000097875 // Havana transcript // kelch-like 17 (Drosophila)[gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// OTTHUMT00000097877 // Havana transcript // kelch-like 17 (Drosophila)[gene_biotype:protein_coding transcript_biotype:retained_intron] // chr1 // 100 // 100 // 0 // --- // 0 /// OTTHUMT00000097878 // Havana transcript // kelch-like 17 (Drosophila)[gene_biotype:protein_coding transcript_biotype:nonsense_mediated_decay] // chr1 // 100 // 100 // 0 // --- // 0 /// OTTHUMT00000097931 // Havana transcript // kelch-like 17 (Drosophila)[gene_biotype:protein_coding transcript_biotype:retained_intron] // chr1 // 100 // 100 // 0 // --- // 0 /// BC166618 // GenBank // Synthetic construct Homo sapiens clone IMAGE:100066344, MGC:195481 kelch-like 17 (Drosophila) (KLHL17) mRNA, encodes complete protein. // chr1 // 100 // 100 // 0 // --- // 0 /// CCDS30550.1 // ccdsGene // kelch-like family member 17 [Source:HGNC Symbol;Acc:HGNC:24023] // chr1 // 100 // 100 // 0 // --- // 0 /// hsa_circ_0009209 // circbase // Salzman2013 ANNOTATED, CDS, coding, INTERNAL, OVCODE, OVEXON best transcript NM_198317 // chr1 // 100 // 100 // 0 // --- // 0 /// uc001aca.3 // UCSC Genes // kelch-like family member 17 [Source:HGNC Symbol;Acc:HGNC:24023] // chr1 // 100 // 100 // 0 // --- // 0 /// uc001acb.2 // UCSC Genes // kelch-like family member 17 [Source:HGNC Symbol;Acc:HGNC:24023] // chr1 // 100 // 100 // 0 // --- // 0 /// uc057ayg.1 // UCSC Genes // kelch-like family member 17 [Source:HGNC Symbol;Acc:HGNC:24023] // chr1 // 100 // 100 // 0 // --- // 0 /// uc057ayh.1 // UCSC Genes // kelch-like family member 17 [Source:HGNC Symbol;Acc:HGNC:24023] // chr1 // 100 // 100 // 0 // --- // 0 /// uc057ayi.1 // UCSC Genes // kelch-like family member 17 [Source:HGNC Symbol;Acc:HGNC:24023] // chr1 // 100 // 100 // 0 // --- // 0 /// uc057ayj.1 // UCSC Genes // N/A // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000617073 // ENSEMBL // ncrna:novel chromosome:GRCh38:1:965110:965166:1 gene:ENSG00000277294 gene_biotype:miRNA transcript_biotype:miRNA // chr1 // 100 // 100 // 0 // --- // 0 /// NONHSAT000216 // lncRNAWiki // Non-coding transcript identified by NONCODE // chr1 // 100 // 100 // 0 // --- // 0 /// NONHSAT000216 // NONCODE // Non-coding transcript identified by NONCODE: Exonic // chr1 // 100 // 100 // 0 // --- // 0']}\n",
      "\n",
      "Examining gene mapping columns:\n",
      "Column 'ID' examples:\n",
      "Example 1: TC0100006437.hg.1\n",
      "Example 2: TC0100006476.hg.1\n",
      "Example 3: TC0100006479.hg.1\n",
      "Example 4: TC0100006480.hg.1\n",
      "Example 5: TC0100006483.hg.1\n",
      "\n",
      "Column 'SPOT_ID.1' examples (contains gene symbols):\n",
      "Example 1: NM_001005484 // RefSeq // Homo sapiens olfactory receptor, family 4, subfamily F, member 5 (OR4F5), mRNA. // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000335137 // ENSEMBL // olfactory receptor, f...\n",
      "Example 2: NM_152486 // RefSeq // Homo sapiens sterile alpha motif domain containing 11 (SAMD11), mRNA. // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000341065 // ENSEMBL // sterile alpha motif domain contain...\n",
      "Example 3: NM_198317 // RefSeq // Homo sapiens kelch-like family member 17 (KLHL17), mRNA. // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000338591 // ENSEMBL // kelch-like family member 17 [gene_biotype:prote...\n",
      "\n",
      "Extracted gene symbols from SPOT_ID.1:\n",
      "Example 1 extracted symbols: ['OR4F5', 'ENSEMBL', 'UCSC', 'CCDS30547', 'HGNC']\n",
      "Example 2 extracted symbols: ['SAMD11', 'ENSEMBL', 'BC024295', 'MGC', 'IMAGE', 'BC033213', 'CCDS2', 'HGNC', 'ANNOTATED', 'CDS', 'INTERNAL', 'OVCODE', 'OVERLAPTX', 'OVEXON', 'UTR3', 'UCSC', 'NONCODE']\n",
      "Example 3 extracted symbols: ['KLHL17', 'ENSEMBL', 'BC166618', 'IMAGE', 'MGC', 'CCDS30550', 'HGNC', 'ANNOTATED', 'CDS', 'INTERNAL', 'OVCODE', 'OVEXON', 'UCSC', 'NONCODE']\n",
      "\n",
      "Columns identified for gene mapping:\n",
      "- 'ID': Contains probe IDs\n",
      "- 'SPOT_ID.1': Contains gene information from which symbols can be extracted\n"
     ]
    }
   ],
   "source": [
    "# 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.\n",
    "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\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=3))\n",
    "\n",
    "# Examine the columns to find gene information\n",
    "print(\"\\nExamining gene mapping columns:\")\n",
    "print(\"Column 'ID' examples:\")\n",
    "id_samples = gene_annotation['ID'].head(5).tolist()\n",
    "for i, sample in enumerate(id_samples):\n",
    "    print(f\"Example {i+1}: {sample}\")\n",
    "\n",
    "# Look at SPOT_ID.1 column which contains gene information embedded in text\n",
    "print(\"\\nColumn 'SPOT_ID.1' examples (contains gene symbols):\")\n",
    "if 'SPOT_ID.1' in gene_annotation.columns:\n",
    "    # Display a few examples of the SPOT_ID.1 column\n",
    "    spot_samples = gene_annotation['SPOT_ID.1'].head(3).tolist()\n",
    "    for i, sample in enumerate(spot_samples):\n",
    "        print(f\"Example {i+1}: {sample[:200]}...\")  # Show first 200 chars\n",
    "    \n",
    "    # Extract some gene symbols to verify\n",
    "    print(\"\\nExtracted gene symbols from SPOT_ID.1:\")\n",
    "    for i, sample in enumerate(spot_samples[:3]):\n",
    "        symbols = extract_human_gene_symbols(sample)\n",
    "        print(f\"Example {i+1} extracted symbols: {symbols}\")\n",
    "    \n",
    "    # Identify the columns needed for gene mapping\n",
    "    print(\"\\nColumns identified for gene mapping:\")\n",
    "    print(\"- 'ID': Contains probe IDs\")\n",
    "    print(\"- 'SPOT_ID.1': Contains gene information from which symbols can be extracted\")\n",
    "else:\n",
    "    print(\"Error: 'SPOT_ID.1' column not found in annotation data.\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3e9218bd",
   "metadata": {},
   "source": [
    "### Step 6: Gene Identifier Mapping"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "84348d68",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:31:05.889258Z",
     "iopub.status.busy": "2025-03-25T08:31:05.889127Z",
     "iopub.status.idle": "2025-03-25T08:31:10.361804Z",
     "shell.execute_reply": "2025-03-25T08:31:10.361410Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene expression data shape: (27189, 137)\n",
      "Gene expression index type: object\n",
      "First few gene IDs: ['23064070', '23064071', '23064072', '23064073', '23064074']\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Created mapping dataframe with 21447 rows.\n",
      "Preview of mapping:\n",
      "                  ID                                               Gene\n",
      "0  TC0100006437.hg.1            [OR4F5, ENSEMBL, UCSC, CCDS30547, HGNC]\n",
      "1  TC0100006476.hg.1  [SAMD11, ENSEMBL, BC024295, MGC, IMAGE, BC0332...\n",
      "2  TC0100006479.hg.1  [KLHL17, ENSEMBL, BC166618, IMAGE, MGC, CCDS30...\n",
      "Number of probes in expression data: 27189\n",
      "Number of probes in mapping data: 21447\n",
      "Number of overlapping probes: 21447\n",
      "Applying gene mapping with 21447 mapped probes...\n",
      "Resulting gene expression data shape: (0, 137)\n",
      "Sample of gene symbols: []\n",
      "Normalizing gene symbols...\n",
      "Final gene expression data shape after normalization: (0, 137)\n",
      "Final sample of gene symbols: []\n",
      "Gene expression data saved to ../../output/preprocess/COVID-19/gene_data/GSE212866.csv\n"
     ]
    }
   ],
   "source": [
    "# 1. Step 1: Observe the gene identifiers in the gene expression data and find corresponding columns in gene annotation\n",
    "# From the previous steps, we can see:\n",
    "# - Gene expression data has numeric IDs starting with numbers like '23064070'\n",
    "# - Gene annotation data has alphanumeric IDs in the 'ID' column like 'TC0100006437.hg.1'\n",
    "\n",
    "# Unfortunately, the probe IDs in the expression data don't directly match the IDs in the annotation data.\n",
    "# We need to check if there's a way to map between them.\n",
    "\n",
    "# Extract expression data again to verify its structure\n",
    "gene_data = get_genetic_data(matrix_file)\n",
    "print(f\"Gene expression data shape: {gene_data.shape}\")\n",
    "print(f\"Gene expression index type: {gene_data.index.dtype}\")\n",
    "print(f\"First few gene IDs: {gene_data.index[:5].tolist()}\")\n",
    "\n",
    "# We'll create a better mapping by extracting gene symbols from SPOT_ID.1\n",
    "# Create a new mapping dataframe with ID and extracted gene symbols\n",
    "mapping_df = pd.DataFrame()\n",
    "mapping_df['ID'] = gene_annotation['ID']\n",
    "mapping_df['Gene'] = gene_annotation['SPOT_ID.1'].apply(extract_human_gene_symbols)\n",
    "\n",
    "# Filter out entries with empty gene lists\n",
    "mapping_df = mapping_df[mapping_df['Gene'].apply(len) > 0]\n",
    "\n",
    "print(f\"Created mapping dataframe with {len(mapping_df)} rows.\")\n",
    "print(\"Preview of mapping:\")\n",
    "print(mapping_df.head(3))\n",
    "\n",
    "# Check the overlap between probe IDs in expression data and mapping data\n",
    "expression_probes = set(gene_data.index)\n",
    "mapping_probes = set(mapping_df['ID'])\n",
    "overlap = expression_probes.intersection(mapping_probes)\n",
    "\n",
    "print(f\"Number of probes in expression data: {len(expression_probes)}\")\n",
    "print(f\"Number of probes in mapping data: {len(mapping_probes)}\")\n",
    "print(f\"Number of overlapping probes: {len(overlap)}\")\n",
    "\n",
    "# There seems to be a mismatch between probe IDs in expression data and gene annotation.\n",
    "# This is a common issue in GEO datasets. We need to try an alternative approach.\n",
    "\n",
    "# Let's try to directly map using positions if there's a 1:1 correspondence\n",
    "# This assumes the order of probes in gene annotation matches the order in expression data\n",
    "if len(gene_data) == len(gene_annotation) or abs(len(gene_data) - len(gene_annotation)) < 100:\n",
    "    print(\"Attempting to map by position due to ID mismatch...\")\n",
    "    # Create a mapping from position to gene symbol\n",
    "    position_mapping = gene_annotation['SPOT_ID.1'].apply(extract_human_gene_symbols)\n",
    "    \n",
    "    # Get probe IDs from expression data in their original order\n",
    "    probe_ids = gene_data.index.tolist()\n",
    "    \n",
    "    # Create position-based mapping dataframe\n",
    "    position_mapping_df = pd.DataFrame({\n",
    "        'ID': probe_ids[:len(position_mapping)],\n",
    "        'Gene': position_mapping[:len(probe_ids)]\n",
    "    })\n",
    "    \n",
    "    # Filter out entries with empty gene lists\n",
    "    position_mapping_df = position_mapping_df[position_mapping_df['Gene'].apply(len) > 0]\n",
    "    \n",
    "    print(f\"Created position-based mapping with {len(position_mapping_df)} rows.\")\n",
    "    print(\"Preview of position-based mapping:\")\n",
    "    print(position_mapping_df.head(3))\n",
    "    \n",
    "    # Use this mapping instead if it has more entries\n",
    "    if len(position_mapping_df) > len(mapping_df):\n",
    "        mapping_df = position_mapping_df\n",
    "        print(\"Using position-based mapping as it has more entries.\")\n",
    "\n",
    "# If we still don't have a proper mapping or the overlap is too small,\n",
    "# let's create a custom mapping based on the ID ranges\n",
    "if len(overlap) < 1000:\n",
    "    print(\"Creating custom mapping based on probe ID patterns...\")\n",
    "    # In GSE212866, looking at the IDs from gene_data vs gene_annotation:\n",
    "    # Gene expression data has numeric IDs (e.g., '23064070')\n",
    "    # Gene annotation has different format IDs (e.g., 'TC0100006437.hg.1')\n",
    "    \n",
    "    # Check if there's a pattern in the SPOT_ID.1 column that contains both numeric IDs and gene symbols\n",
    "    print(\"Checking for ID patterns in SPOT_ID.1...\")\n",
    "    \n",
    "    # Given the apparent mismatch, we can create a direct mapping based on the row position\n",
    "    # Assuming the probe order is preserved between the two files\n",
    "    # This is risky but may be our best option in this specific dataset\n",
    "    \n",
    "    # Extract gene symbols from each annotation entry\n",
    "    gene_symbols = gene_annotation['SPOT_ID.1'].apply(extract_human_gene_symbols)\n",
    "    \n",
    "    # Create a dataframe with expression IDs and corresponding gene symbols\n",
    "    # Taking the minimum length to avoid index errors\n",
    "    min_length = min(len(gene_data.index), len(gene_symbols))\n",
    "    \n",
    "    # Create a mapping from expression IDs to gene symbols\n",
    "    position_mapping_df = pd.DataFrame({\n",
    "        'ID': gene_data.index[:min_length],\n",
    "        'Gene': gene_symbols[:min_length]\n",
    "    })\n",
    "    \n",
    "    # Filter rows with empty gene symbols\n",
    "    position_mapping_df = position_mapping_df[position_mapping_df['Gene'].apply(len) > 0]\n",
    "    \n",
    "    print(f\"Created position-based mapping with {len(position_mapping_df)} rows\")\n",
    "    mapping_df = position_mapping_df\n",
    "\n",
    "# 3. Apply the gene mapping to convert probe-level measurements to gene-level expression\n",
    "print(f\"Applying gene mapping with {len(mapping_df)} mapped probes...\")\n",
    "gene_data = apply_gene_mapping(gene_data, mapping_df)\n",
    "\n",
    "print(f\"Resulting gene expression data shape: {gene_data.shape}\")\n",
    "print(f\"Sample of gene symbols: {list(gene_data.index[:5])}\")\n",
    "\n",
    "# Normalize gene symbols to handle synonyms and aggregate redundant rows\n",
    "print(\"Normalizing gene symbols...\")\n",
    "gene_data = normalize_gene_symbols_in_index(gene_data)\n",
    "\n",
    "print(f\"Final gene expression data shape after normalization: {gene_data.shape}\")\n",
    "print(f\"Final sample of gene symbols: {list(gene_data.index[:5])}\")\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}\")"
   ]
  }
 ],
 "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
}