{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "381796a4", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:58:08.871357Z", "iopub.status.busy": "2025-03-25T07:58:08.871175Z", "iopub.status.idle": "2025-03-25T07:58:09.037280Z", "shell.execute_reply": "2025-03-25T07:58:09.036944Z" } }, "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 = \"Mesothelioma\"\n", "cohort = \"GSE163720\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Mesothelioma\"\n", "in_cohort_dir = \"../../input/GEO/Mesothelioma/GSE163720\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Mesothelioma/GSE163720.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Mesothelioma/gene_data/GSE163720.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Mesothelioma/clinical_data/GSE163720.csv\"\n", "json_path = \"../../output/preprocess/Mesothelioma/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "5d8ec49f", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "00dbcbbe", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:58:09.038767Z", "iopub.status.busy": "2025-03-25T07:58:09.038618Z", "iopub.status.idle": "2025-03-25T07:58:09.309628Z", "shell.execute_reply": "2025-03-25T07:58:09.309262Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Files in the directory:\n", "['GSE163720_family.soft.gz', 'GSE163720_series_matrix.txt.gz']\n", "SOFT file: ../../input/GEO/Mesothelioma/GSE163720/GSE163720_family.soft.gz\n", "Matrix file: ../../input/GEO/Mesothelioma/GSE163720/GSE163720_series_matrix.txt.gz\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Association of RERG Expression to Female Survival Advantage in Malignant Pleural Mesothelioma I\"\n", "!Series_summary\t\"Sex differences in incidence, prognosis, and treatment response have been described for many cancers. In malignant pleural mesothelioma (MPM), a lethal disease associated with asbestos exposure, men outnumber women 4 to 1, but women consistently live longer than men following surgery-based therapy. This study investigated whether tumor expression of genes associated with estrogen signaling could potentially explain observed survival differences. Two microarray datasets of MPM tumors were analyzed to discover estrogen-related genes associated with survival. A validation cohort of MPM tumors was selected to balance the numbers of men and women and control for competing prognostic influences. The RAS like estrogen regulated growth inhibitor (RERG) gene was identified as the most differentially-expressed estrogen-related gene in these tumors and predicted prognosis in discovery datasets. In the sex-matched validation cohort, low RERG expression was significantly associated with increased risk of death among women. No association between RERG expression and survival was found among men, and no relationship between estrogen receptor protein or gene expression and survival was found for either sex. Additional investigations are needed to elucidate the molecular mechanisms underlying this association and its sex specificity.\"\n", "!Series_overall_design\t\"This study investigated whether tumor expression of genes associated with estrogen signaling could potentially explain observed survival differences between men and women affected by malignant pleural mesothelioma.\"\n", "Sample Characteristics Dictionary:\n", "{0: ['organ: Tumor'], 1: ['compartment: Tissue'], 2: ['Sex: F', 'Sex: M']}\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": "a8b4c2e1", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "5baad40e", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:58:09.310968Z", "iopub.status.busy": "2025-03-25T07:58:09.310844Z", "iopub.status.idle": "2025-03-25T07:58:09.538842Z", "shell.execute_reply": "2025-03-25T07:58:09.538499Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Preview of selected clinical data:\n", "{0: [1.0, nan]}\n", "Clinical data saved to ../../output/preprocess/Mesothelioma/clinical_data/GSE163720.csv\n" ] } ], "source": [ "import pandas as pd\n", "import os\n", "import json\n", "from typing import Optional, Callable, Dict, Any\n", "import numpy as np\n", "import gzip\n", "\n", "# 1. Gene Expression Data Availability\n", "# Based on the background information, this seems to be a microarray dataset studying gene expression in MPM tumors\n", "is_gene_available = True # Microarray data is likely gene expression data\n", "\n", "# Read the clinical data from the matrix file\n", "def extract_clinical_data(file_path):\n", " clinical_data = []\n", " in_clinical_section = False\n", " \n", " with gzip.open(file_path, 'rt') as f:\n", " for line in f:\n", " line = line.strip()\n", " if line.startswith('!Sample_'):\n", " in_clinical_section = True\n", " clinical_data.append(line)\n", " elif in_clinical_section and line.startswith('!'):\n", " clinical_data.append(line)\n", " elif line.startswith('#') or line.startswith('^') or line == '':\n", " in_clinical_section = False\n", " \n", " return pd.DataFrame(clinical_data)\n", "\n", "# Load clinical data\n", "clinical_data = extract_clinical_data(os.path.join(in_cohort_dir, \"GSE163720_series_matrix.txt.gz\"))\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "# From the sample characteristics dictionary, we can see:\n", "# - No explicit trait (mesothelioma) column, but all samples are MPM tumors (from Series_summary)\n", "# - No age data in the sample characteristics dictionary\n", "# - Sex information is available at index 2\n", "\n", "# Since all samples are mesothelioma tumors, we'll create a synthetic trait column\n", "trait_row = 0 # We'll use organ: Tumor to denote all samples have mesothelioma\n", "age_row = None # No age data available\n", "gender_row = 2 # Sex data is available in index 2\n", "\n", "# 2.2 Data Type Conversion\n", "\n", "# Convert trait function - All samples are mesothelioma tumors\n", "def convert_trait(value):\n", " # Since all samples are mesothelioma tumors, return 1 for all\n", " return 1\n", "\n", "# Convert age function (not used since age_row is None)\n", "def convert_age(value):\n", " return None # We don't have age data to convert\n", "\n", "# Convert gender function\n", "def convert_gender(value):\n", " if value is None:\n", " return None\n", " \n", " # Extract the value after the colon if it exists\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # Convert gender to binary (0 for female, 1 for male)\n", " if value.upper() == 'F':\n", " return 0\n", " elif value.upper() == 'M':\n", " return 1\n", " else:\n", " return None\n", "\n", "# 3. Save Metadata\n", "# All samples are MPM tumors, so trait data is available\n", "is_trait_available = True\n", "\n", "# Validate and 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. Clinical Feature Extraction\n", "# Extract clinical features since trait_row is not None\n", "if trait_row is not None:\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 selected clinical data\n", " preview = preview_df(selected_clinical_df)\n", " print(\"Preview of selected clinical data:\")\n", " print(preview)\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 selected 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": "91f21bca", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "10a51958", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:58:09.540119Z", "iopub.status.busy": "2025-03-25T07:58:09.539990Z", "iopub.status.idle": "2025-03-25T07:58:10.022805Z", "shell.execute_reply": "2025-03-25T07:58:10.022414Z" } }, "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: 33295\n", "First 20 gene/probe identifiers:\n", "Index(['7892501', '7892502', '7892503', '7892504', '7892505', '7892506',\n", " '7892507', '7892508', '7892509', '7892510', '7892511', '7892512',\n", " '7892513', '7892514', '7892515', '7892516', '7892517', '7892518',\n", " '7892519', '7892520'],\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": "1f397092", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "0b78d237", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:58:10.024152Z", "iopub.status.busy": "2025-03-25T07:58:10.024022Z", "iopub.status.idle": "2025-03-25T07:58:10.025989Z", "shell.execute_reply": "2025-03-25T07:58:10.025694Z" } }, "outputs": [], "source": [ "# Based on the gene identifiers shown (7892501, 7892502, etc.), these appear to be probe IDs\n", "# from an Illumina microarray platform rather than human gene symbols.\n", "# These numeric IDs need to be mapped to standard gene symbols for proper analysis.\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "0cf47cc8", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "5a2a8ea3", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:58:10.027186Z", "iopub.status.busy": "2025-03-25T07:58:10.027074Z", "iopub.status.idle": "2025-03-25T07:58:16.658703Z", "shell.execute_reply": "2025-03-25T07:58:16.658308Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene annotation preview:\n", "{'ID': ['7896736', '7896738', '7896740', '7896742', '7896744'], 'GB_LIST': [nan, nan, 'NM_001005240,NM_001004195,NM_001005484,BC136848,BC136907', 'BC118988,AL137655', 'NM_001005277,NM_001005221,NM_001005224,NM_001005504,BC137547'], 'SPOT_ID': ['chr1:53049-54936', 'chr1:63015-63887', 'chr1:69091-70008', 'chr1:334129-334296', 'chr1:367659-368597'], 'seqname': ['chr1', 'chr1', 'chr1', 'chr1', 'chr1'], 'RANGE_GB': ['NC_000001.10', 'NC_000001.10', 'NC_000001.10', 'NC_000001.10', 'NC_000001.10'], 'RANGE_STRAND': ['+', '+', '+', '+', '+'], 'RANGE_START': [53049.0, 63015.0, 69091.0, 334129.0, 367659.0], 'RANGE_STOP': [54936.0, 63887.0, 70008.0, 334296.0, 368597.0], 'total_probes': [7.0, 31.0, 24.0, 6.0, 36.0], 'gene_assignment': ['---', '---', 'NM_001005240 // OR4F17 // olfactory receptor, family 4, subfamily F, member 17 // 19p13.3 // 81099 /// NM_001004195 // OR4F4 // olfactory receptor, family 4, subfamily F, member 4 // 15q26.3 // 26682 /// NM_001005484 // OR4F5 // olfactory receptor, family 4, subfamily F, member 5 // 1p36.33 // 79501 /// ENST00000318050 // OR4F17 // olfactory receptor, family 4, subfamily F, member 17 // 19p13.3 // 81099 /// ENST00000335137 // OR4F4 // olfactory receptor, family 4, subfamily F, member 4 // 15q26.3 // 26682 /// ENST00000326183 // OR4F5 // olfactory receptor, family 4, subfamily F, member 5 // 1p36.33 // 79501 /// BC136848 // OR4F17 // olfactory receptor, family 4, subfamily F, member 17 // 19p13.3 // 81099 /// BC136907 // OR4F4 // olfactory receptor, family 4, subfamily F, member 4 // 15q26.3 // 26682 /// ENST00000442916 // OR4F17 // olfactory receptor, family 4, subfamily F, member 17 // 19p13.3 // 81099', 'ENST00000388975 // SEPT14 // septin 14 // 7p11.2 // 346288 /// BC118988 // NCRNA00266 // non-protein coding RNA 266 // --- // 140849 /// AL137655 // LOC100134822 // similar to hCG1739109 // --- // 100134822', 'NM_001005277 // OR4F16 // olfactory receptor, family 4, subfamily F, member 16 // 1p36.33 // 81399 /// NM_001005221 // OR4F29 // olfactory receptor, family 4, subfamily F, member 29 // 1p36.33 // 729759 /// NM_001005224 // OR4F3 // olfactory receptor, family 4, subfamily F, member 3 // 5q35.3 // 26683 /// NM_001005504 // OR4F21 // olfactory receptor, family 4, subfamily F, member 21 // 8p23.3 // 441308 /// ENST00000320901 // OR4F21 // olfactory receptor, family 4, subfamily F, member 21 // 8p23.3 // 441308 /// BC137547 // OR4F3 // olfactory receptor, family 4, subfamily F, member 3 // 5q35.3 // 26683 /// BC137547 // OR4F16 // olfactory receptor, family 4, subfamily F, member 16 // 1p36.33 // 81399 /// BC137547 // OR4F29 // olfactory receptor, family 4, subfamily F, member 29 // 1p36.33 // 729759'], 'mrna_assignment': ['---', 'ENST00000328113 // ENSEMBL // cdna:pseudogene chromosome:GRCh37:15:102467008:102467910:-1 gene:ENSG00000183909 // chr1 // 100 // 100 // 31 // 31 // 0 /// ENST00000318181 // ENSEMBL // cdna:pseudogene chromosome:GRCh37:19:104601:105256:1 gene:ENSG00000176705 // chr1 // 100 // 100 // 31 // 31 // 0 /// ENST00000492842 // ENSEMBL // cdna:pseudogene chromosome:GRCh37:1:62948:63887:1 gene:ENSG00000240361 // chr1 // 100 // 100 // 31 // 31 // 0', 'NM_001005240 // RefSeq // Homo sapiens olfactory receptor, family 4, subfamily F, member 17 (OR4F17), mRNA. // chr1 // 100 // 100 // 24 // 24 // 0 /// NM_001004195 // RefSeq // Homo sapiens olfactory receptor, family 4, subfamily F, member 4 (OR4F4), mRNA. // chr1 // 100 // 100 // 24 // 24 // 0 /// NM_001005484 // RefSeq // Homo sapiens olfactory receptor, family 4, subfamily F, member 5 (OR4F5), mRNA. // chr1 // 100 // 100 // 24 // 24 // 0 /// ENST00000318050 // ENSEMBL // Olfactory receptor 4F17 gene:ENSG00000176695 // chr1 // 100 // 100 // 24 // 24 // 0 /// ENST00000335137 // ENSEMBL // Olfactory receptor 4F4 gene:ENSG00000186092 // chr1 // 100 // 100 // 24 // 24 // 0 /// ENST00000326183 // ENSEMBL // Olfactory receptor 4F5 gene:ENSG00000177693 // chr1 // 100 // 100 // 24 // 24 // 0 /// BC136848 // GenBank // Homo sapiens olfactory receptor, family 4, subfamily F, member 17, mRNA (cDNA clone MGC:168462 IMAGE:9020839), complete cds. // chr1 // 100 // 100 // 24 // 24 // 0 /// BC136907 // GenBank // Homo sapiens olfactory receptor, family 4, subfamily F, member 4, mRNA (cDNA clone MGC:168521 IMAGE:9020898), complete cds. // chr1 // 100 // 100 // 24 // 24 // 0 /// ENST00000442916 // ENSEMBL // OR4F4 (Fragment) gene:ENSG00000176695 // chr1 // 100 // 88 // 21 // 21 // 0', 'ENST00000388975 // ENSEMBL // Septin-14 gene:ENSG00000154997 // chr1 // 50 // 100 // 3 // 6 // 0 /// BC118988 // GenBank // Homo sapiens chromosome 20 open reading frame 69, mRNA (cDNA clone MGC:141807 IMAGE:40035995), complete cds. // chr1 // 100 // 100 // 6 // 6 // 0 /// AL137655 // GenBank // Homo sapiens mRNA; cDNA DKFZp434B2016 (from clone DKFZp434B2016). // chr1 // 100 // 100 // 6 // 6 // 0 /// ENST00000428915 // ENSEMBL // cdna:known chromosome:GRCh37:10:38742109:38755311:1 gene:ENSG00000203496 // chr1 // 100 // 100 // 6 // 6 // 0 /// ENST00000455207 // ENSEMBL // cdna:known chromosome:GRCh37:1:334129:446155:1 gene:ENSG00000224813 // chr1 // 100 // 100 // 6 // 6 // 0 /// ENST00000455464 // ENSEMBL // cdna:known chromosome:GRCh37:1:334140:342806:1 gene:ENSG00000224813 // chr1 // 100 // 100 // 6 // 6 // 0 /// ENST00000440200 // ENSEMBL // cdna:known chromosome:GRCh37:1:536816:655580:-1 gene:ENSG00000230021 // chr1 // 100 // 100 // 6 // 6 // 0 /// ENST00000279067 // ENSEMBL // cdna:known chromosome:GRCh37:20:62921738:62934912:1 gene:ENSG00000149656 // chr1 // 100 // 100 // 6 // 6 // 0 /// ENST00000499986 // ENSEMBL // cdna:known chromosome:GRCh37:5:180717576:180761371:1 gene:ENSG00000248628 // chr1 // 100 // 100 // 6 // 6 // 0 /// ENST00000436899 // ENSEMBL // cdna:known chromosome:GRCh37:6:131910:144885:-1 gene:ENSG00000170590 // chr1 // 100 // 100 // 6 // 6 // 0 /// ENST00000432557 // ENSEMBL // cdna:known chromosome:GRCh37:8:132324:150572:-1 gene:ENSG00000250210 // chr1 // 100 // 100 // 6 // 6 // 0 /// ENST00000523795 // ENSEMBL // cdna:known chromosome:GRCh37:8:141690:150563:-1 gene:ENSG00000250210 // chr1 // 100 // 100 // 6 // 6 // 0 /// ENST00000490482 // ENSEMBL // cdna:known chromosome:GRCh37:8:149942:163324:-1 gene:ENSG00000223508 // chr1 // 100 // 100 // 6 // 6 // 0 /// ENST00000307499 // ENSEMBL // cdna:known supercontig::GL000227.1:57780:70752:-1 gene:ENSG00000229450 // chr1 // 100 // 100 // 6 // 6 // 0 /// ENST00000441245 // ENSEMBL // cdna:known chromosome:GRCh37:1:637316:655530:-1 gene:ENSG00000230021 // chr1 // 100 // 67 // 4 // 4 // 0 /// ENST00000425473 // ENSEMBL // cdna:known chromosome:GRCh37:20:62926294:62944485:1 gene:ENSG00000149656 // chr1 // 100 // 67 // 4 // 4 // 0 /// ENST00000471248 // ENSEMBL // cdna:known chromosome:GRCh37:1:110953:129173:-1 gene:ENSG00000238009 // chr1 // 75 // 67 // 3 // 4 // 0', 'NM_001005277 // RefSeq // Homo sapiens olfactory receptor, family 4, subfamily F, member 16 (OR4F16), mRNA. // chr1 // 100 // 100 // 36 // 36 // 0 /// NM_001005221 // RefSeq // Homo sapiens olfactory receptor, family 4, subfamily F, member 29 (OR4F29), mRNA. // chr1 // 100 // 100 // 36 // 36 // 0 /// NM_001005224 // RefSeq // Homo sapiens olfactory receptor, family 4, subfamily F, member 3 (OR4F3), mRNA. // chr1 // 100 // 100 // 36 // 36 // 0 /// NM_001005504 // RefSeq // Homo sapiens olfactory receptor, family 4, subfamily F, member 21 (OR4F21), mRNA. // chr1 // 89 // 100 // 32 // 36 // 0 /// ENST00000320901 // ENSEMBL // Olfactory receptor 4F21 gene:ENSG00000176269 // chr1 // 89 // 100 // 32 // 36 // 0 /// BC137547 // GenBank // Homo sapiens olfactory receptor, family 4, subfamily F, member 3, mRNA (cDNA clone MGC:169170 IMAGE:9021547), complete cds. // chr1 // 100 // 100 // 36 // 36 // 0 /// ENST00000426406 // ENSEMBL // cdna:known chromosome:GRCh37:1:367640:368634:1 gene:ENSG00000235249 // chr1 // 100 // 100 // 36 // 36 // 0 /// ENST00000332831 // ENSEMBL // cdna:known chromosome:GRCh37:1:621096:622034:-1 gene:ENSG00000185097 // chr1 // 100 // 100 // 36 // 36 // 0 /// ENST00000456475 // ENSEMBL // cdna:known chromosome:GRCh37:5:180794269:180795263:1 gene:ENSG00000230178 // chr1 // 100 // 100 // 36 // 36 // 0 /// ENST00000521196 // ENSEMBL // cdna:known chromosome:GRCh37:11:86612:87605:-1 gene:ENSG00000224777 // chr1 // 78 // 100 // 28 // 36 // 0'], 'category': ['---', 'main', 'main', 'main', 'main']}\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": "cdaf4b2e", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "8cec6bac", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:58:16.660134Z", "iopub.status.busy": "2025-03-25T07:58:16.660009Z", "iopub.status.idle": "2025-03-25T07:58:22.859361Z", "shell.execute_reply": "2025-03-25T07:58:22.858957Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Analyzing gene_annotation dataframe for mapping...\n", "Gene annotation shape: (4395073, 12)\n", "Column names: ['ID', 'GB_LIST', 'SPOT_ID', 'seqname', 'RANGE_GB', 'RANGE_STRAND', 'RANGE_START', 'RANGE_STOP', 'total_probes', 'gene_assignment', 'mrna_assignment', 'category']\n", "\n", "Checking non-empty gene assignments:\n", "Number of non-empty gene assignments: 33297\n", "Sample gene assignment:\n", "---\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Mapping dataframe created:\n", "Shape: (33297, 2)\n", "Sample rows:\n", " ID Gene\n", "0 7896736 ---\n", "1 7896738 ---\n", "2 7896740 NM_001005240 // OR4F17 // olfactory receptor, ...\n", "3 7896742 ENST00000388975 // SEPT14 // septin 14 // 7p11...\n", "4 7896744 NM_001005277 // OR4F16 // olfactory receptor, ...\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Gene expression data after mapping:\n", "Shape: (56391, 131)\n", "First few gene symbols:\n", "['A-', 'A-2', 'A-52', 'A-E', 'A-I', 'A-II', 'A-IV', 'A-V', 'A0', 'A1']\n", "\n", "Preview of gene expression data:\n", "{'GSM4984371': [40.82978590711458, 2.4722163096666665, 3.6812360099999997, 0.4998945246428571, 7.462407054], 'GSM4984372': [42.31433168119358, 2.380555236333333, 3.6982861433333336, 0.49363007257142855, 7.9714218106666666], 'GSM4984373': [41.52395721254568, 2.4463299646666665, 3.750415353333333, 0.5757123258571429, 7.627987897666667], 'GSM4984374': [42.953380502051616, 2.183144652333333, 3.8095943233333336, 0.49244132385714284, 7.634283997666667], 'GSM4984375': [40.92898606758679, 2.400156785, 3.7384230066666664, 0.5014482234285714, 7.467193993333334], 'GSM4984376': [41.35172208334675, 2.39238127, 3.6754141233333333, 0.5450305165714285, 7.8151179903333325], 'GSM4984377': [40.8057277339106, 2.3939998113333334, 3.6602529366666663, 0.5130355922142857, 8.135699602333334], 'GSM4984378': [41.990929820679206, 2.2832587146666667, 3.767447883333333, 0.4934049032857143, 7.726414708666667], 'GSM4984379': [42.858148469812775, 2.536389639333333, 3.676269653333333, 0.6128612093571428, 7.927850146666666], 'GSM4984380': [42.083956313414795, 2.424275092, 3.69513108, 0.5126254107142857, 7.599483021666666], 'GSM4984381': [40.430262769684575, 2.463462476333333, 3.667570363333333, 0.5063200302857143, 8.178512928333333], 'GSM4984382': [42.480911237478736, 2.567945033, 3.76451964, 0.5357791802857143, 7.755013943], 'GSM4984383': [43.06178646542702, 2.4089582689999998, 3.595321033333333, 0.47990736935714284, 7.520291313333333], 'GSM4984384': [41.96845564997696, 2.4211960813333335, 3.6810511966666666, 0.5166311494285715, 7.687993407333334], 'GSM4984385': [39.849792927866275, 2.443016197, 3.6850461066666664, 0.4836944969285714, 7.441377272333333], 'GSM4984386': [41.514246474779796, 2.399029446, 3.7340636933333333, 0.49582815407142855, 7.544242715333333], 'GSM4984387': [41.174725546523995, 2.2971190416666665, 3.6882443133333336, 0.5099734990714285, 7.452686341], 'GSM4984388': [41.47626128379008, 2.5263467079999997, 3.6674308566666665, 0.5200867145714285, 7.6652223353333335], 'GSM4984389': [41.56723436060185, 2.304128227666667, 3.6592664866666667, 0.5677078844285715, 7.8418226823333335], 'GSM4984390': [43.207000184723086, 2.3291649276666666, 3.7470123233333332, 0.5056046397857142, 7.671825831333333], 'GSM4984391': [41.92140994249517, 2.4070426813333334, 3.63834559, 0.5049653195, 7.3827331916666665], 'GSM4984392': [42.45229724607202, 2.366486882333333, 3.779491816666667, 0.49479350235714287, 7.409031963], 'GSM4984393': [41.87861574228925, 2.5024000496666665, 3.72607559, 0.5188904201428571, 7.666810761333334], 'GSM4984394': [41.671275609979624, 2.620040458, 3.7393208633333335, 0.4908841859285714, 7.741798872333334], 'GSM4984395': [41.66843039983049, 2.3636864533333335, 3.7034383633333334, 0.5159708468571428, 7.8679557896666665], 'GSM4984396': [41.47748555318187, 2.4204337286666666, 3.7782438666666667, 0.46928875142857146, 8.085213501666667], 'GSM4984397': [44.025851063667865, 2.4077085196666665, 3.7433491, 0.5227002555, 7.901688622666667], 'GSM4984398': [43.75579055103457, 2.406859718666667, 3.7425984666666667, 0.5174651852857143, 7.717231545333334], 'GSM4984399': [40.06252600398521, 2.477550826, 3.74789586, 0.4988131635714286, 7.572510690333333], 'GSM4984400': [42.02632548448512, 2.3807291256666665, 3.81787361, 0.5498856737142858, 7.648568862666667], 'GSM4984401': [41.27391591012769, 2.4585151473333333, 3.7201412566666665, 0.5263936440714285, 7.413323548], 'GSM4984402': [40.498663936900876, 2.2230927223333334, 3.9091366733333337, 0.5310472464285715, 7.943611519333333], 'GSM4984403': [42.60702094230002, 2.361278015, 3.7161685500000003, 0.5313411116428571, 8.621776665], 'GSM4984404': [41.127060969901635, 2.2693005223333333, 3.7700943700000003, 0.4754072434285714, 7.6375370563333345], 'GSM4984405': [41.49875446156428, 2.437000971666667, 3.814496933333333, 0.48425216078571426, 7.358375986666666], 'GSM4984406': [42.265951667084146, 2.396596432, 3.8651943933333333, 0.5081677455, 7.732195783666667], 'GSM4984407': [40.65570605863988, 2.4412355949999998, 3.6342228566666663, 0.5212939800714286, 7.736085155333333], 'GSM4984408': [41.692268393402735, 2.2791424673333336, 3.894923306666667, 0.48861590378571423, 7.620700411333333], 'GSM4984409': [41.91840550677765, 2.485426358666667, 3.7334166233333335, 0.49030294407142855, 7.748569043], 'GSM4984410': [40.26171184274901, 2.4285196743333333, 3.717160043333333, 0.5509080867142857, 7.6572046160000005], 'GSM4984411': [41.22681303035865, 2.3655594066666668, 3.6872369700000003, 0.5178923247142857, 7.699298438333333], 'GSM4984412': [40.878344911705916, 2.3402897923333335, 3.6485972266666664, 0.48082218657142856, 7.765884919666666], 'GSM4984413': [41.71771992632491, 2.4180108590000002, 3.764964586666667, 0.4900379325714286, 7.286582154333334], 'GSM4984414': [42.001351296012, 2.4582089673333334, 3.7880214033333335, 0.5120145868571429, 7.707244900000001], 'GSM4984415': [40.14910049385088, 2.499831786666667, 3.737256, 0.49991775714285713, 7.669073407666667], 'GSM4984416': [42.06743548115594, 2.404589260333333, 3.759343846666667, 0.5238383740714286, 7.821217684333334], 'GSM4984417': [41.123822751018245, 2.4457525936666666, 3.69404108, 0.5198458546428572, 7.401235883333333], 'GSM4984418': [39.715487576759436, 2.6490910916666666, 3.7526965466666664, 0.5332266130714286, 7.920223485666667], 'GSM4984419': [41.4865540734491, 2.535629499, 3.705635773333333, 0.5410614377142857, 7.604183545333333], 'GSM4984420': [37.84620702786567, 2.944274666, 3.677916756666667, 0.5311285751428572, 7.603004089333333], 'GSM4984421': [41.507676254420375, 2.506871316666667, 3.7028129, 0.4997255942857143, 7.75008227], 'GSM4984422': [42.68130212076795, 2.564839743, 3.818435883333333, 0.5033346901428571, 7.617451536], 'GSM4984423': [42.22411525608054, 2.4249789136666666, 3.7468186266666668, 0.45283476242857146, 7.442447358333333], 'GSM4984424': [42.93323701772097, 2.6119296286666667, 3.8285931000000004, 0.5161621081428571, 7.605862209333333], 'GSM4984425': [41.939675348432736, 2.281475778, 3.70560146, 0.5728852642857143, 7.759697657666667], 'GSM4984426': [41.28332986473923, 2.39990755, 3.7519981933333333, 0.5002808899285714, 7.407749582333333], 'GSM4984427': [40.49445994211353, 2.301324150333333, 3.7785145100000004, 0.5545491107857143, 7.912791946666667], 'GSM4984428': [40.81296133857008, 2.4827619743333336, 3.8983675366666666, 0.5297848427857142, 7.839765325666667], 'GSM4984429': [38.35891571365133, 2.3401817676666665, 3.882436323333333, 0.5064152581428571, 7.670485701333334], 'GSM4984430': [41.74788915058858, 2.4817706773333335, 3.82524714, 0.5291211951428572, 7.591877246666666], 'GSM4984431': [40.46801014844068, 2.4744832333333333, 3.910119313333333, 0.4849518835714286, 7.688098423666666], 'GSM4984432': [39.68881162965285, 2.3966240943333332, 3.6035170733333337, 0.4857471878571428, 7.441196228], 'GSM4984433': [41.701115000169146, 2.571017172, 3.8199392, 0.5007394063571429, 7.689452301333334], 'GSM4984434': [41.26025230319335, 2.427456612, 3.83769504, 0.5084859311428571, 7.599890418666667], 'GSM4984435': [39.46348041535544, 2.626448848, 3.6316890633333334, 0.5215255580714285, 7.618014814], 'GSM4984436': [41.639066228505556, 2.3381838883333335, 3.6523649433333336, 0.49485104557142856, 7.367191987333333], 'GSM4984437': [42.32189243264958, 2.4231164240000003, 3.76594063, 0.49601215835714285, 7.332492951333333], 'GSM4984438': [40.865816568383416, 2.451396437666667, 3.807931613333333, 0.5232938759285715, 7.7307312716666665], 'GSM4984439': [41.33210661215102, 2.4677637233333334, 3.6519018333333335, 0.5004271655714285, 7.504569995333334], 'GSM4984440': [40.998451775826496, 2.4098655156666666, 3.62764015, 0.46580800242857145, 7.563723693], 'GSM4984441': [40.700467474715836, 2.5252340663333332, 3.6934702099999996, 0.5069962120714285, 7.587303213], 'GSM4984442': [41.91484275184803, 2.490859529666667, 3.7125900766666664, 0.5255949776428571, 7.434199264], 'GSM4984443': [42.27545494341595, 2.3078745426666667, 3.74133741, 0.48229948857142857, 7.425344280333334], 'GSM4984444': [41.407511545742274, 2.4309593686666666, 3.8638911966666663, 0.4867099609285714, 7.399990103333334], 'GSM4984445': [42.60011544370813, 2.352524316333333, 3.7740360533333335, 0.4942204161428571, 7.35639484], 'GSM4984446': [41.6163802496555, 2.3519426979999998, 3.713642366666667, 0.49989916907142856, 7.379165284000001], 'GSM4984447': [41.19182633225757, 2.510358592333333, 3.751446023333333, 0.5156785657857142, 7.757023476333333], 'GSM4984448': [42.4805008861218, 2.4505782320000002, 3.677076786666667, 0.5144006422857142, 7.696385791333334], 'GSM4984449': [43.85294831971991, 2.347310615, 3.777029986666667, 0.5232211076428571, 7.515900125], 'GSM4984450': [42.45589827656962, 2.3365442913333334, 3.6972362933333334, 0.5245301207142857, 7.627237594], 'GSM4984451': [41.295491688569335, 2.3232147286666667, 3.826272063333333, 0.5253423854285714, 7.583367111666666], 'GSM4984452': [42.5785543397031, 2.161270506, 3.8400610700000004, 0.5245322049285714, 7.608951100666667], 'GSM4984453': [43.12455778767914, 2.545705852333333, 3.8050848266666666, 0.5098509455, 7.478918196], 'GSM4984454': [42.65302204222403, 2.329370208, 3.8140685600000004, 0.5048054145, 7.473574432333334], 'GSM4984455': [41.22125207084827, 2.3944865683333334, 3.7471495066666667, 0.5105785245, 7.6190885176666665], 'GSM4984456': [41.56025900039461, 2.334199391, 3.7462034366666668, 0.5066320964285714, 7.295694625], 'GSM4984457': [39.55098383928545, 2.437587992, 3.8343621833333335, 0.49016824964285716, 7.654463875333333], 'GSM4984458': [40.88328259762078, 2.39346854, 3.7856405399999997, 0.4859869272142857, 7.455199644666667], 'GSM4984459': [40.57779468567065, 2.4066908793333335, 3.7512308433333335, 0.4962932845714286, 7.598307518666667], 'GSM4984460': [40.03615713583335, 2.348076212, 3.7982756566666667, 0.5067522381428572, 7.494289154666667], 'GSM4984461': [41.97956447681479, 2.2856435543333333, 3.8322843933333335, 0.5045592393571429, 7.463331501], 'GSM4984462': [41.851197347210075, 2.4893138906666668, 3.7301299866666664, 0.49340179692857145, 7.981941186], 'GSM4984463': [40.06102533488609, 2.3592407643333333, 3.7866343033333334, 0.5123878543571428, 8.159647681000001], 'GSM4984464': [40.653240183543765, 2.28694783, 3.6988337666666666, 0.5014311089285715, 7.457891013], 'GSM4984465': [39.798709310615386, 2.3756619563333334, 3.7723496966666663, 0.479232428, 7.578296573], 'GSM4984466': [40.496988732483274, 2.2776280986666664, 3.80142681, 0.5011667719285714, 7.477357553666668], 'GSM4984467': [40.14568641639133, 2.4540559243333333, 3.772501613333333, 0.5026540313571429, 7.478540726333334], 'GSM4984468': [42.317076633264875, 2.2352354153333334, 3.694811373333333, 0.5428287147142857, 7.480254148], 'GSM4984469': [40.775481783676334, 2.414126441, 3.6650374266666668, 0.495460562, 7.499297634666666], 'GSM4984470': [41.675650325282604, 2.356440506333333, 3.7486427733333336, 0.4998522957857143, 7.414674362666666], 'GSM4984471': [40.54858575919787, 2.418085684333333, 3.720268716666667, 0.4754705062857143, 7.437211423666667], 'GSM4984472': [42.14918187204053, 2.613877993, 3.859315626666667, 0.5060321057857143, 7.768738023333333], 'GSM4984473': [39.90261749554444, 2.458735817, 3.84627017, 0.49954774385714285, 7.481339088666667], 'GSM4984474': [41.56334691106757, 2.428896562333333, 3.7010496533333335, 0.5119482695, 7.526813234333333], 'GSM4984475': [41.141926961737575, 2.3100652856666666, 3.7749843066666666, 0.5125097845, 7.505531295333333], 'GSM4984476': [42.251857484870456, 2.371726922666667, 3.8493132033333333, 0.5315258672857143, 7.558502481333333], 'GSM4984477': [42.37760227233198, 2.33199987, 3.6633394999999997, 0.5056749700000001, 7.552708334333333], 'GSM4984478': [43.36644292874463, 2.402655960666667, 3.7577790566666667, 0.49565908614285714, 7.904579424333333], 'GSM4984479': [40.975219286757856, 2.5353538270000002, 3.83363612, 0.5046448268571428, 7.588846005666667], 'GSM4984480': [41.283887880727534, 2.4920028443333333, 3.7175591933333334, 0.5201563407142857, 7.450466851666667], 'GSM4984481': [41.57954421959657, 2.5452261853333336, 3.737848956666667, 0.526882061, 7.515837005333333], 'GSM4984482': [42.8727294960886, 2.4016754453333333, 3.7461020566666665, 0.48864455492857145, 7.853649934666667], 'GSM4984483': [42.34641485068516, 2.314287421, 3.711680016666667, 0.4923591827857143, 7.482550132], 'GSM4984484': [42.261063611450496, 2.3595111576666667, 3.7540345966666666, 0.5219362793571428, 7.582907043666666], 'GSM4984485': [40.683702332013596, 2.286275207666667, 3.688701143333333, 0.48691535592857144, 7.5845828143333325], 'GSM4984486': [41.572113916871956, 2.444249053666667, 3.71437365, 0.47672313507142855, 7.696849152], 'GSM4984487': [41.17526468841094, 2.312589322, 3.7016065633333333, 0.48853591585714284, 7.489195992333332], 'GSM4984488': [40.88760935064461, 2.5059555523333334, 3.8338705133333337, 0.5380376256428571, 7.710040823333333], 'GSM4984489': [42.685108723647, 2.4135772903333335, 3.8210126933333335, 0.5293864739285714, 7.733555447666666], 'GSM4984490': [41.97539742583878, 2.4369064796666664, 3.801646846666667, 0.5043402481428572, 7.796774675666667], 'GSM4984491': [41.014250006524755, 2.47218261, 3.8026937833333334, 0.49818345014285714, 7.678524973], 'GSM4984492': [42.12853720046636, 2.454936625333333, 3.7383802533333337, 0.4849560832142857, 7.893340974000001], 'GSM4984493': [42.176028486284, 2.329686710333333, 3.79325568, 0.4989772572142857, 7.6464147186666676], 'GSM4984494': [39.18270131865952, 2.4547612576666666, 3.7529985333333333, 0.4702896822142857, 7.736784159666666], 'GSM4984495': [40.381282759860966, 2.498552183333333, 3.7933798766666667, 0.4847619415, 7.7859368306666665], 'GSM4984496': [41.625036280087684, 2.3799704613333335, 3.7748530633333335, 0.5127356197857142, 7.6135380533333326], 'GSM4984497': [41.04148991329079, 2.357943858, 3.6824538400000004, 0.500830179, 7.631679395666667], 'GSM4984498': [41.66141814469742, 2.473714966333333, 3.8287833800000004, 0.545655174, 7.911144901666667], 'GSM4984499': [41.93305472191488, 2.3984655176666667, 3.7446713166666665, 0.5237145652142857, 7.690846305000001], 'GSM4984500': [40.965684023644776, 2.267912812, 3.714382993333333, 0.5061044385714285, 7.754188282666667], 'GSM4984501': [42.67259733989884, 2.3873183929999997, 3.7557532666666664, 0.5327749778571429, 7.8063083896666665]}\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Gene expression data saved to ../../output/preprocess/Mesothelioma/gene_data/GSE163720.csv\n" ] } ], "source": [ "# 1. Identify the relevant columns for mapping\n", "# Based on the previews:\n", "# - Gene expression data has numeric IDs like '7892501', '7892502', etc.\n", "# - In the gene annotation, the 'ID' column contains similar numeric identifiers\n", "# - The 'gene_assignment' column contains gene symbols and other information\n", "\n", "print(\"Analyzing gene_annotation dataframe for mapping...\")\n", "print(f\"Gene annotation shape: {gene_annotation.shape}\")\n", "print(f\"Column names: {gene_annotation.columns.tolist()}\")\n", "\n", "# 2. Create a gene mapping dataframe\n", "# We need to extract gene symbols from the 'gene_assignment' column\n", "# First check if any rows have gene symbols\n", "print(\"\\nChecking non-empty gene assignments:\")\n", "non_empty_assignments = gene_annotation['gene_assignment'].dropna()\n", "print(f\"Number of non-empty gene assignments: {len(non_empty_assignments)}\")\n", "print(\"Sample gene assignment:\")\n", "print(non_empty_assignments.iloc[0] if len(non_empty_assignments) > 0 else \"No non-empty assignments\")\n", "\n", "# Create the mapping dataframe\n", "mapping_df = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='gene_assignment')\n", "print(\"\\nMapping dataframe created:\")\n", "print(f\"Shape: {mapping_df.shape}\")\n", "print(\"Sample rows:\")\n", "print(mapping_df.head())\n", "\n", "# 3. Apply the gene mapping to convert probe-level measurements to gene expression data\n", "gene_data = apply_gene_mapping(gene_data, mapping_df)\n", "print(\"\\nGene expression data after mapping:\")\n", "print(f\"Shape: {gene_data.shape}\")\n", "print(\"First few gene symbols:\")\n", "print(gene_data.index[:10].tolist())\n", "\n", "# Preview the gene expression data\n", "gene_data_preview = preview_df(gene_data)\n", "print(\"\\nPreview of gene expression data:\")\n", "print(gene_data_preview)\n", "\n", "# Create directory if it doesn't exist\n", "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n", "\n", "# Save the gene expression data\n", "gene_data.to_csv(out_gene_data_file)\n", "print(f\"\\nGene expression data saved to {out_gene_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "20e9338e", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "d4cd8029", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:58:22.860806Z", "iopub.status.busy": "2025-03-25T07:58:22.860680Z", "iopub.status.idle": "2025-03-25T07:58:31.033349Z", "shell.execute_reply": "2025-03-25T07:58:31.033007Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Shape of gene data after normalization: (20124, 131)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Saved normalized gene data to ../../output/preprocess/Mesothelioma/gene_data/GSE163720.csv\n", "Number of samples: 131\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Sample characteristics dictionary:\n", "{0: ['organ: Tumor'], 1: ['compartment: Tissue'], 2: ['Sex: F', 'Sex: M']}\n", "Clinical data preview:\n", " Mesothelioma\n", "GSM4984371 1\n", "GSM4984372 1\n", "GSM4984373 1\n", "GSM4984374 1\n", "GSM4984375 1\n", "Saved clinical data to ../../output/preprocess/Mesothelioma/clinical_data/GSE163720.csv\n", "Shape of linked data: (131, 20125)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Shape of linked data after handling missing values: (131, 20125)\n", "Quartiles for 'Mesothelioma':\n", " 25%: 1.0\n", " 50% (Median): 1.0\n", " 75%: 1.0\n", "Min: 1\n", "Max: 1\n", "The distribution of the feature 'Mesothelioma' in this dataset is severely biased.\n", "\n", "Dataset validation failed due to biased trait variable. Final linked data not saved.\n" ] } ], "source": [ "# 1. Normalize gene symbols in the gene expression data\n", "gene_data_normalized = normalize_gene_symbols_in_index(gene_data)\n", "print(f\"Shape of gene data after normalization: {gene_data_normalized.shape}\")\n", "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n", "gene_data_normalized.to_csv(out_gene_data_file)\n", "print(f\"Saved normalized gene data to {out_gene_data_file}\")\n", "\n", "# 2. Create clinical data from the sample IDs in the gene expression data\n", "# Since all samples are from tumor tissue, they all have mesothelioma (but this is not useful as a trait)\n", "sample_ids = gene_data.columns.tolist()\n", "print(f\"Number of samples: {len(sample_ids)}\")\n", "\n", "# Extract gender information from the original matrix file\n", "gender_data = {}\n", "try:\n", " soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", " \n", " # Read the matrix file to extract sample characteristics\n", " background_info, clinical_data = get_background_and_clinical_data(matrix_file)\n", " \n", " # Display unique values in each row of clinical data\n", " characteristics_dict = get_unique_values_by_row(clinical_data)\n", " print(\"Sample characteristics dictionary:\")\n", " print(characteristics_dict)\n", " \n", " # Try to find gender information in the characteristics\n", " gender_row = None\n", " for idx, values in characteristics_dict.items():\n", " if any('sex:' in str(v).lower() for v in values):\n", " gender_row = idx\n", " break\n", " \n", " if gender_row is not None:\n", " # Extract gender data from the row\n", " for col in clinical_data.columns:\n", " if col != '!Sample_geo_accession':\n", " continue\n", " \n", " for idx, row in clinical_data.iterrows():\n", " if idx == gender_row:\n", " for i, sample_id in enumerate(clinical_data.iloc[0].values):\n", " if i > 0 and sample_id in sample_ids: # Skip the first column (header)\n", " gender_val = clinical_data.iloc[idx, i]\n", " if isinstance(gender_val, str) and 'sex:' in gender_val.lower():\n", " gender = 0 if 'f' in gender_val.lower() else 1 if 'm' in gender_val.lower() else None\n", " gender_data[sample_id] = gender\n", "except Exception as e:\n", " print(f\"Error extracting gender data: {e}\")\n", "\n", "# Create a clinical dataframe\n", "clinical_df = pd.DataFrame(index=sample_ids)\n", "clinical_df['Mesothelioma'] = 1 # All samples have mesothelioma\n", "\n", "# Add gender if available\n", "if gender_data:\n", " clinical_df['Gender'] = clinical_df.index.map(lambda x: gender_data.get(x))\n", " print(f\"Added gender data for {sum(pd.notna(clinical_df['Gender']))} samples\")\n", "\n", "print(\"Clinical data preview:\")\n", "print(clinical_df.head())\n", "\n", "# Save the clinical data\n", "os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", "clinical_df.to_csv(out_clinical_data_file)\n", "print(f\"Saved clinical data to {out_clinical_data_file}\")\n", "\n", "# 3. Link clinical and genetic data (transpose gene expression data to have samples as rows)\n", "linked_data = pd.concat([clinical_df, gene_data_normalized.T], axis=1)\n", "print(f\"Shape of linked data: {linked_data.shape}\")\n", "\n", "# 4. Handle missing values in the linked data\n", "linked_data_cleaned = handle_missing_values(linked_data, 'Mesothelioma')\n", "print(f\"Shape of linked data after handling missing values: {linked_data_cleaned.shape}\")\n", "\n", "# 5. Check if the trait is biased (it will be since all samples are mesothelioma)\n", "is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data_cleaned, 'Mesothelioma')\n", "\n", "# 6. Validate the dataset and save cohort information\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, # We do have trait data, it's just that all values are the same\n", " is_biased=is_trait_biased, # This will be True since all samples have the same trait value\n", " df=unbiased_linked_data,\n", " note=\"Dataset contains gene expression data from mesothelioma patients only (no controls), making trait biased.\"\n", ")\n", "\n", "# 7. Save the linked data if it's usable\n", "if is_usable:\n", " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n", " unbiased_linked_data.to_csv(out_data_file)\n", " print(f\"Saved processed linked data to {out_data_file}\")\n", "else:\n", " print(\"Dataset validation failed due to biased trait variable. Final linked data 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 }