File size: 28,077 Bytes
32677ff |
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 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 |
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"id": "756aada9",
"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 = \"Chronic_kidney_disease\"\n",
"cohort = \"GSE60861\"\n",
"\n",
"# Input paths\n",
"in_trait_dir = \"../../input/GEO/Chronic_kidney_disease\"\n",
"in_cohort_dir = \"../../input/GEO/Chronic_kidney_disease/GSE60861\"\n",
"\n",
"# Output paths\n",
"out_data_file = \"../../output/preprocess/Chronic_kidney_disease/GSE60861.csv\"\n",
"out_gene_data_file = \"../../output/preprocess/Chronic_kidney_disease/gene_data/GSE60861.csv\"\n",
"out_clinical_data_file = \"../../output/preprocess/Chronic_kidney_disease/clinical_data/GSE60861.csv\"\n",
"json_path = \"../../output/preprocess/Chronic_kidney_disease/cohort_info.json\"\n"
]
},
{
"cell_type": "markdown",
"id": "a63a3beb",
"metadata": {},
"source": [
"### Step 1: Initial Data Loading"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "9edd49f1",
"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": "36557a74",
"metadata": {},
"source": [
"### Step 2: Dataset Analysis and Clinical Feature Extraction"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "50c3e3f8",
"metadata": {},
"outputs": [],
"source": [
"I'll correct the code to properly handle the sample characteristics and extract clinical features.\n",
"\n",
"```python\n",
"import pandas as pd\n",
"import os\n",
"import numpy as np\n",
"from typing import Dict, List, Any, Optional, Callable\n",
"\n",
"# 1. Gene Expression Data Availability\n",
"# Based on the background information, this dataset appears to have both miRNA and mRNA data\n",
"# Since it mentions \"renal miRNA- and mRNA-expression signatures\", we can set is_gene_available to True\n",
"is_gene_available = True\n",
"\n",
"# 2. Variable Availability and Data Type Conversion\n",
"# 2.1 Data Availability\n",
"\n",
"# For trait (CKD progression status)\n",
"# Looking at the sample characteristics dictionary, we can see that key 4 contains 'clinical course: stable/progressive'\n",
"trait_row = 4\n",
"\n",
"# For age\n",
"# Looking at the sample characteristics dictionary, keys 1 and 2 contain age data\n",
"# Key 1 has more consistent age data format, so we'll use it\n",
"age_row = 1\n",
"\n",
"# For gender\n",
"# Looking at the sample characteristics dictionary, key 0 contains gender data\n",
"gender_row = 0\n",
"\n",
"# 2.2 Data Type Conversion Functions\n",
"\n",
"def convert_trait(value):\n",
" \"\"\"\n",
" Convert trait data to binary format:\n",
" - 1 for progressive CKD\n",
" - 0 for stable CKD\n",
" - None for unknown/missing values\n",
" \"\"\"\n",
" if pd.isna(value):\n",
" return None\n",
" \n",
" value = value.lower().strip() if isinstance(value, str) else str(value).lower().strip()\n",
" \n",
" if \":\" in value:\n",
" value = value.split(\":\", 1)[1].strip()\n",
" \n",
" if value == \"progressive\":\n",
" return 1\n",
" elif value == \"stable\":\n",
" return 0\n",
" else:\n",
" return None\n",
"\n",
"def convert_age(value):\n",
" \"\"\"\n",
" Convert age data to continuous format.\n",
" Extract numeric age value after the colon.\n",
" \"\"\"\n",
" if pd.isna(value):\n",
" return None\n",
" \n",
" value = str(value).strip()\n",
" \n",
" if \":\" in value:\n",
" age_str = value.split(\":\", 1)[1].strip()\n",
" try:\n",
" return float(age_str)\n",
" except ValueError:\n",
" return None\n",
" else:\n",
" try:\n",
" return float(value)\n",
" except ValueError:\n",
" return None\n",
"\n",
"def convert_gender(value):\n",
" \"\"\"\n",
" Convert gender data to binary format:\n",
" - 0 for female\n",
" - 1 for male\n",
" - None for unknown/missing values\n",
" \"\"\"\n",
" if pd.isna(value):\n",
" return None\n",
" \n",
" value = value.lower().strip() if isinstance(value, str) else str(value).lower().strip()\n",
" \n",
" if \":\" in value:\n",
" value = value.split(\":\", 1)[1].strip()\n",
" \n",
" if value == \"male\":\n",
" return 1\n",
" elif value == \"female\":\n",
" return 0\n",
" else:\n",
" return None\n",
"\n",
"# 3. Save Metadata\n",
"# Determine trait data availability\n",
"is_trait_available = trait_row is not None\n",
"\n",
"# Validate and save cohort information\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 (if trait_row is not None)\n",
"if trait_row is not None:\n",
" # Create clinical_data DataFrame\n",
" # The expected format for geo_select_clinical_features is a DataFrame where\n",
" # each row corresponds to a feature category (gender, age, etc.)\n",
" sample_chars_dict = {\n",
" 0: ['gender: male', 'gender: female', 'tissue: kidney biopsy'],\n",
" 1: ['age (yrs): 72', 'age (yrs): 20', 'age (yrs): 64', 'age (yrs): 17', 'age (yrs): 46', 'age (yrs): 55', 'age (yrs): 74', 'age (yrs): 49', 'age (yrs): 42', 'age (yrs): 73', 'age (yrs): 63', 'age (yrs): 33', 'age (yrs): 24', 'age (yrs): 45', 'age (yrs): 70', 'age (yrs): 60', 'age (yrs): 67', 'age (yrs): 31', 'age (yrs): 53', 'age (yrs): 22', 'age (yrs): 54', 'age (yrs): 40', 'age (yrs): 38', 'age (yrs): 19', 'age (yrs): 28', 'age (yrs): 65', 'age (yrs): 58', 'age (yrs): 56', 'age (yrs): 34', 'age (yrs): 59'],\n",
" 2: ['diagnosis: Diabetic Nephropathy', 'diagnosis: Focal-Segmental Glomerulosclerosis', 'diagnosis: Hypertensive Nephropathy', 'diagnosis: IgA-Nephropathy', 'diagnosis: Membranous Nephropathy', 'diagnosis: Minimal-Change Disease', 'diagnosis: Other/Unknown', 'age (yrs): 41.6', 'age (yrs): 59.0', 'age (yrs): 21.0', 'age (yrs): 33.0', 'age (yrs): 35.0', 'age (yrs): 24.0', 'age (yrs): 70.0', 'age (yrs): 43.0', 'age (yrs): 45.0', 'age (yrs): 44.0', 'age (yrs): 54.0', 'age (yrs): 74.0', 'age (yrs): 31.0', 'age (yrs): 49.0', 'age (yrs): 28.0', 'age (yrs): 26.0', 'age (yrs): 47.0', 'age (yrs): 20.0', 'age (yrs): 71.0', 'age (yrs): 58.0', 'age (yrs): 18.0', 'age (yrs): 32.0', 'age (yrs): 55.0'],\n",
" 3: ['clinical course: stable', 'clinical course: progressive', 'diagnosis: IgA nephropathy', 'diagnosis: Glomerulonephritis, not specified', 'diagnosis: Lupus nephritis class 4', 'diagnosis: Lupus nephritis class 5', 'diagnosis: Membranoproliferative glomerulonephritis', 'diagnosis: Focal-segmental glomerulosclerosis', 'diagnosis: Vasculitis', 'diagnosis: Membranous nephropathy', 'diagnosis: Lupus nephritis class 3', 'diagnosis: Minimal change disease', 'diagnosis: Diabetic nephropathy'],\n",
" 4: [np.nan, 'clinical course: progressive', 'clinical course: stable']\n",
" }\n",
" \n",
" # Create a DataFrame with the correct structure for geo_select_clinical_features\n",
" # Each row is a feature category, with the row index corresponding to the feature row numbers\n",
" max_row = max(sample_chars_dict.keys()) + 1\n",
" clinical_data = pd.DataFrame(index=range(max_row))\n",
" \n",
" # Add each feature's unique values as columns in the DataFrame\n",
" for row_idx, values in sample_chars_dict.items():\n",
" for col_idx, value in enumerate(values):\n",
" clinical_data.loc[row_idx, col_idx] = value\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 extracted clinical features\n",
" print(\"Preview of extracted clinical features:\")\n",
" preview_result = preview_df(selected_clinical_\n"
]
},
{
"cell_type": "markdown",
"id": "6e8bf64d",
"metadata": {},
"source": [
"### Step 3: Dataset Analysis and Clinical Feature Extraction"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "e5c72cd5",
"metadata": {},
"outputs": [],
"source": [
"import pandas as pd\n",
"import os\n",
"import json\n",
"from typing import Optional, Callable, Dict, Any\n",
"import gzip\n",
"\n",
"# Get background information and clinical data from the dataset\n",
"background_info, clinical_data = get_background_and_clinical_data(in_cohort_dir)\n",
"\n",
"# Get unique values for each row to understand the data structure\n",
"row_values = get_unique_values_by_row(clinical_data)\n",
"\n",
"print(\"Background Information:\")\n",
"for key, value in background_info.items():\n",
" print(f\"{key}: {value}\")\n",
"\n",
"print(\"\\nSample Characteristics by Row:\")\n",
"for row_idx, values in row_values.items():\n",
" print(f\"Row {row_idx}: {values}\")\n",
"\n",
"# 1. Gene Expression Data Availability\n",
"# Check if gene expression data is available based on background info\n",
"is_gene_available = True\n",
"if \"platform_technology\" in background_info:\n",
" tech = background_info[\"platform_technology\"].lower()\n",
" if \"mirna\" in tech or \"methylation\" in tech:\n",
" is_gene_available = False\n",
"\n",
"# 2. Variable Availability and Data Type Conversion\n",
"# Analyze the rows to identify trait, age, and gender information\n",
"\n",
"# For trait (Chronic kidney disease)\n",
"trait_row = None\n",
"# Look for rows that might contain disease status information\n",
"for row_idx, values in row_values.items():\n",
" values_str = ' '.join([str(v).lower() for v in values])\n",
" if ('ckd' in values_str or \n",
" 'chronic kidney disease' in values_str or \n",
" 'kidney' in values_str or \n",
" 'control' in values_str or \n",
" 'case' in values_str or \n",
" 'disease' in values_str or\n",
" 'patient' in values_str):\n",
" trait_row = row_idx\n",
" print(f\"Found trait information in row {row_idx}: {values}\")\n",
" break\n",
"\n",
"def convert_trait(value):\n",
" if value is None:\n",
" return None\n",
" value = str(value).lower()\n",
" if ':' in value:\n",
" value = value.split(':', 1)[1].strip()\n",
" \n",
" if ('ckd' in value or \n",
" 'chronic kidney disease' in value or \n",
" 'renal disease' in value or \n",
" 'kidney disease' in value or \n",
" 'patient' in value or \n",
" 'case' in value):\n",
" return 1\n",
" elif ('control' in value or \n",
" 'healthy' in value or \n",
" 'normal' in value):\n",
" return 0\n",
" return None\n",
"\n",
"# For age\n",
"age_row = None\n",
"# Look for rows that might contain age information\n",
"for row_idx, values in row_values.items():\n",
" values_str = ' '.join([str(v).lower() for v in values])\n",
" if 'age' in values_str:\n",
" age_row = row_idx\n",
" print(f\"Found age information in row {row_idx}: {values}\")\n",
" break\n",
"\n",
"def convert_age(value):\n",
" if value is None:\n",
" return None\n",
" value = str(value)\n",
" if ':' in value:\n",
" value = value.split(':', 1)[1].strip()\n",
" \n",
" # Try to extract numeric age\n",
" import re\n",
" matches = re.findall(r'\\d+\\.?\\d*', value)\n",
" if matches:\n",
" try:\n",
" return float(matches[0])\n",
" except:\n",
" return None\n",
" return None\n",
"\n",
"# For gender\n",
"gender_row = None\n",
"# Look for rows that might contain gender information\n",
"for row_idx, values in row_values.items():\n",
" values_str = ' '.join([str(v).lower() for v in values])\n",
" if 'gender' in values_str or 'sex' in values_str or 'male' in values_str or 'female' in values_str:\n",
" gender_row = row_idx\n",
" print(f\"Found gender information in row {row_idx}: {values}\")\n",
" break\n",
"\n",
"def convert_gender(value):\n",
" if value is None:\n",
" return None\n",
" value = str(value).lower()\n",
" if ':' in value:\n",
" value = value.split(':', 1)[1].strip()\n",
" \n",
" if 'female' in value or 'f' == value.strip():\n",
" return 0\n",
" elif 'male' in value or 'm' == value.strip():\n",
" return 1\n",
" return None\n",
"\n",
"# Check if trait data is available\n",
"is_trait_available = trait_row is not None\n",
"\n",
"# 3. Save Metadata\n",
"# Validate and save cohort info\n",
"validate_and_save_cohort_info(\n",
" is_final=False,\n",
" cohort=cohort,\n",
" info_path=json_path,\n",
" is_gene_available=is_gene_available,\n",
" is_trait_available=is_trait_available\n",
")\n",
"\n",
"# 4. Clinical Feature Extraction\n",
"if is_trait_available:\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(\"\\nPreview of selected clinical features:\")\n",
" for key, values in preview.items():\n",
" print(f\"{key}: {values}\")\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",
"else:\n",
" print(\"Cannot process clinical data: trait information not found in the dataset.\")\n"
]
},
{
"cell_type": "markdown",
"id": "c36012e4",
"metadata": {},
"source": [
"### Step 4: Gene Data Extraction"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "a237c321",
"metadata": {},
"outputs": [],
"source": [
"# 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",
"print(f\"SOFT file: {soft_file}\")\n",
"print(f\"Matrix file: {matrix_file}\")\n",
"\n",
"# Set gene availability flag\n",
"is_gene_available = True # Assume gene data is available\n",
"\n",
"# Extract gene data\n",
"try:\n",
" # Extract gene data from the matrix file\n",
" gene_data = get_genetic_data(matrix_file)\n",
" print(f\"Gene data shape: {gene_data.shape}\")\n",
" \n",
" # Print the first 20 gene/probe identifiers\n",
" print(\"First 20 gene/probe identifiers:\")\n",
" print(gene_data.index[:20].tolist())\n",
"except Exception as e:\n",
" print(f\"Error extracting gene data: {e}\")\n",
" print(f\"File path: {matrix_file}\")\n",
" print(\"Please check if the file exists and contains the expected markers.\")\n"
]
},
{
"cell_type": "markdown",
"id": "a5ac7f0f",
"metadata": {},
"source": [
"### Step 5: Gene Identifier Review"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "e52bb4e7",
"metadata": {},
"outputs": [],
"source": [
"# Examine the gene identifiers shown in the previous output\n",
"# These identifiers (like 'A_23_P100001') appear to be Agilent microarray probe IDs\n",
"# They are not standard human gene symbols and will need to be mapped\n",
"\n",
"# Agilent probe IDs typically start with 'A_' followed by numbers and letters\n",
"# This format indicates these are probe identifiers, not gene symbols\n",
"# We will need to map these to standard gene symbols for analysis\n",
"\n",
"requires_gene_mapping = True\n"
]
},
{
"cell_type": "markdown",
"id": "a3b46831",
"metadata": {},
"source": [
"### Step 6: Gene Annotation"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "dcf609b3",
"metadata": {},
"outputs": [],
"source": [
"# 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.\n",
"soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\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",
"# Look more closely at columns that might contain gene information\n",
"print(\"\\nExamining potential gene mapping columns:\")\n",
"potential_gene_columns = ['gene_assignment', 'mrna_assignment', 'swissprot', 'unigene']\n",
"for col in potential_gene_columns:\n",
" if col in gene_annotation.columns:\n",
" print(f\"\\nSample values from '{col}' column:\")\n",
" print(gene_annotation[col].head(3).tolist())\n"
]
},
{
"cell_type": "markdown",
"id": "4bd22cf7",
"metadata": {},
"source": [
"### Step 7: Gene Identifier Mapping"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "2e43a7c8",
"metadata": {},
"outputs": [],
"source": [
"# 1. Analyze the gene annotation dataframe to identify the correct columns for mapping\n",
"# Based on the previous output, we need:\n",
"# - 'ID' column which contains the probe identifiers matching those in gene_data\n",
"# - 'GENE_SYMBOL' column which contains the gene symbols we want to map to\n",
"\n",
"# First get the gene expression data and annotation data again\n",
"soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
"gene_expression_data = get_genetic_data(matrix_file)\n",
"gene_annotation = get_gene_annotation(soft_file)\n",
"\n",
"# Display the first few rows of gene annotation to confirm column selection\n",
"print(\"First few rows of gene annotation:\")\n",
"print(gene_annotation[['ID', 'GENE_SYMBOL']].head())\n",
"\n",
"# 2. Get a gene mapping dataframe\n",
"# Extract the relevant columns for mapping: probe IDs and gene symbols\n",
"mapping_df = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='GENE_SYMBOL')\n",
"print(f\"\\nMapping dataframe shape: {mapping_df.shape}\")\n",
"print(\"First few rows of mapping data:\")\n",
"print(mapping_df.head())\n",
"\n",
"# 3. Apply gene mapping to convert probe-level data to gene-level data\n",
"gene_data = apply_gene_mapping(gene_expression_data, mapping_df)\n",
"print(f\"\\nConverted gene expression data shape: {gene_data.shape}\")\n",
"print(\"First few gene symbols:\")\n",
"print(gene_data.index[:10].tolist())\n",
"\n",
"# Normalize gene symbols to ensure consistency\n",
"gene_data = normalize_gene_symbols_in_index(gene_data)\n",
"print(f\"\\nAfter normalization, gene data shape: {gene_data.shape}\")\n",
"print(\"First few normalized gene symbols:\")\n",
"print(gene_data.index[:10].tolist())\n",
"\n",
"# Save the gene data to a 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": "af08ca6f",
"metadata": {},
"source": [
"### Step 8: Data Normalization and Linking"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "a29771d5",
"metadata": {},
"outputs": [],
"source": [
"# 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",
"# Define the functions for extracting clinical features\n",
"def convert_trait(value):\n",
" \"\"\"Convert clinical course to binary format: 1 for progressive, 0 for stable\"\"\"\n",
" if pd.isna(value):\n",
" return None\n",
" \n",
" value = str(value).lower().strip()\n",
" if ':' in value:\n",
" value = value.split(':', 1)[1].strip()\n",
" \n",
" if value == 'progressive':\n",
" return 1\n",
" elif value == 'stable':\n",
" return 0\n",
" else:\n",
" return None\n",
"\n",
"def convert_age(value):\n",
" \"\"\"Convert age data to float\"\"\"\n",
" if pd.isna(value):\n",
" return None\n",
" \n",
" value = str(value).strip()\n",
" if ':' in value:\n",
" age_str = value.split(':', 1)[1].strip()\n",
" try:\n",
" return float(age_str)\n",
" except ValueError:\n",
" return None\n",
" return None\n",
"\n",
"def convert_gender(value):\n",
" \"\"\"Convert gender to binary: 0 for female, 1 for male\"\"\"\n",
" if pd.isna(value):\n",
" return None\n",
" \n",
" value = str(value).lower().strip()\n",
" if ':' in value:\n",
" value = value.split(':', 1)[1].strip()\n",
" \n",
" if value == 'female':\n",
" return 0\n",
" elif value == 'male':\n",
" return 1\n",
" return None\n",
"\n",
"# Re-extract clinical data if the saved file doesn't exist\n",
"background_info, clinical_data = get_background_and_clinical_data(matrix_file)\n",
"trait_row = 4 # Based on the analysis in step 2\n",
"age_row = 1 # Based on the analysis in step 2\n",
"gender_row = 0 # Based on the analysis in step 2\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",
"print(f\"Clinical data shape: {selected_clinical_df.shape}\")\n",
"print(\"Clinical data preview:\")\n",
"print(preview_df(selected_clinical_df))\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)\n",
"print(f\"Clinical data saved to {out_clinical_data_file}\")\n",
"\n",
"# 1. Load the normalized gene data (already done in step 7)\n",
"if 'gene_data' not in locals():\n",
" gene_data = pd.read_csv(out_gene_data_file, index_col=0)\n",
" print(f\"Loaded gene data from {out_gene_data_file}\")\n",
"\n",
"# 2. Link the clinical and genetic data\n",
"print(\"\\nLinking 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, first 5 columns):\")\n",
"print(linked_data.iloc[:5, :5])\n",
"\n",
"# 3. Handle missing values in the linked data\n",
"print(\"\\nHandling missing values...\")\n",
"linked_data = handle_missing_values(linked_data, trait)\n",
"print(f\"Linked data shape after handling missing values: {linked_data.shape}\")\n",
"\n",
"# 4. Determine if the trait and demographic features are biased\n",
"print(\"\\nChecking for bias in trait and demographic features...\")\n",
"is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n",
"\n",
"# 5. Conduct final quality validation and save relevant information\n",
"print(\"\\nConducting final quality validation...\")\n",
"is_gene_available = True # We've confirmed gene data is available in previous steps\n",
"is_trait_available = True # We've confirmed trait data is available in previous steps\n",
"\n",
"note = \"This dataset contains gene expression data from kidney biopsies. It classifies samples based on clinical course (stable or progressive chronic kidney disease).\"\n",
"\n",
"is_usable = validate_and_save_cohort_info(\n",
" is_final=True,\n",
" cohort=cohort,\n",
" info_path=json_path,\n",
" is_gene_available=is_gene_available,\n",
" is_trait_available=is_trait_available,\n",
" is_biased=is_biased,\n",
" df=linked_data,\n",
" note=note\n",
")\n",
"\n",
"# 6. Save the linked data if it's 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(\"Linked data not saved as dataset is not usable for the current trait study.\")"
]
}
],
"metadata": {},
"nbformat": 4,
"nbformat_minor": 5
}
|