File size: 19,621 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 |
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"id": "e8c1a62a",
"metadata": {},
"outputs": [],
"source": [
"import sys\n",
"import os\n",
"sys.path.append(os.path.abspath(os.path.join(os.getcwd(), '../..')))\n",
"\n",
"# Path Configuration\n",
"from tools.preprocess import *\n",
"\n",
"# Processing context\n",
"trait = \"Chronic_kidney_disease\"\n",
"cohort = \"GSE180394\"\n",
"\n",
"# Input paths\n",
"in_trait_dir = \"../../input/GEO/Chronic_kidney_disease\"\n",
"in_cohort_dir = \"../../input/GEO/Chronic_kidney_disease/GSE180394\"\n",
"\n",
"# Output paths\n",
"out_data_file = \"../../output/preprocess/Chronic_kidney_disease/GSE180394.csv\"\n",
"out_gene_data_file = \"../../output/preprocess/Chronic_kidney_disease/gene_data/GSE180394.csv\"\n",
"out_clinical_data_file = \"../../output/preprocess/Chronic_kidney_disease/clinical_data/GSE180394.csv\"\n",
"json_path = \"../../output/preprocess/Chronic_kidney_disease/cohort_info.json\"\n"
]
},
{
"cell_type": "markdown",
"id": "6874114c",
"metadata": {},
"source": [
"### Step 1: Initial Data Loading"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "b9717358",
"metadata": {},
"outputs": [],
"source": [
"from tools.preprocess import *\n",
"# 1. Identify the paths to the SOFT file and the matrix file\n",
"soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
"\n",
"# 2. Read the matrix file to obtain background information and sample characteristics data\n",
"background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']\n",
"clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']\n",
"background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)\n",
"\n",
"# 3. Obtain the sample characteristics dictionary from the clinical dataframe\n",
"sample_characteristics_dict = get_unique_values_by_row(clinical_data)\n",
"\n",
"# 4. Explicitly print out all the background information and the sample characteristics dictionary\n",
"print(\"Background Information:\")\n",
"print(background_info)\n",
"print(\"Sample Characteristics Dictionary:\")\n",
"print(sample_characteristics_dict)\n"
]
},
{
"cell_type": "markdown",
"id": "42edf409",
"metadata": {},
"source": [
"### Step 2: Dataset Analysis and Clinical Feature Extraction"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "e6415012",
"metadata": {},
"outputs": [],
"source": [
"import pandas as pd\n",
"import numpy as np\n",
"import os\n",
"import re\n",
"from typing import Dict, List, Optional, Callable, Any, Tuple\n",
"\n",
"# 1. Gene Expression Data Availability\n",
"# From the background information, this is gene expression data from Affymetrix microarray\n",
"# \"Profiling was performed on Affymetrix ST2.1 microarray platform\"\n",
"is_gene_available = True\n",
"\n",
"# 2.1 Data Availability\n",
"# For trait:\n",
"# The sample group includes different kidney diseases and living donors\n",
"trait_row = 0 # This corresponds to 'sample group' in the sample characteristics\n",
"\n",
"# For age:\n",
"# No age information is available in the characteristics\n",
"age_row = None\n",
"\n",
"# For gender:\n",
"# No gender information is available in the characteristics\n",
"gender_row = None\n",
"\n",
"# 2.2 Data Type Conversion Functions\n",
"def convert_trait(value_str):\n",
" if not isinstance(value_str, str):\n",
" return None\n",
" \n",
" # Extract the value after colon\n",
" if \":\" in value_str:\n",
" value = value_str.split(\":\", 1)[1].strip()\n",
" else:\n",
" value = value_str.strip()\n",
" \n",
" # Binary classification: Living donor (0) vs CKD (1)\n",
" if \"Living donor\" in value:\n",
" return 0 # Control\n",
" elif any(term in value for term in [\"DN\", \"FSGS\", \"GN\", \"IgAN\", \"Nephritis\", \"Hypertensive Nephrosclerosis\", \n",
" \"Light-Chain Deposit Disease\", \"LN-WHO\", \"MCD\", \"MN\", \"CKD\", \n",
" \"Interstitial fibrosis\", \"Thin-BMD\"]):\n",
" return 1 # CKD patient\n",
" elif \"Tumor Nephrectomy\" in value:\n",
" # These are unaffected parts from tumor nephrectomy, likely normal kidney tissue\n",
" return 0\n",
" \n",
" return None # Unknown or undefined\n",
"\n",
"# The following functions are defined as placeholders since the data is not available\n",
"def convert_age(value_str):\n",
" return None\n",
"\n",
"def convert_gender(value_str):\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 validation\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",
"# We only process this step if clinical data is available\n",
"if trait_row is not None:\n",
" # Convert the sample characteristics dictionary to a DataFrame\n",
" # The dictionary is in the format {row_index: [values_for_samples]}\n",
" # We need to create a DataFrame where each row is a feature and each column is a sample\n",
" \n",
" # Sample characteristics from the previous output\n",
" sample_char_dict = {\n",
" 0: ['sample group: Living donor', \"sample group: 2' FSGS\", 'sample group: chronic Glomerulonephritis (GN) with infiltration by CLL', \n",
" 'sample group: DN', 'sample group: FGGS', 'sample group: FSGS', 'sample group: Hydronephrosis', 'sample group: IgAN', \n",
" 'sample group: Interstitial nephritis', 'sample group: Hypertensive Nephrosclerosis', \n",
" 'sample group: Light-Chain Deposit Disease (IgG lambda)', 'sample group: LN-WHO III', 'sample group: LN-WHO III+V', \n",
" 'sample group: LN-WHO IV', 'sample group: LN-WHO IV+V', 'sample group: LN-WHO V', 'sample group: LN-WHO-I/II', \n",
" 'sample group: MCD', 'sample group: MN', 'sample group: CKD with mod-severe Interstitial fibrosis', \n",
" 'sample group: Thin-BMD', 'sample group: Unaffected parts of Tumor Nephrectomy'],\n",
" 1: ['tissue: Tubuli from kidney biopsy']\n",
" }\n",
" \n",
" # Create a DataFrame from the dictionary\n",
" # Each key in the dictionary becomes a row in the DataFrame\n",
" clinical_data = pd.DataFrame.from_dict(sample_char_dict, orient='index')\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 data\n",
" preview = preview_df(selected_clinical_df)\n",
" print(\"Preview of selected clinical features:\")\n",
" for key, value in preview.items():\n",
" print(f\"{key}: {value}\")\n",
" \n",
" # Ensure output directory exists\n",
" os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
" \n",
" # Save the clinical data\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": "58d3a7ce",
"metadata": {},
"source": [
"### Step 3: Gene Data Extraction"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "df6d0124",
"metadata": {},
"outputs": [],
"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 # Assume gene data is available\n",
"\n",
"# Extract gene data\n",
"try:\n",
" # Extract gene data from the matrix file\n",
" gene_data = get_genetic_data(matrix_file)\n",
" print(f\"Gene data shape: {gene_data.shape}\")\n",
" \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: {e}\")\n",
" print(f\"File path: {matrix_file}\")\n",
" print(\"Please check if the file exists and contains the expected markers.\")\n"
]
},
{
"cell_type": "markdown",
"id": "65b70031",
"metadata": {},
"source": [
"### Step 4: Gene Identifier Review"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "93ad297a",
"metadata": {},
"outputs": [],
"source": [
"# Reviewing the gene identifiers\n",
"# The identifiers follow the pattern \"number_at\" which is characteristic of Affymetrix probe IDs\n",
"# These are not standard human gene symbols and need to be mapped\n",
"# For example, '100009613_at' is an Affymetrix probe ID, not a standard gene symbol like \"BRCA1\"\n",
"\n",
"requires_gene_mapping = True\n"
]
},
{
"cell_type": "markdown",
"id": "3c5252c1",
"metadata": {},
"source": [
"### Step 5: Gene Annotation"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "7c2face4",
"metadata": {},
"outputs": [],
"source": [
"# 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.\n",
"soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\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",
"# Get a more complete view to understand the annotation structure\n",
"print(\"\\nComplete sample of a few rows:\")\n",
"print(gene_annotation.iloc[:3].to_string())\n",
"\n",
"# Check if there are any columns that might contain gene information beyond what we've seen\n",
"potential_gene_columns = [col for col in gene_annotation.columns if \n",
" any(term in col.upper() for term in [\"GENE\", \"SYMBOL\", \"NAME\", \"ID\"])]\n",
"print(f\"\\nPotential gene-related columns: {potential_gene_columns}\")\n",
"\n",
"# Look for additional columns that might contain gene symbols\n",
"# Since we only have 'ID' and 'ENTREZ_GENE_ID', check if we need to use Entrez IDs for mapping\n",
"gene_id_col = 'ID'\n",
"gene_symbol_col = None\n",
"\n",
"# Check various potential column names for gene symbols\n",
"for col_name in ['GENE_SYMBOL', 'SYMBOL', 'GENE', 'GENE_NAME', 'GB_ACC']:\n",
" if col_name in gene_annotation.columns:\n",
" gene_symbol_col = col_name\n",
" break\n",
"\n",
"# If no dedicated symbol column is found, we'll need to use ENTREZ_GENE_ID\n",
"if gene_symbol_col is None and 'ENTREZ_GENE_ID' in gene_annotation.columns:\n",
" gene_symbol_col = 'ENTREZ_GENE_ID'\n",
" print(\"\\nNo direct gene symbol column found. Will use Entrez Gene IDs for mapping.\")\n",
"\n",
"if gene_id_col in gene_annotation.columns and gene_symbol_col is not None:\n",
" print(f\"\\nSample mappings from '{gene_id_col}' to '{gene_symbol_col}':\")\n",
" sample_mappings = gene_annotation[[gene_id_col, gene_symbol_col]].head(10)\n",
" print(sample_mappings)\n",
" \n",
" # Check for non-null mappings to confirm data quality\n",
" non_null_mappings = gene_annotation[[gene_id_col, gene_symbol_col]].dropna(subset=[gene_symbol_col])\n",
" print(f\"\\nNumber of probes with gene ID mappings: {len(non_null_mappings)}\")\n",
" print(f\"Sample of valid mappings:\")\n",
" print(non_null_mappings.head(5))\n",
"else:\n",
" print(\"Required mapping columns not found in the annotation data. Will need to explore alternative mapping approaches.\")\n"
]
},
{
"cell_type": "markdown",
"id": "9e599958",
"metadata": {},
"source": [
"### Step 6: Gene Identifier Mapping"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "5ef38c81",
"metadata": {},
"outputs": [],
"source": [
"# 1. Determine which column in gene annotation corresponds to gene identifiers and which to gene symbols\n",
"# From previous analysis, the gene annotation has 'ID' for probe IDs and 'ENTREZ_GENE_ID' for Entrez Gene IDs\n",
"probe_col = 'ID'\n",
"gene_col = 'ENTREZ_GENE_ID'\n",
"\n",
"# 2. Extract the two columns from the gene annotation dataframe to create the mapping dataframe\n",
"print(\"Creating gene mapping DataFrame...\")\n",
"mapping_data = get_gene_mapping(gene_annotation, probe_col, gene_col)\n",
"print(f\"Created mapping between {probe_col} and {gene_col}\")\n",
"print(f\"Mapping data shape: {mapping_data.shape}\")\n",
"print(\"Sample of mapping data:\")\n",
"print(mapping_data.head())\n",
"\n",
"# 3. We need to ensure our mapping works by examining the data formats\n",
"# Let's get a fresh copy of the gene expression data\n",
"gene_data = get_genetic_data(matrix_file)\n",
"print(f\"Gene expression data shape: {gene_data.shape}\")\n",
"\n",
"# Create a custom mapping approach\n",
"# First, get the overlap of probe IDs between expression data and annotation\n",
"common_probes = set(gene_data.index) & set(mapping_data['ID'])\n",
"print(f\"Number of probes in expression data: {len(gene_data.index)}\")\n",
"print(f\"Number of probes in mapping data: {len(mapping_data['ID'])}\")\n",
"print(f\"Number of common probes: {len(common_probes)}\")\n",
"\n",
"# Filter mapping to only include probes that exist in expression data\n",
"valid_mapping = mapping_data[mapping_data['ID'].isin(common_probes)]\n",
"print(f\"Valid mapping shape after filtering: {valid_mapping.shape}\")\n",
"\n",
"# Create a direct mapping from probe ID to Entrez Gene ID\n",
"probe_to_gene = {}\n",
"for idx, row in valid_mapping.iterrows():\n",
" probe_id = row['ID'] \n",
" gene_id = str(row['Gene']) # Convert to string\n",
" \n",
" if probe_id not in probe_to_gene:\n",
" probe_to_gene[probe_id] = []\n",
" probe_to_gene[probe_id].append(gene_id)\n",
"\n",
"# Create a new gene expression DataFrame\n",
"result = pd.DataFrame()\n",
"\n",
"# For each probe, distribute its expression to its mapped genes\n",
"for probe_id, gene_ids in probe_to_gene.items():\n",
" if not gene_ids: # Skip if no genes mapped\n",
" continue\n",
" \n",
" # Get probe expression data\n",
" probe_expr = gene_data.loc[probe_id]\n",
" \n",
" # Distribute expression equally among genes\n",
" weight = 1.0 / len(gene_ids)\n",
" \n",
" for gene_id in gene_ids:\n",
" # Skip empty gene IDs\n",
" if not gene_id or gene_id == 'nan':\n",
" continue\n",
" \n",
" # Add weighted expression to the gene\n",
" if gene_id in result.index:\n",
" result.loc[gene_id] += probe_expr * weight\n",
" else:\n",
" result.loc[gene_id] = probe_expr * weight\n",
"\n",
"print(f\"Converted probe-level data to gene-level expression\")\n",
"print(f\"Gene data shape after mapping: {result.shape}\")\n",
"\n",
"if not result.empty:\n",
" print(\"First 10 gene symbols after mapping:\")\n",
" print(result.index[:10].tolist())\n",
" \n",
" # Check for top genes with highest expression to verify data quality\n",
" print(\"\\nGenes with highest mean expression:\")\n",
" mean_expression = result.mean(axis=1).sort_values(ascending=False)\n",
" print(mean_expression.head(10))\n",
" \n",
" # Update gene_data with our processed result\n",
" gene_data = result\n",
"else:\n",
" print(\"\\nWarning: No genes were mapped. Check the mapping process.\")\n"
]
},
{
"cell_type": "markdown",
"id": "74e09ccc",
"metadata": {},
"source": [
"### Step 7: Gene Identifier Mapping"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "2b52a8fb",
"metadata": {},
"outputs": [],
"source": [
"# 1. Determine which column in gene annotation corresponds to gene identifiers and which to gene symbols\n",
"# From previous analysis, the gene annotation has 'ID' for probe IDs and 'ENTREZ_GENE_ID' for Entrez Gene IDs\n",
"prob_col = 'ID'\n",
"gene_col = 'ENTREZ_GENE_ID'\n",
"\n",
"# 2. Extract the two columns from the gene annotation dataframe to create the mapping dataframe\n",
"print(\"Creating gene mapping DataFrame...\")\n",
"mapping_data = get_gene_mapping(gene_annotation, prob_col, gene_col)\n",
"print(f\"Created mapping between {prob_col} and {gene_col}\")\n",
"print(f\"Mapping data shape: {mapping_data.shape}\")\n",
"print(\"Sample of mapping data:\")\n",
"print(mapping_data.head())\n",
"\n",
"# 3. Convert probe-level measurements to gene expression data by applying the gene mapping\n",
"print(\"Converting probe-level measurements to gene-level expression data...\")\n",
"\n",
"# Use the library function to convert probe-level data to gene-level expression data\n",
"gene_data = apply_gene_mapping(gene_data, mapping_data)\n",
"print(f\"Resulting gene expression data shape: {gene_data.shape}\")\n",
"\n",
"# Show a sample of the resulting gene data\n",
"print(\"Sample of gene expression data:\")\n",
"if not gene_data.empty:\n",
" print(\"First 10 gene symbols after mapping:\")\n",
" print(gene_data.index[:10].tolist())\n",
" \n",
" # Check for top genes with highest expression to verify data quality\n",
" print(\"\\nGenes with highest mean expression:\")\n",
" mean_expression = gene_data.mean(axis=1).sort_values(ascending=False)\n",
" print(mean_expression.head(10))\n",
"else:\n",
" print(\"WARNING: No genes were mapped successfully.\")"
]
}
],
"metadata": {},
"nbformat": 4,
"nbformat_minor": 5
}
|