{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "68787eea", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:27:41.989984Z", "iopub.status.busy": "2025-03-25T05:27:41.989786Z", "iopub.status.idle": "2025-03-25T05:27:42.184562Z", "shell.execute_reply": "2025-03-25T05:27:42.184094Z" } }, "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 = \"Head_and_Neck_Cancer\"\n", "cohort = \"GSE184944\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Head_and_Neck_Cancer\"\n", "in_cohort_dir = \"../../input/GEO/Head_and_Neck_Cancer/GSE184944\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Head_and_Neck_Cancer/GSE184944.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Head_and_Neck_Cancer/gene_data/GSE184944.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Head_and_Neck_Cancer/clinical_data/GSE184944.csv\"\n", "json_path = \"../../output/preprocess/Head_and_Neck_Cancer/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "694b9551", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "56ad3100", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:27:42.185913Z", "iopub.status.busy": "2025-03-25T05:27:42.185749Z", "iopub.status.idle": "2025-03-25T05:27:42.212386Z", "shell.execute_reply": "2025-03-25T05:27:42.211979Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Immune gene expression analysis for oral leukplakia samples\"\n", "!Series_summary\t\"Oral leukoplakia is common and may in some cases progress to carcinoma. Proliferative leukoplakia (PL) is a progressive, often multifocal subtype with a high rate of malignant transformation (MT) compared to the more common localized leukoplakia (LL). We hypothesized that the immune microenvironment and gene expression patterns would be distinct for PL compared to LL. We summarize key clinicopathologic features among PL and LL and compare cancer-free survival (CFS) between subgroups. We analyze immunologic gene expression profiling (GEP) in PL and LL tissue samples (NanoString PanCancer Immune Oncology Profiling). We integrate immune cell activation and spatial distribution patterns in tissue samples using multiplexed immunofluorescence and digital image capture to further define PL and LL. Among N=58 patients (PL: 29, LL: 29), only the clinical diagnosis of PL was associated with significantly decreased CFS (HR 11.25, p<0.01); 5-year CFS 46.8% and 83.6% among PL and LL patients, respectively. CD8+ T cells and Tregs were more abundant among PL samples (p<0.01) regardless of degree of epithelial dysplasia, and often colocalized to the dysplasia-stromal interface. Gene set analysis identified granzyme-M (GZMM) as the most differentially expressed gene favoring the PL subgroup (log2 fold change 1.93, adjusted p<0.001). PD-L1 was comparatively over-expressed among PL samples, with higher (>5) PD-L1 scores predicting worse CFS (p<0.01). PL predicts a high rate of MT within 5-years of diagnosis. Robust CD8+ T cell and Treg signature along with relative PD-L1 over-expression compared with LL provides strong rationale for PD-1/L1 axis blockade using preventative immunotherapy.\"\n", "!Series_overall_design\t\"RNA from each oral leukoplakia (OL) specimen was isolated from cores punched from areas of epithelial dysplasia (High Pure FFPET RNA Isolation Kit, Roche Diagnostics, Indianapolis, Indiana) marked on FFPE tissue slides and quantified. From our initial retrospective single institution cohort of 149 patients first diagnosed with an OL between 2000 and 2018, 78 had LL and 71 had PL. Among 58 randomly selected patients with available (non-exhausted) tissue samples the two prespecified groups of LL (N=29) and PL (N=29) were balanced in terms of baseline characteristics such as age, gender, smoking history, oral cavity subsite, and pathologic diagnosis. We first compared immune cell type RNA expression profiles for all LL and PL samples, and by degree of histologic atypia. We also sought to interrogate which cytotoxicity genes accounted for immune cell type profiling differences among the LL and PL subgroups. Global significance scores (GSS) were determined to measure the overall differential expression of selected genes relative to LL or PL phenotype ignoring whether genes were up- or down-regulated. Of the 58 samples, 49 passed Nanostring quality metrics for analysis.\"\n", "Sample Characteristics Dictionary:\n", "{0: ['histology: EL', 'histology: LL', 'histology: PEL', 'histology: PL'], 1: ['smoking status: N', 'smoking status: C', 'smoking status: F'], 2: ['gender: M', 'gender: F']}\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": "b0b51747", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "9c73c5fa", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:27:42.213647Z", "iopub.status.busy": "2025-03-25T05:27:42.213533Z", "iopub.status.idle": "2025-03-25T05:27:42.218181Z", "shell.execute_reply": "2025-03-25T05:27:42.217781Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Analysis completed: This dataset contains gene expression data and trait information (histology types).\n", "The trait is binary with PL (Proliferative leukoplakia) representing high risk (1) and other types as lower risk (0).\n", "Gender information is available but age information is not available in this dataset.\n" ] } ], "source": [ "# 1. Gene Expression Data Availability\n", "# This dataset appears to be gene expression data from the NanoString PanCancer Immune Oncology Profiling,\n", "# which focuses on immune gene expression in oral leukoplakia samples\n", "is_gene_available = True\n", "\n", "# 2.1 Data Availability\n", "\n", "# Trait is available in row 0, which indicates histology type (EL, LL, PEL, or PL)\n", "# Based on the background information, PL (Proliferative leukoplakia) has higher rate of \n", "# malignant transformation than LL (localized leukoplakia)\n", "trait_row = 0\n", "\n", "# Age is not available in the sample characteristics\n", "age_row = None\n", "\n", "# Gender is available in row 2\n", "gender_row = 2\n", "\n", "# 2.2 Data Type Conversion\n", "\n", "def convert_trait(value):\n", " \"\"\"\n", " Convert histology type to binary: 1 for PL (higher risk) and 0 for others\n", " \"\"\"\n", " if value is None:\n", " return None\n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " # From background info: PL has higher malignant transformation rate\n", " if value == \"PL\": # Proliferative leukoplakia - high risk\n", " return 1\n", " elif value in [\"LL\", \"EL\", \"PEL\"]: # Other types - lower risk\n", " return 0\n", " else:\n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"\n", " Convert age to continuous value\n", " \"\"\"\n", " # Age data not available\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"\n", " Convert gender to binary: 0 for female, 1 for male\n", " \"\"\"\n", " if value is None:\n", " return None\n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \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", "# Since trait_row is not None, trait data is available\n", "is_usable = 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=(trait_row is not None)\n", ")\n", "\n", "# Note: We're stopping here as we don't have access to the actual clinical data matrix \n", "# needed to perform step 4 (Clinical Feature Extraction). We have identified the rows and\n", "# conversion functions that would be used if we had the data.\n", "print(\"Analysis completed: This dataset contains gene expression data and trait information (histology types).\")\n", "print(\"The trait is binary with PL (Proliferative leukoplakia) representing high risk (1) and other types as lower risk (0).\")\n", "print(\"Gender information is available but age information is not available in this dataset.\")\n" ] }, { "cell_type": "markdown", "id": "f4c5f08a", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "cfc13d41", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:27:42.219385Z", "iopub.status.busy": "2025-03-25T05:27:42.219275Z", "iopub.status.idle": "2025-03-25T05:27:42.232371Z", "shell.execute_reply": "2025-03-25T05:27:42.231912Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Matrix file found: ../../input/GEO/Head_and_Neck_Cancer/GSE184944/GSE184944_series_matrix.txt.gz\n", "Gene data shape: (730, 49)\n", "First 20 gene/probe identifiers:\n", "Index(['A2M', 'ABCB1', 'ABL1', 'ADA', 'ADORA2A', 'AICDA', 'AIRE', 'AKT3',\n", " 'ALCAM', 'AMBP', 'AMICA1', 'ANP32B', 'ANXA1', 'APOE', 'APP', 'ARG1',\n", " 'ARG2', 'ATF1', 'ATF2', 'ATG10'],\n", " dtype='object', name='ID')\n" ] } ], "source": [ "# 1. Get the SOFT and matrix file paths again \n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "print(f\"Matrix file found: {matrix_file}\")\n", "\n", "# 2. Use the get_genetic_data function from the library to get the gene_data\n", "try:\n", " gene_data = get_genetic_data(matrix_file)\n", " print(f\"Gene data shape: {gene_data.shape}\")\n", " \n", " # 3. Print the first 20 row IDs (gene or probe identifiers)\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" ] }, { "cell_type": "markdown", "id": "962e554b", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "7457b7e0", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:27:42.233636Z", "iopub.status.busy": "2025-03-25T05:27:42.233518Z", "iopub.status.idle": "2025-03-25T05:27:42.235533Z", "shell.execute_reply": "2025-03-25T05:27:42.235160Z" } }, "outputs": [], "source": [ "# Based on the gene identifiers shown (A2M, ABCB1, ABL1, etc.), these are already\n", "# standard human gene symbols that don't need mapping.\n", "# These are official gene symbols as recognized by HGNC (HUGO Gene Nomenclature Committee).\n", "\n", "requires_gene_mapping = False\n" ] }, { "cell_type": "markdown", "id": "c7834eae", "metadata": {}, "source": [ "### Step 5: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 6, "id": "62c2201a", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:27:42.236726Z", "iopub.status.busy": "2025-03-25T05:27:42.236617Z", "iopub.status.idle": "2025-03-25T05:27:42.528489Z", "shell.execute_reply": "2025-03-25T05:27:42.528024Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene data shape before normalization: (730, 49)\n", "Gene data shape after normalization: (726, 49)\n", "Normalized gene expression data saved to ../../output/preprocess/Head_and_Neck_Cancer/gene_data/GSE184944.csv\n", "Original clinical data preview:\n", " !Sample_geo_accession GSM5602145 GSM5602146 \\\n", "0 !Sample_characteristics_ch1 histology: EL histology: EL \n", "1 !Sample_characteristics_ch1 smoking status: N smoking status: N \n", "2 !Sample_characteristics_ch1 gender: M gender: M \n", "\n", " GSM5602147 GSM5602148 GSM5602149 GSM5602150 \\\n", "0 histology: EL histology: LL histology: LL histology: LL \n", "1 smoking status: N smoking status: N smoking status: C smoking status: F \n", "2 gender: F gender: F gender: M gender: F \n", "\n", " GSM5602151 GSM5602152 GSM5602153 ... \\\n", "0 histology: LL histology: LL histology: LL ... \n", "1 smoking status: N smoking status: N smoking status: N ... \n", "2 gender: M gender: F gender: F ... \n", "\n", " GSM5602184 GSM5602185 GSM5602186 GSM5602187 \\\n", "0 histology: PL histology: PL histology: PL histology: PL \n", "1 smoking status: F smoking status: F smoking status: F smoking status: N \n", "2 gender: F gender: F gender: F gender: F \n", "\n", " GSM5602188 GSM5602189 GSM5602190 GSM5602191 \\\n", "0 histology: PL histology: PL histology: PL histology: PL \n", "1 smoking status: F smoking status: N smoking status: N smoking status: F \n", "2 gender: M gender: M gender: M gender: M \n", "\n", " GSM5602192 GSM5602193 \n", "0 histology: PL histology: PL \n", "1 smoking status: N smoking status: N \n", "2 gender: M gender: F \n", "\n", "[3 rows x 50 columns]\n", "Selected clinical data shape: (2, 49)\n", "Clinical data preview:\n", " GSM5602145 GSM5602146 GSM5602147 GSM5602148 \\\n", "Head_and_Neck_Cancer 0.0 0.0 0.0 0.0 \n", "Gender 1.0 1.0 0.0 0.0 \n", "\n", " GSM5602149 GSM5602150 GSM5602151 GSM5602152 \\\n", "Head_and_Neck_Cancer 0.0 0.0 0.0 0.0 \n", "Gender 1.0 0.0 1.0 0.0 \n", "\n", " GSM5602153 GSM5602154 ... GSM5602184 GSM5602185 \\\n", "Head_and_Neck_Cancer 0.0 0.0 ... 1.0 1.0 \n", "Gender 0.0 1.0 ... 0.0 0.0 \n", "\n", " GSM5602186 GSM5602187 GSM5602188 GSM5602189 \\\n", "Head_and_Neck_Cancer 1.0 1.0 1.0 1.0 \n", "Gender 0.0 0.0 1.0 1.0 \n", "\n", " GSM5602190 GSM5602191 GSM5602192 GSM5602193 \n", "Head_and_Neck_Cancer 1.0 1.0 1.0 1.0 \n", "Gender 1.0 1.0 1.0 0.0 \n", "\n", "[2 rows x 49 columns]\n", "Linked data shape before processing: (49, 728)\n", "Linked data preview (first 5 rows, 5 columns):\n", " Head_and_Neck_Cancer Gender A2M ABCB1 ABL1\n", "GSM5602145 0.0 1.0 11.137220 6.936910 8.987536\n", "GSM5602146 0.0 1.0 10.803632 7.485260 8.764845\n", "GSM5602147 0.0 0.0 10.026320 5.587971 7.964119\n", "GSM5602148 0.0 0.0 11.191067 7.370523 8.837430\n", "GSM5602149 0.0 1.0 10.219763 6.062984 8.686679\n", "Data shape after handling missing values: (49, 728)\n", "For the feature 'Head_and_Neck_Cancer', the least common label is '1.0' with 15 occurrences. This represents 30.61% of the dataset.\n", "For the feature 'Gender', the least common label is '1.0' with 23 occurrences. This represents 46.94% of the dataset.\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Linked data saved to ../../output/preprocess/Head_and_Neck_Cancer/GSE184944.csv\n" ] } ], "source": [ "# 1. Normalize gene symbols in the gene expression data\n", "# Use normalize_gene_symbols_in_index to standardize gene symbols\n", "normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n", "print(f\"Gene data shape before normalization: {gene_data.shape}\")\n", "print(f\"Gene data shape after normalization: {normalized_gene_data.shape}\")\n", "\n", "# Save the normalized gene data to file\n", "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n", "normalized_gene_data.to_csv(out_gene_data_file)\n", "print(f\"Normalized gene expression data saved to {out_gene_data_file}\")\n", "\n", "# Load the actual clinical data from the matrix file that was previously obtained in Step 1\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "background_info, clinical_data = get_background_and_clinical_data(matrix_file)\n", "\n", "# Get preview of clinical data to understand its structure\n", "print(\"Original clinical data preview:\")\n", "print(clinical_data.head())\n", "\n", "# 2. If we have trait data available, proceed with linking\n", "if trait_row is not None:\n", " # Extract clinical features using the original clinical data\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", " print(f\"Selected clinical data shape: {selected_clinical_df.shape}\")\n", " print(\"Clinical data preview:\")\n", " print(selected_clinical_df.head())\n", "\n", " # Link the clinical and genetic data\n", " linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)\n", " print(f\"Linked data shape before processing: {linked_data.shape}\")\n", " print(\"Linked data preview (first 5 rows, 5 columns):\")\n", " print(linked_data.iloc[:5, :5] if not linked_data.empty else \"Empty dataframe\")\n", "\n", " # 3. Handle missing values\n", " try:\n", " linked_data = handle_missing_values(linked_data, trait)\n", " print(f\"Data shape after handling missing values: {linked_data.shape}\")\n", " except Exception as e:\n", " print(f\"Error handling missing values: {e}\")\n", " linked_data = pd.DataFrame() # Create empty dataframe if error occurs\n", "\n", " # 4. Check for bias in features\n", " if not linked_data.empty and linked_data.shape[0] > 0:\n", " # Check if trait is biased\n", " trait_type = 'binary' if len(linked_data[trait].unique()) <= 2 else 'continuous'\n", " if trait_type == \"binary\":\n", " is_biased = judge_binary_variable_biased(linked_data, trait)\n", " else:\n", " is_biased = judge_continuous_variable_biased(linked_data, trait)\n", " \n", " # Remove biased demographic features\n", " if \"Age\" in linked_data.columns:\n", " age_biased = judge_continuous_variable_biased(linked_data, 'Age')\n", " if age_biased:\n", " linked_data = linked_data.drop(columns='Age')\n", " \n", " if \"Gender\" in linked_data.columns:\n", " gender_biased = judge_binary_variable_biased(linked_data, 'Gender')\n", " if gender_biased:\n", " linked_data = linked_data.drop(columns='Gender')\n", " else:\n", " is_biased = True\n", " print(\"Cannot check for bias as dataframe is empty or has no rows after missing value handling\")\n", "\n", " # 5. Validate and save cohort information\n", " note = \"\"\n", " if linked_data.empty or linked_data.shape[0] == 0:\n", " note = \"Dataset contains gene expression data related to Randall's plaque tissue, but linking clinical and genetic data failed, possibly due to mismatched sample IDs.\"\n", " else:\n", " note = \"Dataset contains gene expression data from Randall's plaque tissue associated with kidney stones.\"\n", " \n", " is_usable = validate_and_save_cohort_info(\n", " is_final=True,\n", " cohort=cohort,\n", " info_path=json_path,\n", " is_gene_available=True,\n", " is_trait_available=True,\n", " is_biased=is_biased,\n", " df=linked_data,\n", " note=note\n", " )\n", "\n", " # 6. Save the linked data if usable\n", " if is_usable:\n", " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n", " linked_data.to_csv(out_data_file)\n", " print(f\"Linked data saved to {out_data_file}\")\n", " else:\n", " print(\"Dataset is not usable for analysis. No linked data file saved.\")\n", "else:\n", " # If no trait data available, validate with trait_available=False\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=False,\n", " is_biased=True, # Set to True since we can't use data without trait\n", " df=pd.DataFrame(), # Empty DataFrame\n", " note=\"Dataset contains gene expression data but lacks proper clinical trait information for kidney stones analysis.\"\n", " )\n", " \n", " print(\"Dataset is not usable for kidney stones analysis due to lack of clinical trait data. No linked data file 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 }