File size: 32,330 Bytes
f88156f |
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": 1,
"id": "fd013f4f",
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-25T07:02:29.371289Z",
"iopub.status.busy": "2025-03-25T07:02:29.371112Z",
"iopub.status.idle": "2025-03-25T07:02:29.535490Z",
"shell.execute_reply": "2025-03-25T07:02:29.535033Z"
}
},
"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 = \"Breast_Cancer\"\n",
"cohort = \"GSE248830\"\n",
"\n",
"# Input paths\n",
"in_trait_dir = \"../../input/GEO/Breast_Cancer\"\n",
"in_cohort_dir = \"../../input/GEO/Breast_Cancer/GSE248830\"\n",
"\n",
"# Output paths\n",
"out_data_file = \"../../output/preprocess/Breast_Cancer/GSE248830.csv\"\n",
"out_gene_data_file = \"../../output/preprocess/Breast_Cancer/gene_data/GSE248830.csv\"\n",
"out_clinical_data_file = \"../../output/preprocess/Breast_Cancer/clinical_data/GSE248830.csv\"\n",
"json_path = \"../../output/preprocess/Breast_Cancer/cohort_info.json\"\n"
]
},
{
"cell_type": "markdown",
"id": "5e6aedde",
"metadata": {},
"source": [
"### Step 1: Initial Data Loading"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "9688b359",
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-25T07:02:29.536782Z",
"iopub.status.busy": "2025-03-25T07:02:29.536634Z",
"iopub.status.idle": "2025-03-25T07:02:29.553211Z",
"shell.execute_reply": "2025-03-25T07:02:29.552835Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Background Information:\n",
"!Series_title\t\"Unlocking Molecular mechanisms and identifying druggable targets in matched-paired brain metastasis of Breast and Lung cancers \"\n",
"!Series_summary\t\"Introduction: The incidence of brain metastases in cancer patients is increasing, with lung and breast cancer being the most common sources. Despite advancements in targeted therapies, the prognosis remains poor, highlighting the importance to investigate the underlying mechanisms in brain metastases. The aim of this study was to investigate the differences in the molecular mechanisms involved in brain metastasis of breast and lung cancers. In addition, we aimed to identify cancer lineage-specific druggable targets in the brain metastasis. Methods: To that aim, a cohort of 44 FFPE tissue samples, including 22 breast cancer and 22 lung adenocarcinoma (LUAD) and their matched-paired brain metastases were collected. Targeted gene expression profiles of primary tumors were compared to their matched-paired brain metastases samples using nCounter PanCancer IO 360™ Panel of NanoString technologies. Pathway analysis was performed using gene set analysis (GSA) and gene set enrichment analysis (GSEA). The validation was performed by using Immunohistochemistry (IHC) to confirm the expression of immune checkpoint inhibitors. Results: Our results revealed the significant upregulation of cancer-related genes in primary tumors compared to their matched-paired brain metastases (adj. p ≤ 0.05). We found that upregulated differentially expressed genes in breast cancer brain metastasis (BM-BC) and brain metastasis from lung adenocarcinoma (BM-LUAD) were associated with the metabolic stress pathway, particularly related to the glycolysis. Additionally, we found that the upregulated genes in BM-BC and BM-LUAD played roles in immune response regulation, tumor growth, and proliferation. Importantly, we identified high expression of the immune checkpoint VTCN1 in BM-BC, and VISTA, IDO1, NT5E, and HDAC3 in BM-LUAD. Validation using immunohistochemistry further supported these findings. Conclusion: In conclusion, the findings highlight the significance of using matched-paired samples to identify cancer lineage-specific therapies that may improve brain metastasis patients outcomes.\"\n",
"!Series_overall_design\t\"RNA was extracted from FFPE samples of (primary LUAD and their matched paired brain metastasis n=22, primary BC and their matched paired brain metastasis n=22)\"\n",
"Sample Characteristics Dictionary:\n",
"{0: ['age at diagnosis: 49', 'age at diagnosis: 44', 'age at diagnosis: 41', 'age at diagnosis: 40', 'age at diagnosis: 48', 'age at diagnosis: 42', 'age at diagnosis: 47', 'age at diagnosis: 53', 'age at diagnosis: 74', 'age at diagnosis: 58', 'age at diagnosis: 51', 'age at diagnosis: 55', 'age at diagnosis: 46', 'age at diagnosis: 59', 'age at diagnosis: 50', 'age at diagnosis: 57', 'age at diagnosis: 60', 'age at diagnosis: 69', 'age at diagnosis: n.a.', 'age at diagnosis: 65', 'age at diagnosis: 37', 'age at diagnosis: 63', 'age at diagnosis: 70', 'age at diagnosis: 66', 'age at diagnosis: 64'], 1: ['Sex: female', 'Sex: male'], 2: ['histology: TNBC', 'histology: ER+ PR+ HER2-', 'histology: Unknown', 'histology: ER- PR- HER2+', 'histology: ER+ PR-HER2+', 'histology: ER+ PR- HER2-', 'histology: ER- PR+ HER2-', 'histology: adenocaricnoma'], 3: ['smoking status: n.a', 'smoking status: former-smoker', 'smoking status: smoker', 'smoking status: Never smoking', 'smoking status: unknown', 'smoking status: former-roker'], 4: ['treatment after surgery of bm: surgery + chemotherpy', 'treatment after surgery of bm: surgery + chemotherpy + Radiotherapy', 'treatment after surgery of bm: surgery + chemotherapy + Radiotherapy', 'treatment after surgery of bm: surgery', 'treatment after surgery of bm: surgery + chemotherapy + Radiotherapy', 'treatment after surgery of bm: surgery + chemotherapy', 'treatment after surgery of bm: surgery + chemotherpy + Radiotherapy', 'treatment after surgery of bm: surgery + chemotheapy + Radiotherapy', 'treatment after surgery of bm: Chemoterapy', 'treatment after surgery of bm: Radiotherapy & Chemoterapy', 'treatment after surgery of bm: Radiotherapy', 'treatment after surgery of bm: Other', 'treatment after surgery of bm: Surgery & Chemotherapy & Radiotherapy', 'treatment after surgery of bm: surgery & Radiotherapy', 'treatment after surgery of bm: surgery & Radiochemotherapy', 'treatment after surgery of bm: No treatment', 'treatment after surgery of bm: WBRT', 'treatment after surgery of bm: SRT']}\n"
]
}
],
"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": "345abae8",
"metadata": {},
"source": [
"### Step 2: Dataset Analysis and Clinical Feature Extraction"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "d14a6b01",
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-25T07:02:29.554176Z",
"iopub.status.busy": "2025-03-25T07:02:29.554062Z",
"iopub.status.idle": "2025-03-25T07:02:29.579894Z",
"shell.execute_reply": "2025-03-25T07:02:29.579353Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Preview of selected clinical data:\n",
"{'GSM7920782': [1.0, 49.0, 0.0], 'GSM7920783': [1.0, 44.0, 0.0], 'GSM7920784': [nan, 41.0, 0.0], 'GSM7920785': [1.0, 40.0, 0.0], 'GSM7920786': [1.0, 48.0, 0.0], 'GSM7920787': [nan, 42.0, 0.0], 'GSM7920788': [1.0, 47.0, 0.0], 'GSM7920789': [1.0, 53.0, 0.0], 'GSM7920790': [1.0, 41.0, 0.0], 'GSM7920791': [1.0, 74.0, 0.0], 'GSM7920792': [1.0, 58.0, 0.0], 'GSM7920793': [1.0, 51.0, 0.0], 'GSM7920794': [1.0, 55.0, 0.0], 'GSM7920795': [nan, 46.0, 0.0], 'GSM7920796': [1.0, 46.0, 0.0], 'GSM7920797': [1.0, 48.0, 0.0], 'GSM7920798': [1.0, 44.0, 0.0], 'GSM7920799': [1.0, 49.0, 0.0], 'GSM7920800': [1.0, 59.0, 0.0], 'GSM7920801': [1.0, 50.0, 0.0], 'GSM7920802': [1.0, 74.0, 0.0], 'GSM7920803': [1.0, 46.0, 0.0], 'GSM7920804': [0.0, 40.0, 0.0], 'GSM7920805': [0.0, 57.0, 1.0], 'GSM7920806': [0.0, 60.0, 1.0], 'GSM7920807': [0.0, 55.0, 0.0], 'GSM7920808': [0.0, 69.0, 0.0], 'GSM7920809': [0.0, nan, 0.0], 'GSM7920810': [0.0, nan, 1.0], 'GSM7920811': [0.0, 57.0, 1.0], 'GSM7920812': [0.0, nan, 0.0], 'GSM7920813': [0.0, 65.0, 1.0], 'GSM7920814': [0.0, 37.0, 1.0], 'GSM7920815': [0.0, 46.0, 0.0], 'GSM7920816': [0.0, 63.0, 1.0], 'GSM7920817': [0.0, 60.0, 1.0], 'GSM7920818': [0.0, 58.0, 0.0], 'GSM7920819': [0.0, 70.0, 0.0], 'GSM7920820': [0.0, 66.0, 0.0], 'GSM7920821': [0.0, 64.0, 1.0], 'GSM7920822': [0.0, 60.0, 1.0], 'GSM7920823': [0.0, 50.0, 0.0], 'GSM7920824': [0.0, 66.0, 1.0], 'GSM7920825': [0.0, 74.0, 1.0]}\n",
"Clinical data saved to ../../output/preprocess/Breast_Cancer/clinical_data/GSE248830.csv\n"
]
}
],
"source": [
"# 1. Gene Expression Data Availability\n",
"# Based on the background information, this appears to be gene expression data\n",
"# The summary mentions \"Targeted gene expression profiles\" using nCounter PanCancer IO 360™ Panel\n",
"is_gene_available = True\n",
"\n",
"# 2. Variable Availability and Data Type Conversion\n",
"\n",
"# 2.1 Data Availability\n",
"# For trait, we can use histology which contains breast cancer information\n",
"trait_row = 2 # histology\n",
"age_row = 0 # age at diagnosis\n",
"gender_row = 1 # Sex\n",
"\n",
"# 2.2 Data Type Conversion Functions\n",
"\n",
"def convert_trait(value):\n",
" \"\"\"Convert breast cancer histology to binary (1 for breast cancer, 0 for others)\"\"\"\n",
" if value is None or 'unknown' in value.lower():\n",
" return None\n",
" \n",
" if ':' in value:\n",
" value = value.split(':', 1)[1].strip()\n",
" \n",
" # If it's adenocarcinoma (lung cancer), it's not breast cancer\n",
" if 'adenocaricnoma' in value.lower():\n",
" return 0\n",
" \n",
" # If it contains any breast cancer markers, it's breast cancer\n",
" if any(marker in value.lower() for marker in ['tnbc', 'er+', 'er-', 'pr+', 'pr-', 'her2+', 'her2-']):\n",
" return 1\n",
" \n",
" return None\n",
"\n",
"def convert_age(value):\n",
" \"\"\"Convert age to continuous numeric value\"\"\"\n",
" if value is None:\n",
" return None\n",
" \n",
" if ':' in value:\n",
" value = value.split(':', 1)[1].strip()\n",
" \n",
" if value.lower() in ['n.a', 'n.a.', 'unknown']:\n",
" return None\n",
" \n",
" try:\n",
" return float(value)\n",
" except ValueError:\n",
" return None\n",
"\n",
"def convert_gender(value):\n",
" \"\"\"Convert gender to binary (0 for female, 1 for male)\"\"\"\n",
" if value is None:\n",
" return None\n",
" \n",
" if ':' in value:\n",
" value = value.split(':', 1)[1].strip().lower()\n",
" \n",
" if value == 'female':\n",
" return 0\n",
" elif value == 'male':\n",
" return 1\n",
" else:\n",
" return None\n",
"\n",
"# 3. Save Metadata\n",
"# Determine if trait data is available\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\n",
"if trait_row is not None:\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 data\n",
" preview = preview_df(selected_clinical_df)\n",
" print(\"Preview of selected clinical data:\")\n",
" print(preview)\n",
" \n",
" # Save the clinical data to CSV\n",
" 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": "1fc1a34f",
"metadata": {},
"source": [
"### Step 3: Gene Data Extraction"
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "d2caea7d",
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-25T07:02:29.581408Z",
"iopub.status.busy": "2025-03-25T07:02:29.581294Z",
"iopub.status.idle": "2025-03-25T07:02:29.596602Z",
"shell.execute_reply": "2025-03-25T07:02:29.596141Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"SOFT file: ../../input/GEO/Breast_Cancer/GSE248830/GSE248830_family.soft.gz\n",
"Matrix file: ../../input/GEO/Breast_Cancer/GSE248830/GSE248830_series_matrix.txt.gz\n",
"Found the matrix table marker at line 58\n",
"Gene data shape: (754, 44)\n",
"First 20 gene/probe identifiers:\n",
"['A2M', 'ACVR1C', 'ADAM12', 'ADGRE1', 'ADM', 'ADORA2A', 'AKT1', 'ALDOA', 'ALDOC', 'ANGPT1', 'ANGPT2', 'ANGPTL4', 'ANLN', 'APC', 'APH1B', 'API5', 'APLNR', 'APOE', 'APOL6', 'AQP9']\n"
]
}
],
"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 # Initially assume gene data is available\n",
"\n",
"# First check if the matrix file contains the expected marker\n",
"found_marker = False\n",
"marker_row = None\n",
"try:\n",
" with gzip.open(matrix_file, 'rt') as file:\n",
" for i, line in enumerate(file):\n",
" if \"!series_matrix_table_begin\" in line:\n",
" found_marker = True\n",
" marker_row = i\n",
" print(f\"Found the matrix table marker at line {i}\")\n",
" break\n",
" \n",
" if not found_marker:\n",
" print(\"Warning: Could not find '!series_matrix_table_begin' marker in the file.\")\n",
" is_gene_available = False\n",
" \n",
" # If marker was found, try to extract gene data\n",
" if is_gene_available:\n",
" try:\n",
" # Try using the library function\n",
" gene_data = get_genetic_data(matrix_file)\n",
" \n",
" if gene_data.shape[0] == 0:\n",
" print(\"Warning: Extracted gene data has 0 rows.\")\n",
" is_gene_available = False\n",
" else:\n",
" print(f\"Gene data shape: {gene_data.shape}\")\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 with get_genetic_data(): {e}\")\n",
" is_gene_available = False\n",
" \n",
" # If gene data extraction failed, examine file content to diagnose\n",
" if not is_gene_available:\n",
" print(\"Examining file content to diagnose the issue:\")\n",
" try:\n",
" with gzip.open(matrix_file, 'rt') as file:\n",
" # Print lines around the marker if found\n",
" if marker_row is not None:\n",
" for i, line in enumerate(file):\n",
" if i >= marker_row - 2 and i <= marker_row + 10:\n",
" print(f\"Line {i}: {line.strip()[:100]}...\")\n",
" if i > marker_row + 10:\n",
" break\n",
" else:\n",
" # If marker not found, print first 10 lines\n",
" for i, line in enumerate(file):\n",
" if i < 10:\n",
" print(f\"Line {i}: {line.strip()[:100]}...\")\n",
" else:\n",
" break\n",
" except Exception as e2:\n",
" print(f\"Error examining file: {e2}\")\n",
" \n",
"except Exception as e:\n",
" print(f\"Error processing file: {e}\")\n",
" is_gene_available = False\n",
"\n",
"# Update validation information if gene data extraction failed\n",
"if not is_gene_available:\n",
" print(\"Gene expression data could not be successfully extracted from this dataset.\")\n",
" # Update the validation record since gene data isn't available\n",
" is_trait_available = False # We already determined trait data isn't available in step 2\n",
" validate_and_save_cohort_info(is_final=False, cohort=cohort, info_path=json_path,\n",
" is_gene_available=is_gene_available, is_trait_available=is_trait_available)\n"
]
},
{
"cell_type": "markdown",
"id": "4f74afde",
"metadata": {},
"source": [
"### Step 4: Gene Identifier Review"
]
},
{
"cell_type": "code",
"execution_count": 5,
"id": "d87fae40",
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-25T07:02:29.598037Z",
"iopub.status.busy": "2025-03-25T07:02:29.597918Z",
"iopub.status.idle": "2025-03-25T07:02:29.600218Z",
"shell.execute_reply": "2025-03-25T07:02:29.599733Z"
}
},
"outputs": [],
"source": [
"# Looking at the gene identifiers from the output above:\n",
"# ['A2M', 'ACVR1C', 'ADAM12', 'ADGRE1', 'ADM', 'ADORA2A', 'AKT1', 'ALDOA', 'ALDOC', 'ANGPT1', 'ANGPT2', 'ANGPTL4', 'ANLN', 'APC', 'APH1B', 'API5', 'APLNR', 'APOE', 'APOL6', 'AQP9']\n",
"# These appear to be standard human gene symbols rather than probe IDs or other identifiers\n",
"# For example: A2M (Alpha-2-Macroglobulin), AKT1 (AKT Serine/Threonine Kinase 1), and APOE (Apolipoprotein E) are well-known gene symbols\n",
"\n",
"requires_gene_mapping = False\n"
]
},
{
"cell_type": "markdown",
"id": "bcc08b17",
"metadata": {},
"source": [
"### Step 5: Data Normalization and Linking"
]
},
{
"cell_type": "code",
"execution_count": 6,
"id": "589e8b40",
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-25T07:02:29.601696Z",
"iopub.status.busy": "2025-03-25T07:02:29.601587Z",
"iopub.status.idle": "2025-03-25T07:02:29.876240Z",
"shell.execute_reply": "2025-03-25T07:02:29.875764Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Gene data shape before normalization: (754, 44)\n",
"Gene data shape after normalization: (746, 44)\n",
"Normalized gene data saved to ../../output/preprocess/Breast_Cancer/gene_data/GSE248830.csv\n",
"Extracted clinical data shape: (3, 44)\n",
"Preview of clinical data (first 5 samples):\n",
" GSM7920782 GSM7920783 GSM7920784 GSM7920785 GSM7920786\n",
"Breast_Cancer 1.0 1.0 NaN 1.0 1.0\n",
"Age 49.0 44.0 41.0 40.0 48.0\n",
"Gender 0.0 0.0 0.0 0.0 0.0\n",
"Clinical data saved to ../../output/preprocess/Breast_Cancer/clinical_data/GSE248830.csv\n",
"Gene data columns (first 5): ['GSM7920782', 'GSM7920783', 'GSM7920784', 'GSM7920785', 'GSM7920786']\n",
"Clinical data columns (first 5): ['GSM7920782', 'GSM7920783', 'GSM7920784', 'GSM7920785', 'GSM7920786']\n",
"Found 44 common samples between gene and clinical data\n",
"Initial linked data shape: (44, 749)\n",
"Preview of linked data (first 5 rows, first 5 columns):\n",
" Breast_Cancer Age Gender A2M ACVR1C\n",
"GSM7920782 1.0 49.0 0.0 13.210102 5.128485\n",
"GSM7920783 1.0 44.0 0.0 13.237969 5.336850\n",
"GSM7920784 NaN 41.0 0.0 14.728878 5.611523\n",
"GSM7920785 1.0 40.0 0.0 15.399663 5.041711\n",
"GSM7920786 1.0 48.0 0.0 12.970464 6.342262\n",
"Linked data shape after handling missing values: (41, 749)\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"For the feature 'Breast_Cancer', the least common label is '1.0' with 19 occurrences. This represents 46.34% of the dataset.\n",
"The distribution of the feature 'Breast_Cancer' in this dataset is fine.\n",
"\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Quartiles for 'Age':\n",
" 25%: 48.0\n",
" 50% (Median): 55.078947368421055\n",
" 75%: 60.0\n",
"Min: 37.0\n",
"Max: 74.0\n",
"The distribution of the feature 'Age' in this dataset is fine.\n",
"\n",
"For the feature 'Gender', the least common label is '1.0' with 12 occurrences. This represents 29.27% of the dataset.\n",
"The distribution of the feature 'Gender' in this dataset is fine.\n",
"\n",
"Linked data saved to ../../output/preprocess/Breast_Cancer/GSE248830.csv\n"
]
}
],
"source": [
"# 1. Normalize gene symbols in the gene expression data\n",
"try:\n",
" # Make sure the directory exists\n",
" os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
" \n",
" # Use the gene_data variable from the previous step (don't try to load it from file)\n",
" print(f\"Gene data shape before normalization: {gene_data.shape}\")\n",
" \n",
" # Apply normalization to gene symbols\n",
" normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n",
" print(f\"Gene data shape after normalization: {normalized_gene_data.shape}\")\n",
" \n",
" # Save the normalized gene data\n",
" normalized_gene_data.to_csv(out_gene_data_file)\n",
" print(f\"Normalized gene data saved to {out_gene_data_file}\")\n",
" \n",
" # Use the normalized data for further processing\n",
" gene_data = normalized_gene_data\n",
" is_gene_available = True\n",
"except Exception as e:\n",
" print(f\"Error normalizing gene data: {e}\")\n",
" is_gene_available = False\n",
"\n",
"# 2. Load clinical data - respecting the analysis from Step 2\n",
"# From Step 2, we determined:\n",
"# trait_row = None # No Breast Cancer subtype data available\n",
"# age_row = 2\n",
"# gender_row = None\n",
"is_trait_available = trait_row is not None\n",
"\n",
"# Skip clinical feature extraction when trait_row is None\n",
"if is_trait_available:\n",
" try:\n",
" # Load the clinical data from file\n",
" soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
" background_info, clinical_data = get_background_and_clinical_data(matrix_file)\n",
" \n",
" # Extract clinical features\n",
" clinical_features = 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",
" age_row=age_row,\n",
" convert_age=convert_age\n",
" )\n",
" \n",
" print(f\"Extracted clinical data shape: {clinical_features.shape}\")\n",
" print(\"Preview of clinical data (first 5 samples):\")\n",
" print(clinical_features.iloc[:, :5])\n",
" \n",
" # Save the properly extracted clinical data\n",
" os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
" clinical_features.to_csv(out_clinical_data_file)\n",
" print(f\"Clinical data saved to {out_clinical_data_file}\")\n",
" except Exception as e:\n",
" print(f\"Error extracting clinical data: {e}\")\n",
" is_trait_available = False\n",
"else:\n",
" print(f\"No trait data ({trait}) available in this dataset based on previous analysis.\")\n",
"\n",
"# 3. Link clinical and genetic data if both are available\n",
"if is_trait_available and is_gene_available:\n",
" try:\n",
" # Debug the column names to ensure they match\n",
" print(f\"Gene data columns (first 5): {gene_data.columns[:5].tolist()}\")\n",
" print(f\"Clinical data columns (first 5): {clinical_features.columns[:5].tolist()}\")\n",
" \n",
" # Check for common sample IDs\n",
" common_samples = set(gene_data.columns).intersection(clinical_features.columns)\n",
" print(f\"Found {len(common_samples)} common samples between gene and clinical data\")\n",
" \n",
" if len(common_samples) > 0:\n",
" # Link the clinical and genetic data\n",
" linked_data = geo_link_clinical_genetic_data(clinical_features, gene_data)\n",
" print(f\"Initial linked data shape: {linked_data.shape}\")\n",
" \n",
" # Debug the trait values before handling missing values\n",
" print(\"Preview of linked data (first 5 rows, first 5 columns):\")\n",
" print(linked_data.iloc[:5, :5])\n",
" \n",
" # Handle 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",
" if linked_data.shape[0] > 0:\n",
" # Check for bias in trait and demographic features\n",
" is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n",
" \n",
" # Validate the data quality and save cohort info\n",
" note = \"Dataset contains gene expression data from triple negative breast cancer vs. luminal tumors, but no explicit breast cancer subtype labels in the sample characteristics.\"\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",
" # 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(\"Data not usable for the trait study - not saving final linked data.\")\n",
" else:\n",
" print(\"After handling missing values, no samples remain.\")\n",
" 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=True,\n",
" df=pd.DataFrame(),\n",
" note=\"No valid samples after handling missing values.\"\n",
" )\n",
" else:\n",
" print(\"No common samples found between gene expression and clinical data.\")\n",
" 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=True,\n",
" df=pd.DataFrame(),\n",
" note=\"No common samples between gene expression and clinical data.\"\n",
" )\n",
" except Exception as e:\n",
" print(f\"Error linking or processing data: {e}\")\n",
" 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=True, # Assume biased if there's an error\n",
" df=pd.DataFrame(), # Empty dataframe for metadata\n",
" note=f\"Error in data processing: {str(e)}\"\n",
" )\n",
"else:\n",
" # Create an empty DataFrame for metadata purposes\n",
" empty_df = pd.DataFrame()\n",
" \n",
" # We can't proceed with linking if either trait or gene data is missing\n",
" print(\"Cannot proceed with data linking due to missing trait or gene data.\")\n",
" 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=True, # Data is unusable if we're missing components\n",
" df=empty_df, # Empty dataframe for metadata\n",
" note=\"Dataset contains gene expression data from triple negative breast cancer vs. luminal tumors, but no explicit breast cancer subtype labels in the sample characteristics.\"\n",
" )"
]
}
],
"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
}
|