File size: 28,377 Bytes
92d2f89 |
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 |
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"id": "545c2632",
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-25T06:39:42.070848Z",
"iopub.status.busy": "2025-03-25T06:39:42.070729Z",
"iopub.status.idle": "2025-03-25T06:39:42.233421Z",
"shell.execute_reply": "2025-03-25T06:39:42.233035Z"
}
},
"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 = \"Asthma\"\n",
"cohort = \"GSE123086\"\n",
"\n",
"# Input paths\n",
"in_trait_dir = \"../../input/GEO/Asthma\"\n",
"in_cohort_dir = \"../../input/GEO/Asthma/GSE123086\"\n",
"\n",
"# Output paths\n",
"out_data_file = \"../../output/preprocess/Asthma/GSE123086.csv\"\n",
"out_gene_data_file = \"../../output/preprocess/Asthma/gene_data/GSE123086.csv\"\n",
"out_clinical_data_file = \"../../output/preprocess/Asthma/clinical_data/GSE123086.csv\"\n",
"json_path = \"../../output/preprocess/Asthma/cohort_info.json\"\n"
]
},
{
"cell_type": "markdown",
"id": "97b90f91",
"metadata": {},
"source": [
"### Step 1: Initial Data Loading"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "0f58458f",
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-25T06:39:42.234936Z",
"iopub.status.busy": "2025-03-25T06:39:42.234785Z",
"iopub.status.idle": "2025-03-25T06:39:42.469400Z",
"shell.execute_reply": "2025-03-25T06:39:42.468992Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Background Information:\n",
"!Series_title\t\"A validated single-cell-based strategy to identify diagnostic and therapeutic targets in complex diseases [study of 13 diseases]\"\n",
"!Series_summary\t\"We conducted prospective clinical studies to validate the importance of CD4+ T cells in 13 diseases from the following ICD-10-CM chapters: Neoplasms (breast cancer, chronic lymphocytic leukemia); endocrine, nutritional and metabolic diseases (type I diabetes, obesity); diseases of the circulatory system (atherosclerosis); diseases of the respiratory system (acute tonsillitis, influenza, seasonal allergic rhinitis, asthma); diseases of the digestive system (Crohn’s disease [CD], ulcerative colitis [UC]); and diseases of the skin and subcutaneous tissue (atopic eczema, psoriatic diseases).\"\n",
"!Series_summary\t\"Study participants were recruited by clinical specialists based on diagnostic criteria defined by organizations representing each specialist’s discipline. Age and gender matched healthy controls (n = 127 and 39, respectively) were recruited in the Southeast region of Sweden from outpatient clinics at the University Hospital, Linköping; Ryhov County Hospital, Jönköping, a primary health care center in Jönköping; and a medical specialist unit for children in Värnamo. Study participants represented both urban and rural populations with an age range of 8–94 years. Patients with type I diabetes and obesity had an age range of 8–18 years. 12 patients had more than one diagnosis.\"\n",
"!Series_overall_design\t\"Total RNA was extracted using the AllPrep DNA/RNA Micro kit (Qiagen, Hilden, Germany; cat. no. 80284) according to the manufacturer’s instructions. RNA concentration and integrity were evaluated using the Agilent RNA 6000 Nano Kit (Agilent Technologies, Santa Clara, California, USA; cat. no. 5067-1511) on an Agilent 2100 Bioanalyzer (Agilent Technologies, Santa Clara, California, USA). Microarrays were then further computationally processed as described in One-Color Microarray-Based Gene Expression Analysis Low Input Quick Amp Labeling protocol (Agilent Technologies, Santa Clara, California, USA).\"\n",
"Sample Characteristics Dictionary:\n",
"{0: ['cell type: CD4+ T cells'], 1: ['primary diagnosis: ASTHMA', 'primary diagnosis: ATHEROSCLEROSIS', 'primary diagnosis: BREAST_CANCER', 'primary diagnosis: CHRONIC_LYMPHOCYTIC_LEUKEMIA', 'primary diagnosis: CROHN_DISEASE', 'primary diagnosis: ATOPIC_ECZEMA', 'primary diagnosis: HEALTHY_CONTROL', 'primary diagnosis: INFLUENZA', 'primary diagnosis: OBESITY', 'primary diagnosis: PSORIASIS', 'primary diagnosis: SEASONAL_ALLERGIC_RHINITIS', 'primary diagnosis: TYPE_1_DIABETES', 'primary diagnosis: ACUTE_TONSILLITIS', 'primary diagnosis: ULCERATIVE_COLITIS'], 2: ['Sex: Male', 'diagnosis2: ATOPIC_ECZEMA', 'Sex: Female', 'diagnosis2: ATHEROSCLEROSIS', 'diagnosis2: ASTHMA_OBESITY', 'diagnosis2: ASTHMA', 'diagnosis2: ASTMHA_SEASONAL_ALLERGIC_RHINITIS', 'diagnosis2: OBESITY'], 3: ['age: 56', 'Sex: Male', 'age: 20', 'age: 51', 'age: 37', 'age: 61', 'age: 31', 'age: 41', 'age: 80', 'age: 53', 'age: 73', 'age: 60', 'age: 76', 'age: 77', 'age: 74', 'age: 69', 'age: 81', 'age: 70', 'age: 82', 'age: 67', 'age: 78', 'age: 72', 'age: 66', 'age: 36', 'age: 45', 'age: 65', 'age: 48', 'age: 50', 'age: 24', 'age: 42'], 4: [nan, 'age: 63', 'age: 74', 'age: 49', 'age: 60', 'age: 68', 'age: 38', 'age: 16', 'age: 12', 'age: 27']}\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": "d9bd2b48",
"metadata": {},
"source": [
"### Step 2: Dataset Analysis and Clinical Feature Extraction"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "87551b3b",
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-25T06:39:42.470665Z",
"iopub.status.busy": "2025-03-25T06:39:42.470543Z",
"iopub.status.idle": "2025-03-25T06:39:42.475901Z",
"shell.execute_reply": "2025-03-25T06:39:42.475515Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Successfully identified data availability for GSE123086:\n",
"- Trait data available at row 1\n",
"- Age data available at row 3\n",
"- Gender data available at row 2\n",
"Clinical data processing will be performed in subsequent steps.\n"
]
}
],
"source": [
"# 1. Gene Expression Data Availability\n",
"# Based on the background information, this dataset contains gene expression data from CD4+ T cells\n",
"# analyzed through microarrays (Agilent)\n",
"is_gene_available = True\n",
"\n",
"# 2. Variable Availability and Data Type Conversion\n",
"# 2.1 Data Availability\n",
"\n",
"# For the trait (Asthma)\n",
"# Looking at index 1 for primary diagnosis, which includes ASTHMA\n",
"trait_row = 1\n",
"\n",
"# For age\n",
"# Looking at indexes 3 and 4, which contain age values\n",
"age_row = 3 # Primary age row\n",
"\n",
"# For gender\n",
"# Looking at indices 2 and 3, both contain gender information\n",
"gender_row = 2 # Primary gender row\n",
"\n",
"# 2.2 Data Type Conversion\n",
"\n",
"def convert_trait(value):\n",
" \"\"\"Convert trait value to binary (0=control, 1=Asthma)\"\"\"\n",
" if value is None or pd.isna(value):\n",
" return None\n",
" \n",
" # Extract value part after colon if present\n",
" if \":\" in value:\n",
" value = value.split(\":\", 1)[1].strip()\n",
" \n",
" # Check if the value indicates Asthma\n",
" if \"ASTHMA\" in value.upper():\n",
" return 1\n",
" elif \"HEALTHY_CONTROL\" in value.upper():\n",
" return 0\n",
" else:\n",
" return None # Other diseases\n",
"\n",
"def convert_age(value):\n",
" \"\"\"Convert age value to continuous numeric value\"\"\"\n",
" if value is None or pd.isna(value):\n",
" return None\n",
" \n",
" # Extract value part after colon if present\n",
" if \":\" in value:\n",
" value = value.split(\":\", 1)[1].strip()\n",
" \n",
" try:\n",
" return float(value)\n",
" except:\n",
" return None\n",
"\n",
"def convert_gender(value):\n",
" \"\"\"Convert gender value to binary (0=female, 1=male)\"\"\"\n",
" if value is None or pd.isna(value):\n",
" return None\n",
" \n",
" # Extract value part after colon if present\n",
" if \":\" in value:\n",
" value = value.split(\":\", 1)[1].strip()\n",
" \n",
" if \"MALE\" in value.upper():\n",
" return 1\n",
" elif \"FEMALE\" in value.upper():\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",
"# Initial filtering on dataset usability\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",
" # For this step, we'd typically load clinical_data from a file\n",
" # But since we don't have access to that file directly,\n",
" # we'll create a placeholder for now, and the actual processing\n",
" # will be done in a subsequent step once we have the actual data\n",
" \n",
" # Simply log that we've completed the identification phase\n",
" print(f\"Successfully identified data availability for {cohort}:\")\n",
" print(f\"- Trait data available at row {trait_row}\")\n",
" print(f\"- Age data available at row {age_row}\")\n",
" print(f\"- Gender data available at row {gender_row}\")\n",
" print(\"Clinical data processing will be performed in subsequent steps.\")\n"
]
},
{
"cell_type": "markdown",
"id": "908c394e",
"metadata": {},
"source": [
"### Step 3: Gene Data Extraction"
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "14759149",
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-25T06:39:42.477042Z",
"iopub.status.busy": "2025-03-25T06:39:42.476924Z",
"iopub.status.idle": "2025-03-25T06:39:42.891489Z",
"shell.execute_reply": "2025-03-25T06:39:42.890948Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Matrix file found: ../../input/GEO/Asthma/GSE123086/GSE123086_series_matrix.txt.gz\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Gene data shape: (22881, 166)\n",
"First 20 gene/probe identifiers:\n",
"Index(['1', '2', '3', '9', '10', '12', '13', '14', '15', '16', '18', '19',\n",
" '20', '21', '22', '23', '24', '25', '26', '27'],\n",
" dtype='object', name='ID')\n"
]
}
],
"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": "59b23b70",
"metadata": {},
"source": [
"### Step 4: Gene Identifier Review"
]
},
{
"cell_type": "code",
"execution_count": 5,
"id": "6e2db696",
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-25T06:39:42.892928Z",
"iopub.status.busy": "2025-03-25T06:39:42.892793Z",
"iopub.status.idle": "2025-03-25T06:39:42.895278Z",
"shell.execute_reply": "2025-03-25T06:39:42.894831Z"
}
},
"outputs": [],
"source": [
"# Review the gene identifiers\n",
"# These appear to be numeric identifiers, not standard human gene symbols.\n",
"# Typically, human gene symbols are alphabetic (like BRCA1, TP53) or alphanumeric (like CD4, IL6).\n",
"# The identifiers shown are purely numeric, suggesting they're likely probe IDs or some other internal identifiers\n",
"# that need to be mapped to actual gene symbols for biological interpretation.\n",
"\n",
"requires_gene_mapping = True\n"
]
},
{
"cell_type": "markdown",
"id": "2569868e",
"metadata": {},
"source": [
"### Step 5: Gene Annotation"
]
},
{
"cell_type": "code",
"execution_count": 6,
"id": "2128713f",
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-25T06:39:42.896597Z",
"iopub.status.busy": "2025-03-25T06:39:42.896477Z",
"iopub.status.idle": "2025-03-25T06:39:48.509522Z",
"shell.execute_reply": "2025-03-25T06:39:48.508890Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Platform title found: Agilent-039494 SurePrint G3 Human GE v2 8x60K Microarray 039381 (Entrez Gene ID version)\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"Gene annotation preview:\n",
"{'ID': ['1', '2', '3', '9', '10', '12', '13', '14', '15', '16'], 'ENTREZ_GENE_ID': ['1', '2', '3', '9', '10', '12', '13', '14', '15', '16'], 'SPOT_ID': [1.0, 2.0, 3.0, 9.0, 10.0, 12.0, 13.0, 14.0, 15.0, 16.0]}\n"
]
}
],
"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",
"# Check if there are any platforms defined in the SOFT file that might contain annotation data\n",
"with gzip.open(soft_file, 'rt') as f:\n",
" soft_content = f.read()\n",
"\n",
"# Look for platform sections in the SOFT file\n",
"platform_sections = re.findall(r'^!Platform_title\\s*=\\s*(.+)$', soft_content, re.MULTILINE)\n",
"if platform_sections:\n",
" print(f\"Platform title found: {platform_sections[0]}\")\n",
"\n",
"# Try to extract more annotation data by reading directly from the SOFT file\n",
"# Look for lines that might contain gene symbol mappings\n",
"symbol_pattern = re.compile(r'ID_REF\\s+Symbol|ID\\s+Gene Symbol', re.IGNORECASE)\n",
"annotation_lines = []\n",
"with gzip.open(soft_file, 'rt') as f:\n",
" for line in f:\n",
" if symbol_pattern.search(line):\n",
" annotation_lines.append(line)\n",
" # Collect the next few lines to see the annotation structure\n",
" for _ in range(10):\n",
" annotation_lines.append(next(f, ''))\n",
"\n",
"if annotation_lines:\n",
" print(\"Found potential gene symbol mappings:\")\n",
" for line in annotation_lines:\n",
" print(line.strip())\n",
"\n",
"# 2. Use the 'preview_df' function from the library to preview the data and print out the results.\n",
"print(\"\\nGene annotation preview:\")\n",
"print(preview_df(gene_annotation, n=10))\n",
"\n",
"# If we need an alternative source of mapping, check if there are any other annotation files in the cohort directory\n",
"cohort_files = os.listdir(in_cohort_dir)\n",
"annotation_files = [f for f in cohort_files if 'annotation' in f.lower() or 'platform' in f.lower()]\n",
"if annotation_files:\n",
" print(\"\\nAdditional annotation files found in the cohort directory:\")\n",
" for file in annotation_files:\n",
" print(file)\n"
]
},
{
"cell_type": "markdown",
"id": "cf97cc12",
"metadata": {},
"source": [
"### Step 6: Gene Identifier Mapping"
]
},
{
"cell_type": "code",
"execution_count": 7,
"id": "7b008462",
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-25T06:39:48.510954Z",
"iopub.status.busy": "2025-03-25T06:39:48.510823Z",
"iopub.status.idle": "2025-03-25T06:39:55.552879Z",
"shell.execute_reply": "2025-03-25T06:39:55.552338Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Gene annotation columns:\n",
"['ID', 'ENTREZ_GENE_ID', 'SPOT_ID']\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Gene mapping shape: (3822578, 2)\n",
"Gene mapping preview:\n",
" ID Gene\n",
"0 1 1\n",
"1 2 2\n",
"2 3 3\n",
"3 9 9\n",
"4 10 10\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Mapped gene expression data shape: (0, 166)\n",
"No genes were mapped. Checking for issues...\n",
"Expression data has 0 unique probe IDs\n",
"Mapping data has 24167 unique probe IDs\n",
"Overlap between the two: 0 probe IDs\n"
]
}
],
"source": [
"# 1. Analyze which columns in gene_annotation match the gene identifiers in gene_data\n",
"# From the platform title, we know this uses Entrez Gene IDs\n",
"# We need to extract these properly for mapping\n",
"\n",
"# Check gene_annotation structure\n",
"print(\"Gene annotation columns:\")\n",
"print(gene_annotation.columns.tolist())\n",
"\n",
"# Create a proper mapping dataframe using Entrez Gene IDs\n",
"probe_col = 'ID'\n",
"gene_col = 'ENTREZ_GENE_ID'\n",
"\n",
"# 2. Get the gene mapping dataframe by extracting the two relevant columns\n",
"gene_mapping = gene_annotation[[probe_col, gene_col]].copy()\n",
"gene_mapping.columns = ['ID', 'Gene'] # Rename to match required format for apply_gene_mapping\n",
"gene_mapping = gene_mapping.dropna() # Remove rows with missing values\n",
"gene_mapping = gene_mapping.astype({'ID': 'str', 'Gene': 'str'}) # Ensure proper types\n",
"\n",
"print(f\"Gene mapping shape: {gene_mapping.shape}\")\n",
"print(\"Gene mapping preview:\")\n",
"print(gene_mapping.head())\n",
"\n",
"# 3. Convert probe-level measurements to gene expression data using the library function\n",
"gene_data = apply_gene_mapping(gene_data, gene_mapping)\n",
"print(f\"Mapped gene expression data shape: {gene_data.shape}\")\n",
"\n",
"# Check if we have valid gene data\n",
"if gene_data.shape[0] > 0:\n",
" print(\"First few gene identifiers after mapping:\")\n",
" print(gene_data.index[:10].tolist())\n",
"else:\n",
" print(\"No genes were mapped. Checking for issues...\")\n",
" \n",
" # Check overlap between probe IDs in expression data and mapping data\n",
" expr_ids = set(gene_data.index.astype(str))\n",
" map_ids = set(gene_mapping['ID'].astype(str))\n",
" overlap = expr_ids.intersection(map_ids)\n",
" \n",
" print(f\"Expression data has {len(expr_ids)} unique probe IDs\")\n",
" print(f\"Mapping data has {len(map_ids)} unique probe IDs\")\n",
" print(f\"Overlap between the two: {len(overlap)} probe IDs\")\n",
" \n",
" # Sample overlapping IDs\n",
" if overlap:\n",
" print(\"Sample overlapping IDs:\", list(overlap)[:5])\n"
]
},
{
"cell_type": "markdown",
"id": "c5fdd06b",
"metadata": {},
"source": [
"### Step 7: Gene Identifier Mapping"
]
},
{
"cell_type": "code",
"execution_count": 8,
"id": "993704d2",
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-25T06:39:55.554413Z",
"iopub.status.busy": "2025-03-25T06:39:55.554161Z",
"iopub.status.idle": "2025-03-25T06:40:02.853775Z",
"shell.execute_reply": "2025-03-25T06:40:02.853406Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Original gene data shape: (22881, 166)\n",
"Gene data index name: ID\n",
"First few probe IDs: ['1', '2', '3', '9', '10']\n",
"\n",
"Checking gene mapping again:\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Gene mapping shape: (3822578, 2)\n",
"Gene mapping sample: [{'ID': '1', 'Gene': '1'}, {'ID': '2', 'Gene': '2'}, {'ID': '3', 'Gene': '3'}, {'ID': '9', 'Gene': '9'}, {'ID': '10', 'Gene': '10'}]\n",
"\n",
"Reset gene data columns: ['ID', 'GSM3494884', 'GSM3494885', 'GSM3494886', 'GSM3494887', 'GSM3494888', 'GSM3494889', 'GSM3494890', 'GSM3494891', 'GSM3494892', 'GSM3494893', 'GSM3494894', 'GSM3494895', 'GSM3494896', 'GSM3494897', 'GSM3494898', 'GSM3494899', 'GSM3494900', 'GSM3494901', 'GSM3494902', 'GSM3494903', 'GSM3494904', 'GSM3494905', 'GSM3494906', 'GSM3494907', 'GSM3494908', 'GSM3494909', 'GSM3494910', 'GSM3494911', 'GSM3494912', 'GSM3494913', 'GSM3494914', 'GSM3494915', 'GSM3494916', 'GSM3494917', 'GSM3494918', 'GSM3494919', 'GSM3494920', 'GSM3494921', 'GSM3494922', 'GSM3494923', 'GSM3494924', 'GSM3494925', 'GSM3494926', 'GSM3494927', 'GSM3494928', 'GSM3494929', 'GSM3494930', 'GSM3494931', 'GSM3494932', 'GSM3494933', 'GSM3494934', 'GSM3494935', 'GSM3494936', 'GSM3494937', 'GSM3494938', 'GSM3494939', 'GSM3494940', 'GSM3494941', 'GSM3494942', 'GSM3494943', 'GSM3494944', 'GSM3494945', 'GSM3494946', 'GSM3494947', 'GSM3494948', 'GSM3494949', 'GSM3494950', 'GSM3494951', 'GSM3494952', 'GSM3494953', 'GSM3494954', 'GSM3494955', 'GSM3494956', 'GSM3494957', 'GSM3494958', 'GSM3494959', 'GSM3494960', 'GSM3494961', 'GSM3494962', 'GSM3494963', 'GSM3494964', 'GSM3494965', 'GSM3494966', 'GSM3494967', 'GSM3494968', 'GSM3494969', 'GSM3494970', 'GSM3494971', 'GSM3494972', 'GSM3494973', 'GSM3494974', 'GSM3494975', 'GSM3494976', 'GSM3494977', 'GSM3494978', 'GSM3494979', 'GSM3494980', 'GSM3494981', 'GSM3494982', 'GSM3494983', 'GSM3494984', 'GSM3494985', 'GSM3494986', 'GSM3494987', 'GSM3494988', 'GSM3494989', 'GSM3494990', 'GSM3494991', 'GSM3494992', 'GSM3494993', 'GSM3494994', 'GSM3494995', 'GSM3494996', 'GSM3494997', 'GSM3494998', 'GSM3494999', 'GSM3495000', 'GSM3495001', 'GSM3495002', 'GSM3495003', 'GSM3495004', 'GSM3495005', 'GSM3495006', 'GSM3495007', 'GSM3495008', 'GSM3495009', 'GSM3495010', 'GSM3495011', 'GSM3495012', 'GSM3495013', 'GSM3495014', 'GSM3495015', 'GSM3495016', 'GSM3495017', 'GSM3495018', 'GSM3495019', 'GSM3495020', 'GSM3495021', 'GSM3495022', 'GSM3495023', 'GSM3495024', 'GSM3495025', 'GSM3495026', 'GSM3495027', 'GSM3495028', 'GSM3495029', 'GSM3495030', 'GSM3495031', 'GSM3495032', 'GSM3495033', 'GSM3495034', 'GSM3495035', 'GSM3495036', 'GSM3495037', 'GSM3495038', 'GSM3495039', 'GSM3495040', 'GSM3495041', 'GSM3495042', 'GSM3495043', 'GSM3495044', 'GSM3495045', 'GSM3495046', 'GSM3495047', 'GSM3495048', 'GSM3495049']\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"Mapped gene expression data shape: (0, 166)\n",
"Still no genes mapped. Let's debug more thoroughly.\n",
"Expression data first few IDs: ['1', '2', '3', '9', '10']\n",
"Mapping data first few IDs: ['1', '2', '3', '9', '10']\n",
"Overlap count after string conversion: 22881\n",
"\n",
"Normalized gene data shape: (0, 166)\n"
]
}
],
"source": [
"# First, let's reload the gene data to ensure we're working with the original structure\n",
"gene_data = get_genetic_data(matrix_file)\n",
"print(f\"Original gene data shape: {gene_data.shape}\")\n",
"print(f\"Gene data index name: {gene_data.index.name}\")\n",
"print(f\"First few probe IDs: {gene_data.index[:5].tolist()}\")\n",
"\n",
"# In the previous step, the gene mapping data frame was created correctly\n",
"# The issue is with the probe IDs in the expression data vs. the mapping data\n",
"print(\"\\nChecking gene mapping again:\")\n",
"probe_col = 'ID'\n",
"gene_col = 'ENTREZ_GENE_ID'\n",
"\n",
"# Get the gene mapping dataframe \n",
"gene_mapping = gene_annotation[[probe_col, gene_col]].copy()\n",
"gene_mapping.columns = ['ID', 'Gene']\n",
"gene_mapping = gene_mapping.dropna()\n",
"gene_mapping = gene_mapping.astype({'ID': 'str', 'Gene': 'str'})\n",
"\n",
"print(f\"Gene mapping shape: {gene_mapping.shape}\")\n",
"print(f\"Gene mapping sample: {gene_mapping.head().to_dict('records')}\")\n",
"\n",
"# The issue might be that the gene_data's index is already named 'ID'\n",
"# Try to apply the mapping with the correct probe/gene relationship\n",
"gene_data_reset = gene_data.reset_index() # This should create a column 'ID' with the probe identifiers\n",
"print(f\"\\nReset gene data columns: {gene_data_reset.columns.tolist()}\")\n",
"\n",
"# Set the index back to 'ID' to ensure proper functionality with apply_gene_mapping\n",
"gene_data_reset.set_index('ID', inplace=True)\n",
"\n",
"# Now apply the gene mapping\n",
"gene_expression = apply_gene_mapping(gene_data_reset, gene_mapping)\n",
"print(f\"\\nMapped gene expression data shape: {gene_expression.shape}\")\n",
"\n",
"# Check the result\n",
"if gene_expression.shape[0] > 0:\n",
" print(\"First few gene identifiers after mapping:\")\n",
" print(gene_expression.index[:10].tolist())\n",
" # Update gene_data to contain the mapped expression data\n",
" gene_data = gene_expression\n",
"else:\n",
" print(\"Still no genes mapped. Let's debug more thoroughly.\")\n",
" # Check the first few IDs in both datasets to see the format difference\n",
" print(f\"Expression data first few IDs: {gene_data.index[:5].tolist()}\")\n",
" print(f\"Mapping data first few IDs: {gene_mapping['ID'].head(5).tolist()}\")\n",
" \n",
" # Try alternative mapping approach in case of formatting differences\n",
" # Create a set with string-converted IDs from both datasets\n",
" expr_ids_set = set(gene_data.index.astype(str).tolist())\n",
" map_ids_set = set(gene_mapping['ID'].astype(str).tolist())\n",
" overlap = expr_ids_set.intersection(map_ids_set)\n",
" print(f\"Overlap count after string conversion: {len(overlap)}\")\n",
" \n",
" # If there's still an issue, we'll normalize the gene IDs directly using extract_human_gene_symbols\n",
" # This uses the ENTREZ_GENE_ID which should contain gene identifiers\n",
" gene_data = normalize_gene_symbols_in_index(gene_data)\n",
" print(f\"\\nNormalized gene data shape: {gene_data.shape}\")"
]
}
],
"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
}
|