File size: 27,995 Bytes
736e4a0 |
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 |
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"id": "c2f3e216",
"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 = \"Anxiety_disorder\"\n",
"cohort = \"GSE68526\"\n",
"\n",
"# Input paths\n",
"in_trait_dir = \"../../input/GEO/Anxiety_disorder\"\n",
"in_cohort_dir = \"../../input/GEO/Anxiety_disorder/GSE68526\"\n",
"\n",
"# Output paths\n",
"out_data_file = \"../../output/preprocess/Anxiety_disorder/GSE68526.csv\"\n",
"out_gene_data_file = \"../../output/preprocess/Anxiety_disorder/gene_data/GSE68526.csv\"\n",
"out_clinical_data_file = \"../../output/preprocess/Anxiety_disorder/clinical_data/GSE68526.csv\"\n",
"json_path = \"../../output/preprocess/Anxiety_disorder/cohort_info.json\"\n"
]
},
{
"cell_type": "markdown",
"id": "a0d41705",
"metadata": {},
"source": [
"### Step 1: Initial Data Loading"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "c7435175",
"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": "676e3e8c",
"metadata": {},
"source": [
"### Step 2: Dataset Analysis and Clinical Feature Extraction"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "679846f6",
"metadata": {},
"outputs": [],
"source": [
"I'll provide a correctly formatted code solution for this step:\n",
"\n",
"```python\n",
"# 1. Determine if gene expression data is available\n",
"# The background information mentions \"Gene expression profiling was carried out on peripheral blood RNA samples\"\n",
"# This suggests the dataset contains gene expression data, not just miRNA or methylation data\n",
"is_gene_available = True\n",
"\n",
"# 2. Identify and convert clinical data\n",
"\n",
"# 2.1. Trait (Anxiety disorder)\n",
"# The sample characteristics include \"anxiety\" scores at index 13\n",
"# This is from the Beck Anxiety Inventory mentioned in the description\n",
"trait_row = 13\n",
"\n",
"def convert_trait(value):\n",
" if 'missing' in str(value).lower():\n",
" return None\n",
" try:\n",
" # Extract the numeric part after the colon\n",
" parts = value.split(':', 1)\n",
" if len(parts) > 1:\n",
" anxiety_score = float(parts[1].strip())\n",
" # Convert to binary based on a threshold\n",
" # Beck Anxiety Inventory: higher values indicate greater anxiety\n",
" # Using threshold of 2.0 (moderate anxiety)\n",
" return 1 if anxiety_score >= 2.0 else 0\n",
" return None\n",
" except:\n",
" return None\n",
"\n",
"# 2.2. Age\n",
"# Age is recorded at index 0\n",
"age_row = 0\n",
"\n",
"def convert_age(value):\n",
" try:\n",
" # Extract the numeric part after the colon\n",
" parts = value.split(':', 1)\n",
" if len(parts) > 1:\n",
" age = float(parts[1].strip())\n",
" return age\n",
" return None\n",
" except:\n",
" return None\n",
"\n",
"# 2.3. Gender\n",
"# Gender is recorded at index 1 as \"female: 0\" or \"female: 1\"\n",
"gender_row = 1\n",
"\n",
"def convert_gender(value):\n",
" try:\n",
" # Extract the numeric part after the colon\n",
" parts = value.split(':', 1)\n",
" if len(parts) > 1:\n",
" female = int(parts[1].strip())\n",
" # Convert to standard format where 0=female, 1=male\n",
" # In the data, female=1 means it's a female, female=0 means it's a male\n",
" return 1 - female # Reverse the coding to match our standard\n",
" return None\n",
" except:\n",
" return None\n",
"\n",
"# 3. Perform initial filtering and 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. Extract clinical features if trait_row is not None\n",
"if trait_row is not None:\n",
" # Create a DataFrame from the sample characteristics dictionary provided\n",
" sample_characteristics = {0: ['age (yrs): 79', 'age (yrs): 76', 'age (yrs): 70', 'age (yrs): 65', 'age (yrs): 64', 'age (yrs): 75', 'age (yrs): 66', 'age (yrs): 93', 'age (yrs): 69', 'age (yrs): 67', 'age (yrs): 77', 'age (yrs): 74', 'age (yrs): 73', 'age (yrs): 80', 'age (yrs): 68', 'age (yrs): 83', 'age (yrs): 87', 'age (yrs): 81', 'age (yrs): 84', 'age (yrs): 55', 'age (yrs): 62', 'age (yrs): 58', 'age (yrs): 60', 'age (yrs): 56', 'age (yrs): 86', 'age (yrs): 78', 'age (yrs): 48', 'age (yrs): 82', 'age (yrs): 95', 'age (yrs): 71'], 1: ['female: 0', 'female: 1'], 2: ['black: 0', 'black: 1'], 3: ['hispanic: 0', 'hispanic: 1'], 4: ['bmi: 22.7', 'bmi: 29.1', 'bmi: 25.8', 'bmi: 24.8', 'bmi: 42.1', 'bmi: 29.6', 'bmi: 21.4', 'bmi: 32.7', 'bmi: 30.7', 'bmi: 29.2', 'bmi: 34.0', 'bmi: 44.3', 'bmi: 28.7', 'bmi: 27.4', 'bmi: 30.6', 'bmi: 31.3', 'bmi: 30.0', 'bmi: 25.1', 'bmi: 26.4', 'bmi: 21.6', 'bmi: 18.6', 'bmi: 24.1', 'bmi: 22.9', 'bmi: 28.6', 'bmi: 25.0', 'bmi: 27.5', 'bmi: 25.5', 'bmi: 23.7', 'bmi: 23.0', 'bmi: 28.5'], 5: ['diabcvdcastr: 1', 'diabcvdcastr: 0'], 6: ['ln_hh_income: 16.03', 'ln_hh_income: 15.49', 'ln_hh_income: 15.34', 'ln_hh_income: 15.52', 'ln_hh_income: 16.41', 'ln_hh_income: 14.20', 'ln_hh_income: 18.09', 'ln_hh_income: 13.57', 'ln_hh_income: 16.29', 'ln_hh_income: 14.64', 'ln_hh_income: 15.28', 'ln_hh_income: 15.30', 'ln_hh_income: 15.93', 'ln_hh_income: 15.02', 'ln_hh_income: 16.93', 'ln_hh_income: 14.44', 'ln_hh_income: 16.10', 'ln_hh_income: 14.22', 'ln_hh_income: 13.18', 'ln_hh_income: 14.90', 'ln_hh_income: 12.97', 'ln_hh_income: 16.36', 'ln_hh_income: 16.14', 'ln_hh_income: 14.91', 'ln_hh_income: 13.71', 'ln_hh_income: 15.99', 'ln_hh_income: 13.77', 'ln_hh_income: 15.46', 'ln_hh_income: 13.86', 'ln_hh_income: 16.42'], 7: ['smoke: 1', 'smoke: 0'], 8: ['alcohol: 0', 'alcohol: 1', 'alcohol: missing'], 9: ['loneliness: 1.00', 'loneliness: 2.00', 'loneliness: 1.67', 'loneliness: 1.33', 'loneliness: 2.67', 'loneliness: missing', 'loneliness: 2.33', 'loneliness: 3.00'], 10: ['pwb_purpose: 4.14', 'pwb_purpose: 6.00', 'pwb_purpose: 5.00', 'pwb_purpose: 5.43', 'pwb_purpose: 3.29', 'pwb_purpose: 5.14', 'pwb_purpose: 4.71', 'pwb_purpose: 5.33', 'pwb_purpose: 4.83', 'pwb_purpose: 2.67', 'pwb_purpose: 5.71', 'pw\n"
]
},
{
"cell_type": "markdown",
"id": "e9f6ca24",
"metadata": {},
"source": [
"### Step 3: Dataset Analysis and Clinical Feature Extraction"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "724b4e54",
"metadata": {},
"outputs": [],
"source": [
"I'll implement code that works with the available files without relying on GEOparse.\n",
"\n",
"```python\n",
"# Step 1: Analyze the dataset to determine gene expression data availability\n",
"import os\n",
"import pandas as pd\n",
"import json\n",
"import numpy as np\n",
"import gzip\n",
"import re\n",
"\n",
"# First, let's check what files are available in the cohort directory\n",
"cohort_files = os.listdir(in_cohort_dir)\n",
"print(f\"Files in cohort directory: {cohort_files}\")\n",
"\n",
"# Let's check if there are matrix files that might contain gene expression data\n",
"matrix_files = [f for f in cohort_files if 'matrix' in f.lower()]\n",
"print(f\"Matrix files: {matrix_files}\")\n",
"\n",
"# Load the series matrix file to check for gene expression data\n",
"series_matrix_path = os.path.join(in_cohort_dir, matrix_files[0] if matrix_files else cohort_files[0])\n",
"\n",
"# Function to check if file contains gene expression data\n",
"def analyze_matrix_file(file_path):\n",
" # Check if the file contains gene expression data by reading header lines\n",
" with gzip.open(file_path, 'rt', encoding='utf-8') as f:\n",
" header_lines = [next(f) for _ in range(100) if '!' in next(f, '')]\n",
" \n",
" # Check if the file contains gene expression data\n",
" is_gene_expression = any(['gene' in line.lower() for line in header_lines]) or \\\n",
" any(['expression' in line.lower() for line in header_lines])\n",
" \n",
" # Check if it's miRNA or methylation only\n",
" is_mirna_only = any(['mirna' in line.lower() for line in header_lines]) and not is_gene_expression\n",
" is_methylation_only = any(['methylation' in line.lower() for line in header_lines]) and not is_gene_expression\n",
" \n",
" return not (is_mirna_only or is_methylation_only)\n",
"\n",
"# Function to parse sample characteristics from series matrix file\n",
"def parse_clinical_data(file_path):\n",
" clinical_data = None\n",
" characteristic_lines = []\n",
" sample_ids = []\n",
" \n",
" with gzip.open(file_path, 'rt', encoding='utf-8') as f:\n",
" in_header = True\n",
" for line in f:\n",
" if in_header:\n",
" if line.startswith('!Sample_geo_accession'):\n",
" sample_ids = line.strip().split('\\t')[1:]\n",
" elif line.startswith('!Sample_characteristics_ch'):\n",
" characteristic_lines.append(line.strip().split('\\t')[1:])\n",
" elif line.startswith('!series_matrix_table_begin'):\n",
" in_header = False\n",
" else:\n",
" break\n",
" \n",
" # Create a dataframe with the clinical data\n",
" if sample_ids and characteristic_lines:\n",
" df_dict = {f'char_{i}': chars for i, chars in enumerate(characteristic_lines)}\n",
" clinical_data = pd.DataFrame(df_dict, index=sample_ids)\n",
" \n",
" return clinical_data\n",
"\n",
"# Determine if gene expression data is available\n",
"try:\n",
" is_gene_available = analyze_matrix_file(series_matrix_path)\n",
" print(f\"Is gene expression data available: {is_gene_available}\")\n",
"except Exception as e:\n",
" print(f\"Error analyzing gene expression: {e}\")\n",
" is_gene_available = False\n",
"\n",
"# Get clinical data from the series matrix file\n",
"try:\n",
" clinical_data = parse_clinical_data(series_matrix_path)\n",
" \n",
" if clinical_data is not None:\n",
" print(\"Clinical data found with shape:\", clinical_data.shape)\n",
" print(\"Sample characteristics:\")\n",
" for i, col in enumerate(clinical_data.columns):\n",
" unique_values = clinical_data[col].unique()\n",
" if len(unique_values) < 10: # Only print if there are few unique values\n",
" print(f\"Row {i}: {col} - Unique values: {unique_values}\")\n",
" else:\n",
" print(f\"Row {i}: {col} - {len(unique_values)} unique values\")\n",
" else:\n",
" print(\"Clinical data not found in the file.\")\n",
"except Exception as e:\n",
" print(f\"Error parsing clinical data: {e}\")\n",
" clinical_data = pd.DataFrame()\n",
"\n",
"# Functions to convert trait, age, and gender data\n",
"def convert_trait(value):\n",
" if pd.isna(value) or value is None:\n",
" return None\n",
" \n",
" # Extract value after colon if present\n",
" if isinstance(value, str) and ':' in value:\n",
" value = value.split(':', 1)[1].strip()\n",
" \n",
" # Convert to binary (0: control, 1: anxiety disorder)\n",
" value = str(value).lower()\n",
" if 'control' in value or 'healthy' in value or 'normal' in value:\n",
" return 0\n",
" elif 'anxiety' in value or 'ptsd' in value or 'stress' in value or 'disorder' in value:\n",
" return 1\n",
" else:\n",
" return None\n",
"\n",
"def convert_age(value):\n",
" if pd.isna(value) or value is None:\n",
" return None\n",
" \n",
" # Extract value after colon if present\n",
" if isinstance(value, str) and ':' in value:\n",
" value = value.split(':', 1)[1].strip()\n",
" \n",
" # Try to convert to float\n",
" try:\n",
" age = float(value)\n",
" return age\n",
" except (ValueError, TypeError):\n",
" # If age is given as a range (e.g., \"25-30\"), take the average\n",
" if isinstance(value, str) and '-' in value:\n",
" try:\n",
" parts = value.split('-')\n",
" return (float(parts[0]) + float(parts[1])) / 2\n",
" except (ValueError, IndexError):\n",
" pass\n",
" return None\n",
"\n",
"def convert_gender(value):\n",
" if pd.isna(value) or value is None:\n",
" return None\n",
" \n",
" # Extract value after colon if present\n",
" if isinstance(value, str) and ':' in value:\n",
" value = value.split(':', 1)[1].strip()\n",
" \n",
" # Convert to binary (0: female, 1: male)\n",
" value = str(value).lower()\n",
" if 'female' in value or 'f' == value:\n",
" return 0\n",
" elif 'male' in value or 'm' == value:\n",
" return 1\n",
" else:\n",
" return None\n",
"\n",
"# Based on the analysis, determine which rows contain trait, age, and gender\n",
"# Setting default values as None (not available)\n",
"trait_row = None\n",
"age_row = None\n",
"gender_row = None\n",
"\n",
"# Analyze clinical data to find relevant rows\n",
"if clinical_data is not None and not clinical_data.empty:\n",
" for i, col in enumerate(clinical_data.columns):\n",
" # Get string representation of column values\n",
" col_str = ' '.join(str(v) for v in clinical_data[col].unique())\n",
" \n",
" # Look for trait indicators\n",
" if ('diagnosis' in col_str.lower() or 'disease' in col_str.lower() or \n",
" 'condition' in col_str.lower() or 'group' in col_str.lower() or \n",
" 'anxiety' in col_str.lower() or 'control' in col_str.lower()):\n",
" # Check if this column could be trait data\n",
" unique_values = clinical_data[col].unique()\n",
" # Verify if the values correspond to trait data (should have at least 2 groups)\n",
" if len(unique_values) > 1:\n",
" trait_row = i\n",
" \n",
" # Look for age indicators\n",
" if 'age' in col_str.lower():\n",
" unique_values = clinical_data[col].unique()\n",
" if len(unique_values) > 1: # Should have variation in age\n",
" age_row = i\n",
" \n",
" # Look for gender indicators\n",
" if 'gender' in col_str.lower() or 'sex' in col_str.lower():\n",
" unique_values = clinical_data[col].unique()\n",
" if len(unique_values) > 1: # Should have both males and females\n",
" gender_row = i\n",
"\n",
"# Determine trait data availability\n",
"is_trait_available = trait_row is not None\n",
"\n",
"print(f\"Trait row: {trait_row}\")\n",
"print(f\"Age row: {age_row}\")\n",
"print(f\"Gender row: {gender_row}\")\n",
"print(f\"Is trait available: {is_trait\n"
]
},
{
"cell_type": "markdown",
"id": "6fc60ab9",
"metadata": {},
"source": [
"### Step 4: Dataset Analysis and Clinical Feature Extraction"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "244b8b4f",
"metadata": {},
"outputs": [],
"source": [
"import pandas as pd\n",
"import numpy as np\n",
"import os\n",
"import re\n",
"import json\n",
"import gzip\n",
"import io\n",
"from typing import Optional, Callable, Dict, Any, List\n",
"\n",
"def get_feature_data(clinical_df, row_index, feature_name, convert_func):\n",
" \"\"\"Helper function to extract and convert feature data from a row.\"\"\"\n",
" feature_series = clinical_df.iloc[row_index].copy()\n",
" feature_series.name = feature_name\n",
" if convert_func is not None:\n",
" feature_series = feature_series.apply(convert_func)\n",
" return pd.DataFrame(feature_series).T\n",
"\n",
"# First, check what files are available in the cohort directory\n",
"files = os.listdir(in_cohort_dir)\n",
"print(f\"Available files: {files}\")\n",
"\n",
"# Determine if gene expression data is available\n",
"# GEO series matrix files typically contain gene expression data\n",
"is_gene_available = any('series_matrix' in f for f in files)\n",
"\n",
"# Extract clinical data from the series matrix file\n",
"clinical_data = None\n",
"series_matrix_file = [f for f in files if 'series_matrix' in f.lower()][0]\n",
"file_path = os.path.join(in_cohort_dir, series_matrix_file)\n",
"\n",
"# Parse the GEO series matrix file to extract sample characteristics\n",
"sample_char_lines = []\n",
"with gzip.open(file_path, 'rt') as f:\n",
" in_sample_char_section = False\n",
" sample_ids = []\n",
" \n",
" for line in f:\n",
" line = line.strip()\n",
" \n",
" # Extract sample IDs\n",
" if line.startswith('!Sample_geo_accession'):\n",
" sample_ids = line.split('\\t')[1:]\n",
" \n",
" # Collect sample characteristics lines\n",
" elif line.startswith('!Sample_characteristics_ch'):\n",
" sample_char_lines.append(line.split('\\t')[1:])\n",
" \n",
" # Check if we're done with the characteristics section\n",
" elif line.startswith('!Sample_') and sample_char_lines:\n",
" continue\n",
" elif line.startswith('!series_matrix_table_begin'):\n",
" break\n",
"\n",
"# Create clinical dataframe if sample characteristics were found\n",
"if sample_char_lines and sample_ids:\n",
" clinical_data = pd.DataFrame(sample_char_lines, columns=sample_ids)\n",
" print(f\"Clinical data shape: {clinical_data.shape}\")\n",
" print(\"First few rows of clinical data:\")\n",
" print(clinical_data.head(10))\n",
"\n",
" # Look for trait (anxiety disorder), age, and gender data in the characteristics\n",
" trait_row = None\n",
" age_row = None\n",
" gender_row = None\n",
" \n",
" # Print unique values for each row to help identify relevant rows\n",
" for i in range(len(clinical_data.index)):\n",
" unique_vals = clinical_data.iloc[i, :].unique()\n",
" print(f\"Row {i} unique values: {unique_vals}\")\n",
" \n",
" # Check if this row might contain trait data\n",
" row_str = ' '.join(str(val).lower() for val in unique_vals)\n",
" if ('anxiety' in row_str or 'patient' in row_str or 'diagnosis' in row_str or \n",
" 'disorder' in row_str or 'case' in row_str or 'control' in row_str):\n",
" print(f\"Potential trait row: {i}\")\n",
" trait_row = i\n",
" \n",
" # Check if this row might contain age data\n",
" if 'age' in row_str or 'years' in row_str:\n",
" print(f\"Potential age row: {i}\")\n",
" age_row = i\n",
" \n",
" # Check if this row might contain gender data\n",
" if 'gender' in row_str or 'sex' in row_str or 'male' in row_str or 'female' in row_str:\n",
" print(f\"Potential gender row: {i}\")\n",
" gender_row = i\n",
"\n",
" # Define conversion functions based on observed data patterns\n",
" def convert_trait(value):\n",
" if pd.isnull(value):\n",
" return None\n",
" value_str = str(value).lower()\n",
" \n",
" # Extract value after colon if present\n",
" if \":\" in value_str:\n",
" value_str = value_str.split(\":\", 1)[1].strip()\n",
" \n",
" # Convert to binary: 1 for anxiety, 0 for control/healthy\n",
" if re.search(r'anxi|patient|disorder|case', value_str):\n",
" return 1\n",
" elif re.search(r'control|healthy|normal', value_str):\n",
" return 0\n",
" return None\n",
"\n",
" def convert_age(value):\n",
" if pd.isnull(value):\n",
" return None\n",
" value_str = str(value).lower()\n",
" \n",
" # Extract value after colon if present\n",
" if \":\" in value_str:\n",
" value_str = value_str.split(\":\", 1)[1].strip()\n",
" \n",
" # Try to extract numeric age value\n",
" age_match = re.search(r'(\\d+(?:\\.\\d+)?)', value_str)\n",
" if age_match:\n",
" return float(age_match.group(1))\n",
" return None\n",
"\n",
" def convert_gender(value):\n",
" if pd.isnull(value):\n",
" return None\n",
" value_str = str(value).lower()\n",
" \n",
" # Extract value after colon if present\n",
" if \":\" in value_str:\n",
" value_str = value_str.split(\":\", 1)[1].strip()\n",
" \n",
" # Convert to binary: 0 for female, 1 for male\n",
" if re.search(r'female|f\\b|woman|women', value_str):\n",
" return 0\n",
" elif re.search(r'male|m\\b|man|men', value_str):\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",
" # Save initial 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 data is available\n",
" if is_trait_available:\n",
" print(\"\\nExtracting clinical features...\")\n",
" selected_clinical_data = 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 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 data\n",
" preview = preview_df(selected_clinical_data)\n",
" print(\"\\nSelected 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_data.to_csv(out_clinical_data_file)\n",
" print(f\"Clinical data saved to {out_clinical_data_file}\")\n",
" else:\n",
" print(\"\\nNo suitable trait data found in the clinical information.\")\n",
"else:\n",
" print(\"No sample characteristics found in the series matrix file.\")\n",
" is_trait_available = False\n",
" \n",
" # Save the negative result\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=False\n",
" )\n"
]
},
{
"cell_type": "markdown",
"id": "35adae85",
"metadata": {},
"source": [
"### Step 5: Gene Data Extraction"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "40f614d6",
"metadata": {},
"outputs": [],
"source": [
"# 1. Re-identify the SOFT and matrix files to ensure we have the correct paths\n",
"soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
"\n",
"# 2. Extract the gene expression data from the matrix file\n",
"gene_data = get_genetic_data(matrix_file)\n",
"\n",
"# 3. Print the first 20 row IDs (gene or probe identifiers)\n",
"print(\"\\nFirst 20 gene/probe identifiers:\")\n",
"print(gene_data.index[:20])\n",
"\n",
"# 4. Print the dimensions of the gene expression data\n",
"print(f\"\\nGene data dimensions: {gene_data.shape[0]} genes × {gene_data.shape[1]} samples\")\n",
"\n",
"# Note: we keep is_gene_available as True since we successfully extracted gene expression data\n",
"is_gene_available = True\n"
]
},
{
"cell_type": "markdown",
"id": "e1b1321a",
"metadata": {},
"source": [
"### Step 6: Gene Identifier Review"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "f5ee5479",
"metadata": {},
"outputs": [],
"source": [
"# The identifiers in the gene expression data appear to be human gene symbols.\n",
"# This can be determined because we see standard gene symbols like A1BG, A2M, AAAS, etc.\n",
"# These are official HGNC (HUGO Gene Nomenclature Committee) gene symbols for human genes.\n",
"\n",
"# Since the data is already using human gene symbols, we don't need to perform mapping.\n",
"requires_gene_mapping = False\n",
"\n",
"# Printing the result for clarification (though the variable assignment above is sufficient)\n",
"print(f\"Gene mapping requirement: {requires_gene_mapping}\")"
]
}
],
"metadata": {},
"nbformat": 4,
"nbformat_minor": 5
}
|