File size: 28,629 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 |
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"id": "02a4035c",
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-25T04:03:00.351830Z",
"iopub.status.busy": "2025-03-25T04:03:00.351687Z",
"iopub.status.idle": "2025-03-25T04:03:00.521206Z",
"shell.execute_reply": "2025-03-25T04:03:00.520775Z"
}
},
"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 = \"GSE208099\"\n",
"\n",
"# Input paths\n",
"in_trait_dir = \"../../input/GEO/Stomach_Cancer\"\n",
"in_cohort_dir = \"../../input/GEO/Stomach_Cancer/GSE208099\"\n",
"\n",
"# Output paths\n",
"out_data_file = \"../../output/preprocess/Stomach_Cancer/GSE208099.csv\"\n",
"out_gene_data_file = \"../../output/preprocess/Stomach_Cancer/gene_data/GSE208099.csv\"\n",
"out_clinical_data_file = \"../../output/preprocess/Stomach_Cancer/clinical_data/GSE208099.csv\"\n",
"json_path = \"../../output/preprocess/Stomach_Cancer/cohort_info.json\"\n"
]
},
{
"cell_type": "markdown",
"id": "0da4f4c0",
"metadata": {},
"source": [
"### Step 1: Initial Data Loading"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "fae13282",
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-25T04:03:00.522774Z",
"iopub.status.busy": "2025-03-25T04:03:00.522624Z",
"iopub.status.idle": "2025-03-25T04:03:00.690641Z",
"shell.execute_reply": "2025-03-25T04:03:00.690151Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Files in the cohort directory:\n",
"['GSE208099_family.soft.gz', 'GSE208099_series_matrix.txt.gz']\n",
"Identified SOFT files: ['GSE208099_family.soft.gz']\n",
"Identified matrix files: ['GSE208099_series_matrix.txt.gz']\n",
"\n",
"Background Information:\n",
"!Series_title\t\"Gene expression analysis of M and SM gastric cancer\"\n",
"!Series_summary\t\"The objective of this study was to identify genes and pathways involved in submucosal invasion of early gastric cancer through comprehensive gene expression analysis.\"\n",
"!Series_overall_design\t\"8 cases with intramucosal gastric cancer (M cancer) and 8 cases with early gastric cancer with submucosal invasion ≥ 500 μm (SM cancer) were enrolled in this study. Biopsies were taken from both tumor site and background normal mucosa.\"\n",
"\n",
"Sample Characteristics Dictionary:\n",
"{0: ['gender: M', 'gender: F'], 1: ['tissue: adenocarcinoma', 'tissue: normal mucosa']}\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": "465969f3",
"metadata": {},
"source": [
"### Step 2: Dataset Analysis and Clinical Feature Extraction"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "248c6e45",
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-25T04:03:00.692437Z",
"iopub.status.busy": "2025-03-25T04:03:00.692293Z",
"iopub.status.idle": "2025-03-25T04:03:00.702352Z",
"shell.execute_reply": "2025-03-25T04:03:00.701582Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Clinical Data Preview:\n",
"{0: [nan, 1.0], 1: [0.0, nan]}\n",
"Clinical data saved to ../../output/preprocess/Stomach_Cancer/clinical_data/GSE208099.csv\n"
]
}
],
"source": [
"# 1. Gene Expression Data Availability\n",
"is_gene_available = True # Based on background information, this dataset contains gene expression data\n",
"\n",
"# 2. Variable Availability and Data Type Conversion\n",
"# 2.1 Data Availability\n",
"trait_row = 1 # 'tissue' row contains information about whether the sample is cancer or normal\n",
"age_row = None # Age information is not available in the sample characteristics\n",
"gender_row = 0 # Gender information is available\n",
"\n",
"# 2.2 Data Type Conversion Functions\n",
"def convert_trait(value):\n",
" \"\"\"Convert tissue type to binary trait (1 for cancer, 0 for normal).\"\"\"\n",
" if isinstance(value, str) and \":\" in value:\n",
" value = value.split(\":\", 1)[1].strip().lower()\n",
" else:\n",
" value = str(value).lower()\n",
" \n",
" if \"adenocarcinoma\" in value or \"cancer\" in value or \"tumor\" in value:\n",
" return 1\n",
" elif \"normal\" in value:\n",
" return 0\n",
" return None\n",
"\n",
"def convert_gender(value):\n",
" \"\"\"Convert gender to binary (0 for female, 1 for male).\"\"\"\n",
" if isinstance(value, str) and \":\" in value:\n",
" value = value.split(\":\", 1)[1].strip().upper()\n",
" else:\n",
" value = str(value).upper()\n",
" \n",
" if value == \"F\" or value == \"FEMALE\":\n",
" return 0\n",
" elif value == \"M\" or value == \"MALE\":\n",
" return 1\n",
" return None\n",
"\n",
"# 3. Save Metadata\n",
"is_trait_available = trait_row is not None\n",
"validate_and_save_cohort_info(\n",
" is_final=False,\n",
" cohort=cohort,\n",
" info_path=json_path,\n",
" is_gene_available=is_gene_available,\n",
" is_trait_available=is_trait_available\n",
")\n",
"\n",
"# 4. Clinical Feature Extraction\n",
"if trait_row is not None:\n",
" # Assuming clinical_data is already available from a previous step\n",
" # If not, it would require proper parsing of the GEO matrix file with appropriate header handling\n",
" \n",
" # Load the sample characteristics dictionary directly\n",
" sample_char_dict = {0: ['gender: M', 'gender: F'], 1: ['tissue: adenocarcinoma', 'tissue: normal mucosa']}\n",
" \n",
" # Create a DataFrame to mimic the structure expected by geo_select_clinical_features\n",
" clinical_data = pd.DataFrame()\n",
" for row_idx, values in sample_char_dict.items():\n",
" clinical_data[row_idx] = values\n",
" \n",
" # Extract and process 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",
" gender_row=gender_row,\n",
" convert_gender=convert_gender\n",
" )\n",
" \n",
" # Preview the clinical data\n",
" preview = preview_df(selected_clinical_df)\n",
" print(\"Clinical Data Preview:\")\n",
" print(preview)\n",
" \n",
" # Save the clinical data\n",
" os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
" selected_clinical_df.to_csv(out_clinical_data_file, index=False)\n",
" print(f\"Clinical data saved to {out_clinical_data_file}\")\n"
]
},
{
"cell_type": "markdown",
"id": "4d9513d3",
"metadata": {},
"source": [
"### Step 3: Gene Data Extraction"
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "4f26b544",
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-25T04:03:00.703981Z",
"iopub.status.busy": "2025-03-25T04:03:00.703868Z",
"iopub.status.idle": "2025-03-25T04:03:00.928293Z",
"shell.execute_reply": "2025-03-25T04:03:00.927729Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"First 20 gene/probe identifiers:\n",
"Index(['A_19_P00315452', 'A_19_P00315492', 'A_19_P00315493', 'A_19_P00315502',\n",
" 'A_19_P00315506', 'A_19_P00315518', 'A_19_P00315519', 'A_19_P00315529',\n",
" 'A_19_P00315541', 'A_19_P00315543', 'A_19_P00315551', 'A_19_P00315581',\n",
" 'A_19_P00315584', 'A_19_P00315593', 'A_19_P00315603', 'A_19_P00315625',\n",
" 'A_19_P00315627', 'A_19_P00315631', 'A_19_P00315641', 'A_19_P00315647'],\n",
" dtype='object', name='ID')\n",
"\n",
"Gene expression data shape: (58201, 32)\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": "2c5b0896",
"metadata": {},
"source": [
"### Step 4: Gene Identifier Review"
]
},
{
"cell_type": "code",
"execution_count": 5,
"id": "f62d0c30",
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-25T04:03:00.930225Z",
"iopub.status.busy": "2025-03-25T04:03:00.930072Z",
"iopub.status.idle": "2025-03-25T04:03:00.932582Z",
"shell.execute_reply": "2025-03-25T04:03:00.932150Z"
}
},
"outputs": [],
"source": [
"# Looking at the gene identifiers, these appear to be Agilent microarray probe IDs,\n",
"# not standard human gene symbols. These identifiers (A_19_PXXXXXXXX format) are typical\n",
"# of Agilent microarray platforms and need to be mapped to actual gene symbols.\n",
"\n",
"# The format \"A_19_P00315452\" indicates these are probe IDs from an Agilent microarray platform,\n",
"# not standard human gene symbols like \"TP53\", \"EGFR\", etc.\n",
"\n",
"requires_gene_mapping = True\n"
]
},
{
"cell_type": "markdown",
"id": "3cda807a",
"metadata": {},
"source": [
"### Step 5: Gene Annotation"
]
},
{
"cell_type": "code",
"execution_count": 6,
"id": "ad1099f0",
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-25T04:03:00.934727Z",
"iopub.status.busy": "2025-03-25T04:03:00.934618Z",
"iopub.status.idle": "2025-03-25T04:03:04.584663Z",
"shell.execute_reply": "2025-03-25T04:03:04.584294Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Gene annotation preview:\n",
"{'ID': ['GE_BrightCorner', 'DarkCorner', 'A_21_P0014386', 'A_33_P3396872', 'A_33_P3267760'], 'CONTROL_TYPE': ['pos', 'pos', 'FALSE', 'FALSE', 'FALSE'], 'REFSEQ': [nan, nan, nan, 'NM_001105533', nan], 'GB_ACC': [nan, nan, nan, 'NM_001105533', nan], 'LOCUSLINK_ID': [nan, nan, nan, 79974.0, 54880.0], 'GENE_SYMBOL': [nan, nan, nan, 'CPED1', 'BCOR'], 'GENE_NAME': [nan, nan, nan, 'cadherin-like and PC-esterase domain containing 1', 'BCL6 corepressor'], 'UNIGENE_ID': [nan, nan, nan, 'Hs.189652', nan], 'ENSEMBL_ID': [nan, nan, nan, nan, 'ENST00000378463'], 'ACCESSION_STRING': [nan, nan, nan, 'ref|NM_001105533|gb|AK025639|gb|BC030538|tc|THC2601673', 'ens|ENST00000378463'], 'CHROMOSOMAL_LOCATION': [nan, nan, 'unmapped', 'chr7:120901888-120901947', 'chrX:39909128-39909069'], 'CYTOBAND': [nan, nan, nan, 'hs|7q31.31', 'hs|Xp11.4'], 'DESCRIPTION': [nan, nan, nan, 'Homo sapiens cadherin-like and PC-esterase domain containing 1 (CPED1), transcript variant 2, mRNA [NM_001105533]', 'BCL6 corepressor [Source:HGNC Symbol;Acc:HGNC:20893] [ENST00000378463]'], 'GO_ID': [nan, nan, nan, 'GO:0005783(endoplasmic reticulum)', 'GO:0000122(negative regulation of transcription from RNA polymerase II promoter)|GO:0000415(negative regulation of histone H3-K36 methylation)|GO:0003714(transcription corepressor activity)|GO:0004842(ubiquitin-protein ligase activity)|GO:0005515(protein binding)|GO:0005634(nucleus)|GO:0006351(transcription, DNA-dependent)|GO:0007507(heart development)|GO:0008134(transcription factor binding)|GO:0030502(negative regulation of bone mineralization)|GO:0031072(heat shock protein binding)|GO:0031519(PcG protein complex)|GO:0035518(histone H2A monoubiquitination)|GO:0042476(odontogenesis)|GO:0042826(histone deacetylase binding)|GO:0044212(transcription regulatory region DNA binding)|GO:0045892(negative regulation of transcription, DNA-dependent)|GO:0051572(negative regulation of histone H3-K4 methylation)|GO:0060021(palate development)|GO:0065001(specification of axis polarity)|GO:0070171(negative regulation of tooth mineralization)'], 'SEQUENCE': [nan, nan, 'AATACATGTTTTGGTAAACACTCGGTCAGAGCACCCTCTTTCTGTGGAATCAGACTGGCA', 'GCTTATCTCACCTAATACAGGGACTATGCAACCAAGAAACTGGAAATAAAAACAAAGATA', 'CATCAAAGCTACGAGAGATCCTACACACCCAGATTTAAAAAATAATAAAAACTTAAGGGC'], 'SPOT_ID': ['GE_BrightCorner', 'DarkCorner', 'A_21_P0014386', 'A_33_P3396872', 'A_33_P3267760']}\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": "819b0f33",
"metadata": {},
"source": [
"### Step 6: Gene Identifier Mapping"
]
},
{
"cell_type": "code",
"execution_count": 7,
"id": "e23a45af",
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-25T04:03:04.585856Z",
"iopub.status.busy": "2025-03-25T04:03:04.585738Z",
"iopub.status.idle": "2025-03-25T04:03:05.390743Z",
"shell.execute_reply": "2025-03-25T04:03:05.390366Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Using ID as probe identifier column and GENE_SYMBOL as gene symbol column\n",
"Created gene mapping dataframe with shape: (48862, 2)\n",
"Gene mapping preview:\n",
" ID Gene\n",
"3 A_33_P3396872 CPED1\n",
"4 A_33_P3267760 BCOR\n",
"5 A_32_P194264 CHAC2\n",
"6 A_23_P153745 IFI30\n",
"10 A_21_P0014180 GPR146\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Converted gene expression data shape: (29222, 32)\n",
"First 10 gene symbols after mapping:\n",
"Index(['A1BG', 'A1BG-AS1', 'A1CF', 'A1CF-2', 'A1CF-3', 'A2M', 'A2M-1',\n",
" 'A2M-AS1', 'A2ML1', 'A2MP1'],\n",
" dtype='object', name='Gene')\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Gene expression data saved to ../../output/preprocess/Stomach_Cancer/gene_data/GSE208099.csv\n"
]
}
],
"source": [
"# 1. Determine which columns to use for mapping based on the gene annotation preview\n",
"# Based on the preview, we need to map from 'ID' (probe identifier) to 'GENE_SYMBOL' (gene symbols)\n",
"probe_col = 'ID'\n",
"gene_col = 'GENE_SYMBOL'\n",
"\n",
"# Print selected columns to confirm our choice\n",
"print(f\"Using {probe_col} as probe identifier column and {gene_col} as gene symbol column\")\n",
"\n",
"# 2. Get a gene mapping dataframe\n",
"gene_mapping = get_gene_mapping(gene_annotation, probe_col, gene_col)\n",
"print(f\"Created gene mapping dataframe with shape: {gene_mapping.shape}\")\n",
"\n",
"# Preview the mapping to verify structure\n",
"print(\"Gene mapping preview:\")\n",
"print(gene_mapping.head())\n",
"\n",
"# 3. Apply gene mapping to convert probe-level measurements to gene expression data\n",
"try:\n",
" gene_data = apply_gene_mapping(gene_data, gene_mapping)\n",
" print(f\"Converted gene expression data shape: {gene_data.shape}\")\n",
" print(\"First 10 gene symbols after mapping:\")\n",
" print(gene_data.index[:10])\n",
" \n",
" # Save the gene expression data\n",
" os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
" gene_data.to_csv(out_gene_data_file)\n",
" print(f\"Gene expression data saved to {out_gene_data_file}\")\n",
" \n",
"except Exception as e:\n",
" print(f\"Error applying gene mapping: {e}\")\n"
]
},
{
"cell_type": "markdown",
"id": "12a93af9",
"metadata": {},
"source": [
"### Step 7: Data Normalization and Linking"
]
},
{
"cell_type": "code",
"execution_count": 8,
"id": "11b6bd81",
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-25T04:03:05.392023Z",
"iopub.status.busy": "2025-03-25T04:03:05.391904Z",
"iopub.status.idle": "2025-03-25T04:03:05.923006Z",
"shell.execute_reply": "2025-03-25T04:03:05.922637Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Normalized gene data shape: (20778, 32)\n",
"First few normalized gene symbols: ['A1BG', 'A1BG-AS1', 'A1CF', 'A2M', 'A2M-AS1', 'A2ML1', 'A2MP1', 'A3GALT2', 'A4GALT', 'A4GNT']\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Normalized gene data saved to ../../output/preprocess/Stomach_Cancer/gene_data/GSE208099.csv\n",
"Loaded clinical data with shape: (2, 2)\n",
"Clinical data columns: ['0', '1']\n",
"Trait column 'Stomach_Cancer' not found in clinical data. Available columns: [0, 1]\n",
"Abnormality detected in the cohort: GSE208099. Preprocessing failed.\n",
"Data quality check failed. Required trait information is missing.\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. Load the clinical data from the previously saved file\n",
"try:\n",
" clinical_data = pd.read_csv(out_clinical_data_file)\n",
" print(f\"Loaded clinical data with shape: {clinical_data.shape}\")\n",
" print(f\"Clinical data columns: {clinical_data.columns.tolist()}\")\n",
"except Exception as e:\n",
" print(f\"Error loading clinical data: {e}\")\n",
" # If there's an issue loading the data, attempt to recreate it\n",
" clinical_data = pd.DataFrame()\n",
" if trait_row is not None:\n",
" print(\"Regenerating clinical data from original sources...\")\n",
" # Get clinical data from the matrix file again\n",
" _, clinical_raw = get_background_and_clinical_data(matrix_file_path)\n",
" clinical_data = geo_select_clinical_features(\n",
" clinical_df=clinical_raw,\n",
" trait=trait,\n",
" trait_row=trait_row,\n",
" convert_trait=convert_trait,\n",
" gender_row=gender_row,\n",
" convert_gender=convert_gender\n",
" )\n",
"\n",
"# Transpose clinical data to ensure proper format for linking\n",
"if not clinical_data.empty:\n",
" clinical_data_transposed = clinical_data.T\n",
" # Rename the index column to ensure proper linking\n",
" if trait in clinical_data_transposed.columns:\n",
" # Link clinical and genetic data\n",
" linked_data = geo_link_clinical_genetic_data(clinical_data_transposed, normalized_gene_data)\n",
" print(f\"Linked data shape: {linked_data.shape}\")\n",
" print(f\"Linked data columns (first few): {linked_data.columns[:10].tolist()}\")\n",
" \n",
" # Check if trait column exists in linked data\n",
" if trait in linked_data.columns:\n",
" # 3. Handle missing values in the linked data\n",
" linked_data = handle_missing_values(linked_data, trait)\n",
" print(f\"After handling missing values, linked data shape: {linked_data.shape}\")\n",
" \n",
" # 4. Check if the trait and demographic features are biased\n",
" is_trait_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n",
" \n",
" # 5. Validate the data quality and save the validation results\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,\n",
" is_biased=is_trait_biased, \n",
" df=linked_data,\n",
" note=\"Dataset contains gene expression data comparing adenocarcinoma vs normal mucosa in stomach tissue.\"\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, index=True)\n",
" print(f\"Linked data saved to {out_data_file}\")\n",
" else:\n",
" print(f\"Data quality check failed. The dataset cannot be used for association studies.\")\n",
" else:\n",
" print(f\"Trait column '{trait}' not found in linked data. Available columns: {linked_data.columns[:5].tolist()}\")\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,\n",
" is_biased=True, \n",
" df=pd.DataFrame(),\n",
" note=\"Clinical data structure incompatible with trait analysis requirements.\"\n",
" )\n",
" print(\"Data quality check failed. The trait column was not properly linked.\")\n",
" else:\n",
" print(f\"Trait column '{trait}' not found in clinical data. Available columns: {clinical_data_transposed.columns.tolist()}\")\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,\n",
" is_biased=True, \n",
" df=pd.DataFrame(),\n",
" note=\"Clinical data lacks the specific trait column needed for analysis.\"\n",
" )\n",
" print(\"Data quality check failed. Required trait information is missing.\")\n",
"else:\n",
" print(\"No clinical data available for this cohort.\")\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,\n",
" is_biased=True, \n",
" df=pd.DataFrame(),\n",
" note=\"Dataset lacks clinical annotations required for association studies.\"\n",
" )\n",
" print(\"Data quality check failed. No clinical data 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
}
|