{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "83f9efec", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:19:41.925534Z", "iopub.status.busy": "2025-03-25T07:19:41.925114Z", "iopub.status.idle": "2025-03-25T07:19:42.088951Z", "shell.execute_reply": "2025-03-25T07:19:42.088526Z" } }, "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 = \"Kidney_Papillary_Cell_Carcinoma\"\n", "cohort = \"GSE48352\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Kidney_Papillary_Cell_Carcinoma\"\n", "in_cohort_dir = \"../../input/GEO/Kidney_Papillary_Cell_Carcinoma/GSE48352\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Kidney_Papillary_Cell_Carcinoma/GSE48352.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Kidney_Papillary_Cell_Carcinoma/gene_data/GSE48352.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Kidney_Papillary_Cell_Carcinoma/clinical_data/GSE48352.csv\"\n", "json_path = \"../../output/preprocess/Kidney_Papillary_Cell_Carcinoma/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "191e0179", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "cdc5dd47", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:19:42.090200Z", "iopub.status.busy": "2025-03-25T07:19:42.090059Z", "iopub.status.idle": "2025-03-25T07:19:42.151304Z", "shell.execute_reply": "2025-03-25T07:19:42.150914Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"DPYS as a potential diagnostic biomarker in hereditary and sporadic PRCC2\"\n", "!Series_summary\t\"Papillary renal cell carcinoma type 2 (PRCC2) is known to be very aggressive type of tumor without effictive therapy. Hereditary form of PRCC2 is caused by Fumarate Hydratase (FH) gene mutation that accompanied Hereditary Leiomyomatosis and Renal Cell Carcinoma (HLRCC) disorder. In sporadic form of PRCC2 the mutation of FH gene has not been reported. Both forms of tumors have the similar histopathological characteristics with poor survival prognosis.\"\n", "!Series_summary\t\"In this study, we profiled the gene expression of renal tumors and normal tissue from PRCC2 (hereditary and sporadic) patients in order to better understand commonalities and differences in the transcriptional landscape of PRCC2.\"\n", "!Series_overall_design\t\"Microarray gene expression profiling was performed on eight normal kidney tissue samples, five hereditary PRCC2 tumor tissue samples and 19 sporadic PRCC2 tumor tissue samples. Hereditary PRCC2 (HPRCC2) patients were confirmed by DNA sequencing of the FH gene.\"\n", "Sample Characteristics Dictionary:\n", "{0: ['tissue type: Normal', 'tissue type: Cancer'], 1: ['disease status: hereditary PRCC2', 'disease status: sporadic PRCC2']}\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": "3dd1dcab", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "53fe6a40", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:19:42.152559Z", "iopub.status.busy": "2025-03-25T07:19:42.152452Z", "iopub.status.idle": "2025-03-25T07:19:42.161392Z", "shell.execute_reply": "2025-03-25T07:19:42.161017Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Found clinical data file: ../../input/GEO/Kidney_Papillary_Cell_Carcinoma/GSE48352/GSE48352_series_matrix.txt.gz\n", "Error processing clinical data: Error tokenizing data. C error: Expected 2 fields in line 31, saw 33\n", "\n", "Skipping clinical data extraction step.\n" ] } ], "source": [ "# 1. Gene Expression Data Availability\n", "# Based on the Series_title and Series_overall_design information, this dataset is about gene expression profiling\n", "# of renal tumors (PRCC2). It explicitly mentions \"Microarray gene expression profiling\".\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "# For trait: Key 0 contains 'tissue type: Normal' and 'tissue type: Cancer'\n", "# This is our trait information for kidney papillary cell carcinoma\n", "trait_row = 0 \n", "\n", "# There's also key 1 with disease status information, but we'll focus on the primary \n", "# Normal vs Cancer distinction for the main trait\n", "\n", "# For age: Not available in the sample characteristics dictionary\n", "age_row = None\n", "\n", "# For gender: Not available in the sample characteristics dictionary\n", "gender_row = None\n", "\n", "# 2.2 Data Type Conversion\n", "def convert_trait(value):\n", " \"\"\"\n", " Convert the trait value to binary format.\n", " 0 for Normal tissue, 1 for Cancer tissue.\n", " \"\"\"\n", " if isinstance(value, str) and ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " if value.lower() == 'normal':\n", " return 0\n", " elif value.lower() == 'cancer':\n", " return 1\n", " else:\n", " return None # Unknown value\n", "\n", "def convert_age(value):\n", " \"\"\"\n", " No age data is available, but adding this function for completeness.\n", " \"\"\"\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"\n", " No gender data is available, but adding this function for completeness.\n", " \"\"\"\n", " return None\n", "\n", "# 3. Save Metadata\n", "# Trait data is available since trait_row is not None\n", "is_trait_available = trait_row is not None\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", "# Since trait_row is not None, we need to extract clinical features\n", "if trait_row is not None:\n", " try:\n", " # Let's identify the true clinical data path\n", " import glob\n", " \n", " # Look for any files that might contain clinical data\n", " potential_files = glob.glob(f\"{in_cohort_dir}/*clinical*.csv\") + \\\n", " glob.glob(f\"{in_cohort_dir}/*series*.txt*\") + \\\n", " glob.glob(f\"{in_cohort_dir}/*metadata*.txt*\")\n", " \n", " if potential_files:\n", " # Use the first file found\n", " clinical_data_path = potential_files[0]\n", " print(f\"Found clinical data file: {clinical_data_path}\")\n", " \n", " # Determine file type and load accordingly\n", " if clinical_data_path.endswith('.gz'):\n", " clinical_data = pd.read_csv(clinical_data_path, sep='\\t', compression='gzip')\n", " elif clinical_data_path.endswith('.txt'):\n", " clinical_data = pd.read_csv(clinical_data_path, sep='\\t')\n", " else:\n", " clinical_data = pd.read_csv(clinical_data_path)\n", " else:\n", " # If no files are found, use sample characteristics information directly\n", " print(\"No clinical data files found. Using sample characteristics information.\")\n", " \n", " # Based on the sample characteristics dictionary and background information:\n", " # - We know there are 8 normal kidney tissues\n", " # - 5 hereditary PRCC2 tumor tissues\n", " # - 19 sporadic PRCC2 tumor tissues\n", " \n", " sample_ids = [f\"Sample_{i+1}\" for i in range(32)] # Total 32 samples based on counts\n", " \n", " # First 8 are normal tissues, rest are cancer\n", " tissue_types = ['tissue type: Normal'] * 8 + ['tissue type: Cancer'] * 24\n", " \n", " # Of the cancer samples, first 5 are hereditary, rest are sporadic\n", " disease_status = [None] * 8 + ['disease status: hereditary PRCC2'] * 5 + ['disease status: sporadic PRCC2'] * 19\n", " \n", " # Create dataframe that mimics the expected structure\n", " clinical_data = pd.DataFrame({\n", " '!Sample_geo_accession': sample_ids,\n", " 0: tissue_types,\n", " 1: disease_status\n", " })\n", " \n", " # Extract clinical features using the library function\n", " selected_clinical_df = geo_select_clinical_features(\n", " clinical_df=clinical_data,\n", " trait=trait,\n", " trait_row=trait_row,\n", " convert_trait=convert_trait,\n", " age_row=age_row,\n", " convert_age=convert_age,\n", " gender_row=gender_row,\n", " convert_gender=convert_gender\n", " )\n", " \n", " # Preview the extracted clinical data\n", " print(\"Preview of extracted clinical data:\")\n", " print(preview_df(selected_clinical_df))\n", " \n", " # Save the extracted clinical data to CSV\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " selected_clinical_df.to_csv(out_clinical_data_file, index=False)\n", " print(f\"Clinical data saved to {out_clinical_data_file}\")\n", " \n", " except Exception as e:\n", " print(f\"Error processing clinical data: {e}\")\n", " print(\"Skipping clinical data extraction step.\")\n" ] }, { "cell_type": "markdown", "id": "561d0443", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "9a91c903", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:19:42.162588Z", "iopub.status.busy": "2025-03-25T07:19:42.162484Z", "iopub.status.idle": "2025-03-25T07:19:42.239991Z", "shell.execute_reply": "2025-03-25T07:19:42.239521Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Examining matrix file structure...\n", "Line 0: !Series_title\t\"DPYS as a potential diagnostic biomarker in hereditary and sporadic PRCC2\"\n", "Line 1: !Series_geo_accession\t\"GSE48352\"\n", "Line 2: !Series_status\t\"Public on Jun 01 2016\"\n", "Line 3: !Series_submission_date\t\"Jun 27 2013\"\n", "Line 4: !Series_last_update_date\t\"Jun 02 2016\"\n", "Line 5: !Series_summary\t\"Papillary renal cell carcinoma type 2 (PRCC2) is known to be very aggressive type of tumor without effictive therapy. Hereditary form of PRCC2 is caused by Fumarate Hydratase (FH) gene mutation that accompanied Hereditary Leiomyomatosis and Renal Cell Carcinoma (HLRCC) disorder. In sporadic form of PRCC2 the mutation of FH gene has not been reported. Both forms of tumors have the similar histopathological characteristics with poor survival prognosis.\"\n", "Line 6: !Series_summary\t\"In this study, we profiled the gene expression of renal tumors and normal tissue from PRCC2 (hereditary and sporadic) patients in order to better understand commonalities and differences in the transcriptional landscape of PRCC2.\"\n", "Line 7: !Series_overall_design\t\"Microarray gene expression profiling was performed on eight normal kidney tissue samples, five hereditary PRCC2 tumor tissue samples and 19 sporadic PRCC2 tumor tissue samples. Hereditary PRCC2 (HPRCC2) patients were confirmed by DNA sequencing of the FH gene.\"\n", "Line 8: !Series_type\t\"Expression profiling by array\"\n", "Line 9: !Series_contributor\t\"Victoria,,PERRIER-TRUDOVA\"\n", "Found table marker at line 63\n", "First few lines after marker:\n", "\"ID_REF\"\t\"GSM1176286\"\t\"GSM1176287\"\t\"GSM1176288\"\t\"GSM1176289\"\t\"GSM1176290\"\t\"GSM1176291\"\t\"GSM1176292\"\t\"GSM1176293\"\t\"GSM1176294\"\t\"GSM1176295\"\t\"GSM1176296\"\t\"GSM1176297\"\t\"GSM1176298\"\t\"GSM1176299\"\t\"GSM1176300\"\t\"GSM1176301\"\t\"GSM1176302\"\t\"GSM1176303\"\t\"GSM1176304\"\t\"GSM1176305\"\t\"GSM1176306\"\t\"GSM1176307\"\t\"GSM1176308\"\t\"GSM1176309\"\t\"GSM1176310\"\t\"GSM1176311\"\t\"GSM1176312\"\t\"GSM1176313\"\t\"GSM1176314\"\t\"GSM1176315\"\t\"GSM1176316\"\t\"GSM1176317\"\n", "\"100009676_at\"\t5.969916147\t5.825797155\t6.192869967\t5.801392132\t6.230770328\t6.032705758\t5.875213887\t5.843381534\t5.814644672\t5.88966654\t5.905527383\t5.609706469\t5.445401411\t5.938500099\t5.68641053\t5.566488384\t6.043563351\t5.999241407\t5.982595344\t5.933868765\t5.950816216\t6.066806118\t6.050776362\t6.109249782\t5.921912889\t5.993330603\t6.251628152\t6.939953895\t6.820101971\t5.860415007\t5.681934277\t6.378339305\n", "\"10000_at\"\t5.515433543\t5.566104811\t5.446933361\t6.343041776\t6.00260324\t5.836804773\t5.336765616\t5.351248994\t5.190161737\t5.153228509\t6.732027887\t6.793090802\t6.275379596\t5.336351671\t5.591014794\t5.545293791\t5.586171135\t5.665573795\t5.790742277\t5.971749924\t6.033746309\t5.511734892\t5.448119079\t5.363143576\t6.069874293\t6.018249758\t5.393451556\t6.035686725\t6.402522289\t6.44685144\t5.798981603\t6.129965169\n", "\"10001_at\"\t7.748288831\t7.953183004\t6.881361769\t7.552706573\t7.122793649\t7.088315718\t7.867503021\t7.541141234\t8.034581039\t8.092112496\t8.952485896\t8.725511946\t8.583317157\t7.781106018\t7.722639178\t8.012111104\t6.772223853\t7.714014995\t7.321215177\t7.157693852\t6.349980313\t7.997940467\t6.962124346\t7.451745418\t7.870760054\t7.322591514\t7.541378703\t6.452161035\t6.277621094\t6.818989207\t7.217907106\t6.415465384\n", "\"10002_at\"\t4.977823932\t5.161046856\t5.361237592\t4.982865257\t5.141288652\t5.185527596\t5.356876939\t5.34641608\t5.134285965\t5.230850297\t5.069274563\t5.004026603\t5.180537459\t5.044294103\t5.079927367\t5.170062046\t5.40511864\t5.169081927\t5.201489415\t5.453928477\t5.135744566\t5.227291003\t5.128408338\t5.004439597\t5.05283442\t5.234994949\t5.286033936\t6.981670472\t6.982565202\t5.450178678\t5.43161325\t6.50771516\n", "Total lines examined: 64\n", "\n", "Attempting to extract gene data from matrix file...\n", "Successfully extracted gene data with 19070 rows\n", "First 20 gene IDs:\n", "Index(['100009676_at', '10000_at', '10001_at', '10002_at', '10003_at',\n", " '100048912_at', '100049716_at', '10004_at', '10005_at', '10006_at',\n", " '10007_at', '10008_at', '100093630_at', '10009_at', '1000_at',\n", " '100101467_at', '100101938_at', '10010_at', '100113407_at', '10011_at'],\n", " dtype='object', name='ID')\n", "\n", "Gene expression data available: True\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", "# Add diagnostic code to check file content and structure\n", "print(\"Examining matrix file structure...\")\n", "with gzip.open(matrix_file, 'rt') as file:\n", " table_marker_found = False\n", " lines_read = 0\n", " for i, line in enumerate(file):\n", " lines_read += 1\n", " if '!series_matrix_table_begin' in line:\n", " table_marker_found = True\n", " print(f\"Found table marker at line {i}\")\n", " # Read a few lines after the marker to check data structure\n", " next_lines = [next(file, \"\").strip() for _ in range(5)]\n", " print(\"First few lines after marker:\")\n", " for next_line in next_lines:\n", " print(next_line)\n", " break\n", " if i < 10: # Print first few lines to see file structure\n", " print(f\"Line {i}: {line.strip()}\")\n", " if i > 100: # Don't read the entire file\n", " break\n", " \n", " if not table_marker_found:\n", " print(\"Table marker '!series_matrix_table_begin' not found in first 100 lines\")\n", " print(f\"Total lines examined: {lines_read}\")\n", "\n", "# 2. Try extracting gene expression data from the matrix file again with better diagnostics\n", "try:\n", " print(\"\\nAttempting to extract gene data from matrix file...\")\n", " gene_data = get_genetic_data(matrix_file)\n", " if gene_data.empty:\n", " print(\"Extracted gene expression data is empty\")\n", " is_gene_available = False\n", " else:\n", " print(f\"Successfully extracted gene data with {len(gene_data.index)} rows\")\n", " print(\"First 20 gene IDs:\")\n", " print(gene_data.index[:20])\n", " is_gene_available = True\n", "except Exception as e:\n", " print(f\"Error extracting gene data: {str(e)}\")\n", " print(\"This dataset appears to have an empty or malformed gene expression matrix\")\n", " is_gene_available = False\n", "\n", "print(f\"\\nGene expression data available: {is_gene_available}\")\n", "\n", "# If data extraction failed, try an alternative approach using pandas directly\n", "if not is_gene_available:\n", " print(\"\\nTrying alternative approach to read gene expression data...\")\n", " try:\n", " with gzip.open(matrix_file, 'rt') as file:\n", " # Skip lines until we find the marker\n", " for line in file:\n", " if '!series_matrix_table_begin' in line:\n", " break\n", " \n", " # Try to read the data directly with pandas\n", " gene_data = pd.read_csv(file, sep='\\t', index_col=0)\n", " \n", " if not gene_data.empty:\n", " print(f\"Successfully extracted gene data with alternative method: {gene_data.shape}\")\n", " print(\"First 20 gene IDs:\")\n", " print(gene_data.index[:20])\n", " is_gene_available = True\n", " else:\n", " print(\"Alternative extraction method also produced empty data\")\n", " except Exception as e:\n", " print(f\"Alternative extraction failed: {str(e)}\")\n" ] }, { "cell_type": "markdown", "id": "1e89ee3a", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "ff61202f", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:19:42.241205Z", "iopub.status.busy": "2025-03-25T07:19:42.241090Z", "iopub.status.idle": "2025-03-25T07:19:42.243110Z", "shell.execute_reply": "2025-03-25T07:19:42.242774Z" } }, "outputs": [], "source": [ "# Examining the gene identifiers in the gene expression data\n", "# Let's analyze the format of the gene IDs\n", "\n", "# Based on the observed gene identifiers (e.g., \"100009676_at\", \"10000_at\", etc.),\n", "# these appear to be microarray probe identifiers, not standard human gene symbols.\n", "# The '_at' suffix is characteristic of Affymetrix microarray platform probe IDs.\n", "# These will need to be mapped to standard gene symbols for biological interpretation.\n", "\n", "# These are likely Affymetrix probe IDs that require mapping to HGNC gene symbols\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "5ac4bf14", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "030f8014", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:19:42.244259Z", "iopub.status.busy": "2025-03-25T07:19:42.244153Z", "iopub.status.idle": "2025-03-25T07:19:42.864077Z", "shell.execute_reply": "2025-03-25T07:19:42.863527Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Extracting gene annotation data from SOFT file...\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Successfully extracted gene annotation data with 629342 rows\n", "\n", "Gene annotation preview (first few rows):\n", "{'ID': ['1_at', '10_at', '100_at', '1000_at', '10000_at'], 'SPOT_ID': ['1', '10', '100', '1000', '10000'], 'Description': ['alpha-1-B glycoprotein', 'N-acetyltransferase 2 (arylamine N-acetyltransferase)', 'adenosine deaminase', 'cadherin 2, type 1, N-cadherin (neuronal)', 'v-akt murine thymoma viral oncogene homolog 3 (protein kinase B, gamma)']}\n", "\n", "Column names in gene annotation data:\n", "['ID', 'SPOT_ID', 'Description']\n", "\n", "The dataset contains genomic regions (SPOT_ID) that could be used for location-based gene mapping.\n", "Example SPOT_ID format: 1\n" ] } ], "source": [ "# 1. Extract gene annotation data from the SOFT file\n", "print(\"Extracting gene annotation data from SOFT file...\")\n", "try:\n", " # Use the library function to extract gene annotation\n", " gene_annotation = get_gene_annotation(soft_file)\n", " print(f\"Successfully extracted gene annotation data with {len(gene_annotation.index)} rows\")\n", " \n", " # Preview the annotation DataFrame\n", " print(\"\\nGene annotation preview (first few rows):\")\n", " print(preview_df(gene_annotation))\n", " \n", " # Show column names to help identify which columns we need for mapping\n", " print(\"\\nColumn names in gene annotation data:\")\n", " print(gene_annotation.columns.tolist())\n", " \n", " # Check for relevant mapping columns\n", " if 'GB_ACC' in gene_annotation.columns:\n", " print(\"\\nThe dataset contains GenBank accessions (GB_ACC) that could be used for gene mapping.\")\n", " # Count non-null values in GB_ACC column\n", " non_null_count = gene_annotation['GB_ACC'].count()\n", " print(f\"Number of rows with GenBank accessions: {non_null_count} out of {len(gene_annotation)}\")\n", " \n", " if 'SPOT_ID' in gene_annotation.columns:\n", " print(\"\\nThe dataset contains genomic regions (SPOT_ID) that could be used for location-based gene mapping.\")\n", " print(\"Example SPOT_ID format:\", gene_annotation['SPOT_ID'].iloc[0])\n", " \n", "except Exception as e:\n", " print(f\"Error processing gene annotation data: {e}\")\n", " is_gene_available = False\n" ] }, { "cell_type": "markdown", "id": "2e18e294", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "6fe959e0", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:19:42.865740Z", "iopub.status.busy": "2025-03-25T07:19:42.865624Z", "iopub.status.idle": "2025-03-25T07:21:32.478611Z", "shell.execute_reply": "2025-03-25T07:21:32.478261Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Analyzing gene annotation and expression data for mapping...\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Found 19070 direct matches between expression data and annotation IDs\n", "\n", "Sample gene descriptions:\n", "alpha-1-B glycoprotein\n", "N-acetyltransferase 2 (arylamine N-acetyltransferase)\n", "adenosine deaminase\n", "cadherin 2, type 1, N-cadherin (neuronal)\n", "v-akt murine thymoma viral oncogene homolog 3 (protein kinase B, gamma)\n", "hypothetical LOC100009676\n", "mediator complex subunit 6\n", "nuclear receptor subfamily 2, group E, member 3\n", "N-acetylated alpha-linked acidic dipeptidase 2\n", "N-acetylated alpha-linked acidic dipeptidase-like 1\n", "\n", "Extracting gene symbols from descriptions...\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Sample mappings (ID -> extracted gene symbols):\n", "1_at -> []\n", "10_at -> ['N-']\n", "100_at -> []\n", "1000_at -> ['N-']\n", "10000_at -> []\n", "100009676_at -> []\n", "10001_at -> []\n", "10002_at -> []\n", "10003_at -> ['N-']\n", "10004_at -> ['N-']\n", "\n", "Mapping dataframe contains 5688 rows after filtering\n", "\n", "Applying gene mapping to expression data...\n", "Generated gene expression data with 0 genes\n", "\n", "Preview of gene expression data:\n", "{'GSM1176286': [], 'GSM1176287': [], 'GSM1176288': [], 'GSM1176289': [], 'GSM1176290': [], 'GSM1176291': [], 'GSM1176292': [], 'GSM1176293': [], 'GSM1176294': [], 'GSM1176295': [], 'GSM1176296': [], 'GSM1176297': [], 'GSM1176298': [], 'GSM1176299': [], 'GSM1176300': [], 'GSM1176301': [], 'GSM1176302': [], 'GSM1176303': [], 'GSM1176304': [], 'GSM1176305': [], 'GSM1176306': [], 'GSM1176307': [], 'GSM1176308': [], 'GSM1176309': [], 'GSM1176310': [], 'GSM1176311': [], 'GSM1176312': [], 'GSM1176313': [], 'GSM1176314': [], 'GSM1176315': [], 'GSM1176316': [], 'GSM1176317': []}\n", "\n", "Gene expression data saved to ../../output/preprocess/Kidney_Papillary_Cell_Carcinoma/gene_data/GSE48352.csv\n" ] } ], "source": [ "# 1. Observe the gene annotation and identify mapping columns\n", "print(\"Analyzing gene annotation and expression data for mapping...\")\n", "\n", "# Based on previous inspection, we need to map the gene expression identifiers (e.g., \"10000_at\")\n", "# to gene symbols, which appear to be contained in the \"Description\" column of the annotation data\n", "\n", "# Check if there are direct matches between gene expression IDs and annotation IDs\n", "overlap_count = sum(1 for id in gene_data.index if id in gene_annotation['ID'].values)\n", "print(f\"Found {overlap_count} direct matches between expression data and annotation IDs\")\n", "\n", "# 2. Get a gene mapping dataframe\n", "# Extract the ID column and Description column for mapping\n", "mapping_df = gene_annotation[['ID', 'Description']].copy()\n", "\n", "# Check if the Description actually contains gene symbols by examining a few entries\n", "print(\"\\nSample gene descriptions:\")\n", "for desc in mapping_df['Description'].head(10):\n", " print(desc)\n", "\n", "# The Description column contains gene names, but not in standardized HGNC symbol format\n", "# Need to extract gene symbols using the helper function\n", "print(\"\\nExtracting gene symbols from descriptions...\")\n", "mapping_df['Gene'] = mapping_df['Description'].apply(extract_human_gene_symbols)\n", "\n", "# Show the resulting mapping for a few entries\n", "print(\"\\nSample mappings (ID -> extracted gene symbols):\")\n", "for i, row in mapping_df.head(10).iterrows():\n", " print(f\"{row['ID']} -> {row['Gene']}\")\n", "\n", "# Remove rows where no gene symbol could be extracted\n", "mapping_df = mapping_df[mapping_df['Gene'].apply(lambda x: len(x) > 0)]\n", "print(f\"\\nMapping dataframe contains {len(mapping_df)} rows after filtering\")\n", "\n", "# 3. Apply gene mapping to convert probe-level measurements to gene expression data\n", "print(\"\\nApplying gene mapping to expression data...\")\n", "gene_data = apply_gene_mapping(gene_data, mapping_df[['ID', 'Gene']])\n", "print(f\"Generated gene expression data with {len(gene_data)} genes\")\n", "\n", "# Preview the first few rows of the gene expression data\n", "print(\"\\nPreview of gene expression data:\")\n", "print(preview_df(gene_data, n=5))\n", "\n", "# Save the gene expression 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\"\\nGene expression 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 }