{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "fcd517de", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:28:07.006731Z", "iopub.status.busy": "2025-03-25T05:28:07.006542Z", "iopub.status.idle": "2025-03-25T05:28:07.186536Z", "shell.execute_reply": "2025-03-25T05:28:07.186200Z" } }, "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 = \"GSE218109\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Head_and_Neck_Cancer\"\n", "in_cohort_dir = \"../../input/GEO/Head_and_Neck_Cancer/GSE218109\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Head_and_Neck_Cancer/GSE218109.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Head_and_Neck_Cancer/gene_data/GSE218109.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Head_and_Neck_Cancer/clinical_data/GSE218109.csv\"\n", "json_path = \"../../output/preprocess/Head_and_Neck_Cancer/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "efffd75a", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "58a2519a", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:28:07.188007Z", "iopub.status.busy": "2025-03-25T05:28:07.187847Z", "iopub.status.idle": "2025-03-25T05:28:07.260504Z", "shell.execute_reply": "2025-03-25T05:28:07.260200Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Esophageal Squamous Cell Carcinoma tumors from Indian patients: nuclear-stabilized p53 (NS+) versus unstable p53 (NS-) protein\"\n", "!Series_summary\t\"Transcriptional profiling of Esophageal Squamous Cell Carcinoma (ESCC) tumors comparing samples harbouring nuclear-stabilized p53 (NS+) versus unstable p53 (NS-) protein, determined through immunohistochemistry (IHC) staining of the tumor sections. The goal was to identify the genes that were differentially regulated between NS+ and NS- ESCC samples.\"\n", "!Series_overall_design\t\"Two-condition experiment, NS+ versus NS- esophageal tumors. NS+ tumors: 17, NS- tumors: 19.\"\n", "Sample Characteristics Dictionary:\n", "{0: ['Sex: M', 'Sex: F'], 1: ['age: 22', 'age: 45', 'age: 52', 'age: 50', 'age: 34', 'age: 55', 'age: 48', 'age: 64', 'age: 70', 'age: 68', 'age: 23', 'age: 62', 'age: 59', 'age: 58', 'age: 41', 'age: 47', 'age: 66', 'age: 38', 'age: 79', 'age: 61', 'age: 39', 'age: 32', 'age: 46', 'age: 69', 'age: 54'], 2: ['tissue: Esophageal Squamous Cell Carcinoma'], 3: ['Stage: pT3N2', 'Stage: pT3N0', 'Stage: pT3N1', 'Stage: pT3N1bM1b', 'Stage: pT2PN1a', 'Stage: pT2N0Mx', 'Stage: pT2N2', 'Stage: NA', 'Stage: pT2N0', 'Stage: pT2N1b', 'Stage: pT3N1Mx', 'Stage: pT3N2Mx', 'Stage: pT2N1', 'Stage: pT3N0Mx'], 4: ['grade: I', 'grade: II'], 5: ['p53 status: unstable p53 (NS-)', 'p53 status: nuclear-stabilized p53 (NS+)']}\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": "8f4775e6", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "141a2deb", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:28:07.261707Z", "iopub.status.busy": "2025-03-25T05:28:07.261597Z", "iopub.status.idle": "2025-03-25T05:28:07.267252Z", "shell.execute_reply": "2025-03-25T05:28:07.266984Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Error in clinical feature extraction: [Errno 2] No such file or directory: '../../input/GEO/Head_and_Neck_Cancer/GSE218109/clinical_data.csv'\n" ] } ], "source": [ "import pandas as pd\n", "import os\n", "import json\n", "from typing import Dict, Any, Optional, Callable\n", "\n", "# 1. Gene Expression Data Availability Analysis\n", "# Based on the background information, this dataset appears to contain gene expression data\n", "# as it mentions \"Transcriptional profiling of Esophageal Squamous Cell Carcinoma (ESCC) tumors\"\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "\n", "# 2.1 Data Availability\n", "# Trait: The trait here appears to be related to p53 status (NS+ vs NS-) from index 5\n", "trait_row = 5\n", "\n", "# Age: Available at index 1\n", "age_row = 1\n", "\n", "# Gender: Available at index 0\n", "gender_row = 0\n", "\n", "# 2.2 Data Type Conversion\n", "\n", "def convert_trait(value):\n", " \"\"\"Convert p53 status to binary: 1 for NS+, 0 for NS-\"\"\"\n", " if not isinstance(value, str):\n", " return None\n", " \n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " if 'nuclear-stabilized p53 (NS+)' in value:\n", " return 1\n", " elif 'unstable p53 (NS-)' in value:\n", " return 0\n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age to continuous numeric value\"\"\"\n", " if not isinstance(value, str):\n", " return None\n", " \n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " try:\n", " return float(value)\n", " except:\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"Convert gender to binary: 0 for female, 1 for male\"\"\"\n", " if not isinstance(value, str):\n", " return None\n", " \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", " return None\n", "\n", "# 3. Save Metadata\n", "# Trait data is available since trait_row is not None\n", "is_trait_available = trait_row is not None\n", "\n", "# Initial filtering and saving metadata\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", "# If trait data is available, extract clinical features\n", "if is_trait_available:\n", " # Assuming clinical_data was loaded in a previous step\n", " try:\n", " # Assuming clinical_data exists from previous step\n", " clinical_data_path = os.path.join(in_cohort_dir, \"clinical_data.csv\")\n", " clinical_data = pd.read_csv(clinical_data_path)\n", " \n", " # Extract clinical features\n", " selected_clinical_df = geo_select_clinical_features(\n", " clinical_df=clinical_data,\n", " trait=trait,\n", " trait_row=trait_row,\n", " convert_trait=convert_trait,\n", " age_row=age_row,\n", " convert_age=convert_age,\n", " gender_row=gender_row,\n", " convert_gender=convert_gender\n", " )\n", " \n", " # Preview the extracted clinical features\n", " preview = preview_df(selected_clinical_df)\n", " print(\"Preview of selected clinical features:\")\n", " print(preview)\n", " \n", " # Ensure output directory exists\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " \n", " # Save the clinical data\n", " selected_clinical_df.to_csv(out_clinical_data_file, index=False)\n", " print(f\"Clinical data saved to {out_clinical_data_file}\")\n", " except Exception as e:\n", " print(f\"Error in clinical feature extraction: {e}\")\n", " # If there's an error, we still want to proceed with the rest of the pipeline\n" ] }, { "cell_type": "markdown", "id": "bdd2a696", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "5d114d86", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:28:07.268271Z", "iopub.status.busy": "2025-03-25T05:28:07.268166Z", "iopub.status.idle": "2025-03-25T05:28:07.365711Z", "shell.execute_reply": "2025-03-25T05:28:07.365324Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Matrix file found: ../../input/GEO/Head_and_Neck_Cancer/GSE218109/GSE218109_series_matrix.txt.gz\n", "Gene data shape: (31214, 36)\n", "First 20 gene/probe identifiers:\n", "Index(['12', '14', '15', '16', '17', '18', '19', '20', '22', '23', '24', '25',\n", " '26', '27', '30', '33', '35', '36', '37', '38'],\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": "3a995b14", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "3d4e7130", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:28:07.366950Z", "iopub.status.busy": "2025-03-25T05:28:07.366839Z", "iopub.status.idle": "2025-03-25T05:28:07.368742Z", "shell.execute_reply": "2025-03-25T05:28:07.368463Z" } }, "outputs": [], "source": [ "# Reviewing the gene identifiers from the previous output\n", "\n", "# The identifiers shown are numeric values like '12', '14', '15', etc.\n", "# These are not standard human gene symbols, which would typically be alphanumeric \n", "# like 'BRCA1', 'TP53', 'EGFR', etc.\n", "# \n", "# These appear to be probe IDs or some other numeric identifiers that would need \n", "# to be mapped to actual gene symbols for meaningful biological interpretation.\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "a9b3c419", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "a21b03c8", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:28:07.369804Z", "iopub.status.busy": "2025-03-25T05:28:07.369701Z", "iopub.status.idle": "2025-03-25T05:28:09.341477Z", "shell.execute_reply": "2025-03-25T05:28:09.341111Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "Gene annotation preview:\n", "Columns in gene annotation: ['ID', 'COL', 'ROW', 'NAME', 'SPOT_ID', 'CONTROL_TYPE', 'REFSEQ', 'GB_ACC', 'GENE', 'GENE_SYMBOL', 'GENE_NAME', 'UNIGENE_ID', 'ENSEMBL_ID', 'TIGR_ID', 'ACCESSION_STRING', 'CHROMOSOMAL_LOCATION', 'CYTOBAND', 'DESCRIPTION', 'GO_ID', 'SEQUENCE', 'SPOT_ID.1', 'ORDER']\n", "{'ID': ['1', '2', '3', '4', '5'], 'COL': ['266', '266', '266', '266', '266'], 'ROW': [170.0, 168.0, 166.0, 164.0, 162.0], 'NAME': ['GE_BrightCorner', 'DarkCorner', 'DarkCorner', 'DarkCorner', 'DarkCorner'], 'SPOT_ID': ['GE_BrightCorner', 'DarkCorner', 'DarkCorner', 'DarkCorner', 'DarkCorner'], 'CONTROL_TYPE': ['pos', 'pos', 'pos', 'pos', 'pos'], 'REFSEQ': [nan, nan, nan, nan, nan], 'GB_ACC': [nan, nan, nan, nan, nan], 'GENE': [nan, nan, nan, nan, nan], 'GENE_SYMBOL': [nan, nan, nan, nan, nan], 'GENE_NAME': [nan, nan, nan, nan, nan], 'UNIGENE_ID': [nan, nan, nan, nan, nan], 'ENSEMBL_ID': [nan, nan, nan, nan, nan], 'TIGR_ID': [nan, nan, nan, nan, nan], 'ACCESSION_STRING': [nan, nan, nan, nan, nan], 'CHROMOSOMAL_LOCATION': [nan, nan, nan, nan, nan], 'CYTOBAND': [nan, nan, nan, nan, nan], 'DESCRIPTION': [nan, nan, nan, nan, nan], 'GO_ID': [nan, nan, nan, nan, nan], 'SEQUENCE': [nan, nan, nan, nan, nan], 'SPOT_ID.1': [nan, nan, nan, nan, nan], 'ORDER': [1.0, 2.0, 3.0, 4.0, 5.0]}\n", "\n", "Searching for platform information in SOFT file:\n", "!Series_platform_id = GPL4133\n", "\n", "Searching for gene symbol information in SOFT file:\n", "Found references to gene symbols:\n", "#GENE_SYMBOL = Gene Symbol\n", "ID\tCOL\tROW\tNAME\tSPOT_ID\tCONTROL_TYPE\tREFSEQ\tGB_ACC\tGENE\tGENE_SYMBOL\tGENE_NAME\tUNIGENE_ID\tENSEMBL_ID\tTIGR_ID\tACCESSION_STRING\tCHROMOSOMAL_LOCATION\tCYTOBAND\tDESCRIPTION\tGO_ID\tSEQUENCE\tSPOT_ID\tORDER\n", "\n", "Checking for additional annotation files in the directory:\n", "[]\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. Analyze the gene annotation dataframe to identify which columns contain the gene identifiers and gene symbols\n", "print(\"\\nGene annotation preview:\")\n", "print(f\"Columns in gene annotation: {gene_annotation.columns.tolist()}\")\n", "print(preview_df(gene_annotation, n=5))\n", "\n", "# Let's look for platform information in the SOFT file to understand the annotation better\n", "print(\"\\nSearching for platform information in SOFT file:\")\n", "with gzip.open(soft_file, 'rt') as f:\n", " for i, line in enumerate(f):\n", " if '!Series_platform_id' in line:\n", " print(line.strip())\n", " break\n", " if i > 100: # Limit search to first 100 lines\n", " print(\"Platform ID not found in first 100 lines\")\n", " break\n", "\n", "# Check if the SOFT file includes any reference to gene symbols\n", "print(\"\\nSearching for gene symbol information in SOFT file:\")\n", "with gzip.open(soft_file, 'rt') as f:\n", " gene_symbol_lines = []\n", " for i, line in enumerate(f):\n", " if 'GENE_SYMBOL' in line or 'gene_symbol' in line.lower() or 'symbol' in line.lower():\n", " gene_symbol_lines.append(line.strip())\n", " if i > 1000 and len(gene_symbol_lines) > 0: # Limit search but ensure we found something\n", " break\n", " \n", " if gene_symbol_lines:\n", " print(\"Found references to gene symbols:\")\n", " for line in gene_symbol_lines[:5]: # Show just first 5 matches\n", " print(line)\n", " else:\n", " print(\"No explicit gene symbol references found in first 1000 lines\")\n", "\n", "# Look for alternative annotation files or references in the directory\n", "print(\"\\nChecking for additional annotation files in the directory:\")\n", "all_files = os.listdir(in_cohort_dir)\n", "print([f for f in all_files if 'annotation' in f.lower() or 'platform' in f.lower() or 'gpl' in f.lower()])\n" ] }, { "cell_type": "markdown", "id": "0fdb168e", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "e7b60e86", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:28:09.342745Z", "iopub.status.busy": "2025-03-25T05:28:09.342624Z", "iopub.status.idle": "2025-03-25T05:28:09.766621Z", "shell.execute_reply": "2025-03-25T05:28:09.766256Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Using 'ID' column as probe ID and 'GENE_SYMBOL' column as gene symbol\n", "Gene mapping shape: (32696, 2)\n", "First 5 rows of gene mapping:\n", " ID Gene\n", "11 12 APOBEC3B\n", "13 14 ATP11B\n", "14 15 LOC100132006\n", "15 16 DNAJA1\n", "17 18 EHMT2\n", "After mapping, gene data shape: (15298, 36)\n", "First 10 mapped gene symbols:\n", "Index(['A1BG', 'A1CF', 'A2LD1', 'A2M', 'A2ML1', 'A4GALT', 'AAAS', 'AACS',\n", " 'AADAC', 'AADACL1'],\n", " dtype='object', name='Gene')\n", "Number of unique genes after mapping: 15298\n", "After normalization, gene data shape: (14998, 36)\n", "First 10 normalized gene symbols:\n", "Index(['A1BG', 'A1CF', 'A2M', 'A2ML1', 'A4GALT', 'AAAS', 'AACS', 'AADAC',\n", " 'AADAT', 'AAK1'],\n", " dtype='object', name='Gene')\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene expression data saved to ../../output/preprocess/Head_and_Neck_Cancer/gene_data/GSE218109.csv\n" ] } ], "source": [ "# 1. Decide which column in gene annotation maps to gene expression data identifiers\n", "# From the previous outputs, we can see:\n", "# - Gene expression data has numeric IDs like '12', '14', '15', etc. \n", "# - Gene annotation has an 'ID' column, which contains numeric values\n", "# - We need gene symbols which are in the 'GENE_SYMBOL' column\n", "\n", "# Extract gene identifier and gene symbol columns\n", "prob_col = 'ID'\n", "gene_col = 'GENE_SYMBOL'\n", "print(f\"Using '{prob_col}' column as probe ID and '{gene_col}' column as gene symbol\")\n", "\n", "# 2. Get gene mapping dataframe \n", "gene_mapping = get_gene_mapping(gene_annotation, prob_col=prob_col, gene_col=gene_col)\n", "print(f\"Gene mapping shape: {gene_mapping.shape}\")\n", "print(\"First 5 rows of gene mapping:\")\n", "print(gene_mapping.head())\n", "\n", "# 3. Apply gene mapping to convert probe data to gene expression data\n", "gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=gene_mapping)\n", "print(f\"After mapping, gene data shape: {gene_data.shape}\")\n", "print(\"First 10 mapped gene symbols:\")\n", "print(gene_data.index[:10])\n", "\n", "# Check the quality of mapping - how many genes have been successfully mapped\n", "print(f\"Number of unique genes after mapping: {len(gene_data.index)}\")\n", "\n", "# Normalize gene symbols to standardize them\n", "gene_data = normalize_gene_symbols_in_index(gene_data)\n", "print(f\"After normalization, gene data shape: {gene_data.shape}\")\n", "print(\"First 10 normalized gene symbols:\")\n", "print(gene_data.index[:10])\n", "\n", "# Save the processed gene 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\"Gene expression data saved to {out_gene_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "ac7c5699", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "84d6df08", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:28:09.767916Z", "iopub.status.busy": "2025-03-25T05:28:09.767792Z", "iopub.status.idle": "2025-03-25T05:28:15.321823Z", "shell.execute_reply": "2025-03-25T05:28:15.321488Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene data shape before normalization: (14998, 36)\n", "Gene data shape after normalization: (14998, 36)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene expression data saved to ../../output/preprocess/Head_and_Neck_Cancer/gene_data/GSE218109.csv\n", "Original clinical data preview:\n", " !Sample_geo_accession GSM6734720 \\\n", "0 !Sample_characteristics_ch1 Sex: M \n", "1 !Sample_characteristics_ch1 age: 22 \n", "2 !Sample_characteristics_ch1 tissue: Esophageal Squamous Cell Carcinoma \n", "3 !Sample_characteristics_ch1 Stage: pT3N2 \n", "4 !Sample_characteristics_ch1 grade: I \n", "\n", " GSM6734721 \\\n", "0 Sex: M \n", "1 age: 45 \n", "2 tissue: Esophageal Squamous Cell Carcinoma \n", "3 Stage: pT3N0 \n", "4 grade: I \n", "\n", " GSM6734722 \\\n", "0 Sex: F \n", "1 age: 52 \n", "2 tissue: Esophageal Squamous Cell Carcinoma \n", "3 Stage: pT3N1 \n", "4 grade: I \n", "\n", " GSM6734723 \\\n", "0 Sex: F \n", "1 age: 50 \n", "2 tissue: Esophageal Squamous Cell Carcinoma \n", "3 Stage: pT3N1 \n", "4 grade: I \n", "\n", " GSM6734724 \\\n", "0 Sex: F \n", "1 age: 34 \n", "2 tissue: Esophageal Squamous Cell Carcinoma \n", "3 Stage: pT3N1 \n", "4 grade: I \n", "\n", " GSM6734725 \\\n", "0 Sex: M \n", "1 age: 55 \n", "2 tissue: Esophageal Squamous Cell Carcinoma \n", "3 Stage: pT3N2 \n", "4 grade: I \n", "\n", " GSM6734726 \\\n", "0 Sex: F \n", "1 age: 48 \n", "2 tissue: Esophageal Squamous Cell Carcinoma \n", "3 Stage: pT3N1bM1b \n", "4 grade: II \n", "\n", " GSM6734727 \\\n", "0 Sex: M \n", "1 age: 64 \n", "2 tissue: Esophageal Squamous Cell Carcinoma \n", "3 Stage: pT2PN1a \n", "4 grade: II \n", "\n", " GSM6734728 ... \\\n", "0 Sex: M ... \n", "1 age: 70 ... \n", "2 tissue: Esophageal Squamous Cell Carcinoma ... \n", "3 Stage: pT3N1 ... \n", "4 grade: II ... \n", "\n", " GSM6734746 \\\n", "0 Sex: M \n", "1 age: 59 \n", "2 tissue: Esophageal Squamous Cell Carcinoma \n", "3 Stage: pT3N0 \n", "4 grade: I \n", "\n", " GSM6734747 \\\n", "0 Sex: F \n", "1 age: 39 \n", "2 tissue: Esophageal Squamous Cell Carcinoma \n", "3 Stage: pT2N0 \n", "4 grade: I \n", "\n", " GSM6734748 \\\n", "0 Sex: F \n", "1 age: 32 \n", "2 tissue: Esophageal Squamous Cell Carcinoma \n", "3 Stage: pT3N2Mx \n", "4 grade: I \n", "\n", " GSM6734749 \\\n", "0 Sex: F \n", "1 age: 55 \n", "2 tissue: Esophageal Squamous Cell Carcinoma \n", "3 Stage: pT3N1 \n", "4 grade: I \n", "\n", " GSM6734750 \\\n", "0 Sex: M \n", "1 age: 46 \n", "2 tissue: Esophageal Squamous Cell Carcinoma \n", "3 Stage: pT3N1 \n", "4 grade: I \n", "\n", " GSM6734751 \\\n", "0 Sex: M \n", "1 age: 69 \n", "2 tissue: Esophageal Squamous Cell Carcinoma \n", "3 Stage: pT3N0 \n", "4 grade: II \n", "\n", " GSM6734752 \\\n", "0 Sex: M \n", "1 age: 61 \n", "2 tissue: Esophageal Squamous Cell Carcinoma \n", "3 Stage: pT2N1 \n", "4 grade: I \n", "\n", " GSM6734753 \\\n", "0 Sex: M \n", "1 age: 54 \n", "2 tissue: Esophageal Squamous Cell Carcinoma \n", "3 Stage: pT2N1 \n", "4 grade: II \n", "\n", " GSM6734754 \\\n", "0 Sex: M \n", "1 age: 38 \n", "2 tissue: Esophageal Squamous Cell Carcinoma \n", "3 Stage: pT3N0 \n", "4 grade: I \n", "\n", " GSM6734755 \n", "0 Sex: M \n", "1 age: 64 \n", "2 tissue: Esophageal Squamous Cell Carcinoma \n", "3 Stage: pT3N0 \n", "4 grade: I \n", "\n", "[5 rows x 37 columns]\n", "Selected clinical data shape: (3, 36)\n", "Clinical data preview:\n", " GSM6734720 GSM6734721 GSM6734722 GSM6734723 \\\n", "Head_and_Neck_Cancer 0.0 0.0 0.0 0.0 \n", "Age 22.0 45.0 52.0 50.0 \n", "Gender 1.0 1.0 0.0 0.0 \n", "\n", " GSM6734724 GSM6734725 GSM6734726 GSM6734727 \\\n", "Head_and_Neck_Cancer 0.0 0.0 0.0 0.0 \n", "Age 34.0 55.0 48.0 64.0 \n", "Gender 0.0 1.0 0.0 1.0 \n", "\n", " GSM6734728 GSM6734729 ... GSM6734746 GSM6734747 \\\n", "Head_and_Neck_Cancer 0.0 1.0 ... 1.0 1.0 \n", "Age 70.0 68.0 ... 59.0 39.0 \n", "Gender 1.0 0.0 ... 1.0 0.0 \n", "\n", " GSM6734748 GSM6734749 GSM6734750 GSM6734751 \\\n", "Head_and_Neck_Cancer 0.0 0.0 1.0 1.0 \n", "Age 32.0 55.0 46.0 69.0 \n", "Gender 0.0 0.0 1.0 1.0 \n", "\n", " GSM6734752 GSM6734753 GSM6734754 GSM6734755 \n", "Head_and_Neck_Cancer 1.0 1.0 1.0 0.0 \n", "Age 61.0 54.0 38.0 64.0 \n", "Gender 1.0 1.0 1.0 1.0 \n", "\n", "[3 rows x 36 columns]\n", "Linked data shape before processing: (36, 15001)\n", "Linked data preview (first 5 rows, 5 columns):\n", " Head_and_Neck_Cancer Age Gender A1BG A1CF\n", "GSM6734720 0.0 22.0 1.0 5040.0 31.0\n", "GSM6734721 0.0 45.0 1.0 1800.0 137.0\n", "GSM6734722 0.0 52.0 0.0 3190.0 25.3\n", "GSM6734723 0.0 50.0 0.0 3580.0 30.3\n", "GSM6734724 0.0 34.0 0.0 873.0 42.9\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Data shape after handling missing values: (36, 15001)\n", "For the feature 'Head_and_Neck_Cancer', the least common label is '1.0' with 17 occurrences. This represents 47.22% of the dataset.\n", "Quartiles for 'Age':\n", " 25%: 44.0\n", " 50% (Median): 53.0\n", " 75%: 62.0\n", "Min: 22.0\n", "Max: 79.0\n", "For the feature 'Gender', the least common label is '0.0' with 14 occurrences. This represents 38.89% of the dataset.\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Linked data saved to ../../output/preprocess/Head_and_Neck_Cancer/GSE218109.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 }