File size: 33,825 Bytes
32677ff |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 |
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"id": "c02f8562",
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-25T08:35:04.781498Z",
"iopub.status.busy": "2025-03-25T08:35:04.781398Z",
"iopub.status.idle": "2025-03-25T08:35:04.943708Z",
"shell.execute_reply": "2025-03-25T08:35:04.943369Z"
}
},
"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 = \"Cystic_Fibrosis\"\n",
"cohort = \"GSE129168\"\n",
"\n",
"# Input paths\n",
"in_trait_dir = \"../../input/GEO/Cystic_Fibrosis\"\n",
"in_cohort_dir = \"../../input/GEO/Cystic_Fibrosis/GSE129168\"\n",
"\n",
"# Output paths\n",
"out_data_file = \"../../output/preprocess/Cystic_Fibrosis/GSE129168.csv\"\n",
"out_gene_data_file = \"../../output/preprocess/Cystic_Fibrosis/gene_data/GSE129168.csv\"\n",
"out_clinical_data_file = \"../../output/preprocess/Cystic_Fibrosis/clinical_data/GSE129168.csv\"\n",
"json_path = \"../../output/preprocess/Cystic_Fibrosis/cohort_info.json\"\n"
]
},
{
"cell_type": "markdown",
"id": "dfcf5971",
"metadata": {},
"source": [
"### Step 1: Initial Data Loading"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "4f3f951a",
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-25T08:35:04.945154Z",
"iopub.status.busy": "2025-03-25T08:35:04.945013Z",
"iopub.status.idle": "2025-03-25T08:35:05.005716Z",
"shell.execute_reply": "2025-03-25T08:35:05.005420Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Background Information:\n",
"!Series_title\t\"High-throughput screening for modulators of CFTR activity applying an organotypic functional assay based on genetically engineered Cystic Fibrosis disease-specific iPSCs\"\n",
"!Series_summary\t\"Organotypic culture systems from disease-specific induced pluripotent stem cells (iPSCs) exhibit obvious advantages compared to immortalized cell lines and primary cell cultures but implementation of iPSC-based high throughput (HT) assays is still technically challenging. Here we demonstrate the development and conduction of an organotypic HT Cl-/I- exchange assay using Cystic Fibrosis (CF) disease-specific iPSCs. The introduction of a halide sensitive YFP variant enabled automated quantitative measurement of Cystic Fibrosis Transmembrane Conductance Regulator (CFTR) function in iPSC-derived intestinal epithelia. CFTR function was partially rescued by treatment with VX-770 and VX-809, and seamless gene correction of the p.Phe508del mutation resulted in full restoration of CFTR function. The identification of a series of validated primary hits that improve the function of p.Phe508del CFTR from a library of ~ 42.500 chemical compounds demonstrates that the advantages of complex iPSC-derived culture systems for disease modelling can also be utilized for drug screening at a true HT format.\"\n",
"!Series_overall_design\t\"For detailed analysis of the differentiated hiPSC cell populations on day 15 of differentiation 32 samples in total were analyzed. Three independent donor lines were utilized (donor 1 and 6 CFTR WT, donor 2 (p.Phe508del)) and one isogenic gene corrected control line (donor 2 gene corrected-CFTR WT.) Samples from undifferentiated and differentiated cells represent biological replicates (n=3). As controls RNA from adult intestine, liver and colon was. Tissue samples are represented as technical replicates.\"\n",
"Sample Characteristics Dictionary:\n",
"{0: ['donor line: donor 2', 'donor line: donor 2 gene corrected', 'donor line: donor 6', 'donor line: donor 1', 'tissue: small intestine', 'tissue: colon', 'tissue: liver'], 1: ['cell type: pluripotent stem cell', 'developmental stage: adult'], 2: ['genotype: CFiPS (p.Phe508del)', 'genotype: CFiPS (p.Phe508del) gene corrected', 'genotype: iPS CFTR WT', 'genotype: CFTR WT'], 3: ['treatment: untreated/undifferentiated', 'treatment: day 15 of differentiation', nan]}\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": "fb80c221",
"metadata": {},
"source": [
"### Step 2: Dataset Analysis and Clinical Feature Extraction"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "cc17f829",
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-25T08:35:05.006916Z",
"iopub.status.busy": "2025-03-25T08:35:05.006688Z",
"iopub.status.idle": "2025-03-25T08:35:05.011063Z",
"shell.execute_reply": "2025-03-25T08:35:05.010778Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Clinical data file not found at ../../input/GEO/Cystic_Fibrosis/GSE129168/clinical_data.csv\n"
]
}
],
"source": [
"# 1. Gene Expression Data Availability\n",
"# This dataset contains gene expression data as it relates to CFTR function analysis\n",
"is_gene_available = True\n",
"\n",
"# 2. Variable Availability and Data Type Conversion\n",
"# 2.1 Data Availability\n",
"\n",
"# For trait (Cystic Fibrosis): \n",
"# We can infer this from row 2 which contains genotype information about CFTR mutations\n",
"trait_row = 2\n",
"\n",
"# For age: Age is not explicitly provided and cannot be reliably inferred\n",
"age_row = None\n",
"\n",
"# For gender: Gender is not specified in the sample characteristics\n",
"gender_row = None\n",
"\n",
"# 2.2 Data Type Conversion Functions\n",
"\n",
"def convert_trait(value):\n",
" \"\"\"Convert CFTR genotype to binary trait value for Cystic Fibrosis\"\"\"\n",
" if pd.isna(value):\n",
" return None\n",
" \n",
" # Extract value after colon if present\n",
" if ':' in value:\n",
" value = value.split(':', 1)[1].strip()\n",
" \n",
" # CFTR p.Phe508del mutation indicates CF\n",
" if 'p.Phe508del' in value and 'gene corrected' not in value:\n",
" return 1 # Has CF\n",
" else:\n",
" return 0 # Does not have CF (CFTR WT or gene corrected)\n",
"\n",
"def convert_age(value):\n",
" \"\"\"Placeholder function since age data is not available\"\"\"\n",
" return None\n",
"\n",
"def convert_gender(value):\n",
" \"\"\"Placeholder function since gender data is not available\"\"\"\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 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",
" # Read the clinical data file\n",
" clinical_data_path = os.path.join(in_cohort_dir, \"clinical_data.csv\")\n",
" if os.path.exists(clinical_data_path):\n",
" clinical_data = pd.read_csv(clinical_data_path)\n",
" \n",
" # Extract clinical features\n",
" selected_clinical_df = geo_select_clinical_features(\n",
" clinical_df=clinical_data,\n",
" trait=trait,\n",
" trait_row=trait_row,\n",
" convert_trait=convert_trait,\n",
" age_row=age_row,\n",
" convert_age=convert_age,\n",
" gender_row=gender_row,\n",
" convert_gender=convert_gender\n",
" )\n",
" \n",
" # Preview the dataframe\n",
" print(\"Preview of selected clinical features:\")\n",
" print(preview_df(selected_clinical_df))\n",
" \n",
" # Create directory if it doesn't exist\n",
" os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
" \n",
" # Save the clinical features dataframe\n",
" selected_clinical_df.to_csv(out_clinical_data_file, index=False)\n",
" print(f\"Clinical data saved to {out_clinical_data_file}\")\n",
" else:\n",
" print(f\"Clinical data file not found at {clinical_data_path}\")\n"
]
},
{
"cell_type": "markdown",
"id": "2b30c678",
"metadata": {},
"source": [
"### Step 3: Gene Data Extraction"
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "c6ab63f3",
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-25T08:35:05.012077Z",
"iopub.status.busy": "2025-03-25T08:35:05.011971Z",
"iopub.status.idle": "2025-03-25T08:35:05.080214Z",
"shell.execute_reply": "2025-03-25T08:35:05.079885Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Found data marker at line 73\n",
"Header line: \"ID_REF\"\t\"GSM3701915\"\t\"GSM3701916\"\t\"GSM3701917\"\t\"GSM3701918\"\t\"GSM3701919\"\t\"GSM3701920\"\t\"GSM3701921\"\t\"GSM3701922\"\t\"GSM3701923\"\t\"GSM3701924\"\t\"GSM3701925\"\t\"GSM3701926\"\t\"GSM3701927\"\t\"GSM3701928\"\t\"GSM3701929\"\t\"GSM3701930\"\t\"GSM3701931\"\t\"GSM3701932\"\t\"GSM3701933\"\t\"GSM3701934\"\t\"GSM3701935\"\t\"GSM3701936\"\t\"GSM3701937\"\t\"GSM3701938\"\t\"GSM3701939\"\t\"GSM3701940\"\t\"GSM3701941\"\t\"GSM3701942\"\t\"GSM3701943\"\t\"GSM3701944\"\t\"GSM3701945\"\t\"GSM3701946\"\n",
"First data line: \"A_23_P100001\"\t1884\t1647\t1959\t3268\t3346\t3801\t1817\t1418\t1572\t3890\t3638\t4027\t2250\t1820\t7073\t8081\t7426\t2005\t2163\t2350\t5476\t4873\t4716\t2374\t2490\t2381\t1399\t1333\t1287\t818\t984\t901\n",
"Index(['A_23_P100001', 'A_23_P100022', 'A_23_P100056', 'A_23_P100074',\n",
" 'A_23_P100127', 'A_23_P100141', 'A_23_P100189', 'A_23_P100196',\n",
" 'A_23_P100203', 'A_23_P100220', 'A_23_P100240', 'A_23_P10025',\n",
" 'A_23_P100292', 'A_23_P100315', 'A_23_P100326', 'A_23_P100344',\n",
" 'A_23_P100355', 'A_23_P100386', 'A_23_P100392', 'A_23_P100420'],\n",
" dtype='object', name='ID')\n"
]
}
],
"source": [
"# 1. Get the file paths for the SOFT file and matrix file\n",
"soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
"\n",
"# 2. First, let's examine the structure of the matrix file to understand its format\n",
"import gzip\n",
"\n",
"# Peek at the first few lines of the file to understand its structure\n",
"with gzip.open(matrix_file, 'rt') as file:\n",
" # Read first 100 lines to find the header structure\n",
" for i, line in enumerate(file):\n",
" if '!series_matrix_table_begin' in line:\n",
" print(f\"Found data marker at line {i}\")\n",
" # Read the next line which should be the header\n",
" header_line = next(file)\n",
" print(f\"Header line: {header_line.strip()}\")\n",
" # And the first data line\n",
" first_data_line = next(file)\n",
" print(f\"First data line: {first_data_line.strip()}\")\n",
" break\n",
" if i > 100: # Limit search to first 100 lines\n",
" print(\"Matrix table marker not found in first 100 lines\")\n",
" break\n",
"\n",
"# 3. Now try to get the genetic data with better error handling\n",
"try:\n",
" gene_data = get_genetic_data(matrix_file)\n",
" print(gene_data.index[:20])\n",
"except KeyError as e:\n",
" print(f\"KeyError: {e}\")\n",
" \n",
" # Alternative approach: manually extract the data\n",
" print(\"\\nTrying alternative approach to read the gene data:\")\n",
" with gzip.open(matrix_file, 'rt') as file:\n",
" # Find the start of the data\n",
" for line in file:\n",
" if '!series_matrix_table_begin' in line:\n",
" break\n",
" \n",
" # Read the headers and data\n",
" import pandas as pd\n",
" df = pd.read_csv(file, sep='\\t', index_col=0)\n",
" print(f\"Column names: {df.columns[:5]}\")\n",
" print(f\"First 20 row IDs: {df.index[:20]}\")\n",
" gene_data = df\n"
]
},
{
"cell_type": "markdown",
"id": "e010ed08",
"metadata": {},
"source": [
"### Step 4: Gene Identifier Review"
]
},
{
"cell_type": "code",
"execution_count": 5,
"id": "e53445f2",
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-25T08:35:05.081483Z",
"iopub.status.busy": "2025-03-25T08:35:05.081379Z",
"iopub.status.idle": "2025-03-25T08:35:05.083189Z",
"shell.execute_reply": "2025-03-25T08:35:05.082914Z"
}
},
"outputs": [],
"source": [
"# Based on the output, the gene identifiers in this dataset appear to be Agilent microarray probe IDs \n",
"# (format A_23_Pxxxxxx), not human gene symbols. These identifiers need to be mapped to gene symbols\n",
"# for proper analysis.\n",
"\n",
"requires_gene_mapping = True\n"
]
},
{
"cell_type": "markdown",
"id": "c657ad9e",
"metadata": {},
"source": [
"### Step 5: Gene Annotation"
]
},
{
"cell_type": "code",
"execution_count": 6,
"id": "0aa49076",
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-25T08:35:05.084298Z",
"iopub.status.busy": "2025-03-25T08:35:05.084203Z",
"iopub.status.idle": "2025-03-25T08:35:06.854120Z",
"shell.execute_reply": "2025-03-25T08:35:06.853735Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Gene annotation preview:\n",
"{'ID': ['A_23_P100001', 'A_23_P100022', 'A_23_P100056', 'A_23_P100074', 'A_23_P100127'], 'SPOT_ID': [nan, nan, nan, nan, nan], 'CONTROL_TYPE': ['FALSE', 'FALSE', 'FALSE', 'FALSE', 'FALSE'], 'REFSEQ': ['NM_207446', 'NM_014848', 'NM_194272', 'NM_020371', 'NM_170589'], 'GB_ACC': ['NM_207446', 'NM_014848', 'NM_194272', 'NM_020371', 'NM_170589'], 'LOCUSLINK_ID': [400451.0, 9899.0, 348093.0, 57099.0, 57082.0], 'GENE_SYMBOL': ['FAM174B', 'SV2B', 'RBPMS2', 'AVEN', 'KNL1'], 'GENE_NAME': ['family with sequence similarity 174 member B', 'synaptic vesicle glycoprotein 2B', 'RNA binding protein, mRNA processing factor 2', 'apoptosis and caspase activation inhibitor', 'kinetochore scaffold 1'], 'UNIGENE_ID': ['Hs.27373', 'Hs.21754', 'Hs.436518', 'Hs.555966', 'Hs.181855'], 'ENSEMBL_ID': ['ENST00000553393', nan, nan, 'ENST00000306730', 'ENST00000527044'], 'TIGR_ID': [nan, nan, nan, nan, nan], 'ACCESSION_STRING': ['ref|NM_207446|ens|ENST00000553393|ens|ENST00000327355|ref|XR_931815', 'ref|NM_014848|ref|NM_001323039|ref|NM_001323032|ref|NM_001323037', 'ref|NM_194272|ref|NR_138350|ref|NR_138363|ref|NR_138364', 'ref|NM_020371|ens|ENST00000306730|ref|XM_011521819|ref|XM_011521818', 'ref|NM_170589|ref|NM_144508|ens|ENST00000527044|ens|ENST00000533001'], 'CHROMOSOMAL_LOCATION': ['chr15:93160848-93160789', 'chr15:91838329-91838388', 'chr15:65032375-65032316', 'chr15:34158739-34158680', 'chr15:40917525-40917584'], 'CYTOBAND': ['hs|15q26.1', 'hs|15q26.1', 'hs|15q22.31', 'hs|15q14', 'hs|15q15.1'], 'DESCRIPTION': ['Homo sapiens family with sequence similarity 174 member B (FAM174B), mRNA [NM_207446]', 'Homo sapiens synaptic vesicle glycoprotein 2B (SV2B), transcript variant 1, mRNA [NM_014848]', 'Homo sapiens RNA binding protein, mRNA processing factor 2 (RBPMS2), transcript variant 1, mRNA [NM_194272]', 'Homo sapiens apoptosis and caspase activation inhibitor (AVEN), mRNA [NM_020371]', 'Homo sapiens kinetochore scaffold 1 (KNL1), transcript variant 1, mRNA [NM_170589]'], 'GO_ID': ['GO:0016021(integral component of membrane)', 'GO:0001669(acrosomal vesicle)|GO:0005515(protein binding)|GO:0005886(plasma membrane)|GO:0006836(neurotransmitter transport)|GO:0007268(chemical synaptic transmission)|GO:0008021(synaptic vesicle)|GO:0016020(membrane)|GO:0016021(integral component of membrane)|GO:0022857(transmembrane transporter activity)|GO:0030054(cell junction)|GO:0030672(synaptic vesicle membrane)|GO:0043005(neuron projection)|GO:0055085(transmembrane transport)', 'GO:0000398(mRNA splicing, via spliceosome)|GO:0003729(mRNA binding)|GO:0005515(protein binding)|GO:0005737(cytoplasm)|GO:0030514(negative regulation of BMP signaling pathway)|GO:0035614(snRNA stem-loop binding)|GO:0042803(protein homodimerization activity)|GO:0048557(embryonic digestive tract morphogenesis)|GO:0048661(positive regulation of smooth muscle cell proliferation)|GO:0051151(negative regulation of smooth muscle cell differentiation)', 'GO:0005515(protein binding)|GO:0005622(intracellular)|GO:0006915(apoptotic process)|GO:0012505(endomembrane system)|GO:0016020(membrane)|GO:0043066(negative regulation of apoptotic process)', 'GO:0000777(condensed chromosome kinetochore)|GO:0001669(acrosomal vesicle)|GO:0001675(acrosome assembly)|GO:0005515(protein binding)|GO:0005634(nucleus)|GO:0005654(nucleoplasm)|GO:0005829(cytosol)|GO:0008608(attachment of spindle microtubules to kinetochore)|GO:0010923(negative regulation of phosphatase activity)|GO:0016604(nuclear body)|GO:0034080(CENP-A containing nucleosome assembly)|GO:0034501(protein localization to kinetochore)|GO:0051301(cell division)'], 'SEQUENCE': ['ATCTCATGGAAAAGCTGGATTCCTCTGCCTTACGCAGAAACACCCGGGCTCCATCTGCCA', 'ATGTCGGCTGTGGAGGGTTAAAGGGATGAGGCTTTCCTTTGTTTAGCAAATCTGTTCACA', 'CCCTGTCAGATAAGTTTAATGTTTAGTTTGAGGCATGAAGAAGAAAAGGGTTTCCATTCT', 'GACCAGCCAGTTTACAAGCATGTCTCAAGCTAGTGTGTTCCATTATGCTCACAGCAGTAA', 'CGGTCTCTAGCAAAGATTCAGGCATTGGATCTGTTGCAGGTAAACTGAACCTAAGTCCTT']}\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. Use the 'preview_df' function from the library to preview the data and print out the results.\n",
"print(\"Gene annotation preview:\")\n",
"print(preview_df(gene_annotation))\n"
]
},
{
"cell_type": "markdown",
"id": "8c51b3c5",
"metadata": {},
"source": [
"### Step 6: Gene Identifier Mapping"
]
},
{
"cell_type": "code",
"execution_count": 7,
"id": "36ec5cbe",
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-25T08:35:06.855429Z",
"iopub.status.busy": "2025-03-25T08:35:06.855313Z",
"iopub.status.idle": "2025-03-25T08:35:06.982482Z",
"shell.execute_reply": "2025-03-25T08:35:06.982015Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Using probe IDs from column 'ID' and gene symbols from 'GENE_SYMBOL'\n",
"First few probe IDs: ['A_23_P100001', 'A_23_P100022', 'A_23_P100056', 'A_23_P100074', 'A_23_P100127']\n",
"First few gene symbols: ['FAM174B', 'SV2B', 'RBPMS2', 'AVEN', 'KNL1']\n",
"Created mapping dataframe with shape: (30331, 2)\n",
"Mapping preview: {'ID': ['A_23_P100001', 'A_23_P100022', 'A_23_P100056', 'A_23_P100074', 'A_23_P100127'], 'Gene': ['FAM174B', 'SV2B', 'RBPMS2', 'AVEN', 'KNL1']}\n",
"Generated gene expression data with shape: (20520, 32)\n",
"First 5 gene symbols in the gene expression data: ['A1BG', 'A1BG-AS1', 'A1CF', 'A2M', 'A2M-1']\n"
]
}
],
"source": [
"# 1. Identify the columns in gene annotation for mapping\n",
"probe_column = 'ID' # This is the probe identifier column that matches the gene expression index\n",
"gene_symbol_column = 'GENE_SYMBOL' # This is the column with the gene symbols we want to map to\n",
"\n",
"# Print relevant information for validation\n",
"print(f\"Using probe IDs from column '{probe_column}' and gene symbols from '{gene_symbol_column}'\")\n",
"print(f\"First few probe IDs: {gene_annotation[probe_column][:5].tolist()}\")\n",
"print(f\"First few gene symbols: {gene_annotation[gene_symbol_column][:5].tolist()}\")\n",
"\n",
"# 2. Create a mapping dataframe with these two columns\n",
"mapping_df = get_gene_mapping(gene_annotation, probe_column, gene_symbol_column)\n",
"print(f\"Created mapping dataframe with shape: {mapping_df.shape}\")\n",
"print(f\"Mapping preview: {preview_df(mapping_df)}\")\n",
"\n",
"# 3. Apply gene mapping to convert probe-level measurements to gene expression data\n",
"# This function handles the many-to-many mapping and proper distribution of expression values\n",
"gene_data = apply_gene_mapping(gene_data, mapping_df)\n",
"print(f\"Generated gene expression data with shape: {gene_data.shape}\")\n",
"print(f\"First 5 gene symbols in the gene expression data: {gene_data.index[:5].tolist()}\")\n"
]
},
{
"cell_type": "markdown",
"id": "0718db00",
"metadata": {},
"source": [
"### Step 7: Data Normalization and Linking"
]
},
{
"cell_type": "code",
"execution_count": 8,
"id": "42f5a015",
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-25T08:35:06.983916Z",
"iopub.status.busy": "2025-03-25T08:35:06.983807Z",
"iopub.status.idle": "2025-03-25T08:35:15.368133Z",
"shell.execute_reply": "2025-03-25T08:35:15.367780Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Normalized gene data shape: (20134, 32)"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"First few genes with their expression values after normalization:\n",
" GSM3701915 GSM3701916 GSM3701917 GSM3701918 GSM3701919 \\\n",
"Gene \n",
"A1BG 4010.0 4608.0 3222.0 865.0 889.0 \n",
"A1BG-AS1 197.0 166.0 205.0 122.0 101.0 \n",
"A1CF 7.0 8.0 7.0 5318.0 5750.0 \n",
"A2M 11.0 10.0 255.0 1018.0 1230.0 \n",
"A2M-AS1 224.0 215.0 218.0 222.0 265.0 \n",
"\n",
" GSM3701920 GSM3701921 GSM3701922 GSM3701923 GSM3701924 ... \\\n",
"Gene ... \n",
"A1BG 810.0 5707.0 4568.0 3420.0 841.0 ... \n",
"A1BG-AS1 155.0 147.0 179.0 178.0 163.0 ... \n",
"A1CF 5530.0 6.0 6.0 7.0 5716.0 ... \n",
"A2M 1378.0 5.0 10.0 83.0 1544.0 ... \n",
"A2M-AS1 288.0 174.0 227.0 208.0 216.0 ... \n",
"\n",
" GSM3701937 GSM3701938 GSM3701939 GSM3701940 GSM3701941 \\\n",
"Gene \n",
"A1BG 795.0 1465.0 1499.0 1616.0 1044.0 \n",
"A1BG-AS1 162.0 172.0 199.0 175.0 121.0 \n",
"A1CF 4115.0 2257.0 2270.0 2159.0 2176.0 \n",
"A2M 17876.0 70912.0 75801.0 69552.0 56138.0 \n",
"A2M-AS1 237.0 738.0 807.0 834.0 419.0 \n",
"\n",
" GSM3701942 GSM3701943 GSM3701944 GSM3701945 GSM3701946 \n",
"Gene \n",
"A1BG 990.0 953.0 200616.0 205414.0 203146.0 \n",
"A1BG-AS1 120.0 119.0 41.0 37.0 44.0 \n",
"A1CF 2090.0 2057.0 26980.0 27768.0 27456.0 \n",
"A2M 52852.0 49948.0 151045.0 157701.0 150048.0 \n",
"A2M-AS1 395.0 391.0 1355.0 1466.0 1380.0 \n",
"\n",
"[5 rows x 32 columns]\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Normalized gene data saved to ../../output/preprocess/Cystic_Fibrosis/gene_data/GSE129168.csv\n",
"Raw clinical data shape: (4, 33)\n",
"Clinical features:\n",
" GSM3701915 GSM3701916 GSM3701917 GSM3701918 GSM3701919 \\\n",
"Cystic_Fibrosis 1.0 1.0 1.0 1.0 1.0 \n",
"\n",
" GSM3701920 GSM3701921 GSM3701922 GSM3701923 GSM3701924 \\\n",
"Cystic_Fibrosis 1.0 0.0 0.0 0.0 0.0 \n",
"\n",
" ... GSM3701937 GSM3701938 GSM3701939 GSM3701940 \\\n",
"Cystic_Fibrosis ... 0.0 0.0 0.0 0.0 \n",
"\n",
" GSM3701941 GSM3701942 GSM3701943 GSM3701944 GSM3701945 \\\n",
"Cystic_Fibrosis 0.0 0.0 0.0 0.0 0.0 \n",
"\n",
" GSM3701946 \n",
"Cystic_Fibrosis 0.0 \n",
"\n",
"[1 rows x 32 columns]\n",
"Clinical features saved to ../../output/preprocess/Cystic_Fibrosis/clinical_data/GSE129168.csv\n",
"Linked data shape: (32, 20135)\n",
"Linked data preview (first 5 rows, first 5 columns):\n",
" Cystic_Fibrosis A1BG A1BG-AS1 A1CF A2M\n",
"GSM3701915 1.0 4010.0 197.0 7.0 11.0\n",
"GSM3701916 1.0 4608.0 166.0 8.0 10.0\n",
"GSM3701917 1.0 3222.0 205.0 7.0 255.0\n",
"GSM3701918 1.0 865.0 122.0 5318.0 1018.0\n",
"GSM3701919 1.0 889.0 101.0 5750.0 1230.0\n",
"Missing values before handling:\n",
" Trait (Cystic_Fibrosis) missing: 0 out of 32\n",
" Genes with >20% missing: 0\n",
" Samples with >5% missing genes: 0\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Data shape after handling missing values: (32, 20135)\n",
"For the feature 'Cystic_Fibrosis', the least common label is '1.0' with 6 occurrences. This represents 18.75% of the dataset.\n",
"The distribution of the feature 'Cystic_Fibrosis' in this dataset is fine.\n",
"\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Linked data saved to ../../output/preprocess/Cystic_Fibrosis/GSE129168.csv\n"
]
}
],
"source": [
"# 1. Normalize gene symbols in the gene expression data\n",
"normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n",
"print(f\"Normalized gene data shape: {normalized_gene_data.shape}\")\n",
"print(\"First few genes with their expression values after normalization:\")\n",
"print(normalized_gene_data.head())\n",
"\n",
"# Save the normalized gene data\n",
"os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
"normalized_gene_data.to_csv(out_gene_data_file)\n",
"print(f\"Normalized gene data saved to {out_gene_data_file}\")\n",
"\n",
"# 2. Extract clinical features directly from the matrix file\n",
"try:\n",
" # Get the file paths for the matrix file to extract clinical data\n",
" _, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
" \n",
" # Get raw clinical data from the matrix file\n",
" _, clinical_raw = get_background_and_clinical_data(matrix_file)\n",
" \n",
" # Verify clinical data structure\n",
" print(\"Raw clinical data shape:\", clinical_raw.shape)\n",
" \n",
" # Extract clinical features using the defined conversion functions\n",
" clinical_features = geo_select_clinical_features(\n",
" clinical_df=clinical_raw,\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",
" print(\"Clinical features:\")\n",
" print(clinical_features)\n",
" \n",
" # Save clinical features to file\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 features saved to {out_clinical_data_file}\")\n",
" \n",
" # 3. Link clinical and genetic data\n",
" linked_data = geo_link_clinical_genetic_data(clinical_features, normalized_gene_data)\n",
" print(f\"Linked data shape: {linked_data.shape}\")\n",
" print(\"Linked data preview (first 5 rows, first 5 columns):\")\n",
" print(linked_data.iloc[:5, :5])\n",
" \n",
" # 4. Handle missing values\n",
" print(\"Missing values before handling:\")\n",
" print(f\" Trait ({trait}) missing: {linked_data[trait].isna().sum()} out of {len(linked_data)}\")\n",
" if 'Age' in linked_data.columns:\n",
" print(f\" Age missing: {linked_data['Age'].isna().sum()} out of {len(linked_data)}\")\n",
" if 'Gender' in linked_data.columns:\n",
" print(f\" Gender missing: {linked_data['Gender'].isna().sum()} out of {len(linked_data)}\")\n",
" print(f\" Genes with >20% missing: {sum(linked_data.iloc[:, 1:].isna().mean() > 0.2)}\")\n",
" print(f\" Samples with >5% missing genes: {sum(linked_data.iloc[:, 1:].isna().mean(axis=1) > 0.05)}\")\n",
" \n",
" cleaned_data = handle_missing_values(linked_data, trait)\n",
" print(f\"Data shape after handling missing values: {cleaned_data.shape}\")\n",
" \n",
" # 5. Evaluate bias in trait and demographic features\n",
" is_trait_biased = False\n",
" if len(cleaned_data) > 0:\n",
" trait_biased, cleaned_data = judge_and_remove_biased_features(cleaned_data, trait)\n",
" is_trait_biased = trait_biased\n",
" else:\n",
" print(\"No data remains after handling missing values.\")\n",
" is_trait_biased = True\n",
" \n",
" # 6. Final validation and save\n",
" is_usable = validate_and_save_cohort_info(\n",
" is_final=True, \n",
" cohort=cohort, \n",
" info_path=json_path, \n",
" is_gene_available=True, \n",
" is_trait_available=True, \n",
" is_biased=is_trait_biased, \n",
" df=cleaned_data,\n",
" note=\"Dataset contains gene expression data comparing CFTR WT vs CFTR mutant (p.Phe508del) samples.\"\n",
" )\n",
" \n",
" # 7. Save if usable\n",
" if is_usable and len(cleaned_data) > 0:\n",
" os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n",
" cleaned_data.to_csv(out_data_file)\n",
" print(f\"Linked data saved to {out_data_file}\")\n",
" else:\n",
" print(\"Data was determined to be unusable or empty and was not saved\")\n",
" \n",
"except Exception as e:\n",
" print(f\"Error processing data: {e}\")\n",
" # Handle the error case by still recording cohort info\n",
" validate_and_save_cohort_info(\n",
" is_final=True, \n",
" cohort=cohort, \n",
" info_path=json_path, \n",
" is_gene_available=True, \n",
" is_trait_available=False, # Mark as not available due to processing issues\n",
" is_biased=True, \n",
" df=pd.DataFrame(), # Empty dataframe\n",
" note=f\"Error processing data: {str(e)}\"\n",
" )\n",
" print(\"Data was determined to be unusable and was not saved\")"
]
}
],
"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
}
|