File size: 25,722 Bytes
82732bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "879df130",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T04:01:40.573778Z",
     "iopub.status.busy": "2025-03-25T04:01:40.573676Z",
     "iopub.status.idle": "2025-03-25T04:01:40.750517Z",
     "shell.execute_reply": "2025-03-25T04:01:40.750170Z"
    }
   },
   "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 = \"Stomach_Cancer\"\n",
    "cohort = \"GSE130823\"\n",
    "\n",
    "# Input paths\n",
    "in_trait_dir = \"../../input/GEO/Stomach_Cancer\"\n",
    "in_cohort_dir = \"../../input/GEO/Stomach_Cancer/GSE130823\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/Stomach_Cancer/GSE130823.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/Stomach_Cancer/gene_data/GSE130823.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/Stomach_Cancer/clinical_data/GSE130823.csv\"\n",
    "json_path = \"../../output/preprocess/Stomach_Cancer/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "367bd76e",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "0ceab183",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T04:01:40.751958Z",
     "iopub.status.busy": "2025-03-25T04:01:40.751812Z",
     "iopub.status.idle": "2025-03-25T04:01:41.039899Z",
     "shell.execute_reply": "2025-03-25T04:01:41.039534Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Files in the cohort directory:\n",
      "['GSE130823_family.soft.gz', 'GSE130823_series_matrix.txt.gz']\n",
      "Identified SOFT files: ['GSE130823_family.soft.gz']\n",
      "Identified matrix files: ['GSE130823_series_matrix.txt.gz']\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "Background Information:\n",
      "!Series_title\t\"Dissecting Expression Profiles of Gastric Precancerous Lesions and Early Gastric Cancer to Explore Crucial Molecules in Intestinal-type Gastric Cancer Tumorigenesis\"\n",
      "!Series_summary\t\"To investigate the changes in molecular expression, biological processes, stemness, immune microenvironment, tumor hallmark activities and co-expression relationships during intestinal-type gastric cancer carcinogenesis and to excavate the prognostic information contained in the carcinogenesis process. RNA expression profiles of ninety-four gastroscope biopsy samples with different stages of precancerous lesions or early gastric cancers and their paired controls were detected by Agilent Microarray.\"\n",
      "!Series_overall_design\t\"RNA expression profiles of ninety-four gastroscope biopsy samples with different stages of precancerous lesions or early gastric cancers and their paired controls were detected by Agilent Microarray.\"\n",
      "\n",
      "Sample Characteristics Dictionary:\n",
      "{0: ['tissue: gastric'], 1: ['gender: Female', 'gender: Male'], 2: ['age: 74', 'age: 61', 'age: 54', 'age: 60', 'age: 63', 'age: 58', 'age: 44', 'age: 56', 'age: 59', 'age: 55', 'age: 46', 'age: 71', 'age: 77', 'age: 62', 'age: 65', 'age: 69', 'age: 66', 'age: 73', 'age: 57', 'age: 78', 'age: 38', 'age: 68', 'age: 42', 'age: 43']}\n"
     ]
    }
   ],
   "source": [
    "# 1. Let's first list the directory contents to understand what files are available\n",
    "import os\n",
    "\n",
    "print(\"Files in the cohort directory:\")\n",
    "files = os.listdir(in_cohort_dir)\n",
    "print(files)\n",
    "\n",
    "# Adapt file identification to handle different naming patterns\n",
    "soft_files = [f for f in files if 'soft' in f.lower() or '.soft' in f.lower() or '_soft' in f.lower()]\n",
    "matrix_files = [f for f in files if 'matrix' in f.lower() or '.matrix' in f.lower() or '_matrix' in f.lower()]\n",
    "\n",
    "# If no files with these patterns are found, look for alternative file types\n",
    "if not soft_files:\n",
    "    soft_files = [f for f in files if f.endswith('.txt') or f.endswith('.gz')]\n",
    "if not matrix_files:\n",
    "    matrix_files = [f for f in files if f.endswith('.txt') or f.endswith('.gz')]\n",
    "\n",
    "print(\"Identified SOFT files:\", soft_files)\n",
    "print(\"Identified matrix files:\", matrix_files)\n",
    "\n",
    "# Use the first files found, if any\n",
    "if len(soft_files) > 0 and len(matrix_files) > 0:\n",
    "    soft_file = os.path.join(in_cohort_dir, soft_files[0])\n",
    "    matrix_file = os.path.join(in_cohort_dir, matrix_files[0])\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(\"\\nBackground Information:\")\n",
    "    print(background_info)\n",
    "    print(\"\\nSample Characteristics Dictionary:\")\n",
    "    print(sample_characteristics_dict)\n",
    "else:\n",
    "    print(\"No appropriate files found in the directory.\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7f903d72",
   "metadata": {},
   "source": [
    "### Step 2: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "99cfae34",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T04:01:41.041321Z",
     "iopub.status.busy": "2025-03-25T04:01:41.041054Z",
     "iopub.status.idle": "2025-03-25T04:01:41.045294Z",
     "shell.execute_reply": "2025-03-25T04:01:41.044997Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Clinical feature extraction skipped because trait data is not available.\n"
     ]
    }
   ],
   "source": [
    "# 1. Gene Expression Data Availability\n",
    "# Based on the background information, this dataset contains RNA expression profiles \n",
    "# detected by Agilent Microarray, which indicates gene expression data is available\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",
    "# - trait: Not explicitly available as a separate category\n",
    "# - age: Available at key 2\n",
    "# - gender: Available at key 1\n",
    "\n",
    "# Looking at the background information, this study focuses on gastric cancer,\n",
    "# but we don't have a clear indicator of cancer status in the provided characteristics.\n",
    "# Therefore, we cannot determine trait status at this stage.\n",
    "trait_row = None  # Cannot determine cancer status from available sample characteristics\n",
    "age_row = 2       # Age information is at key 2\n",
    "gender_row = 1    # Gender information is at key 1\n",
    "\n",
    "# 2.2 Data Type Conversion\n",
    "def convert_trait(value):\n",
    "    \"\"\"\n",
    "    Convert cancer status to binary trait values.\n",
    "    Not implemented as we cannot determine trait status.\n",
    "    \"\"\"\n",
    "    return None  # Cannot determine trait status\n",
    "\n",
    "def convert_age(value):\n",
    "    \"\"\"Convert age string to numerical value.\"\"\"\n",
    "    if value is None:\n",
    "        return None\n",
    "    \n",
    "    # Extract value after colon if present\n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip()\n",
    "    \n",
    "    try:\n",
    "        return int(value)\n",
    "    except:\n",
    "        return None\n",
    "\n",
    "def convert_gender(value):\n",
    "    \"\"\"Convert gender string to binary (0 for female, 1 for male).\"\"\"\n",
    "    if value is None:\n",
    "        return None\n",
    "    \n",
    "    # Extract value after colon if present\n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip().lower()\n",
    "    \n",
    "    if 'female' in value:\n",
    "        return 0\n",
    "    elif 'male' in value:\n",
    "        return 1\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "# 3. Save Metadata\n",
    "# Since trait_row is None, set is_trait_available to False\n",
    "is_trait_available = False\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. Skip clinical feature extraction since trait data is not available (trait_row is None)\n",
    "print(\"Clinical feature extraction skipped because trait data is not available.\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "05d72dc8",
   "metadata": {},
   "source": [
    "### Step 3: Gene Data Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "2de0bb50",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T04:01:41.046443Z",
     "iopub.status.busy": "2025-03-25T04:01:41.046337Z",
     "iopub.status.idle": "2025-03-25T04:01:41.609954Z",
     "shell.execute_reply": "2025-03-25T04:01:41.609482Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "First 20 gene/probe identifiers:\n",
      "Index(['(+)E1A_r60_1', '(+)E1A_r60_3', '(+)E1A_r60_a104', '(+)E1A_r60_a107',\n",
      "       '(+)E1A_r60_a135', '(+)E1A_r60_a20', '(+)E1A_r60_a22', '(+)E1A_r60_a97',\n",
      "       '(+)E1A_r60_n11', '(+)E1A_r60_n9', '3xSLv1', 'A_19_P00315452',\n",
      "       'A_19_P00315459', 'A_19_P00315482', 'A_19_P00315492', 'A_19_P00315493',\n",
      "       'A_19_P00315502', 'A_19_P00315506', 'A_19_P00315518', 'A_19_P00315519'],\n",
      "      dtype='object', name='ID')\n",
      "\n",
      "Gene expression data shape: (50739, 94)\n"
     ]
    }
   ],
   "source": [
    "# Use the helper function to get the proper file paths\n",
    "soft_file_path, matrix_file_path = geo_get_relevant_filepaths(in_cohort_dir)\n",
    "\n",
    "# Extract gene expression data\n",
    "try:\n",
    "    gene_data = get_genetic_data(matrix_file_path)\n",
    "    \n",
    "    # Print the first 20 row IDs (gene or probe identifiers)\n",
    "    print(\"First 20 gene/probe identifiers:\")\n",
    "    print(gene_data.index[:20])\n",
    "    \n",
    "    # Print shape to understand the dataset dimensions\n",
    "    print(f\"\\nGene expression data shape: {gene_data.shape}\")\n",
    "    \n",
    "except Exception as e:\n",
    "    print(f\"Error extracting gene data: {e}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3be6ec43",
   "metadata": {},
   "source": [
    "### Step 4: Gene Identifier Review"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "8478029b",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T04:01:41.611403Z",
     "iopub.status.busy": "2025-03-25T04:01:41.611286Z",
     "iopub.status.idle": "2025-03-25T04:01:41.613908Z",
     "shell.execute_reply": "2025-03-25T04:01:41.613514Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene mapping required: True\n",
      "These appear to be Agilent microarray probe IDs, not standard human gene symbols.\n"
     ]
    }
   ],
   "source": [
    "# The gene identifiers observed appear to be microarray probe IDs (like \"(+)E1A_r60_1\", \"A_19_P00315452\"), not standard human gene symbols.\n",
    "# These look like Agilent microarray probe identifiers which need to be mapped to human gene symbols.\n",
    "\n",
    "requires_gene_mapping = True\n",
    "\n",
    "# Print the conclusion for clarity\n",
    "print(f\"Gene mapping required: {requires_gene_mapping}\")\n",
    "print(\"These appear to be Agilent microarray probe IDs, not standard human gene symbols.\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "619b0f09",
   "metadata": {},
   "source": [
    "### Step 5: Gene Annotation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "009ff239",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T04:01:41.615163Z",
     "iopub.status.busy": "2025-03-25T04:01:41.615055Z",
     "iopub.status.idle": "2025-03-25T04:01:50.123686Z",
     "shell.execute_reply": "2025-03-25T04:01:50.123366Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene annotation preview:\n",
      "{'ID': ['GE_BrightCorner', 'DarkCorner', 'A_23_P117082', 'A_33_P3246448', 'A_33_P3318220'], 'SPOT_ID': ['CONTROL', 'CONTROL', 'A_23_P117082', 'A_33_P3246448', 'A_33_P3318220'], 'CONTROL_TYPE': ['pos', 'pos', 'FALSE', 'FALSE', 'FALSE'], 'REFSEQ': [nan, nan, 'NM_015987', 'NM_080671', 'NM_178466'], 'GB_ACC': [nan, nan, 'NM_015987', 'NM_080671', 'NM_178466'], 'LOCUSLINK_ID': [nan, nan, 50865.0, 23704.0, 128861.0], 'GENE_SYMBOL': [nan, nan, 'HEBP1', 'KCNE4', 'BPIFA3'], 'GENE_NAME': [nan, nan, 'heme binding protein 1', 'potassium voltage-gated channel, Isk-related family, member 4', 'BPI fold containing family A, member 3'], 'UNIGENE_ID': [nan, nan, 'Hs.642618', 'Hs.348522', 'Hs.360989'], 'ENSEMBL_ID': [nan, nan, 'ENST00000014930', 'ENST00000281830', 'ENST00000375454'], 'ACCESSION_STRING': [nan, nan, 'ref|NM_015987|ens|ENST00000014930|gb|AF117615|gb|BC016277', 'ref|NM_080671|ens|ENST00000281830|tc|THC2655788', 'ref|NM_178466|ens|ENST00000375454|ens|ENST00000471233|tc|THC2478474'], 'CHROMOSOMAL_LOCATION': [nan, nan, 'chr12:13127906-13127847', 'chr2:223920197-223920256', 'chr20:31812208-31812267'], 'CYTOBAND': [nan, nan, 'hs|12p13.1', 'hs|2q36.1', 'hs|20q11.21'], 'DESCRIPTION': [nan, nan, 'Homo sapiens heme binding protein 1 (HEBP1), mRNA [NM_015987]', 'Homo sapiens potassium voltage-gated channel, Isk-related family, member 4 (KCNE4), mRNA [NM_080671]', 'Homo sapiens BPI fold containing family A, member 3 (BPIFA3), transcript variant 1, mRNA [NM_178466]'], 'GO_ID': [nan, nan, 'GO:0005488(binding)|GO:0005576(extracellular region)|GO:0005737(cytoplasm)|GO:0005739(mitochondrion)|GO:0005829(cytosol)|GO:0007623(circadian rhythm)|GO:0020037(heme binding)', 'GO:0005244(voltage-gated ion channel activity)|GO:0005249(voltage-gated potassium channel activity)|GO:0006811(ion transport)|GO:0006813(potassium ion transport)|GO:0016020(membrane)|GO:0016021(integral to membrane)|GO:0016324(apical plasma membrane)', 'GO:0005576(extracellular region)|GO:0008289(lipid binding)'], 'SEQUENCE': [nan, nan, 'AAGGGGGAAAATGTGATTTGTGCCTGATCTTTCATCTGTGATTCTTATAAGAGCTTTGTC', 'GCAAGTCTCTCTGCACCTATTAAAAAGTGATGTATATACTTCCTTCTTATTCTGTTGAGT', 'CATTCCATAAGGAGTGGTTCTCGGCAAATATCTCACTTGAATTTGACCTTGAATTGAGAC']}\n"
     ]
    }
   ],
   "source": [
    "# 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.\n",
    "try:\n",
    "    # Use the correct variable name from previous steps\n",
    "    gene_annotation = get_gene_annotation(soft_file_path)\n",
    "    \n",
    "    # 2. Preview the gene annotation dataframe\n",
    "    print(\"Gene annotation preview:\")\n",
    "    print(preview_df(gene_annotation))\n",
    "    \n",
    "except UnicodeDecodeError as e:\n",
    "    print(f\"Unicode decoding error: {e}\")\n",
    "    print(\"Trying alternative approach...\")\n",
    "    \n",
    "    # Read the file with Latin-1 encoding which is more permissive\n",
    "    import gzip\n",
    "    import pandas as pd\n",
    "    \n",
    "    # Manually read the file line by line with error handling\n",
    "    data_lines = []\n",
    "    with gzip.open(soft_file_path, 'rb') as f:\n",
    "        for line in f:\n",
    "            # Skip lines starting with prefixes we want to filter out\n",
    "            line_str = line.decode('latin-1')\n",
    "            if not line_str.startswith('^') and not line_str.startswith('!') and not line_str.startswith('#'):\n",
    "                data_lines.append(line_str)\n",
    "    \n",
    "    # Create dataframe from collected lines\n",
    "    if data_lines:\n",
    "        gene_data_str = '\\n'.join(data_lines)\n",
    "        gene_annotation = pd.read_csv(pd.io.common.StringIO(gene_data_str), sep='\\t', low_memory=False)\n",
    "        print(\"Gene annotation preview (alternative method):\")\n",
    "        print(preview_df(gene_annotation))\n",
    "    else:\n",
    "        print(\"No valid gene annotation data found after filtering.\")\n",
    "        gene_annotation = pd.DataFrame()\n",
    "    \n",
    "except Exception as e:\n",
    "    print(f\"Error extracting gene annotation data: {e}\")\n",
    "    gene_annotation = pd.DataFrame()\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e0d39bb2",
   "metadata": {},
   "source": [
    "### Step 6: Gene Identifier Mapping"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "4f6155b1",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T04:01:50.125218Z",
     "iopub.status.busy": "2025-03-25T04:01:50.125100Z",
     "iopub.status.idle": "2025-03-25T04:01:50.601088Z",
     "shell.execute_reply": "2025-03-25T04:01:50.600752Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene mapping dataframe shape: (46204, 2)\n",
      "First few rows of gene mapping:\n",
      "              ID          Gene\n",
      "2   A_23_P117082         HEBP1\n",
      "3  A_33_P3246448         KCNE4\n",
      "4  A_33_P3318220        BPIFA3\n",
      "5  A_33_P3236322  LOC100129869\n",
      "6  A_33_P3319925          IRG1\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "Resulting gene expression data shape: (19847, 94)\n",
      "First few rows of gene expression data:\n",
      "          GSM3754774  GSM3754775  GSM3754776  GSM3754777  GSM3754778  \\\n",
      "Gene                                                                   \n",
      "A1BG       -0.156597   -0.789875    1.512063    0.087390    0.577830   \n",
      "A1BG-AS1   -0.055273   -1.115357    1.203011    0.361480    0.520860   \n",
      "A1CF        0.060761    4.167142    0.721337    3.379362    3.042676   \n",
      "A2M         1.730769   -0.925951    1.529119    0.470597   -0.023590   \n",
      "A2ML1       0.114604   -0.132678   -0.101793    0.342719    0.013418   \n",
      "\n",
      "          GSM3754779  GSM3754780  GSM3754781  GSM3754782  GSM3754783  ...  \\\n",
      "Gene                                                                  ...   \n",
      "A1BG       -0.408904    0.921989   -1.117775   -1.007375   -0.585641  ...   \n",
      "A1BG-AS1   -0.628904    0.711314   -0.730740   -0.651767   -1.438113  ...   \n",
      "A1CF        0.437447    0.190483    1.911350    2.402059    4.377823  ...   \n",
      "A2M        -0.872226    1.652595    0.143312   -0.682341   -0.867899  ...   \n",
      "A2ML1      -0.206153    0.024301    0.175596    0.225302   -0.076763  ...   \n",
      "\n",
      "          GSM3754858  GSM3754859  GSM3754860  GSM3754861  GSM3754862  \\\n",
      "Gene                                                                   \n",
      "A1BG       -0.006824    0.521656    0.265956    1.654205   -0.476906   \n",
      "A1BG-AS1   -0.172644    0.927442    0.934098    1.588539   -0.742384   \n",
      "A1CF       -2.451899   -3.947608   -0.419664    0.280682   -3.851371   \n",
      "A2M         1.021807    2.353894    1.703777    1.027817   -0.295080   \n",
      "A2ML1       0.064888    2.028134    1.118435    0.160938    0.079693   \n",
      "\n",
      "          GSM3754863  GSM3754864  GSM3754865  GSM3754866  GSM3754867  \n",
      "Gene                                                                  \n",
      "A1BG        1.054766   -0.568381   -0.134526    0.753157    1.452306  \n",
      "A1BG-AS1    1.480629    0.933561    0.720043    1.538296    1.667827  \n",
      "A1CF        0.715678   -3.306372    3.026614    3.772440    2.164036  \n",
      "A2M         0.810758   -0.009463   -0.367532    0.301483    2.315752  \n",
      "A2ML1      -0.162874    0.046059   -0.137830   -0.234484   -0.075579  \n",
      "\n",
      "[5 rows x 94 columns]\n"
     ]
    }
   ],
   "source": [
    "# 1. Observe the data to determine appropriate columns for mapping\n",
    "# From the gene annotation preview, we can see:\n",
    "# - 'ID' matches the probe identifiers from the gene expression data (like \"A_33_P3246448\")\n",
    "# - 'GENE_SYMBOL' contains the human gene symbols (like \"HEBP1\", \"KCNE4\")\n",
    "\n",
    "# 2. Extract mapping between probe IDs and gene symbols\n",
    "# Define the column names for the identifiers and gene symbols\n",
    "probe_id_col = 'ID'\n",
    "gene_symbol_col = 'GENE_SYMBOL'\n",
    "\n",
    "# Get the mapping dataframe using the helper function\n",
    "gene_mapping_df = get_gene_mapping(gene_annotation, prob_col=probe_id_col, gene_col=gene_symbol_col)\n",
    "\n",
    "# Print mapping info\n",
    "print(f\"Gene mapping dataframe shape: {gene_mapping_df.shape}\")\n",
    "print(\"First few rows of gene mapping:\")\n",
    "print(gene_mapping_df.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_df)\n",
    "\n",
    "# Normalize gene symbols to handle synonyms and case variations\n",
    "gene_data = normalize_gene_symbols_in_index(gene_data)\n",
    "\n",
    "# Print info about the resulting gene expression data\n",
    "print(f\"\\nResulting gene expression data shape: {gene_data.shape}\")\n",
    "print(\"First few rows of gene expression data:\")\n",
    "print(gene_data.head())\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3becef1d",
   "metadata": {},
   "source": [
    "### Step 7: Data Normalization and Linking"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "df8975f8",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T04:01:50.602368Z",
     "iopub.status.busy": "2025-03-25T04:01:50.602246Z",
     "iopub.status.idle": "2025-03-25T04:01:51.755178Z",
     "shell.execute_reply": "2025-03-25T04:01:51.754829Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Normalized gene data shape: (19847, 94)\n",
      "First few normalized gene symbols: ['A1BG', 'A1BG-AS1', 'A1CF', 'A2M', 'A2ML1', 'A2MP1', 'A4GALT', 'A4GNT', 'AA06', 'AAA1']\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Normalized gene data saved to ../../output/preprocess/Stomach_Cancer/gene_data/GSE130823.csv\n",
      "Trait data availability: Not available\n",
      "Gene expression data was processed and saved, but no linked data was created due to missing trait information.\n"
     ]
    }
   ],
   "source": [
    "# 1. Normalize gene symbols in the obtained gene expression data\n",
    "normalized_gene_data = gene_data  # It's already normalized in Step 6\n",
    "print(f\"Normalized gene data shape: {normalized_gene_data.shape}\")\n",
    "print(f\"First few normalized gene symbols: {list(normalized_gene_data.index[:10])}\")\n",
    "\n",
    "# Save the normalized gene data\n",
    "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
    "normalized_gene_data.to_csv(out_gene_data_file)\n",
    "print(f\"Normalized gene data saved to {out_gene_data_file}\")\n",
    "\n",
    "# Check if trait data is available (from Step 2 we determined it was not)\n",
    "is_trait_available = False\n",
    "print(f\"Trait data availability: {'Available' if is_trait_available else 'Not available'}\")\n",
    "\n",
    "# Since trait data is not available, we cannot create clinical features or linked data\n",
    "# We'll use the initial validation since we can't perform the final validation without trait data\n",
    "validate_result = validate_and_save_cohort_info(\n",
    "    is_final=False,\n",
    "    cohort=cohort, \n",
    "    info_path=json_path, \n",
    "    is_gene_available=True,  \n",
    "    is_trait_available=is_trait_available\n",
    ")\n",
    "\n",
    "print(f\"Gene expression data was processed and saved, but no linked data was created due to missing trait information.\")"
   ]
  }
 ],
 "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
}