File size: 30,213 Bytes
7ae1978 |
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": null,
"id": "b381ed7e",
"metadata": {},
"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 = \"Bipolar_disorder\"\n",
"cohort = \"GSE92538\"\n",
"\n",
"# Input paths\n",
"in_trait_dir = \"../../input/GEO/Bipolar_disorder\"\n",
"in_cohort_dir = \"../../input/GEO/Bipolar_disorder/GSE92538\"\n",
"\n",
"# Output paths\n",
"out_data_file = \"../../output/preprocess/Bipolar_disorder/GSE92538.csv\"\n",
"out_gene_data_file = \"../../output/preprocess/Bipolar_disorder/gene_data/GSE92538.csv\"\n",
"out_clinical_data_file = \"../../output/preprocess/Bipolar_disorder/clinical_data/GSE92538.csv\"\n",
"json_path = \"../../output/preprocess/Bipolar_disorder/cohort_info.json\"\n"
]
},
{
"cell_type": "markdown",
"id": "68a8bbdf",
"metadata": {},
"source": [
"### Step 1: Initial Data Loading"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "c7fd9cf2",
"metadata": {},
"outputs": [],
"source": [
"from tools.preprocess import *\n",
"# 1. Identify the paths to the SOFT file and the matrix file\n",
"soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
"\n",
"# 2. Read the matrix file to obtain background information and sample characteristics data\n",
"background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']\n",
"clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']\n",
"background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)\n",
"\n",
"# 3. Obtain the sample characteristics dictionary from the clinical dataframe\n",
"sample_characteristics_dict = get_unique_values_by_row(clinical_data)\n",
"\n",
"# 4. Explicitly print out all the background information and the sample characteristics dictionary\n",
"print(\"Background Information:\")\n",
"print(background_info)\n",
"print(\"Sample Characteristics Dictionary:\")\n",
"print(sample_characteristics_dict)\n"
]
},
{
"cell_type": "markdown",
"id": "6fa7bd63",
"metadata": {},
"source": [
"### Step 2: Dataset Analysis and Clinical Feature Extraction"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "6161e74f",
"metadata": {},
"outputs": [],
"source": [
"As a domain expert in this biomedical research project, I'll provide the corrected code for this step:\n",
"\n",
"```python\n",
"import pandas as pd\n",
"import os\n",
"import json\n",
"from typing import Optional, Callable, Dict, Any\n",
"\n",
"# 1. Check for gene expression data availability\n",
"# Based on the background information, this dataset contains transcriptomic data\n",
"# from human brain (dorsolateral prefrontal cortex) with 11,911 ENTREZ transcripts\n",
"is_gene_available = True # Gene expression data is available\n",
"\n",
"# 2. Identify variable availability and create conversion functions\n",
"\n",
"# 2.1 Trait (Bipolar disorder)\n",
"# From the sample characteristics, trait information is in row 2 (\"diagnosis: ...\")\n",
"trait_row = 2\n",
"\n",
"# 2.2 Age information\n",
"# Age is available in row 8\n",
"age_row = 8\n",
"\n",
"# 2.3 Gender information\n",
"# Gender is available in row 6\n",
"gender_row = 6\n",
"\n",
"# Conversion functions\n",
"def convert_trait(value):\n",
" \"\"\"Convert diagnosis information to binary trait indicator for Bipolar disorder.\"\"\"\n",
" if value is None or pd.isna(value):\n",
" return None\n",
" \n",
" # Extract the value after the colon\n",
" if ':' in value:\n",
" value = value.split(':', 1)[1].strip()\n",
" \n",
" # Check if it's Bipolar Disorder (case-insensitive)\n",
" if 'bipolar' in value.lower():\n",
" return 1\n",
" elif value.lower() in ['control', 'major depressive disorder', 'schizophrenia']:\n",
" return 0\n",
" else:\n",
" return None # Unknown or other diagnosis\n",
"\n",
"def convert_age(value):\n",
" \"\"\"Convert age information to continuous numerical value.\"\"\"\n",
" if value is None or pd.isna(value):\n",
" return None\n",
" \n",
" # Extract the value after the colon\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",
" \"\"\"Convert gender information to binary (0=female, 1=male).\"\"\"\n",
" if value is None or pd.isna(value):\n",
" return None\n",
" \n",
" # Extract the value after the colon\n",
" if ':' in value:\n",
" value = value.split(':', 1)[1].strip()\n",
" \n",
" # Convert to binary values\n",
" if value.upper() == 'F':\n",
" return 0\n",
" elif value.upper() == 'M':\n",
" return 1\n",
" else:\n",
" return None # Unknown gender\n",
"\n",
"# 3. Save metadata through initial filtering\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. Extract clinical features if available\n",
"if trait_row is not None:\n",
" # Create a DataFrame from the sample characteristics dictionary\n",
" sample_chars = {\n",
" 0: ['cohort: Schiz Cohort 1', 'cohort: Dep Cohort 3', 'cohort: Dep Cohort 4', 'cohort: Dep Cohort 2', 'cohort: Dep Cohort 1'], \n",
" 1: ['site of processing: UC_Davis', 'site of processing: UC_Irvine', 'site of processing: U_Michigan'], \n",
" 2: ['diagnosis: Schizophrenia', 'diagnosis: Control', 'diagnosis: Major Depressive Disorder', 'diagnosis: Bipolar Disorder'], \n",
" 3: ['subject id: 101078', 'subject id: 101244', 'subject id: 101283', 'subject id: 101309', 'subject id: 101431', 'subject id: 101488', 'subject id: 101597', 'subject id: 101657', 'subject id: 101674', 'subject id: 101690', 'subject id: 101736', 'subject id: 101739', 'subject id: 101811', 'subject id: 101923', 'subject id: 101956', 'subject id: 102038', 'subject id: 102118', 'subject id: 102212', 'subject id: 102420', 'subject id: 102422', 'subject id: 102432', 'subject id: 102440', 'subject id: 102475', 'subject id: 102513', 'subject id: 102539', 'subject id: 102636', 'subject id: 102785', 'subject id: 103037', 'subject id: 103068', 'subject id: 103091'], \n",
" 4: ['agonal factor: 0', 'agonal factor: NA', 'agonal factor: 1', 'agonal factor: 2', 'agonal factor: 3'], \n",
" 5: ['tissue ph (cerebellum): 6.83', 'tissue ph (cerebellum): 6.97', 'tissue ph (cerebellum): 7.01', 'tissue ph (cerebellum): NA', 'tissue ph (cerebellum): 6.87', 'tissue ph (cerebellum): 7.05', 'tissue ph (cerebellum): 6.38', 'tissue ph (cerebellum): 6.72', 'tissue ph (cerebellum): 6.91', 'tissue ph (cerebellum): 6.06', 'tissue ph (cerebellum): 7', 'tissue ph (cerebellum): 7.02', 'tissue ph (cerebellum): 6.86', 'tissue ph (cerebellum): 6.54', 'tissue ph (cerebellum): 7.21', 'tissue ph (cerebellum): 6.63', 'tissue ph (cerebellum): 6.42', 'tissue ph (cerebellum): 6.89', 'tissue ph (cerebellum): 7.19', 'tissue ph (cerebellum): 6.68', 'tissue ph (cerebellum): 6.62', 'tissue ph (cerebellum): 7.17', 'tissue ph (cerebellum): 6.84', 'tissue ph (cerebellum): 6.76', 'tissue ph (cerebellum): 6.93', 'tissue ph (cerebellum): 6.59', 'tissue ph (cerebellum): 6.61', 'tissue ph (cerebellum): 6.79', 'tissue ph (cerebellum): 7.2', 'tissue ph (cerebellum): 6.81'], \n",
" 6: ['gender: M', 'gender: F'], \n",
" 7: ['race: Caucasian', 'race: Hispanic', 'race: Asian', 'race: Other', 'race: African American'], \n",
" 8: ['age: 39', 'age: 32', 'age: 63', 'age: 70', 'age: 71', 'age: 44', 'age: 66', 'age: 59', 'age: 65', 'age: 69', 'age: 52', 'age: 49', 'age: 58', 'age: 45', 'age: 72', 'age: 73', 'age: 64', 'age: 77', 'age: 55', 'age: 53', 'age: 62', 'age: 47', 'age: 67', 'age: 57', 'age: 35', 'age: 48', 'age: 19', 'age: 54', 'age: 50', 'age: 56'], \n",
" 9: ['post-mortem interval: 7.5', 'post-mortem interval: 27.25', 'post-mortem interval: 29.5', 'post-mortem interval: 14.5', 'post-mortem interval: 36.5', 'post-mortem interval: 23', 'post-mortem interval: 32', 'post-mortem interval: 13.25', 'post-mortem interval: 26', 'post-mortem interval: 11.25', 'post-mortem interval:\n"
]
},
{
"cell_type": "markdown",
"id": "cea28f95",
"metadata": {},
"source": [
"### Step 3: Dataset Analysis and Clinical Feature Extraction"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "a050473f",
"metadata": {},
"outputs": [],
"source": [
"I understand the issue now. I need to extract and parse the GEO files, focusing on the .soft file which contains the clinical information.\n",
"\n",
"```python\n",
"import pandas as pd\n",
"import numpy as np\n",
"import os\n",
"import json\n",
"import gzip\n",
"import re\n",
"from typing import Callable, Optional, Dict, Any\n",
"\n",
"# Function to extract and parse the .soft file\n",
"def parse_geo_soft_file(file_path):\n",
" # Dictionary to store sample characteristics by sample_id\n",
" sample_characteristics = {}\n",
" current_sample = None\n",
" \n",
" # Open the gzipped file and decode it\n",
" with gzip.open(file_path, 'rt') as f:\n",
" for line in f:\n",
" line = line.strip()\n",
" \n",
" # Identify when we start a new sample\n",
" if line.startswith(\"^SAMPLE = \"):\n",
" current_sample = line.split(\"^SAMPLE = \")[1]\n",
" sample_characteristics[current_sample] = {}\n",
" \n",
" # Extract sample characteristics\n",
" elif current_sample and line.startswith(\"!Sample_characteristics_ch1 = \"):\n",
" char_value = line.replace(\"!Sample_characteristics_ch1 = \", \"\").strip()\n",
" if \":\" in char_value:\n",
" key, value = char_value.split(\":\", 1)\n",
" sample_characteristics[current_sample][key.strip()] = value.strip()\n",
" else:\n",
" # Handle characteristics without a key-value format\n",
" sample_characteristics[current_sample][char_value] = True\n",
" \n",
" # Extract sample title\n",
" elif current_sample and line.startswith(\"!Sample_title = \"):\n",
" title = line.replace(\"!Sample_title = \", \"\").strip()\n",
" sample_characteristics[current_sample][\"title\"] = title\n",
" \n",
" return sample_characteristics\n",
"\n",
"# First, check if the soft file exists\n",
"soft_file_path = os.path.join(in_cohort_dir, \"GSE92538_family.soft.gz\")\n",
"if os.path.exists(soft_file_path):\n",
" print(f\"Parsing SOFT file: {soft_file_path}\")\n",
" sample_data = parse_geo_soft_file(soft_file_path)\n",
" \n",
" # Convert to DataFrame for easier analysis\n",
" samples_list = []\n",
" for sample_id, characteristics in sample_data.items():\n",
" sample_dict = {'sample_id': sample_id}\n",
" sample_dict.update(characteristics)\n",
" samples_list.append(sample_dict)\n",
" \n",
" if samples_list:\n",
" clinical_df = pd.DataFrame(samples_list)\n",
" print(\"Clinical data structure:\")\n",
" print(clinical_df.head())\n",
" print(f\"Number of samples: {len(clinical_df)}\")\n",
" print(f\"Columns: {clinical_df.columns.tolist()}\")\n",
" \n",
" # Check unique values in relevant columns to identify trait, age, and gender\n",
" for col in clinical_df.columns:\n",
" if col != 'sample_id':\n",
" unique_vals = clinical_df[col].unique()\n",
" print(f\"Column '{col}' unique values: {unique_vals}\")\n",
" \n",
" # Look for columns containing relevant information\n",
" col_lower = col.lower()\n",
" if 'disease' in col_lower or 'diagnosis' in col_lower or 'status' in col_lower or 'group' in col_lower:\n",
" print(f\"Potential trait column: {col}\")\n",
" elif 'age' in col_lower:\n",
" print(f\"Potential age column: {col}\")\n",
" elif 'gender' in col_lower or 'sex' in col_lower:\n",
" print(f\"Potential gender column: {col}\")\n",
" \n",
" # Check if gene expression data is available by looking for matrix files\n",
" is_gene_available = any(f.endswith('_series_matrix.txt.gz') for f in os.listdir(in_cohort_dir))\n",
" \n",
" # Now, based on the column analysis, define trait_row, age_row, and gender_row\n",
" # These will be set based on the analysis output\n",
" trait_row = None\n",
" age_row = None\n",
" gender_row = None\n",
" \n",
" # For demonstration, let's create a transposed clinical data for geo_select_clinical_features\n",
" # In a real scenario, we would identify the specific rows from the DataFrame\n",
" data_dict = {}\n",
" for i, col in enumerate(clinical_df.columns):\n",
" if col != 'sample_id':\n",
" data_dict[i] = clinical_df[col].tolist()\n",
" \n",
" transposed_clinical_df = pd.DataFrame(data_dict, index=clinical_df['sample_id'])\n",
" \n",
" # Check the title column for trait information\n",
" if 'title' in clinical_df.columns:\n",
" title_unique = clinical_df['title'].unique()\n",
" print(f\"Sample titles: {title_unique}\")\n",
" \n",
" # Check if titles contain bipolar/control information\n",
" has_bipolar_info = any('bipolar' in str(title).lower() or 'control' in str(title).lower() for title in title_unique)\n",
" if has_bipolar_info:\n",
" trait_row = list(clinical_df.columns).index('title') - 1 # Adjust for sample_id column\n",
" print(f\"Found trait information in 'title' column, row: {trait_row}\")\n",
" \n",
" # Conversion functions based on the data analysis\n",
" def convert_trait(value):\n",
" if pd.isna(value):\n",
" return None\n",
" value_str = str(value).lower()\n",
" \n",
" if 'control' in value_str or 'healthy' in value_str or 'normal' in value_str:\n",
" return 0\n",
" elif 'bipolar' in value_str or 'bd' in value_str or 'bp' in value_str or 'patient' in value_str:\n",
" return 1\n",
" return None\n",
" \n",
" def convert_age(value):\n",
" if pd.isna(value):\n",
" return None\n",
" try:\n",
" # Extract numbers from text\n",
" nums = re.findall(r'\\d+\\.?\\d*', str(value))\n",
" if nums:\n",
" return float(nums[0])\n",
" return None\n",
" except:\n",
" return None\n",
" \n",
" def convert_gender(value):\n",
" if pd.isna(value):\n",
" return None\n",
" value_str = str(value).lower()\n",
" \n",
" if 'female' in value_str or 'f' == value_str:\n",
" return 0\n",
" elif 'male' in value_str or 'm' == value_str:\n",
" return 1\n",
" return None\n",
" \n",
" # For this dataset, determine trait availability based on analysis\n",
" is_trait_available = trait_row is not None\n",
" \n",
" # Save metadata\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",
" # Extract clinical features if trait is available\n",
" if is_trait_available:\n",
" selected_clinical_df = geo_select_clinical_features(\n",
" clinical_df=transposed_clinical_df,\n",
" trait=trait,\n",
" trait_row=trait_row,\n",
" convert_trait=convert_trait,\n",
" age_row=age_row,\n",
" convert_age=convert_age if age_row is not None else None,\n",
" gender_row=gender_row,\n",
" convert_gender=convert_gender if gender_row is not None else None\n",
" )\n",
" \n",
" # Preview the selected clinical features\n",
" print(\"Preview of selected clinical features:\")\n",
" preview = preview_df(selected_clinical_df)\n",
" print(preview)\n",
" \n",
" # Save the selected clinical features to a CSV file\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",
" else:\n",
" print(\"Clinical feature extraction skipped: Trait data not available\")\n",
" else:\n",
" print(\"No sample data found in the SOFT file\")\n",
" is_gene_available = any(f.endswith('_series_matrix.txt.gz') for f in os.listdir(in_cohort_dir))\n",
" validate_and_save_cohort_info(\n",
" is_final=False,\n"
]
},
{
"cell_type": "markdown",
"id": "dad6f9ee",
"metadata": {},
"source": [
"### Step 4: Gene Data Extraction"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "febec8ac",
"metadata": {},
"outputs": [],
"source": [
"# 1. Get the SOFT and matrix file paths again \n",
"soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
"print(f\"Matrix file found: {matrix_file}\")\n",
"\n",
"# 2. Use the get_genetic_data function from the library to get the gene_data\n",
"try:\n",
" gene_data = get_genetic_data(matrix_file)\n",
" print(f\"Gene data shape: {gene_data.shape}\")\n",
" \n",
" # 3. Print the first 20 row IDs (gene or probe identifiers)\n",
" print(\"First 20 gene/probe identifiers:\")\n",
" print(gene_data.index[:20])\n",
"except Exception as e:\n",
" print(f\"Error extracting gene data: {e}\")\n"
]
},
{
"cell_type": "markdown",
"id": "8c255d38",
"metadata": {},
"source": [
"### Step 5: Gene Identifier Review"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "88b0f606",
"metadata": {},
"outputs": [],
"source": [
"# Examining the gene identifiers\n",
"# The format appears to be Affymetrix probe IDs (format: XXXXX_at)\n",
"# These are not standard human gene symbols and need to be mapped\n",
"# Affymetrix probe IDs typically need to be mapped to gene symbols\n",
"\n",
"requires_gene_mapping = True\n"
]
},
{
"cell_type": "markdown",
"id": "8140c9ea",
"metadata": {},
"source": [
"### Step 6: Gene Annotation"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "148035e8",
"metadata": {},
"outputs": [],
"source": [
"# 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.\n",
"gene_annotation = get_gene_annotation(soft_file)\n",
"\n",
"# 2. Analyze the gene annotation dataframe to identify which columns contain the gene identifiers and gene symbols\n",
"print(\"\\nGene annotation preview:\")\n",
"print(f\"Columns in gene annotation: {gene_annotation.columns.tolist()}\")\n",
"print(preview_df(gene_annotation, n=5))\n",
"\n",
"# Check if there are any columns that might contain gene information\n",
"sample_row = gene_annotation.iloc[0].to_dict()\n",
"print(\"\\nFirst row as dictionary:\")\n",
"for col, value in sample_row.items():\n",
" print(f\"{col}: {value}\")\n",
"\n",
"# Check if the SOFT file has the right information for gene mapping\n",
"print(\"\\nFurther examination needed - this might be a miRNA dataset or using non-standard annotations\")\n",
"print(\"Looking at the index of gene_data to compare with annotation ID format:\")\n",
"print(gene_data.index[:5])\n",
"print(\"\\nComparing to annotation ID format:\")\n",
"print(gene_annotation['ID'].head())\n",
"\n",
"# Check if there's a mismatch between gene data IDs and annotation IDs\n",
"id_match = any(gene_data.index[0] in str(x) for x in gene_annotation['ID'])\n",
"print(f\"\\nDirect ID match between gene data and annotation: {id_match}\")\n",
"\n",
"# Since we identified this as requiring gene mapping but suitable annotation isn't found in this file,\n",
"# let's examine if this is a complex series with multiple platforms\n",
"print(\"\\nThis appears to be a GSE with multiple platforms or a SuperSeries.\")\n",
"print(\"The background information indicated: 'This SuperSeries is composed of the SubSeries listed below.'\")\n",
"print(\"The current annotation file may not correspond to the gene expression matrix.\")\n"
]
},
{
"cell_type": "markdown",
"id": "d64dfd51",
"metadata": {},
"source": [
"### Step 7: Gene Identifier Mapping"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "d939e07d",
"metadata": {},
"outputs": [],
"source": [
"# 1. Determine which columns in gene_annotation contain probe IDs and gene symbols\n",
"# From the previous output, we can see:\n",
"# - 'ID' column in gene_annotation contains identifiers like \"10000_at\" which match gene_data index\n",
"# - 'SYMBOL' column contains gene symbols like \"AKT3\"\n",
"\n",
"# 2. Get a gene mapping dataframe by extracting the two relevant columns\n",
"mapping_df = get_gene_mapping(gene_annotation, prob_col=\"ID\", gene_col=\"SYMBOL\")\n",
"\n",
"print(\"Gene mapping dataframe preview:\")\n",
"print(mapping_df.head())\n",
"print(f\"Shape of mapping dataframe: {mapping_df.shape}\")\n",
"\n",
"# 3. Apply gene mapping to convert probe-level measurements to gene expression data\n",
"gene_data = apply_gene_mapping(gene_data, mapping_df)\n",
"\n",
"print(\"After mapping, gene expression data preview:\")\n",
"print(f\"Shape of gene expression data: {gene_data.shape}\")\n",
"print(f\"First 10 gene symbols: {gene_data.index[:10].tolist()}\")\n",
"\n",
"# Normalize gene symbols in the index\n",
"gene_data = normalize_gene_symbols_in_index(gene_data)\n",
"\n",
"print(\"After normalizing gene symbols:\")\n",
"print(f\"Shape of normalized gene expression data: {gene_data.shape}\")\n",
"print(f\"First 10 normalized gene symbols: {gene_data.index[:10].tolist()}\")\n",
"\n",
"# Save the gene expression data to a CSV file\n",
"os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
"gene_data.to_csv(out_gene_data_file)\n",
"print(f\"Gene expression data saved to {out_gene_data_file}\")\n"
]
},
{
"cell_type": "markdown",
"id": "850a690a",
"metadata": {},
"source": [
"### Step 8: Data Normalization and Linking"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "6d628ecf",
"metadata": {},
"outputs": [],
"source": [
"# 1. We already normalized gene symbols in the gene expression data in step 7\n",
"# Load the normalized gene data that was saved in the previous step\n",
"gene_data = pd.read_csv(out_gene_data_file, index_col=0)\n",
"print(f\"Loaded gene expression data with shape: {gene_data.shape}\")\n",
"\n",
"# Reload the background and clinical data from the matrix file\n",
"soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\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",
"# 2. Link the clinical and genetic data\n",
"# Define conversion functions:\n",
"def convert_trait(value):\n",
" \"\"\"Convert bipolar disorder status to binary format.\"\"\"\n",
" if not isinstance(value, str):\n",
" return None\n",
" value = value.lower()\n",
" # Extract the value after the colon if present\n",
" if ':' in value:\n",
" value = value.split(':', 1)[1].strip()\n",
" \n",
" if \"bipolar disorder\" in value:\n",
" return 1 # Has bipolar disorder\n",
" elif value in [\"control\", \"schizophrenia\", \"major depressive disorder\"]:\n",
" return 0 # Control/other diagnosis\n",
" return None\n",
"\n",
"def convert_age(value):\n",
" \"\"\"Convert age data to continuous format.\"\"\"\n",
" if not isinstance(value, str):\n",
" return None\n",
" # Extract the value after the colon if present\n",
" if ':' in value:\n",
" value = value.split(':', 1)[1].strip()\n",
" try:\n",
" return float(value)\n",
" except:\n",
" return None\n",
"\n",
"def convert_gender(value):\n",
" \"\"\"Convert gender data to binary format (0 for female, 1 for male).\"\"\"\n",
" if not isinstance(value, str):\n",
" return None\n",
" # Extract the value after the colon if present\n",
" if ':' in value:\n",
" value = value.split(':', 1)[1].strip()\n",
" \n",
" value = value.lower()\n",
" if value == \"f\":\n",
" return 0\n",
" elif value == \"m\":\n",
" return 1\n",
" return None\n",
"\n",
"# Get clinical data using the correct row indices\n",
"selected_clinical_df = geo_select_clinical_features(\n",
" clinical_df=clinical_data,\n",
" trait=trait,\n",
" trait_row=2, # Based on output showing diagnosis in row 2\n",
" convert_trait=convert_trait,\n",
" age_row=8, # Age data is in row 8 based on first step output\n",
" convert_age=convert_age,\n",
" gender_row=6, # Gender data is in row 6 based on first step output\n",
" convert_gender=convert_gender\n",
")\n",
"\n",
"print(f\"Selected clinical data shape: {selected_clinical_df.shape}\")\n",
"print(\"Clinical data preview:\")\n",
"print(preview_df(selected_clinical_df))\n",
"\n",
"# Save clinical data for future reference\n",
"os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
"selected_clinical_df.to_csv(out_clinical_data_file)\n",
"print(f\"Clinical data saved to {out_clinical_data_file}\")\n",
"\n",
"# Link clinical and genetic data\n",
"linked_data = geo_link_clinical_genetic_data(selected_clinical_df, gene_data)\n",
"print(f\"Linked data shape: {linked_data.shape}\")\n",
"print(\"Linked data preview (first 5 rows, 5 columns):\")\n",
"print(linked_data.iloc[:5, :5] if not linked_data.empty else \"Linked data is empty\")\n",
"\n",
"# 3. Handle missing values\n",
"linked_data = handle_missing_values(linked_data, trait)\n",
"print(f\"Data shape after handling missing values: {linked_data.shape}\")\n",
"\n",
"# 4. Check for bias in features\n",
"is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n",
"\n",
"# 5. Validate and save 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=True,\n",
" is_biased=is_biased,\n",
" df=linked_data,\n",
" note=\"Dataset contains gene expression data from brain samples with diagnoses including Bipolar Disorder, Major Depressive Disorder, Schizophrenia, and Control.\"\n",
")\n",
"\n",
"# 6. Save the linked data if 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(\"Dataset is not usable for analysis. No linked data file saved.\")"
]
}
],
"metadata": {},
"nbformat": 4,
"nbformat_minor": 5
}
|