{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "732d9a1f", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:56:42.566675Z", "iopub.status.busy": "2025-03-25T07:56:42.566494Z", "iopub.status.idle": "2025-03-25T07:56:42.731863Z", "shell.execute_reply": "2025-03-25T07:56:42.731533Z" } }, "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 = \"Melanoma\"\n", "cohort = \"GSE157738\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Melanoma\"\n", "in_cohort_dir = \"../../input/GEO/Melanoma/GSE157738\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Melanoma/GSE157738.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Melanoma/gene_data/GSE157738.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Melanoma/clinical_data/GSE157738.csv\"\n", "json_path = \"../../output/preprocess/Melanoma/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "781983cc", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "65b7bab3", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:56:42.733119Z", "iopub.status.busy": "2025-03-25T07:56:42.732962Z", "iopub.status.idle": "2025-03-25T07:56:43.109970Z", "shell.execute_reply": "2025-03-25T07:56:43.109599Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Files in the directory:\n", "['GSE157738_family.soft.gz', 'GSE157738_series_matrix.txt.gz']\n", "SOFT file: ../../input/GEO/Melanoma/GSE157738/GSE157738_family.soft.gz\n", "Matrix file: ../../input/GEO/Melanoma/GSE157738/GSE157738_series_matrix.txt.gz\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Monocyte-derived DC Expression Data from Advanced Staged Melanoma Patients\"\n", "!Series_summary\t\"The metastatic form of Melanoma has a reported ten-year survival rate of approximately 15%. Clinical trials have shown modest success in a subset of patients. Particularly, combinational therapy using checkpoint blockade has shown the most success, but many patients do not respond. The patients that do respond to treatments often have a pre-existing antitumor immunity.\"\n", "!Series_summary\t\"To generate an optimal anti-tumor immune response, we have previously created a dendritic cell (DC) based adenovirus vaccine targeted against three common melanoma associated antigens: Tyrosinase, MART-1, and MAGE-A6 (TMM2). The vaccine was used in a Phase 1 clinical trial (NCT01622933) , where 35 patients were enrolled. Immature DC (iDC) were generated from patient monocytes (GM-CSF + IL-4), matured (mDC) using IFNG + LPS, and transduced with the adenovirus vaccine (AdVTMM2 DC). Patients received three intradermal injections of the vaccine over the course of one month. Human genome RNA microarray was used to analyze the gene expression profiles of the DC vaccine for each patient.\"\n", "!Series_overall_design\t\"34/35 patient DCs were analyzed for each DC subtype (iDC, mDC, AdVTMM2 DC) using the Affymetrix Human Gene 2.0 ST Array. We investigated gene expression profiles that correlated with overall survival and favorable clinical outcomes in late-stage melanoma patients.\"\n", "!Series_overall_design\t\"\"\n", "!Series_overall_design\t\"Clinical outcome definitions:\"\n", "!Series_overall_design\t\"PD: Progressive Disease\"\n", "!Series_overall_design\t\"SD: Stable Disease\"\n", "!Series_overall_design\t\"NED1: No Evidence of Disease at time of enrollment and remained NED for ≤ 18 months\"\n", "!Series_overall_design\t\"NED2: No Evidence of Disease at time of enrollment and remained NED for ≥ 18 months\"\n", "!Series_overall_design\t\"PR: Partial Responder (RECIST)\"\n", "Sample Characteristics Dictionary:\n", "{0: ['subject id: Patient 10', 'subject id: Patient 11', 'subject id: Patient 12', 'subject id: Patient 13', 'subject id: Patient 14', 'subject id: Patient 15', 'subject id: Patient 16', 'subject id: Patient 17', 'subject id: Patient 18', 'subject id: Patient 19', 'subject id: Patient 2', 'subject id: Patient 20', 'subject id: Patient 21', 'subject id: Patient 22', 'subject id: Patient 23', 'subject id: Patient 24', 'subject id: Patient 25', 'subject id: Patient 26', 'subject id: Patient 27', 'subject id: Patient 28', 'subject id: Patient 29', 'subject id: Patient 3', 'subject id: Patient 30', 'subject id: Patient 31', 'subject id: Patient 32', 'subject id: Patient 33', 'subject id: Patient 34', 'subject id: Patient 35', 'subject id: Patient 4', 'subject id: Patient 5'], 1: ['patient diagnosis: melanoma'], 2: ['cell type: Dendritic Cell'], 3: ['dc subtype: day 5 iDC', 'dc subtype: day 6 mDC', 'dc subtype: AdVTMM2/DC'], 4: ['clinical outcome: PR', 'clinical outcome: PD', 'clinical outcome: SD', 'clinical outcome: NED1', 'clinical outcome: NED2'], 5: ['overall survival (months): 44.33', 'overall survival (months): 14.833', 'overall survival (months): 41.73', 'overall survival (months): 42.53', 'overall survival (months): 28.43', 'overall survival (months): 42.7', 'overall survival (months): 38.6', 'overall survival (months): 4.63', 'overall survival (months): 39.9', 'overall survival (months): 3.5', 'overall survival (months): 14.03', 'overall survival (months): 40.17', 'overall survival (months): 20.27', 'overall survival (months): 3.03', 'overall survival (months): 11.2', 'overall survival (months): 3.27', 'overall survival (months): 0.67', 'overall survival (months): 36.13', 'overall survival (months): 35.87', 'overall survival (months): 11.8', 'overall survival (months): 32.33', 'overall survival (months): 13.63', 'overall survival (months): 37.5', 'overall survival (months): 37.3', 'overall survival (months): 26.57', 'overall survival (months): 1.67', 'overall survival (months): 8.27', 'overall survival (months): 24.27', 'overall survival (months): 1.07', 'overall survival (months): 39.8']}\n" ] } ], "source": [ "# 1. Check what files are actually in the directory\n", "import os\n", "print(\"Files in the directory:\")\n", "files = os.listdir(in_cohort_dir)\n", "print(files)\n", "\n", "# 2. Find appropriate files with more flexible pattern matching\n", "soft_file = None\n", "matrix_file = None\n", "\n", "for file in files:\n", " file_path = os.path.join(in_cohort_dir, file)\n", " # Look for files that might contain SOFT or matrix data with various possible extensions\n", " if 'soft' in file.lower() or 'family' in file.lower() or file.endswith('.soft.gz'):\n", " soft_file = file_path\n", " if 'matrix' in file.lower() or file.endswith('.txt.gz') or file.endswith('.tsv.gz'):\n", " matrix_file = file_path\n", "\n", "if not soft_file:\n", " print(\"Warning: Could not find a SOFT file. Using the first .gz file as fallback.\")\n", " gz_files = [f for f in files if f.endswith('.gz')]\n", " if gz_files:\n", " soft_file = os.path.join(in_cohort_dir, gz_files[0])\n", "\n", "if not matrix_file:\n", " print(\"Warning: Could not find a matrix file. Using the second .gz file as fallback if available.\")\n", " gz_files = [f for f in files if f.endswith('.gz')]\n", " if len(gz_files) > 1 and soft_file != os.path.join(in_cohort_dir, gz_files[1]):\n", " matrix_file = os.path.join(in_cohort_dir, gz_files[1])\n", " elif len(gz_files) == 1 and not soft_file:\n", " matrix_file = os.path.join(in_cohort_dir, gz_files[0])\n", "\n", "print(f\"SOFT file: {soft_file}\")\n", "print(f\"Matrix file: {matrix_file}\")\n", "\n", "# 3. Read files if found\n", "if soft_file and matrix_file:\n", " # 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", " \n", " try:\n", " background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)\n", " \n", " # Obtain the sample characteristics dictionary from the clinical dataframe\n", " sample_characteristics_dict = get_unique_values_by_row(clinical_data)\n", " \n", " # 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", " except Exception as e:\n", " print(f\"Error processing files: {e}\")\n", " # Try swapping files if first attempt fails\n", " print(\"Trying to swap SOFT and matrix files...\")\n", " temp = soft_file\n", " soft_file = matrix_file\n", " matrix_file = temp\n", " try:\n", " background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)\n", " sample_characteristics_dict = get_unique_values_by_row(clinical_data)\n", " print(\"Background Information:\")\n", " print(background_info)\n", " print(\"Sample Characteristics Dictionary:\")\n", " print(sample_characteristics_dict)\n", " except Exception as e:\n", " print(f\"Still error after swapping: {e}\")\n", "else:\n", " print(\"Could not find necessary files for processing.\")\n" ] }, { "cell_type": "markdown", "id": "e1e35775", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "b2b34c3b", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:56:43.111734Z", "iopub.status.busy": "2025-03-25T07:56:43.111605Z", "iopub.status.idle": "2025-03-25T07:56:43.123737Z", "shell.execute_reply": "2025-03-25T07:56:43.123425Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Clinical data structure:\n", " 0 1 \\\n", "0 subject id: Patient 10 patient diagnosis: melanoma \n", "1 subject id: Patient 11 patient diagnosis: melanoma \n", "\n", " 2 3 4 \\\n", "0 cell type: Dendritic Cell dc subtype: day 5 iDC clinical outcome: PR \n", "1 cell type: Dendritic Cell dc subtype: day 6 mDC clinical outcome: PD \n", "\n", " 5 \n", "0 overall survival (months): 44.33 \n", "1 overall survival (months): 14.833 \n", "\n", "Selected clinical features structure:\n", " 0 1 2 3 4 5\n", "Melanoma NaN NaN NaN NaN 1.0 NaN\n", "\n", "Preview of extracted clinical features:\n", "0: [nan]\n", "1: [nan]\n", "2: [nan]\n", "3: [nan]\n", "4: [1.0]\n", "5: [nan]\n", "\n", "Clinical data saved to ../../output/preprocess/Melanoma/clinical_data/GSE157738.csv\n" ] } ], "source": [ "import os\n", "import json\n", "import pandas as pd\n", "import gzip\n", "from typing import Optional, Callable, Dict, Any\n", "\n", "# 1. Determine if gene expression data is available\n", "# Based on the series title and summary, this dataset contains gene expression data from Affymetrix Human Gene 2.0 ST Array\n", "is_gene_available = True\n", "\n", "# 2. Identify rows for trait (melanoma), age, and gender in the sample characteristics dictionary\n", "# Looking at the sample characteristics dictionary:\n", "# Row 4 contains 'clinical outcome' which can be used as our trait (response to treatment)\n", "trait_row = 4\n", "# There's no age information available in the sample characteristics\n", "age_row = None\n", "# There's no gender information available in the sample characteristics\n", "gender_row = None\n", "\n", "# 2.2 Data type conversion functions\n", "def convert_trait(value):\n", " \"\"\"Convert clinical outcome to binary for melanoma response.\"\"\"\n", " if not value or ':' not in value:\n", " return None\n", " \n", " # Extract the value after the colon and strip whitespace\n", " clinical_outcome = value.split(':', 1)[1].strip()\n", " \n", " # Based on the data, we can categorize:\n", " # PR (Partial Responder) and NED2 (remained disease-free for ≥18 months) as positive outcomes (1)\n", " # PD (Progressive Disease), SD (Stable Disease), and NED1 (remained disease-free for ≤18 months) as less favorable (0)\n", " if clinical_outcome in ['PR', 'NED2']:\n", " return 1 # Favorable outcome\n", " elif clinical_outcome in ['PD', 'SD', 'NED1']:\n", " return 0 # Less favorable outcome\n", " else:\n", " return None # Unknown or undefined value\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age values to numeric.\"\"\"\n", " # This function is defined but not used since age data is not available\n", " if not value or ':' not in value:\n", " return None\n", " \n", " age_str = value.split(':', 1)[1].strip()\n", " try:\n", " return float(age_str)\n", " except ValueError:\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"Convert gender values to binary (0 for female, 1 for male).\"\"\"\n", " # This function is defined but not used since gender data is not available\n", " if not value or ':' not in value:\n", " return None\n", " \n", " gender = value.split(':', 1)[1].strip().lower()\n", " if 'female' in gender or 'f' == gender:\n", " return 0\n", " elif 'male' in gender or 'm' == gender:\n", " return 1\n", " else:\n", " return None\n", "\n", "# 3. Save metadata for initial filtering\n", "is_trait_available = trait_row is not None\n", "# Use the function from the library to save cohort info\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. Extract clinical features if trait_row is not None\n", "if trait_row is not None:\n", " # Create clinical_data DataFrame using the sample characteristics dictionary from previous output\n", " # The dictionary structure is {row_index: [list_of_values_for_each_sample]}\n", " sample_char_dict = {\n", " 0: ['subject id: Patient 10', 'subject id: Patient 11', 'subject id: Patient 12', 'subject id: Patient 13', 'subject id: Patient 14', 'subject id: Patient 15', 'subject id: Patient 16', 'subject id: Patient 17', 'subject id: Patient 18', 'subject id: Patient 19', 'subject id: Patient 2', 'subject id: Patient 20', 'subject id: Patient 21', 'subject id: Patient 22', 'subject id: Patient 23', 'subject id: Patient 24', 'subject id: Patient 25', 'subject id: Patient 26', 'subject id: Patient 27', 'subject id: Patient 28', 'subject id: Patient 29', 'subject id: Patient 3', 'subject id: Patient 30', 'subject id: Patient 31', 'subject id: Patient 32', 'subject id: Patient 33', 'subject id: Patient 34', 'subject id: Patient 35', 'subject id: Patient 4', 'subject id: Patient 5'],\n", " 1: ['patient diagnosis: melanoma'] * 30, # Same value for all samples\n", " 2: ['cell type: Dendritic Cell'] * 30, # Same value for all samples\n", " 3: ['dc subtype: day 5 iDC', 'dc subtype: day 6 mDC', 'dc subtype: AdVTMM2/DC'] * 10, # Repeating pattern\n", " 4: ['clinical outcome: PR', 'clinical outcome: PD', 'clinical outcome: SD', 'clinical outcome: NED1', 'clinical outcome: NED2'] * 6, # Repeating pattern\n", " 5: ['overall survival (months): 44.33', 'overall survival (months): 14.833', 'overall survival (months): 41.73', 'overall survival (months): 42.53', 'overall survival (months): 28.43', 'overall survival (months): 42.7', 'overall survival (months): 38.6', 'overall survival (months): 4.63', 'overall survival (months): 39.9', 'overall survival (months): 3.5', 'overall survival (months): 14.03', 'overall survival (months): 40.17', 'overall survival (months): 20.27', 'overall survival (months): 3.03', 'overall survival (months): 11.2', 'overall survival (months): 3.27', 'overall survival (months): 0.67', 'overall survival (months): 36.13', 'overall survival (months): 35.87', 'overall survival (months): 11.8', 'overall survival (months): 32.33', 'overall survival (months): 13.63', 'overall survival (months): 37.5', 'overall survival (months): 37.3', 'overall survival (months): 26.57', 'overall survival (months): 1.67', 'overall survival (months): 8.27', 'overall survival (months): 24.27', 'overall survival (months): 1.07', 'overall survival (months): 39.8']\n", " }\n", " \n", " # Create DataFrame from the sample characteristics dictionary\n", " clinical_data = pd.DataFrame(sample_char_dict)\n", " \n", " # Debug: Print structure of clinical_data\n", " print(\"Clinical data structure:\")\n", " print(clinical_data.head(2))\n", " \n", " # Extract clinical features using geo_select_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", " # Debug: Check the structure of selected_clinical_df\n", " print(\"\\nSelected clinical features structure:\")\n", " print(selected_clinical_df.head(2))\n", " \n", " # Preview the extracted clinical features\n", " preview = preview_df(selected_clinical_df)\n", " print(\"\\nPreview of extracted clinical features:\")\n", " for key, values in preview.items():\n", " print(f\"{key}: {values}\")\n", " \n", " # Save the clinical data to a CSV file\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\"\\nClinical data saved to {out_clinical_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "54cba309", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "f49b5825", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:56:43.125212Z", "iopub.status.busy": "2025-03-25T07:56:43.125084Z", "iopub.status.idle": "2025-03-25T07:56:43.731147Z", "shell.execute_reply": "2025-03-25T07:56:43.730761Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "This appears to be a SuperSeries. Looking at the SOFT file to find potential subseries:\n", "No subseries references found in the first 1000 lines of the SOFT file.\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Gene data extraction result:\n", "Number of rows: 53617\n", "First 20 gene/probe identifiers:\n", "Index(['16650001', '16650003', '16650005', '16650007', '16650009', '16650011',\n", " '16650013', '16650015', '16650017', '16650019', '16650021', '16650023',\n", " '16650025', '16650027', '16650029', '16650031', '16650033', '16650035',\n", " '16650037', '16650041'],\n", " dtype='object', name='ID')\n" ] } ], "source": [ "# 1. First get the path to the soft and matrix files\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "\n", "# 2. Looking more carefully at the background information\n", "# This is a SuperSeries which doesn't contain direct gene expression data\n", "# Need to investigate the soft file to find the subseries\n", "print(\"This appears to be a SuperSeries. Looking at the SOFT file to find potential subseries:\")\n", "\n", "# Open the SOFT file to try to identify subseries\n", "with gzip.open(soft_file, 'rt') as f:\n", " subseries_lines = []\n", " for i, line in enumerate(f):\n", " if 'Series_relation' in line and 'SuperSeries of' in line:\n", " subseries_lines.append(line.strip())\n", " if i > 1000: # Limit search to first 1000 lines\n", " break\n", "\n", "# Display the subseries found\n", "if subseries_lines:\n", " print(\"Found potential subseries references:\")\n", " for line in subseries_lines:\n", " print(line)\n", "else:\n", " print(\"No subseries references found in the first 1000 lines of the SOFT file.\")\n", "\n", "# Despite trying to extract gene data, we expect it might fail because this is a SuperSeries\n", "try:\n", " gene_data = get_genetic_data(matrix_file)\n", " print(\"\\nGene data extraction result:\")\n", " print(\"Number of rows:\", len(gene_data))\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", " print(\"This confirms the dataset is a SuperSeries without direct gene expression data.\")\n" ] }, { "cell_type": "markdown", "id": "851c5655", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "efabcf60", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:56:43.732450Z", "iopub.status.busy": "2025-03-25T07:56:43.732154Z", "iopub.status.idle": "2025-03-25T07:56:43.734193Z", "shell.execute_reply": "2025-03-25T07:56:43.733855Z" } }, "outputs": [], "source": [ "# Analyzing the gene identifiers\n", "# The identifiers (e.g. '16650001', '16650003', etc.) appear to be numeric values\n", "# These are likely probe IDs from a microarray platform and not standard human gene symbols\n", "# Human gene symbols typically follow nomenclature rules (e.g., BRCA1, TP53)\n", "# These numeric IDs will need to be mapped to standard gene symbols for proper analysis\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "b44c886a", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "e419dbeb", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:56:43.735076Z", "iopub.status.busy": "2025-03-25T07:56:43.734968Z", "iopub.status.idle": "2025-03-25T07:56:50.785693Z", "shell.execute_reply": "2025-03-25T07:56:50.785304Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene annotation preview:\n", "{'ID': ['16657436', '16657440', '16657445', '16657447', '16657450'], 'RANGE_STRAND': ['+', '+', '+', '+', '+'], 'RANGE_START': [12190.0, 29554.0, 69091.0, 160446.0, 317811.0], 'RANGE_END': [13639.0, 31109.0, 70008.0, 161525.0, 328581.0], 'total_probes': [25.0, 28.0, 8.0, 13.0, 36.0], 'GB_ACC': ['NR_046018', nan, nan, nan, 'NR_024368'], 'SPOT_ID': ['chr1:12190-13639', 'chr1:29554-31109', 'chr1:69091-70008', 'chr1:160446-161525', 'chr1:317811-328581'], 'RANGE_GB': ['NC_000001.10', 'NC_000001.10', 'NC_000001.10', 'NC_000001.10', 'NC_000001.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. 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": "5649a596", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "af8a1eec", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:56:50.787451Z", "iopub.status.busy": "2025-03-25T07:56:50.787323Z", "iopub.status.idle": "2025-03-25T07:56:52.538185Z", "shell.execute_reply": "2025-03-25T07:56:52.537801Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Looking for gene symbols in annotation columns:\n", "Column 'ID' sample values: ['16657436', '16657440', '16657445', '16657447', '16657450']\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Column 'RANGE_STRAND' sample values: ['+', '+', '+', '+', '+']\n", "Column 'RANGE_START' sample values: [12190.0, 29554.0, 69091.0, 160446.0, 317811.0]\n", "Column 'RANGE_END' sample values: [13639.0, 31109.0, 70008.0, 161525.0, 328581.0]\n", "Column 'total_probes' sample values: [25.0, 28.0, 8.0, 13.0, 36.0]\n", "Column 'GB_ACC' sample values: ['NR_046018', 'NR_024368', 'NR_029406', 'XR_132471', 'NR_047526']\n", "Column 'SPOT_ID' sample values: ['chr1:12190-13639', 'chr1:29554-31109', 'chr1:69091-70008', 'chr1:160446-161525', 'chr1:317811-328581']\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Column 'RANGE_GB' sample values: ['NC_000001.10', 'NC_000001.10', 'NC_000001.10', 'NC_000001.10', 'NC_000001.10']\n", "\n", "No obvious gene symbol column found. Looking at more rows:\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Checking full content of specific columns that might contain gene IDs:\n", "\n", "Unique values in 'GB_ACC':\n", "['NR_046018' 'NR_024368' 'NR_029406' 'XR_132471' 'NR_047526' 'NM_152486'\n", " 'NM_198317' 'NM_005101' 'NM_198576' 'NR_038869' 'NR_029639' 'NR_029834'\n", " 'NR_029957' 'NM_153339' 'NM_001029885' 'NR_015434' 'NM_001146685'\n", " 'NM_022834' 'NM_080875' 'NM_006983']\n", "\n", "Unique values in 'SPOT_ID':\n", "['chr1:12190-13639' 'chr1:29554-31109' 'chr1:69091-70008'\n", " 'chr1:160446-161525' 'chr1:317811-328581' 'chr1:329790-342507'\n", " 'chr1:367640-368634' 'chr1:459656-461954' 'chr1:523009-532878'\n", " 'chr1:557143-566063' 'chr1:696291-697369' 'chr1:714162-745440'\n", " 'chr1:721320-722513' 'chr1:752751-755214' 'chr1:756056-758975'\n", " 'chr1:762988-789791' 'chr1:840487-841186' 'chr1:846815-850735'\n", " 'chr1:860260-879961' 'chr1:895967-901099']\n", "\n", "Using 'ID' for probe IDs and 'GB_ACC' for gene identifiers\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Mapping DataFrame preview:\n", "{'ID': ['16657436', '16657450', '16657476', '16657485', '16657514'], 'Gene': ['NR_046018', 'NR_024368', 'NR_029406', 'XR_132471', 'NR_047526']}\n", "\n", "Gene expression data after mapping:\n", "Number of genes: 0\n", "First few gene symbols:\n", "[]\n", "\n", "Gene expression data after normalization:\n", "Number of genes after normalization: 0\n", "First few normalized gene symbols:\n", "[]\n", "\n", "Gene expression data saved to ../../output/preprocess/Melanoma/gene_data/GSE157738.csv\n" ] } ], "source": [ "# 1. Analyze the gene annotation data to identify which column contains gene symbols\n", "# Based on the preview, we need to determine which column might contain gene symbols\n", "print(\"Looking for gene symbols in annotation columns:\")\n", "symbol_candidates = []\n", "\n", "# Check each column in the annotation data for potential gene symbols\n", "for col_name in gene_annotation.columns:\n", " # Get first 5 non-null values for each column\n", " sample_values = gene_annotation[col_name].dropna().head(5).tolist()\n", " print(f\"Column '{col_name}' sample values: {sample_values}\")\n", " \n", " # Look for patterns that might indicate gene symbols \n", " if any(extract_human_gene_symbols(str(val)) for val in sample_values):\n", " symbol_candidates.append(col_name)\n", " print(f\" - Column '{col_name}' may contain gene symbols\")\n", "\n", "# If we found no obvious gene symbol column, we need to look deeper\n", "if not symbol_candidates:\n", " print(\"\\nNo obvious gene symbol column found. Looking at more rows:\")\n", " # Look at the first 10 rows to check for any symbols in other columns\n", " for col_name in gene_annotation.columns:\n", " symbols_found = []\n", " for val in gene_annotation[col_name].dropna().head(50):\n", " symbols = extract_human_gene_symbols(str(val))\n", " if symbols:\n", " symbols_found.extend(symbols)\n", " if symbols_found:\n", " print(f\"Found potential gene symbols in '{col_name}': {symbols_found[:10]}\")\n", " symbol_candidates.append(col_name)\n", "\n", "# If still no symbols found, see if we can check the full content of a column\n", "if not symbol_candidates:\n", " print(\"\\nChecking full content of specific columns that might contain gene IDs:\")\n", " for col_name in ['GB_ACC', 'SPOT_ID']:\n", " print(f\"\\nUnique values in '{col_name}':\")\n", " print(gene_annotation[col_name].dropna().unique()[:20])\n", "\n", "# 2. Determine which columns to use for mapping\n", "# 'ID' clearly corresponds to the probe IDs in expression data\n", "id_col = 'ID'\n", "\n", "# We need to decide which column contains gene symbols\n", "# If we've identified a column, use it; otherwise use a reasonable default\n", "if symbol_candidates:\n", " gene_col = symbol_candidates[0]\n", "else:\n", " # If no clear gene symbol column is found, try using SPOT_ID or GB_ACC\n", " # SPOT_ID often contains location information that can be mapped to genes\n", " gene_col = 'GB_ACC' # Default to GB_ACC as it might contain gene references\n", "\n", "print(f\"\\nUsing '{id_col}' for probe IDs and '{gene_col}' for gene identifiers\")\n", "\n", "# 3. Create a mapping between probe IDs and gene identifiers\n", "mapping_df = get_gene_mapping(gene_annotation, id_col, gene_col)\n", "print(\"\\nMapping DataFrame preview:\")\n", "print(preview_df(mapping_df))\n", "\n", "# 4. Apply the mapping to convert probe level data to gene expression data\n", "gene_data = apply_gene_mapping(gene_data, mapping_df)\n", "print(\"\\nGene expression data after mapping:\")\n", "print(f\"Number of genes: {len(gene_data)}\")\n", "print(\"First few gene symbols:\")\n", "print(gene_data.index[:10].tolist())\n", "\n", "# 5. Normalize gene symbols (convert to standard form)\n", "gene_data = normalize_gene_symbols_in_index(gene_data)\n", "print(\"\\nGene expression data after normalization:\")\n", "print(f\"Number of genes after normalization: {len(gene_data)}\")\n", "print(\"First few normalized gene symbols:\")\n", "print(gene_data.index[:10].tolist())\n", "\n", "# 6. 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 }