File size: 24,936 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
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "6a80dcf7",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T04:02:07.350560Z",
     "iopub.status.busy": "2025-03-25T04:02:07.350397Z",
     "iopub.status.idle": "2025-03-25T04:02:07.519039Z",
     "shell.execute_reply": "2025-03-25T04:02:07.518608Z"
    }
   },
   "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 = \"GSE147163\"\n",
    "\n",
    "# Input paths\n",
    "in_trait_dir = \"../../input/GEO/Stomach_Cancer\"\n",
    "in_cohort_dir = \"../../input/GEO/Stomach_Cancer/GSE147163\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/Stomach_Cancer/GSE147163.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/Stomach_Cancer/gene_data/GSE147163.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/Stomach_Cancer/clinical_data/GSE147163.csv\"\n",
    "json_path = \"../../output/preprocess/Stomach_Cancer/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1849b95b",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "3a397c4f",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T04:02:07.520699Z",
     "iopub.status.busy": "2025-03-25T04:02:07.520553Z",
     "iopub.status.idle": "2025-03-25T04:02:07.716467Z",
     "shell.execute_reply": "2025-03-25T04:02:07.716088Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Files in the cohort directory:\n",
      "['GSE147163_family.soft.gz', 'GSE147163_series_matrix.txt.gz']\n",
      "Identified SOFT files: ['GSE147163_family.soft.gz']\n",
      "Identified matrix files: ['GSE147163_series_matrix.txt.gz']\n",
      "\n",
      "Background Information:\n",
      "!Series_title\t\"Molecular subtypes in gastric cancer. [III]\"\n",
      "!Series_summary\t\"We identified the molecular subtypes and conserved modules in gastric cancer by unsupervised clustering algorithm. We defined six molecular signatrues of gastric cancer associated with the biological heterogeneity of gastric cancer and clinical outcome of patients.\"\n",
      "!Series_overall_design\t\"We obtained gene expression profile of gastrectomy samples from 401 gastric cancer patients by HumanHT-12 v3.0 Expression BeadChip array (Illumina). Total RNA was extracted from the fresh-frozen gastrectomy specimens at the Yonsei University Severance Hospital (South Korea) between 2000 and 2010.\"\n",
      "\n",
      "Sample Characteristics Dictionary:\n",
      "{0: ['tissue: gastric cancer']}\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": "a958ec33",
   "metadata": {},
   "source": [
    "### Step 2: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "a4aefd84",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T04:02:07.717634Z",
     "iopub.status.busy": "2025-03-25T04:02:07.717521Z",
     "iopub.status.idle": "2025-03-25T04:02:07.723805Z",
     "shell.execute_reply": "2025-03-25T04:02:07.723502Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "False"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 1. Gene Expression Data Availability\n",
    "# This dataset appears to be a gene expression microarray data (HumanHT-12 v3.0 Expression BeadChip array)\n",
    "# from the background information, so gene expression data should be available\n",
    "is_gene_available = True\n",
    "\n",
    "# 2.1 Data Availability\n",
    "# From the sample characteristics, we only have 'tissue: gastric cancer'\n",
    "# This indicates all samples are gastric cancer tissue, without control samples\n",
    "# There is no explicit trait variable that differentiates between cases and controls\n",
    "# There is also no age or gender information available in the sample characteristics\n",
    "\n",
    "trait_row = None  # No trait variable that differentiates between cases and controls\n",
    "age_row = None    # No age information available\n",
    "gender_row = None # No gender information available\n",
    "\n",
    "# 2.2 Data Type Conversion (defining functions even though they won't be used in this case)\n",
    "def convert_trait(value):\n",
    "    \"\"\"Convert trait value to binary (0 for control, 1 for case)\"\"\"\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",
    "    # No conversion rule needed as we don't have trait data\n",
    "    return None\n",
    "\n",
    "def convert_age(value):\n",
    "    \"\"\"Convert age value to continuous\"\"\"\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",
    "    # No conversion rule needed as we don't have age data\n",
    "    return None\n",
    "\n",
    "def convert_gender(value):\n",
    "    \"\"\"Convert gender value 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()\n",
    "    \n",
    "    # No conversion rule needed as we don't have gender data\n",
    "    return None\n",
    "\n",
    "# 3. Save Metadata\n",
    "# Determine trait data availability\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 - Skip as trait_row is None\n",
    "# No clinical feature extraction is needed as we don't have trait data\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "19310415",
   "metadata": {},
   "source": [
    "### Step 3: Gene Data Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "4e93b836",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T04:02:07.724773Z",
     "iopub.status.busy": "2025-03-25T04:02:07.724667Z",
     "iopub.status.idle": "2025-03-25T04:02:08.025860Z",
     "shell.execute_reply": "2025-03-25T04:02:08.025523Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "First 20 gene/probe identifiers:\n",
      "Index(['ILMN_1343048', 'ILMN_1343049', 'ILMN_1343050', 'ILMN_1343052',\n",
      "       'ILMN_1343059', 'ILMN_1343061', 'ILMN_1343062', 'ILMN_1343063',\n",
      "       'ILMN_1343064', 'ILMN_1343291', 'ILMN_1343295', 'ILMN_1343296',\n",
      "       'ILMN_1343297', 'ILMN_1343298', 'ILMN_1343299', 'ILMN_1343301',\n",
      "       'ILMN_1343302', 'ILMN_1343303', 'ILMN_1343304', 'ILMN_1343305'],\n",
      "      dtype='object', name='ID')\n",
      "\n",
      "Gene expression data shape: (49576, 50)\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": "9965a4bf",
   "metadata": {},
   "source": [
    "### Step 4: Gene Identifier Review"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "fac0f971",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T04:02:08.027602Z",
     "iopub.status.busy": "2025-03-25T04:02:08.027462Z",
     "iopub.status.idle": "2025-03-25T04:02:08.029503Z",
     "shell.execute_reply": "2025-03-25T04:02:08.029215Z"
    }
   },
   "outputs": [],
   "source": [
    "# These identifiers with prefix \"ILMN_\" are Illumina BeadArray probe IDs, not human gene symbols.\n",
    "# They need to be mapped to human gene symbols for downstream analysis.\n",
    "# The \"ILMN_\" prefix indicates these are from Illumina microarray platforms.\n",
    "\n",
    "requires_gene_mapping = True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e4c6e35a",
   "metadata": {},
   "source": [
    "### Step 5: Gene Annotation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "7d1d0685",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T04:02:08.031215Z",
     "iopub.status.busy": "2025-03-25T04:02:08.031080Z",
     "iopub.status.idle": "2025-03-25T04:02:13.229650Z",
     "shell.execute_reply": "2025-03-25T04:02:13.229171Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene annotation preview:\n",
      "{'ID': ['ILMN_1725881', 'ILMN_1910180', 'ILMN_1804174', 'ILMN_1796063', 'ILMN_1811966'], 'nuID': ['rp13_p1x6D80lNLk3c', 'NEX0oqCV8.er4HVfU4', 'KyqQynMZxJcruyylEU', 'xXl7eXuF7sbPEp.KFI', '9ckqJrioiaej9_ajeQ'], 'Species': ['Homo sapiens', 'Homo sapiens', 'Homo sapiens', 'Homo sapiens', 'Homo sapiens'], 'Source': ['RefSeq', 'Unigene', 'RefSeq', 'RefSeq', 'RefSeq'], 'Search_Key': ['ILMN_44919', 'ILMN_127219', 'ILMN_139282', 'ILMN_5006', 'ILMN_38756'], 'Transcript': ['ILMN_44919', 'ILMN_127219', 'ILMN_139282', 'ILMN_5006', 'ILMN_38756'], 'ILMN_Gene': ['LOC23117', 'HS.575038', 'FCGR2B', 'TRIM44', 'LOC653895'], 'Source_Reference_ID': ['XM_933824.1', 'Hs.575038', 'XM_938851.1', 'NM_017583.3', 'XM_936379.1'], 'RefSeq_ID': ['XM_933824.1', nan, 'XM_938851.1', 'NM_017583.3', 'XM_936379.1'], 'Unigene_ID': [nan, 'Hs.575038', nan, nan, nan], 'Entrez_Gene_ID': [23117.0, nan, 2213.0, 54765.0, 653895.0], 'GI': [89040007.0, 10437021.0, 88952550.0, 29029528.0, 89033487.0], 'Accession': ['XM_933824.1', 'AK024680', 'XM_938851.1', 'NM_017583.3', 'XM_936379.1'], 'Symbol': ['LOC23117', nan, 'FCGR2B', 'TRIM44', 'LOC653895'], 'Protein_Product': ['XP_938917.1', nan, 'XP_943944.1', 'NP_060053.2', 'XP_941472.1'], 'Array_Address_Id': [1710221.0, 5900364.0, 2480717.0, 1300239.0, 4480719.0], 'Probe_Type': ['I', 'S', 'I', 'S', 'S'], 'Probe_Start': [122.0, 1409.0, 1643.0, 2901.0, 25.0], 'SEQUENCE': ['GGCTCCTCTTTGGGCTCCTACTGGAATTTATCAGCCATCAGTGCATCTCT', 'ACACCTTCAGGAGGGAAGCCCTTATTTCTGGGTTGAACTCCCCTTCCATG', 'TAGGGGCAATAGGCTATACGCTACAGCCTAGGTGTGTAGTAGGCCACACC', 'CCTGCCTGTCTGCCTGTGACCTGTGTACGTATTACAGGCTTTAGGACCAG', 'CTAGCAGGGAGCGGTGAGGGAGAGCGGCTGGATTTCTTGCGGGATCTGCA'], 'Chromosome': ['16', nan, nan, '11', nan], 'Probe_Chr_Orientation': ['-', nan, nan, '+', nan], 'Probe_Coordinates': ['21766363-21766363:21769901-21769949', nan, nan, '35786070-35786119', nan], 'Cytoband': ['16p12.2a', nan, '1q23.3b', '11p13a', '10q11.23b'], 'Definition': ['PREDICTED: Homo sapiens KIAA0220-like protein, transcript variant 11 (LOC23117), mRNA.', 'Homo sapiens cDNA: FLJ21027 fis, clone CAE07110', 'PREDICTED: Homo sapiens Fc fragment of IgG, low affinity IIb, receptor (CD32) (FCGR2B), mRNA.', 'Homo sapiens tripartite motif-containing 44 (TRIM44), mRNA.', 'PREDICTED: Homo sapiens similar to protein geranylgeranyltransferase type I, beta subunit (LOC653895), mRNA.'], 'Ontology_Component': [nan, nan, nan, 'intracellular [goid 5622] [evidence IEA]', nan], 'Ontology_Process': [nan, nan, nan, nan, nan], 'Ontology_Function': [nan, nan, nan, 'zinc ion binding [goid 8270] [evidence IEA]; metal ion binding [goid 46872] [evidence IEA]', nan], 'Synonyms': [nan, nan, nan, 'MGC3490; MC7; HSA249128; DIPB', nan], 'Obsolete_Probe_Id': [nan, nan, nan, 'MGC3490; MC7; HSA249128; DIPB', nan], 'GB_ACC': ['XM_933824.1', 'AK024680', 'XM_938851.1', 'NM_017583.3', 'XM_936379.1']}\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": "af12def0",
   "metadata": {},
   "source": [
    "### Step 6: Gene Identifier Mapping"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "ec7a7d34",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T04:02:13.231048Z",
     "iopub.status.busy": "2025-03-25T04:02:13.230916Z",
     "iopub.status.idle": "2025-03-25T04:02:13.453110Z",
     "shell.execute_reply": "2025-03-25T04:02:13.452588Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Created gene mapping with 36157 entries.\n",
      "First few rows of mapping data:\n",
      "             ID       Gene\n",
      "0  ILMN_1725881   LOC23117\n",
      "2  ILMN_1804174     FCGR2B\n",
      "3  ILMN_1796063     TRIM44\n",
      "4  ILMN_1811966  LOC653895\n",
      "5  ILMN_1668162    DGAT2L3\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "Converted to gene expression data with 19120 genes and 50 samples.\n",
      "First few genes:\n",
      "Index(['A1BG', 'A1CF', 'A26A1', 'A26B1', 'A26C1B', 'A26C3', 'A2BP1', 'A2M',\n",
      "       'A2ML1', 'A3GALT2'],\n",
      "      dtype='object', name='Gene')\n",
      "\n",
      "Preview of gene expression data:\n",
      "        GSM4419484  GSM4419485  GSM4419486  GSM4419487  GSM4419488\n",
      "Gene                                                              \n",
      "A1BG      9.853618   10.537068    9.865281    9.937021    9.831023\n",
      "A1CF     23.955097   20.615845   15.110226   14.553892   18.103539\n",
      "A26A1     9.452464    9.388353    9.605953    9.653673    9.743757\n",
      "A26B1     4.776131    4.864010    4.798284    4.826584    4.919554\n",
      "A26C1B    4.971237    4.679716    4.754202    4.698224    4.954362\n"
     ]
    }
   ],
   "source": [
    "# 1. Determine which columns in the gene annotation contain identifiers and symbols\n",
    "# Looking at the gene annotation preview and gene expression data:\n",
    "# - The gene expression data index contains probe IDs like 'ILMN_1343048'\n",
    "# - The gene annotation has 'ID' column with similar values like 'ILMN_1725881'\n",
    "# - The gene symbols appear to be in the 'Symbol' column\n",
    "\n",
    "# 2. Get gene mapping dataframe\n",
    "probe_col = 'ID'  # Column containing probe identifiers\n",
    "symbol_col = 'Symbol'  # Column containing gene symbols\n",
    "\n",
    "# Extract mapping data and handle potential issues\n",
    "mapping_df = get_gene_mapping(gene_annotation, probe_col, symbol_col)\n",
    "\n",
    "print(f\"Created gene mapping with {len(mapping_df)} entries.\")\n",
    "print(\"First few rows of mapping data:\")\n",
    "print(mapping_df.head())\n",
    "\n",
    "# 3. Apply gene mapping to convert probe measurements to gene expression data\n",
    "gene_data = apply_gene_mapping(gene_data, mapping_df)\n",
    "\n",
    "print(f\"\\nConverted to gene expression data with {len(gene_data)} genes and {gene_data.shape[1]} samples.\")\n",
    "print(\"First few genes:\")\n",
    "print(gene_data.index[:10])\n",
    "\n",
    "# Preview the first few rows of gene expression data\n",
    "print(\"\\nPreview of gene expression data:\")\n",
    "print(gene_data.iloc[:5, :5])\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "afb694ef",
   "metadata": {},
   "source": [
    "### Step 7: Data Normalization and Linking"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "f26838a0",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T04:02:13.454618Z",
     "iopub.status.busy": "2025-03-25T04:02:13.454498Z",
     "iopub.status.idle": "2025-03-25T04:02:19.343771Z",
     "shell.execute_reply": "2025-03-25T04:02:19.343305Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Normalized gene data shape: (18326, 50)\n",
      "First few normalized gene symbols: ['A1BG', 'A1CF', 'A2M', 'A2ML1', 'A3GALT2', 'A4GALT', 'A4GNT', 'AAA1', 'AAAS', 'AACS']\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Normalized gene data saved to ../../output/preprocess/Stomach_Cancer/gene_data/GSE147163.csv\n",
      "Created linked data with dummy trait column. Shape: (50, 18327)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Linked data shape after handling missing values: (50, 18327)\n",
      "Trait distribution assessment: dataset is biased (all samples are gastric cancer)\n",
      "Data quality check result: Not usable\n",
      "Data not saved due to quality issues (no trait differentiation available).\n"
     ]
    }
   ],
   "source": [
    "# 1. Normalize gene symbols in the obtained gene expression data\n",
    "normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\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",
    "# 2. Create a minimal DataFrame with a dummy trait column since no clinical data is available\n",
    "# For datasets where all samples are the same class (all gastric cancer), we need to mark them all the same\n",
    "linked_data = normalized_gene_data.T.copy()\n",
    "linked_data[trait] = 1  # All samples marked as cases (gastric cancer)\n",
    "print(f\"Created linked data with dummy trait column. Shape: {linked_data.shape}\")\n",
    "\n",
    "# 3. Handle missing values in gene data\n",
    "linked_data = handle_missing_values(linked_data, trait)\n",
    "print(f\"Linked data shape after handling missing values: {linked_data.shape}\")\n",
    "\n",
    "# 4. Since all samples have the same trait value (all are gastric cancer), the dataset is biased by definition\n",
    "is_trait_biased = True\n",
    "print(f\"Trait distribution assessment: dataset is biased (all samples are gastric cancer)\")\n",
    "\n",
    "# 5. Conduct quality check and save the cohort information\n",
    "is_usable = validate_and_save_cohort_info(\n",
    "    is_final=True, \n",
    "    cohort=cohort, \n",
    "    info_path=json_path, \n",
    "    is_gene_available=True,\n",
    "    is_trait_available=False,  # Although we created a dummy trait column, the actual trait data isn't available\n",
    "    is_biased=is_trait_biased, \n",
    "    df=linked_data,\n",
    "    note=\"Dataset contains gene expression data from gastric cancer samples but lacks control samples or trait differentiation.\"\n",
    ")\n",
    "\n",
    "# 6. No need to save the linked data as it's not usable for trait association\n",
    "print(f\"Data quality check result: {'Usable' if is_usable else 'Not usable'}\")\n",
    "if is_usable:\n",
    "    os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n",
    "    linked_data.to_csv(out_data_file)\n",
    "    print(f\"Linked data saved to {out_data_file}\")\n",
    "else:\n",
    "    print(f\"Data not saved due to quality issues (no trait differentiation available).\")"
   ]
  }
 ],
 "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
}