File size: 33,521 Bytes
3923fb8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "fc2fdb2b",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T04:03:06.803811Z",
     "iopub.status.busy": "2025-03-25T04:03:06.803672Z",
     "iopub.status.idle": "2025-03-25T04:03:06.974667Z",
     "shell.execute_reply": "2025-03-25T04:03:06.974193Z"
    }
   },
   "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 = \"GSE98708\"\n",
    "\n",
    "# Input paths\n",
    "in_trait_dir = \"../../input/GEO/Stomach_Cancer\"\n",
    "in_cohort_dir = \"../../input/GEO/Stomach_Cancer/GSE98708\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/Stomach_Cancer/GSE98708.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/Stomach_Cancer/gene_data/GSE98708.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/Stomach_Cancer/clinical_data/GSE98708.csv\"\n",
    "json_path = \"../../output/preprocess/Stomach_Cancer/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f45a460f",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "e95fdc08",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T04:03:06.976598Z",
     "iopub.status.busy": "2025-03-25T04:03:06.976267Z",
     "iopub.status.idle": "2025-03-25T04:03:07.150355Z",
     "shell.execute_reply": "2025-03-25T04:03:07.149943Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Files in the cohort directory:\n",
      "['GSE98708_family.soft.gz', 'GSE98708_series_matrix.txt.gz']\n",
      "Identified SOFT files: ['GSE98708_family.soft.gz']\n",
      "Identified matrix files: ['GSE98708_series_matrix.txt.gz']\n",
      "\n",
      "Background Information:\n",
      "!Series_title\t\"Expression profiling of frozen primary and patient derived xenograft gastric cancer\"\n",
      "!Series_summary\t\"Expression profiling of frozen primary and patient derived xenograft gastric cancer\"\n",
      "!Series_overall_design\t\"Expression profiling of frozen primary and patient derived xenograft gastric cancer\"\n",
      "\n",
      "Sample Characteristics Dictionary:\n",
      "{0: ['tissue: gastric cancer'], 1: ['sample type: PDX', 'sample type: primary tumor'], 2: ['patient id: GTR0222', 'patient id: GTR0227', 'patient id: GTR0230', 'patient id: GTR0233', 'patient id: GTR0244', 'patient id: GTR0245', 'patient id: GTR0247', 'patient id: GTR0249', 'patient id: GTR0255', 'patient id: GTR0259', 'patient id: GTR0263', 'patient id: GTR0220', 'patient id: GTR0102', 'patient id: GTR0103', 'patient id: GTR0105', 'patient id: GTR0124', 'patient id: GTR0145', 'patient id: GTR0164', 'patient id: GTR0193', 'patient id: GTR0194', 'patient id: GTR0202', 'patient id: GTR0207', 'patient id: GTR0208', 'patient id: GTR0213', 'patient id: GTR0032', 'patient id: GTR0060', 'patient id: GTR0165', 'patient id: GTR0181', 'patient id: GTR0044', 'patient id: GTR0219']}\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": "815926e9",
   "metadata": {},
   "source": [
    "### Step 2: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "e5c62701",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T04:03:07.151543Z",
     "iopub.status.busy": "2025-03-25T04:03:07.151429Z",
     "iopub.status.idle": "2025-03-25T04:03:07.160315Z",
     "shell.execute_reply": "2025-03-25T04:03:07.159916Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Preview of selected clinical data:\n",
      "{0: [1.0]}\n",
      "Clinical data saved to ../../output/preprocess/Stomach_Cancer/clinical_data/GSE98708.csv\n"
     ]
    }
   ],
   "source": [
    "# 1. Gene Expression Data Availability\n",
    "# Based on the background information and summary, the dataset appears to be expression profiling of gastric cancer\n",
    "# samples, suggesting 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",
    "\n",
    "# Trait (Stomach Cancer)\n",
    "# Looking at the sample characteristics, row 0 contains 'tissue: gastric cancer'\n",
    "# This confirms all samples are gastric cancer tissue\n",
    "trait_row = 0\n",
    "\n",
    "# Age data is not available in the sample characteristics dictionary\n",
    "age_row = None\n",
    "\n",
    "# Gender data is not available in the sample characteristics dictionary\n",
    "gender_row = None\n",
    "\n",
    "# 2.2 Data Type Conversion\n",
    "def convert_trait(value):\n",
    "    \"\"\"Convert the trait value to binary (1 for gastric cancer, 0 for normal)\"\"\"\n",
    "    if value is None:\n",
    "        return None\n",
    "    \n",
    "    # Handle non-string types\n",
    "    if not isinstance(value, str):\n",
    "        return None\n",
    "    \n",
    "    # Extract the value after the colon\n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip().lower()\n",
    "    \n",
    "    # Check if it's related to gastric cancer\n",
    "    if 'gastric cancer' in value:\n",
    "        return 1\n",
    "    elif 'normal' in value:\n",
    "        return 0\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "def convert_age(value):\n",
    "    \"\"\"Function to convert age to continuous value (not used in this dataset)\"\"\"\n",
    "    if value is None:\n",
    "        return None\n",
    "    \n",
    "    if not isinstance(value, str):\n",
    "        return None\n",
    "    \n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip()\n",
    "    \n",
    "    try:\n",
    "        return float(value)\n",
    "    except (ValueError, TypeError):\n",
    "        return None\n",
    "\n",
    "def convert_gender(value):\n",
    "    \"\"\"Function to convert gender to binary (0 for female, 1 for male) (not used in this dataset)\"\"\"\n",
    "    if value is None:\n",
    "        return None\n",
    "    \n",
    "    if not isinstance(value, str):\n",
    "        return None\n",
    "    \n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip().lower()\n",
    "    \n",
    "    if value in ['male', 'm']:\n",
    "        return 1\n",
    "    elif value in ['female', 'f']:\n",
    "        return 0\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "# 3. Save Metadata\n",
    "# is_trait_available is determined by whether trait_row is None\n",
    "is_trait_available = trait_row is not None\n",
    "\n",
    "# Validate and save cohort info (initial filtering)\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",
    "# Since trait_row is not None, we proceed with clinical feature extraction\n",
    "if trait_row is not None:\n",
    "    try:\n",
    "        # Load the clinical data from the provided dictionary instead of parsing the file again\n",
    "        # Use whatever clinical_data source that was provided in the previous step\n",
    "        # For this dataset, we know the clinical characteristics from the dictionary already shown\n",
    "        clinical_data = pd.DataFrame()\n",
    "        \n",
    "        # Add the sample characteristic row for trait (gastric cancer)\n",
    "        clinical_data.loc[trait_row, 0] = 'tissue: gastric cancer'\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 dataframe\n",
    "        preview = preview_df(selected_clinical_df)\n",
    "        print(\"Preview of selected clinical data:\")\n",
    "        print(preview)\n",
    "        \n",
    "        # Save the clinical data to CSV\n",
    "        selected_clinical_df.to_csv(out_clinical_data_file, index=False)\n",
    "        print(f\"Clinical data saved to {out_clinical_data_file}\")\n",
    "    except Exception as e:\n",
    "        print(f\"Error processing clinical data: {e}\")\n",
    "        # If clinical data processing fails, update metadata\n",
    "        is_trait_available = False\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"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ad93723e",
   "metadata": {},
   "source": [
    "### Step 3: Gene Data Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "088e6dda",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T04:03:07.161418Z",
     "iopub.status.busy": "2025-03-25T04:03:07.161310Z",
     "iopub.status.idle": "2025-03-25T04:03:07.523731Z",
     "shell.execute_reply": "2025-03-25T04:03:07.523134Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "First 20 gene/probe identifiers:\n",
      "Index(['ILMN_1343291', 'ILMN_1343295', 'ILMN_1651199', 'ILMN_1651209',\n",
      "       'ILMN_1651210', 'ILMN_1651221', 'ILMN_1651228', 'ILMN_1651229',\n",
      "       'ILMN_1651230', 'ILMN_1651232', 'ILMN_1651235', 'ILMN_1651236',\n",
      "       'ILMN_1651237', 'ILMN_1651238', 'ILMN_1651249', 'ILMN_1651253',\n",
      "       'ILMN_1651254', 'ILMN_1651259', 'ILMN_1651260', 'ILMN_1651262'],\n",
      "      dtype='object', name='ID')\n",
      "\n",
      "Gene expression data shape: (47323, 102)\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": "6d90a9a3",
   "metadata": {},
   "source": [
    "### Step 4: Gene Identifier Review"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "8c602d86",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T04:03:07.525684Z",
     "iopub.status.busy": "2025-03-25T04:03:07.525534Z",
     "iopub.status.idle": "2025-03-25T04:03:07.528061Z",
     "shell.execute_reply": "2025-03-25T04:03:07.527570Z"
    }
   },
   "outputs": [],
   "source": [
    "# These identifiers (ILMN_) are Illumina probe IDs, not standard human gene symbols.\n",
    "# They need to be mapped to official gene symbols for proper biological interpretation.\n",
    "# ILMN_ prefix indicates these are Illumina BeadArray probe identifiers.\n",
    "\n",
    "requires_gene_mapping = True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0de84677",
   "metadata": {},
   "source": [
    "### Step 5: Gene Annotation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "43133822",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T04:03:07.529668Z",
     "iopub.status.busy": "2025-03-25T04:03:07.529535Z",
     "iopub.status.idle": "2025-03-25T04:03:16.514296Z",
     "shell.execute_reply": "2025-03-25T04:03:16.513962Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene annotation preview:\n",
      "{'ID': ['ILMN_1343048', 'ILMN_1343049', 'ILMN_1343050', 'ILMN_1343052', 'ILMN_1343059'], 'Species': [nan, nan, nan, nan, nan], 'Source': [nan, nan, nan, nan, nan], 'Search_Key': [nan, nan, nan, nan, nan], 'Transcript': [nan, nan, nan, nan, nan], 'ILMN_Gene': [nan, nan, nan, nan, nan], 'Source_Reference_ID': [nan, nan, nan, nan, nan], 'RefSeq_ID': [nan, nan, nan, nan, nan], 'Unigene_ID': [nan, nan, nan, nan, nan], 'Entrez_Gene_ID': [nan, nan, nan, nan, nan], 'GI': [nan, nan, nan, nan, nan], 'Accession': [nan, nan, nan, nan, nan], 'Symbol': ['phage_lambda_genome', 'phage_lambda_genome', 'phage_lambda_genome:low', 'phage_lambda_genome:low', 'thrB'], 'Protein_Product': [nan, nan, nan, nan, 'thrB'], 'Probe_Id': [nan, nan, nan, nan, nan], 'Array_Address_Id': [5090180.0, 6510136.0, 7560739.0, 1450438.0, 1240647.0], 'Probe_Type': [nan, nan, nan, nan, nan], 'Probe_Start': [nan, nan, nan, nan, nan], 'SEQUENCE': ['GAATAAAGAACAATCTGCTGATGATCCCTCCGTGGATCTGATTCGTGTAA', 'CCATGTGATACGAGGGCGCGTAGTTTGCATTATCGTTTTTATCGTTTCAA', 'CCGACAGATGTATGTAAGGCCAACGTGCTCAAATCTTCATACAGAAAGAT', 'TCTGTCACTGTCAGGAAAGTGGTAAAACTGCAACTCAATTACTGCAATGC', 'CTTGTGCCTGAGCTGTCAAAAGTAGAGCACGTCGCCGAGATGAAGGGCGC'], 'Chromosome': [nan, nan, nan, nan, nan], 'Probe_Chr_Orientation': [nan, nan, nan, nan, nan], 'Probe_Coordinates': [nan, nan, nan, nan, nan], 'Cytoband': [nan, nan, nan, nan, nan], 'Definition': [nan, nan, nan, nan, nan], 'Ontology_Component': [nan, nan, nan, nan, nan], 'Ontology_Process': [nan, nan, nan, nan, nan], 'Ontology_Function': [nan, nan, nan, nan, nan], 'Synonyms': [nan, nan, nan, nan, nan], 'Obsolete_Probe_Id': [nan, nan, nan, nan, nan], 'GB_ACC': [nan, nan, nan, nan, nan]}\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": "f957bc19",
   "metadata": {},
   "source": [
    "### Step 6: Gene Identifier Mapping"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "3aaf341e",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T04:03:16.515482Z",
     "iopub.status.busy": "2025-03-25T04:03:16.515360Z",
     "iopub.status.idle": "2025-03-25T04:03:17.985803Z",
     "shell.execute_reply": "2025-03-25T04:03:17.985469Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene mapping preview (probe ID to gene symbol):\n",
      "{'ID': ['ILMN_1343048', 'ILMN_1343049', 'ILMN_1343050', 'ILMN_1343052', 'ILMN_1343059'], 'Gene': ['phage_lambda_genome', 'phage_lambda_genome', 'phage_lambda_genome:low', 'phage_lambda_genome:low', 'thrB']}\n",
      "\n",
      "Gene expression data after mapping (first few genes):\n",
      "{'GSM2610417': [246.4, 340.3, 267.6, 398.4, 207.5], 'GSM2610418': [246.60000000000002, 324.1, 333.3, 392.0, 95.3], 'GSM2610419': [223.3, 330.7, 280.1, 484.2, 137.9], 'GSM2610420': [262.1, 1330.2, 291.9, 369.7, 358.5], 'GSM2610421': [229.5, 1021.2, 396.3, 422.7, 367.4], 'GSM2610422': [281.20000000000005, 344.9, 386.6, 398.79999999999995, 322.2], 'GSM2610423': [235.0, 1637.0, 311.1, 352.4, 587.1], 'GSM2610424': [241.89999999999998, 858.5, 324.29999999999995, 348.7, 718.5], 'GSM2610425': [247.5, 1440.1999999999998, 364.0, 389.0, 575.5], 'GSM2610426': [265.8, 310.8, 247.7, 336.7, 1204.7], 'GSM2610427': [254.79999999999998, 732.6, 290.6, 354.9, 715.8], 'GSM2610428': [258.5, 323.3, 238.6, 354.1, 242.4], 'GSM2610429': [363.1, 3131.3999999999996, 345.6, 456.2, 381.0], 'GSM2610430': [293.4, 482.0, 329.5, 420.0, 255.4], 'GSM2610431': [244.3, 347.70000000000005, 318.4, 393.7, 286.9], 'GSM2610432': [249.6, 3272.2, 328.1, 393.6, 581.2], 'GSM2610433': [241.4, 671.5, 317.8, 366.9, 389.3], 'GSM2610434': [247.2, 313.8, 353.6, 326.6, 378.5], 'GSM2610435': [226.7, 449.8, 295.0, 420.1, 646.5], 'GSM2610436': [248.6, 319.4, 265.0, 383.8, 334.4], 'GSM2610437': [226.7, 725.8, 296.4, 379.1, 185.2], 'GSM2610438': [273.0, 725.4000000000001, 328.40000000000003, 436.5, 449.3], 'GSM2610439': [249.8, 9212.7, 338.0, 422.8, 761.8], 'GSM2610440': [277.29999999999995, 797.0, 329.4, 450.0, 675.9], 'GSM2610441': [314.5, 1810.2, 356.6, 467.2, 330.6], 'GSM2610442': [210.5, 761.5, 341.8, 381.7, 283.7], 'GSM2610443': [218.5, 313.5, 341.7, 371.9, 273.2], 'GSM2610444': [305.9, 356.1, 355.8, 421.6, 696.1], 'GSM2610445': [223.4, 2342.0, 314.6, 406.6, 282.0], 'GSM2610446': [253.3, 1722.9, 270.2, 373.7, 148.1], 'GSM2610447': [217.89999999999998, 1418.9, 266.5, 342.8, 276.8], 'GSM2610448': [220.2, 2376.0, 291.7, 336.8, 210.5], 'GSM2610449': [255.2, 358.90000000000003, 315.5, 321.9, 343.3], 'GSM2610450': [231.0, 318.2, 317.7, 354.2, 180.5], 'GSM2610451': [443.8, 1184.4, 431.6, 606.8, 640.5], 'GSM2610452': [292.79999999999995, 513.6, 400.9, 444.2, 684.2], 'GSM2610453': [300.2, 426.6, 387.1, 422.0, 1020.8], 'GSM2610454': [339.6, 1700.4, 405.1, 488.09999999999997, 770.3], 'GSM2610455': [321.2, 619.5, 409.9, 503.1, 265.7], 'GSM2610456': [301.79999999999995, 425.0, 375.5, 428.8, 238.2], 'GSM2610457': [286.1, 429.7, 356.9, 508.9, 510.7], 'GSM2610458': [331.5, 2544.1, 397.29999999999995, 489.09999999999997, 414.7], 'GSM2610459': [328.3, 761.1, 424.0, 548.1999999999999, 502.3], 'GSM2610460': [268.9, 2103.6, 370.70000000000005, 444.9, 674.9], 'GSM2610461': [344.8, 438.5, 409.6, 521.4, 655.7], 'GSM2610462': [261.7, 3788.0, 387.4, 512.2, 276.1], 'GSM2610463': [284.1, 351.9, 335.3, 449.5, 325.4], 'GSM2610464': [383.70000000000005, 444.6, 436.5, 541.3, 313.5], 'GSM2610465': [342.9, 792.8, 368.0, 492.5, 242.6], 'GSM2610466': [331.2, 409.90000000000003, 429.5, 1173.5, 201.4], 'GSM2610467': [336.8, 2114.5, 493.70000000000005, 528.8, 591.1], 'GSM2610468': [361.6, 1647.6, 477.3, 510.20000000000005, 1403.4], 'GSM2610469': [325.1, 1081.4, 407.8, 516.3, 400.7], 'GSM2610470': [316.1, 2580.1000000000004, 373.6, 523.9000000000001, 600.2], 'GSM2610471': [302.6, 3471.9, 354.1, 452.3, 492.0], 'GSM2610472': [306.3, 1579.2, 346.1, 476.4, 439.7], 'GSM2610473': [273.8, 768.0, 376.9, 546.7, 614.4], 'GSM2610474': [279.6, 509.5, 368.3, 462.2, 288.3], 'GSM2610475': [295.1, 325.6, 361.5, 529.0, 581.6], 'GSM2610476': [272.9, 406.6, 340.5, 472.7, 289.7], 'GSM2610477': [329.5, 410.6, 340.6, 498.5, 747.5], 'GSM2610478': [417.5, 439.90000000000003, 437.5, 531.7, 485.6], 'GSM2610479': [414.6, 958.2, 496.3, 690.2, 397.2], 'GSM2610480': [394.7, 501.4, 472.5, 608.0, 461.5], 'GSM2610481': [347.3, 527.5, 480.2, 580.4, 309.0], 'GSM2610482': [396.20000000000005, 568.7, 558.5, 602.9, 346.8], 'GSM2610483': [416.7, 1108.8, 469.9, 615.0, 212.6], 'GSM2610484': [399.5, 507.9, 485.8, 886.5999999999999, 511.2], 'GSM2610485': [376.8, 579.4, 457.0, 598.9000000000001, 704.2], 'GSM2610486': [342.4, 418.5, 463.1, 588.3, 294.6], 'GSM2610487': [369.4, 446.7, 515.0, 656.7, 507.8], 'GSM2610488': [462.5, 1228.7, 535.4, 764.4, 684.8], 'GSM2610489': [314.1, 2193.8, 526.1, 685.9, 557.1], 'GSM2610490': [401.3, 4018.7, 528.3, 710.1, 764.8], 'GSM2610491': [394.1, 606.2, 466.6, 643.2, 903.6], 'GSM2610492': [402.70000000000005, 476.5, 470.6, 860.9, 308.1], 'GSM2610493': [414.9, 632.0, 475.9, 620.4, 367.8], 'GSM2610494': [429.79999999999995, 527.8, 477.5, 748.6, 378.4], 'GSM2610495': [356.6, 1705.2, 411.4, 532.3, 213.2], 'GSM2610496': [310.1, 2395.9, 422.29999999999995, 511.29999999999995, 356.2], 'GSM2610497': [346.5, 426.2, 363.9, 559.4, 276.8], 'GSM2610498': [301.9, 1792.7, 426.6, 470.4, 511.1], 'GSM2610499': [263.2, 1975.9, 361.7, 423.2, 869.2], 'GSM2610500': [347.9, 698.7, 393.9, 497.2, 423.3], 'GSM2610501': [267.5, 1912.7, 341.6, 496.40000000000003, 175.1], 'GSM2610502': [313.5, 1284.8, 381.0, 548.4, 1024.7], 'GSM2610503': [406.20000000000005, 485.79999999999995, 427.8, 565.8, 255.6], 'GSM2610504': [304.5, 1183.3999999999999, 323.4, 566.4, 310.0], 'GSM2610505': [341.0, 1177.0, 404.4, 573.4, 256.7], 'GSM2610506': [406.1, 457.5, 398.5, 473.0, 263.7], 'GSM2610507': [322.8, 1984.8, 416.4, 565.6, 655.9], 'GSM2610508': [372.8, 456.4, 402.8, 516.1, 342.3], 'GSM2610509': [379.4, 514.9, 381.0, 581.5, 558.4], 'GSM2610510': [263.9, 456.1, 366.6, 474.8, 418.4], 'GSM2610511': [319.0, 5572.6, 400.1, 770.8, 613.8], 'GSM2610512': [337.8, 7739.0, 437.70000000000005, 573.4, 743.6], 'GSM2610513': [377.70000000000005, 433.0, 435.9, 497.90000000000003, 638.6], 'GSM2610514': [297.4, 394.8, 477.3, 545.9, 394.8], 'GSM2610515': [342.6, 460.1, 446.4, 523.0, 135.7], 'GSM2610516': [360.5, 2514.3999999999996, 400.9, 519.1, 1333.5], 'GSM2610517': [340.9, 668.6, 376.0, 536.1, 468.5], 'GSM2610518': [317.6, 2906.0, 392.1, 529.3, 452.5]}\n",
      "Mapped gene data shape: (21464, 102)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "Normalized gene data shape: (20259, 102)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene expression data saved to ../../output/preprocess/Stomach_Cancer/gene_data/GSE98708.csv\n"
     ]
    }
   ],
   "source": [
    "# 1. Observing the gene identifiers and annotation data:\n",
    "# In gene expression data, the indices are in the format \"ILMN_XXXXXXX\"\n",
    "# In the gene annotation data, the \"ID\" column contains this same identifier format\n",
    "# The \"Symbol\" column appears to contain the gene symbols we need to map to\n",
    "\n",
    "# 2. Extract the gene mapping dataframe\n",
    "gene_mapping = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='Symbol')\n",
    "\n",
    "# Print a preview of the mapping\n",
    "print(\"Gene mapping preview (probe ID to gene symbol):\")\n",
    "print(preview_df(gene_mapping))\n",
    "\n",
    "# 3. Apply the gene mapping to convert probe-level measurements to gene expression data\n",
    "# This divides probe values among multiple genes and sums contributions for each gene\n",
    "gene_data = apply_gene_mapping(gene_data, gene_mapping)\n",
    "\n",
    "# Check the resulting gene expression data\n",
    "print(\"\\nGene expression data after mapping (first few genes):\")\n",
    "print(preview_df(gene_data))\n",
    "print(f\"Mapped gene data shape: {gene_data.shape}\")\n",
    "\n",
    "# Normalize gene symbols (handle case variations and synonyms)\n",
    "gene_data = normalize_gene_symbols_in_index(gene_data)\n",
    "print(f\"\\nNormalized gene data shape: {gene_data.shape}\")\n",
    "\n",
    "# Save the processed gene expression data\n",
    "gene_data.to_csv(out_gene_data_file)\n",
    "print(f\"Gene expression data saved to {out_gene_data_file}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ffdb41e9",
   "metadata": {},
   "source": [
    "### Step 7: Data Normalization and Linking"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "b85ee988",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T04:03:17.987135Z",
     "iopub.status.busy": "2025-03-25T04:03:17.987013Z",
     "iopub.status.idle": "2025-03-25T04:03:24.317019Z",
     "shell.execute_reply": "2025-03-25T04:03:24.316519Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Normalized gene data shape: (20259, 102)\n",
      "First few normalized gene symbols: ['A1BG', 'A1BG-AS1', 'A1CF', 'A2M', 'A2ML1', 'A3GALT2', 'A4GALT', 'A4GNT', 'AAA1', 'AAAS']\n",
      "Loaded clinical data with shape: (1, 1)\n",
      "Error in processing clinical data: 102 columns passed, passed data had 1 columns\n",
      "Created default clinical features with shape: (1, 102)\n",
      "Linked data shape: (102, 20260)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Data shape after handling missing values: (102, 20260)\n",
      "Quartiles for 'Stomach_Cancer':\n",
      "  25%: 1.0\n",
      "  50% (Median): 1.0\n",
      "  75%: 1.0\n",
      "Min: 1.0\n",
      "Max: 1.0\n",
      "The distribution of the feature 'Stomach_Cancer' in this dataset is severely biased.\n",
      "\n",
      "Data quality check result: Not usable\n",
      "Data quality check failed. The dataset is not suitable for association studies.\n"
     ]
    }
   ],
   "source": [
    "# 1. Normalize gene symbols in the obtained gene expression data\n",
    "# (This step was already completed in the previous step)\n",
    "print(f\"Normalized gene data shape: {gene_data.shape}\")\n",
    "print(f\"First few normalized gene symbols: {list(gene_data.index[:10])}\")\n",
    "\n",
    "# 2. Load the previously saved clinical data and prepare it for linking\n",
    "try:\n",
    "    # Read the clinical CSV file\n",
    "    clinical_data = pd.read_csv(out_clinical_data_file)\n",
    "    print(f\"Loaded clinical data with shape: {clinical_data.shape}\")\n",
    "    \n",
    "    # Create properly structured clinical features for linking\n",
    "    # The geo_select_clinical_features function should have created a DataFrame with traits as rows\n",
    "    # But we'll verify and fix the structure if needed\n",
    "    if trait not in clinical_data.columns:\n",
    "        # Create a properly formatted clinical features DataFrame with trait as row\n",
    "        clinical_features = pd.DataFrame(index=[trait], data=[clinical_data.iloc[0].values], \n",
    "                                         columns=gene_data.columns)\n",
    "        print(f\"Restructured clinical features with shape: {clinical_features.shape}\")\n",
    "    else:\n",
    "        # If the column exists, transpose to have traits as rows\n",
    "        clinical_features = clinical_data.set_index(trait).T\n",
    "        clinical_features = pd.DataFrame(index=[trait], data=[clinical_features.iloc[0].values], \n",
    "                                         columns=gene_data.columns)\n",
    "except Exception as e:\n",
    "    print(f\"Error in processing clinical data: {e}\")\n",
    "    # Create a DataFrame with all samples classified as cancer (trait = 1)\n",
    "    # Since the sample characteristics indicated all are gastric cancer\n",
    "    clinical_features = pd.DataFrame(index=[trait], data=[[1.0] * len(gene_data.columns)], \n",
    "                                    columns=gene_data.columns)\n",
    "    print(f\"Created default clinical features with shape: {clinical_features.shape}\")\n",
    "\n",
    "# Link the clinical and genetic data\n",
    "linked_data = geo_link_clinical_genetic_data(clinical_features, gene_data)\n",
    "print(f\"Linked data shape: {linked_data.shape}\")\n",
    "\n",
    "# 3. Handle missing values systematically\n",
    "# Since we know trait values are all 1, create a direct column\n",
    "linked_data[trait] = 1.0  # Explicitly add the trait column\n",
    "linked_data = handle_missing_values(linked_data, trait)\n",
    "print(f\"Data shape after handling missing values: {linked_data.shape}\")\n",
    "\n",
    "# 4. Evaluate bias in trait and demographic features\n",
    "is_trait_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n",
    "\n",
    "# 5. Conduct final quality validation and save metadata\n",
    "is_usable = validate_and_save_cohort_info(\n",
    "    is_final=True, \n",
    "    cohort=cohort, \n",
    "    info_path=json_path, \n",
    "    is_gene_available=True,\n",
    "    is_trait_available=True,  # We determined earlier that trait data is available (all samples are cancer)\n",
    "    is_biased=is_trait_biased, \n",
    "    df=linked_data,\n",
    "    note=\"Dataset contains gene expression data from gastric cancer samples. All samples are cancer (trait=1).\"\n",
    ")\n",
    "\n",
    "# 6. Save the linked data if it's usable\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 quality check failed. The dataset is not suitable for association studies.\")"
   ]
  }
 ],
 "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
}