File size: 27,049 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 |
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"id": "92f789e9",
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-25T08:40:18.752457Z",
"iopub.status.busy": "2025-03-25T08:40:18.752357Z",
"iopub.status.idle": "2025-03-25T08:40:18.912903Z",
"shell.execute_reply": "2025-03-25T08:40:18.912567Z"
}
},
"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 = \"Eczema\"\n",
"cohort = \"GSE123086\"\n",
"\n",
"# Input paths\n",
"in_trait_dir = \"../../input/GEO/Eczema\"\n",
"in_cohort_dir = \"../../input/GEO/Eczema/GSE123086\"\n",
"\n",
"# Output paths\n",
"out_data_file = \"../../output/preprocess/Eczema/GSE123086.csv\"\n",
"out_gene_data_file = \"../../output/preprocess/Eczema/gene_data/GSE123086.csv\"\n",
"out_clinical_data_file = \"../../output/preprocess/Eczema/clinical_data/GSE123086.csv\"\n",
"json_path = \"../../output/preprocess/Eczema/cohort_info.json\"\n"
]
},
{
"cell_type": "markdown",
"id": "b4dd6f2f",
"metadata": {},
"source": [
"### Step 1: Initial Data Loading"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "5e01943d",
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-25T08:40:18.914324Z",
"iopub.status.busy": "2025-03-25T08:40:18.914185Z",
"iopub.status.idle": "2025-03-25T08:40:19.139742Z",
"shell.execute_reply": "2025-03-25T08:40:19.139380Z"
}
},
"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": "ca40a92c",
"metadata": {},
"source": [
"### Step 2: Dataset Analysis and Clinical Feature Extraction"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "69111922",
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-25T08:40:19.141111Z",
"iopub.status.busy": "2025-03-25T08:40:19.140996Z",
"iopub.status.idle": "2025-03-25T08:40:19.153124Z",
"shell.execute_reply": "2025-03-25T08:40:19.152850Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Preview of selected clinical features:\n",
"{0: [nan, 56.0, 1.0], 1: [nan, nan, nan], 2: [nan, 20.0, 0.0], 3: [nan, 51.0, nan], 4: [nan, 37.0, nan], 5: [1.0, 61.0, nan], 6: [0.0, 31.0, nan], 7: [nan, 41.0, nan], 8: [nan, 80.0, nan], 9: [nan, 53.0, nan], 10: [nan, 73.0, nan], 11: [nan, 60.0, nan], 12: [nan, 76.0, nan], 13: [nan, 77.0, nan], 14: [nan, 74.0, nan], 15: [nan, 69.0, nan], 16: [nan, 81.0, nan], 17: [nan, 70.0, nan], 18: [nan, 82.0, nan], 19: [nan, 67.0, nan], 20: [nan, 78.0, nan], 21: [nan, 72.0, nan], 22: [nan, 66.0, nan], 23: [nan, 36.0, nan], 24: [nan, 45.0, nan], 25: [nan, 65.0, nan], 26: [nan, 48.0, nan], 27: [nan, 50.0, nan], 28: [nan, 24.0, nan], 29: [nan, 42.0, nan]}\n",
"Clinical data saved to ../../output/preprocess/Eczema/clinical_data/GSE123086.csv\n"
]
}
],
"source": [
"# 1. Gene Expression Data Availability\n",
"# Based on the background information, this study used microarrays to analyze gene expression\n",
"# from CD4+ T cells, so gene expression data should be available\n",
"is_gene_available = True\n",
"\n",
"# 2. Variable Availability and Data Type Conversion\n",
"# 2.1 Data Availability\n",
"\n",
"# For trait (eczema):\n",
"# Looking at the sample characteristics, primary diagnosis is at index 1\n",
"# and includes \"ATOPIC_ECZEMA\" as one of the possible values\n",
"trait_row = 1\n",
"\n",
"# For age:\n",
"# Age information appears to be available at indices 3 and 4\n",
"age_row = 3\n",
"\n",
"# For gender:\n",
"# Gender information (Sex) appears to be at index 2\n",
"gender_row = 2\n",
"\n",
"# 2.2 Data Type Conversion\n",
"\n",
"def convert_trait(value):\n",
" \"\"\"Convert trait value to binary (1 for Eczema, 0 for control)\"\"\"\n",
" if not isinstance(value, str):\n",
" return None\n",
" \n",
" # Extract the value after the colon\n",
" if ':' in value:\n",
" value = value.split(':', 1)[1].strip()\n",
" \n",
" # Map values to binary\n",
" if 'ATOPIC_ECZEMA' in value:\n",
" return 1\n",
" elif 'HEALTHY_CONTROL' in value:\n",
" return 0\n",
" return None\n",
"\n",
"def convert_age(value):\n",
" \"\"\"Convert age value to continuous numeric value\"\"\"\n",
" if not isinstance(value, str):\n",
" return None\n",
" \n",
" # Extract the value after the colon\n",
" if ':' in value:\n",
" value = value.split(':', 1)[1].strip()\n",
" \n",
" # Try to convert to float\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 not isinstance(value, str):\n",
" return None\n",
" \n",
" # Extract the value after the colon\n",
" if ':' in value:\n",
" value = value.split(':', 1)[1].strip()\n",
" \n",
" # Map values to binary\n",
" if value.upper() == 'FEMALE':\n",
" return 0\n",
" elif value.upper() == 'MALE':\n",
" return 1\n",
" return None\n",
"\n",
"# 3. Save Metadata\n",
"# Check if trait data is available\n",
"is_trait_available = trait_row is not None\n",
"validate_and_save_cohort_info(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",
"# 4. Clinical Feature Extraction\n",
"if trait_row is not None:\n",
" # Use the sample characteristics dictionary to create a DataFrame\n",
" # This dictionary is assumed to be available from the previous step\n",
" sample_chars_dict = {0: ['cell type: CD4+ T cells'], \n",
" 1: ['primary diagnosis: ASTHMA', 'primary diagnosis: ATHEROSCLEROSIS', \n",
" 'primary diagnosis: BREAST_CANCER', 'primary diagnosis: CHRONIC_LYMPHOCYTIC_LEUKEMIA', \n",
" 'primary diagnosis: CROHN_DISEASE', 'primary diagnosis: ATOPIC_ECZEMA', \n",
" 'primary diagnosis: HEALTHY_CONTROL', 'primary diagnosis: INFLUENZA', \n",
" 'primary diagnosis: OBESITY', 'primary diagnosis: PSORIASIS', \n",
" 'primary diagnosis: SEASONAL_ALLERGIC_RHINITIS', 'primary diagnosis: TYPE_1_DIABETES', \n",
" 'primary diagnosis: ACUTE_TONSILLITIS', 'primary diagnosis: ULCERATIVE_COLITIS'], \n",
" 2: ['Sex: Male', 'diagnosis2: ATOPIC_ECZEMA', 'Sex: Female', 'diagnosis2: ATHEROSCLEROSIS', \n",
" 'diagnosis2: ASTHMA_OBESITY', 'diagnosis2: ASTHMA', \n",
" 'diagnosis2: ASTMHA_SEASONAL_ALLERGIC_RHINITIS', 'diagnosis2: OBESITY'], \n",
" 3: ['age: 56', 'Sex: Male', 'age: 20', 'age: 51', 'age: 37', 'age: 61', 'age: 31', \n",
" 'age: 41', 'age: 80', 'age: 53', 'age: 73', 'age: 60', 'age: 76', 'age: 77', \n",
" 'age: 74', 'age: 69', 'age: 81', 'age: 70', 'age: 82', 'age: 67', 'age: 78', \n",
" 'age: 72', 'age: 66', 'age: 36', 'age: 45', 'age: 65', 'age: 48', 'age: 50', \n",
" 'age: 24', 'age: 42'], \n",
" 4: [float('nan'), 'age: 63', 'age: 74', 'age: 49', 'age: 60', 'age: 68', 'age: 38', \n",
" 'age: 16', 'age: 12', 'age: 27']}\n",
" \n",
" clinical_data = pd.DataFrame.from_dict(sample_chars_dict, orient='index')\n",
" \n",
" try:\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 data\n",
" preview = preview_df(selected_clinical_df)\n",
" print(\"Preview of selected clinical features:\")\n",
" print(preview)\n",
" \n",
" # Save 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",
" \n",
" except Exception as e:\n",
" print(f\"An error occurred during clinical feature extraction: {e}\")\n"
]
},
{
"cell_type": "markdown",
"id": "17a943e2",
"metadata": {},
"source": [
"### Step 3: Gene Data Extraction"
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "bce8a868",
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-25T08:40:19.154298Z",
"iopub.status.busy": "2025-03-25T08:40:19.154198Z",
"iopub.status.idle": "2025-03-25T08:40:19.541334Z",
"shell.execute_reply": "2025-03-25T08:40:19.540962Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Matrix file found: ../../input/GEO/Eczema/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": "6db78aec",
"metadata": {},
"source": [
"### Step 4: Gene Identifier Review"
]
},
{
"cell_type": "code",
"execution_count": 5,
"id": "2d13c964",
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-25T08:40:19.542629Z",
"iopub.status.busy": "2025-03-25T08:40:19.542517Z",
"iopub.status.idle": "2025-03-25T08:40:19.544382Z",
"shell.execute_reply": "2025-03-25T08:40:19.544113Z"
}
},
"outputs": [],
"source": [
"# These identifiers are not human gene symbols. They appear to be numeric probe identifiers \n",
"# from a microarray platform, which need to be mapped to actual gene symbols.\n",
"\n",
"requires_gene_mapping = True\n"
]
},
{
"cell_type": "markdown",
"id": "4358bcc5",
"metadata": {},
"source": [
"### Step 5: Gene Annotation"
]
},
{
"cell_type": "code",
"execution_count": 6,
"id": "60d55c42",
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-25T08:40:19.545634Z",
"iopub.status.busy": "2025-03-25T08:40:19.545535Z",
"iopub.status.idle": "2025-03-25T08:40:25.189612Z",
"shell.execute_reply": "2025-03-25T08:40:25.189279Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"Gene annotation preview:\n",
"Columns in gene annotation: ['ID', 'ENTREZ_GENE_ID', 'SPOT_ID']\n",
"{'ID': ['1', '2', '3', '9', '10'], 'ENTREZ_GENE_ID': ['1', '2', '3', '9', '10'], 'SPOT_ID': [1.0, 2.0, 3.0, 9.0, 10.0]}\n",
"\n",
"Exploring SOFT file more thoroughly for gene information:\n",
"!Series_platform_id = GPL25864\n",
"!Platform_title = Agilent-039494 SurePrint G3 Human GE v2 8x60K Microarray 039381 (Entrez Gene ID version)\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"No explicit gene info patterns found\n",
"\n",
"Analyzing ENTREZ_GENE_ID column:\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Number of entries where ENTREZ_GENE_ID differs from ID: 3798412\n",
"Some ENTREZ_GENE_ID values differ from probe IDs - this could be useful for mapping\n",
" ID ENTREZ_GENE_ID SPOT_ID\n",
"24166 ID_REF VALUE NaN\n",
"24167 3553 15.35998289 NaN\n",
"24168 1609 10.05521694 NaN\n",
"24169 10112 4.22140954 NaN\n",
"24170 57827 8.437124629 NaN\n",
"\n",
"Looking for alternative annotation approaches:\n",
"- Checking for platform ID or accession number in SOFT file\n",
"\n",
"Preparing provisional gene mapping using ENTREZ_GENE_ID:\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Provisional mapping data shape: (3822578, 2)\n",
"{'ID': ['1', '2', '3', '9', '10'], 'Gene': ['1', '2', '3', '9', '10']}\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",
"# 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",
"# Let's explore the SOFT file more thoroughly to find gene symbols\n",
"print(\"\\nExploring SOFT file more thoroughly for gene information:\")\n",
"gene_info_patterns = []\n",
"entrez_to_symbol = {}\n",
"\n",
"with gzip.open(soft_file, 'rt') as f:\n",
" for i, line in enumerate(f):\n",
" if i < 1000: # Check header section for platform info\n",
" if '!Series_platform_id' in line or '!Platform_title' in line:\n",
" print(line.strip())\n",
" \n",
" # Look for gene-related columns and patterns in the file\n",
" if 'GENE_SYMBOL' in line or 'gene_symbol' in line or 'Symbol' in line:\n",
" gene_info_patterns.append(line.strip())\n",
" \n",
" # Extract a mapping using ENTREZ_GENE_ID if available\n",
" if len(gene_info_patterns) < 2 and 'ENTREZ_GENE_ID' in line and '\\t' in line:\n",
" parts = line.strip().split('\\t')\n",
" if len(parts) >= 2:\n",
" try:\n",
" # Attempt to add to mapping - assuming ENTREZ_GENE_ID could help with lookup\n",
" entrez_id = parts[1]\n",
" probe_id = parts[0]\n",
" if entrez_id.isdigit() and entrez_id != probe_id:\n",
" entrez_to_symbol[probe_id] = entrez_id\n",
" except:\n",
" pass\n",
" \n",
" if i > 10000 and len(gene_info_patterns) > 0: # Limit search but ensure we found something\n",
" break\n",
"\n",
"# Show some of the patterns found\n",
"if gene_info_patterns:\n",
" print(\"\\nFound gene-related patterns:\")\n",
" for pattern in gene_info_patterns[:5]:\n",
" print(pattern)\n",
"else:\n",
" print(\"\\nNo explicit gene info patterns found\")\n",
"\n",
"# Let's try to match the ENTREZ_GENE_ID to the probe IDs\n",
"print(\"\\nAnalyzing ENTREZ_GENE_ID column:\")\n",
"if 'ENTREZ_GENE_ID' in gene_annotation.columns:\n",
" # Check if ENTREZ_GENE_ID contains actual Entrez IDs (different from probe IDs)\n",
" gene_annotation['ENTREZ_GENE_ID'] = gene_annotation['ENTREZ_GENE_ID'].astype(str)\n",
" different_ids = (gene_annotation['ENTREZ_GENE_ID'] != gene_annotation['ID']).sum()\n",
" print(f\"Number of entries where ENTREZ_GENE_ID differs from ID: {different_ids}\")\n",
" \n",
" if different_ids > 0:\n",
" print(\"Some ENTREZ_GENE_ID values differ from probe IDs - this could be useful for mapping\")\n",
" # Show examples of differing values\n",
" diff_examples = gene_annotation[gene_annotation['ENTREZ_GENE_ID'] != gene_annotation['ID']].head(5)\n",
" print(diff_examples)\n",
" else:\n",
" print(\"ENTREZ_GENE_ID appears to be identical to probe ID - not useful for mapping\")\n",
"\n",
"# Search for additional annotation information in the dataset\n",
"print(\"\\nLooking for alternative annotation approaches:\")\n",
"print(\"- Checking for platform ID or accession number in SOFT file\")\n",
"\n",
"platform_id = None\n",
"with gzip.open(soft_file, 'rt') as f:\n",
" for i, line in enumerate(f):\n",
" if '!Platform_geo_accession' in line:\n",
" platform_id = line.split('=')[1].strip().strip('\"')\n",
" print(f\"Found platform GEO accession: {platform_id}\")\n",
" break\n",
" if i > 200:\n",
" break\n",
"\n",
"# If we don't find proper gene symbol mappings, prepare to use the ENTREZ_GENE_ID as is\n",
"if 'ENTREZ_GENE_ID' in gene_annotation.columns:\n",
" print(\"\\nPreparing provisional gene mapping using ENTREZ_GENE_ID:\")\n",
" mapping_data = gene_annotation[['ID', 'ENTREZ_GENE_ID']].copy()\n",
" mapping_data.rename(columns={'ENTREZ_GENE_ID': 'Gene'}, inplace=True)\n",
" print(f\"Provisional mapping data shape: {mapping_data.shape}\")\n",
" print(preview_df(mapping_data, n=5))\n",
"else:\n",
" print(\"\\nWarning: No suitable mapping column found for gene symbols\")\n"
]
},
{
"cell_type": "markdown",
"id": "3487c987",
"metadata": {},
"source": [
"### Step 6: Gene Identifier Mapping"
]
},
{
"cell_type": "code",
"execution_count": 7,
"id": "fed35a2e",
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-25T08:40:25.191261Z",
"iopub.status.busy": "2025-03-25T08:40:25.191142Z",
"iopub.status.idle": "2025-03-25T08:40:32.374731Z",
"shell.execute_reply": "2025-03-25T08:40:32.374207Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Mapping dataframe shape: (3822578, 2)\n",
"First few rows of mapping data:\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": [
"Number of unique probe IDs: 24167\n",
"Number of unique gene symbols: 1275651\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Gene-level data shape: (0, 166)\n",
"First few gene symbols:\n",
"Index([], dtype='object', name='Gene')\n",
"Gene data saved to ../../output/preprocess/Eczema/gene_data/GSE123086.csv\n"
]
}
],
"source": [
"# 1. Identify the column names for gene identifiers and gene symbols\n",
"# From the preview, we saw that ID is the probe identifier and ENTREZ_GENE_ID contains the gene IDs\n",
"id_column = 'ID' # Column with probe identifiers that match gene_data index\n",
"gene_column = 'ENTREZ_GENE_ID' # Column with gene identifiers (Entrez IDs in this case)\n",
"\n",
"# 2. Get gene mapping dataframe\n",
"mapping_df = get_gene_mapping(gene_annotation, id_column, gene_column)\n",
"print(f\"Mapping dataframe shape: {mapping_df.shape}\")\n",
"print(\"First few rows of mapping data:\")\n",
"print(mapping_df.head())\n",
"\n",
"# Check how many unique probe IDs and gene symbols are in the mapping\n",
"unique_probes = mapping_df['ID'].nunique()\n",
"unique_genes = mapping_df['Gene'].nunique()\n",
"print(f\"Number of unique probe IDs: {unique_probes}\")\n",
"print(f\"Number of unique gene symbols: {unique_genes}\")\n",
"\n",
"# 3. Apply gene mapping to convert probe-level data to gene-level data\n",
"gene_data = apply_gene_mapping(gene_data, mapping_df)\n",
"print(f\"Gene-level data shape: {gene_data.shape}\")\n",
"print(\"First few gene symbols:\")\n",
"print(gene_data.index[:10])\n",
"\n",
"# Save the processed gene data\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 data saved to {out_gene_data_file}\")"
]
}
],
"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
}
|