{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "87faa4e2", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:11:51.299782Z", "iopub.status.busy": "2025-03-25T05:11:51.299561Z", "iopub.status.idle": "2025-03-25T05:11:51.469238Z", "shell.execute_reply": "2025-03-25T05:11:51.468875Z" } }, "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 = \"Esophageal_Cancer\"\n", "cohort = \"GSE104958\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Esophageal_Cancer\"\n", "in_cohort_dir = \"../../input/GEO/Esophageal_Cancer/GSE104958\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Esophageal_Cancer/GSE104958.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Esophageal_Cancer/gene_data/GSE104958.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Esophageal_Cancer/clinical_data/GSE104958.csv\"\n", "json_path = \"../../output/preprocess/Esophageal_Cancer/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "59651d5c", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "0a71feda", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:11:51.470715Z", "iopub.status.busy": "2025-03-25T05:11:51.470568Z", "iopub.status.idle": "2025-03-25T05:11:51.656270Z", "shell.execute_reply": "2025-03-25T05:11:51.655912Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"A 17-molecule set as a predictor of complete response to neoadjuvant chemotherapy with docetaxel, cisplatin, and 5-fluorouracil in esophageal cancer\"\n", "!Series_summary\t\"Background Recently, neoadjuvant chemotherapy with docetaxel/cisplatin/5-fluorouracil (NAC-DCF) was identified as a novel strong regimen with a high rate of pathological complete response (pCR) in advanced esophageal cancer in Japan. Predicting pCR will contribute to the therapeutic strategy and the prevention of surgical invasion. However, a predictor of pCR after NAC-DCF has not yet been developed. The aim of this study was to identify a novel predictor of pCR in locally advanced esophageal cancer treated with NAC-DCF. Patients and Methods A total of 32 patients who received NAC-DCF followed by esophagectomy between June 2013 and March 2016 were enrolled in this study. We divided the patients into the following 2 groups: pCR group (9 cases) and non-pCR group (23 cases), and compared gene expressions between these groups using DNA microarray data and KeyMolnet. Subsequently, a validation study of candidate molecular expression was performed in 7 additional cases. Results Seventeen molecules, including transcription factor E2F, T-cell-specific transcription factor, Src (known as “proto-oncogene tyrosine-protein kinase of sarcoma”), interferon regulatory factor 1, thymidylate synthase, cyclin B, cyclin-dependent kinase (CDK) 4, CDK, caspase-1, vitamin D receptor, histone deacetylase, MAPK/ERK kinase, bcl-2-associated X protein, runt-related transcription factor 1, PR domain zinc finger protein 1, platelet-derived growth factor receptor, and interleukin 1, were identified as candidate molecules. The molecules were mainly associated with pathways, such as transcriptional regulation by SMAD, RB/E2F, and STAT. The validation study indicated that 12 of the 17 molecules (71%) matched the trends of molecular expression. Conclusions A 17-molecule set that predicts pCR after NAC-DCF for locally advanced esophageal cancer was identified.\"\n", "!Series_overall_design\t\"The aim of this study was to identify the predictors of pCR after NAC-DCF for locally advanced esophageal cancer. We investigated gene expressions in clinical esophageal cancer samples and performed comparisons between pCR cases and non-pCR cases using DNA microarray data and KeyMolnet (KM Data; www.km-data.jp). Esophageal cancer tissue samples were collected at biopsy during endoscopic examination before the administration of the first course of chemotherapy. The biopsy specimen was collected from an elevated part at the proximal side of the tumor in a unified manner. The specimens were frozen and preserved in a freezer maintained at −80℃. The pathological response was evaluated according to the Japanese Classification of Esophageal Cancer 11th edition as follows: grade 0, no recognizable cytological or histological therapeutic effect; grade 1a, viable cancer cells account for two-thirds or more of the tumor tissue; grade 1b, viable cancer cells account for between one-third and two-thirds of the tumor tissue; grade 2, viable cancer cells account for less than one-third of the tumor tissue; grade 3, no viable cancer cells are apparent (pCR). Patients were divided into 2 groups (pCR and non-pCR) according to the pathological response. We analyzed these data using 39 cases. The samples of RNA 1, 4, 7, 10, 12, 17, 24, 29, 35, and 43 were pCR group. The samples of RNA 3, 5, 6, 8, 9, 11, 14, 15, 16, 18, 19, 20, 21, 22, 25, 26, 27, 28, 30, 31, 32, 33, 34, 36, 37, 38, 39, 41, and 42 were non-pCR group.\"\n", "Sample Characteristics Dictionary:\n", "{0: ['organ: esophagus'], 1: ['tissue: cancer tissue', 'tissue: normal tissue']}\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": "041f6e97", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "a351cad3", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:11:51.657549Z", "iopub.status.busy": "2025-03-25T05:11:51.657428Z", "iopub.status.idle": "2025-03-25T05:11:51.664575Z", "shell.execute_reply": "2025-03-25T05:11:51.664258Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Preview of selected clinical features:\n", "{0: [1.0], 1: [0.0]}\n", "Clinical data saved to ../../output/preprocess/Esophageal_Cancer/clinical_data/GSE104958.csv\n" ] } ], "source": [ "import pandas as pd\n", "import os\n", "import re\n", "import json\n", "from typing import Dict, Any, Optional, Callable, List\n", "import numpy as np\n", "\n", "# 1. Check if gene expression data is available\n", "# Based on the background information, this dataset contains DNA microarray data\n", "# The study specifically mentions gene expression analysis in esophageal cancer tissues\n", "is_gene_available = True\n", "\n", "# 2. Variable availability and data type conversion\n", "\n", "# 2.1 Data Availability\n", "# From the sample characteristics dictionary, we can see:\n", "# Key 1 has information about tissue type (cancer vs normal tissue)\n", "# For tissue: we can identify cancer/normal samples which is related to the trait\n", "trait_row = 1 # The row containing cancer/normal tissue information\n", "\n", "# There is no explicit age information in the sample characteristics\n", "age_row = None\n", "\n", "# There is no explicit gender information in the sample characteristics\n", "gender_row = None\n", "\n", "# 2.2 Data Type Conversion Functions\n", "\n", "def convert_trait(value: str) -> int:\n", " \"\"\"\n", " Convert tissue information to binary trait values.\n", " 0 = normal tissue, 1 = cancer tissue\n", " \"\"\"\n", " if not value or pd.isna(value):\n", " return None\n", " \n", " # Get the value after the colon if present\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " if 'cancer' in value.lower():\n", " return 1\n", " elif 'normal' in value.lower():\n", " return 0\n", " else:\n", " return None\n", "\n", "def convert_age(value: str) -> Optional[float]:\n", " \"\"\"\n", " Convert age information to float.\n", " This function is defined but not used since age data is not available.\n", " \"\"\"\n", " return None\n", "\n", "def convert_gender(value: str) -> Optional[int]:\n", " \"\"\"\n", " Convert gender information to binary.\n", " This function is defined but not used since gender data is not available.\n", " \"\"\"\n", " return None\n", "\n", "# 3. Save Metadata\n", "# We need to check if trait data is available\n", "is_trait_available = trait_row is not None\n", "\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", "# Only proceed if trait_row is not None\n", "if trait_row is not None:\n", " # Load the clinical data - create a properly structured DataFrame from the sample characteristics\n", " # Create a dictionary where all lists have the same length\n", " clinical_data_dict = {\n", " 0: ['organ: esophagus', 'organ: esophagus'], # Duplicate to match length\n", " 1: ['tissue: cancer tissue', 'tissue: normal tissue']\n", " }\n", " \n", " # Convert to DataFrame\n", " clinical_data = pd.DataFrame.from_dict(clinical_data_dict, orient='index')\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 dataframe\n", " print(\"Preview of selected clinical features:\")\n", " print(preview_df(selected_clinical_df))\n", " \n", " # Save the clinical data to CSV\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " selected_clinical_df.to_csv(out_clinical_data_file, index=False)\n", " print(f\"Clinical data saved to {out_clinical_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "b7e1cf84", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "712584ad", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:11:51.665711Z", "iopub.status.busy": "2025-03-25T05:11:51.665605Z", "iopub.status.idle": "2025-03-25T05:11:51.983589Z", "shell.execute_reply": "2025-03-25T05:11:51.983126Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Found data marker at line 68\n", "Header line: \"ID_REF\"\t\"GSM2811122\"\t\"GSM2811123\"\t\"GSM2811124\"\t\"GSM2811125\"\t\"GSM2811126\"\t\"GSM2811127\"\t\"GSM2811128\"\t\"GSM2811129\"\t\"GSM2811130\"\t\"GSM2811131\"\t\"GSM2811132\"\t\"GSM2811133\"\t\"GSM2811134\"\t\"GSM2811135\"\t\"GSM2811136\"\t\"GSM2811137\"\t\"GSM2811138\"\t\"GSM2811139\"\t\"GSM2811140\"\t\"GSM2811141\"\t\"GSM2811142\"\t\"GSM2811143\"\t\"GSM2811144\"\t\"GSM2811145\"\t\"GSM2811146\"\t\"GSM2811147\"\t\"GSM2811148\"\t\"GSM2811149\"\t\"GSM2811150\"\t\"GSM2811151\"\t\"GSM2811152\"\t\"GSM2811153\"\t\"GSM2811154\"\t\"GSM2811155\"\t\"GSM2811156\"\t\"GSM2811157\"\t\"GSM2811158\"\t\"GSM2811159\"\t\"GSM2811160\"\t\"GSM2811161\"\t\"GSM2811162\"\t\"GSM2811163\"\t\"GSM2811164\"\t\"GSM2811165\"\t\"GSM2811166\"\t\"GSM2811167\"\n", "First data line: \"(+)E1A_r60_1\"\t0.12522125\t0.100678444\t-0.19952202\t0.20687675\t-0.6983681\t0.011138916\t-0.24957657\t-0.25128937\t0.31498814\t-0.26011658\t-0.8179703\t0.21413231\t-0.19338608\t0.2784319\t-0.84678745\t0.28999233\t-0.09785175\t0.6191282\t0.25938606\t-0.13983536\t0.78502464\t-0.18253994\t0.53778267\t0.53588676\t0.38568115\t-0.37277508\t0.76341057\t-0.22571278\t-0.407876\t0.72065735\t-0.32657242\t-0.7705221\t-0.23686409\t-0.45980644\t-0.39142323\t-0.69904804\t-0.5596304\t-0.011138916\t0.58158493\t0.8415909\t0.3644724\t0.2761097\t-0.062433243\t1.0589762\t0.7222929\t0.7388687\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Index(['(+)E1A_r60_1', '(+)E1A_r60_3', '(+)E1A_r60_a104', '(+)E1A_r60_a107',\n", " '(+)E1A_r60_a135', '(+)E1A_r60_a20', '(+)E1A_r60_a22', '(+)E1A_r60_a97',\n", " '(+)E1A_r60_n11', '(+)E1A_r60_n9', '3xSLv1', 'A_19_P00315452',\n", " 'A_19_P00315492', 'A_19_P00315493', 'A_19_P00315502', 'A_19_P00315506',\n", " 'A_19_P00315518', 'A_19_P00315519', 'A_19_P00315529', 'A_19_P00315541'],\n", " dtype='object', name='ID')\n" ] } ], "source": [ "# 1. Get the file paths for the SOFT file and matrix file\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "\n", "# 2. First, let's examine the structure of the matrix file to understand its format\n", "import gzip\n", "\n", "# Peek at the first few lines of the file to understand its structure\n", "with gzip.open(matrix_file, 'rt') as file:\n", " # Read first 100 lines to find the header structure\n", " for i, line in enumerate(file):\n", " if '!series_matrix_table_begin' in line:\n", " print(f\"Found data marker at line {i}\")\n", " # Read the next line which should be the header\n", " header_line = next(file)\n", " print(f\"Header line: {header_line.strip()}\")\n", " # And the first data line\n", " first_data_line = next(file)\n", " print(f\"First data line: {first_data_line.strip()}\")\n", " break\n", " if i > 100: # Limit search to first 100 lines\n", " print(\"Matrix table marker not found in first 100 lines\")\n", " break\n", "\n", "# 3. Now try to get the genetic data with better error handling\n", "try:\n", " gene_data = get_genetic_data(matrix_file)\n", " print(gene_data.index[:20])\n", "except KeyError as e:\n", " print(f\"KeyError: {e}\")\n", " \n", " # Alternative approach: manually extract the data\n", " print(\"\\nTrying alternative approach to read the gene data:\")\n", " with gzip.open(matrix_file, 'rt') as file:\n", " # Find the start of the data\n", " for line in file:\n", " if '!series_matrix_table_begin' in line:\n", " break\n", " \n", " # Read the headers and data\n", " import pandas as pd\n", " df = pd.read_csv(file, sep='\\t', index_col=0)\n", " print(f\"Column names: {df.columns[:5]}\")\n", " print(f\"First 20 row IDs: {df.index[:20]}\")\n", " gene_data = df\n" ] }, { "cell_type": "markdown", "id": "9a6c8fbe", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "3e3fe397", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:11:51.985070Z", "iopub.status.busy": "2025-03-25T05:11:51.984946Z", "iopub.status.idle": "2025-03-25T05:11:51.986883Z", "shell.execute_reply": "2025-03-25T05:11:51.986604Z" } }, "outputs": [], "source": [ "# Looking at the provided gene identifiers:\n", "# The IDs include items like \"(+)E1A_r60_1\", \"3xSLv1\", and \"A_19_P00315452\"\n", "# These do not appear to be standard human gene symbols (like BRCA1, TP53, etc.)\n", "# The \"A_19_P\" prefix suggests these are likely probe IDs from an Agilent microarray platform\n", "\n", "# These identifiers will need to be mapped to standard gene symbols\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "71827d61", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "68a16201", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:11:51.988045Z", "iopub.status.busy": "2025-03-25T05:11:51.987939Z", "iopub.status.idle": "2025-03-25T05:11:52.531267Z", "shell.execute_reply": "2025-03-25T05:11:52.530648Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Examining SOFT file structure:\n", "Line 0: ^DATABASE = GeoMiame\n", "Line 1: !Database_name = Gene Expression Omnibus (GEO)\n", "Line 2: !Database_institute = NCBI NLM NIH\n", "Line 3: !Database_web_link = http://www.ncbi.nlm.nih.gov/geo\n", "Line 4: !Database_email = geo@ncbi.nlm.nih.gov\n", "Line 5: ^SERIES = GSE104958\n", "Line 6: !Series_title = A 17-molecule set as a predictor of complete response to neoadjuvant chemotherapy with docetaxel, cisplatin, and 5-fluorouracil in esophageal cancer\n", "Line 7: !Series_geo_accession = GSE104958\n", "Line 8: !Series_status = Public on Oct 14 2017\n", "Line 9: !Series_submission_date = Oct 13 2017\n", "Line 10: !Series_last_update_date = Jul 25 2021\n", "Line 11: !Series_pubmed_id = 29136005\n", "Line 12: !Series_summary = Background Recently, neoadjuvant chemotherapy with docetaxel/cisplatin/5-fluorouracil (NAC-DCF) was identified as a novel strong regimen with a high rate of pathological complete response (pCR) in advanced esophageal cancer in Japan. Predicting pCR will contribute to the therapeutic strategy and the prevention of surgical invasion. However, a predictor of pCR after NAC-DCF has not yet been developed. The aim of this study was to identify a novel predictor of pCR in locally advanced esophageal cancer treated with NAC-DCF. Patients and Methods A total of 32 patients who received NAC-DCF followed by esophagectomy between June 2013 and March 2016 were enrolled in this study. We divided the patients into the following 2 groups: pCR group (9 cases) and non-pCR group (23 cases), and compared gene expressions between these groups using DNA microarray data and KeyMolnet. Subsequently, a validation study of candidate molecular expression was performed in 7 additional cases. Results Seventeen molecules, including transcription factor E2F, T-cell-specific transcription factor, Src (known as “proto-oncogene tyrosine-protein kinase of sarcoma”), interferon regulatory factor 1, thymidylate synthase, cyclin B, cyclin-dependent kinase (CDK) 4, CDK, caspase-1, vitamin D receptor, histone deacetylase, MAPK/ERK kinase, bcl-2-associated X protein, runt-related transcription factor 1, PR domain zinc finger protein 1, platelet-derived growth factor receptor, and interleukin 1, were identified as candidate molecules. The molecules were mainly associated with pathways, such as transcriptional regulation by SMAD, RB/E2F, and STAT. The validation study indicated that 12 of the 17 molecules (71%) matched the trends of molecular expression. Conclusions A 17-molecule set that predicts pCR after NAC-DCF for locally advanced esophageal cancer was identified.\n", "Line 13: !Series_overall_design = The aim of this study was to identify the predictors of pCR after NAC-DCF for locally advanced esophageal cancer. We investigated gene expressions in clinical esophageal cancer samples and performed comparisons between pCR cases and non-pCR cases using DNA microarray data and KeyMolnet (KM Data; www.km-data.jp). Esophageal cancer tissue samples were collected at biopsy during endoscopic examination before the administration of the first course of chemotherapy. The biopsy specimen was collected from an elevated part at the proximal side of the tumor in a unified manner. The specimens were frozen and preserved in a freezer maintained at −80℃. The pathological response was evaluated according to the Japanese Classification of Esophageal Cancer 11th edition as follows: grade 0, no recognizable cytological or histological therapeutic effect; grade 1a, viable cancer cells account for two-thirds or more of the tumor tissue; grade 1b, viable cancer cells account for between one-third and two-thirds of the tumor tissue; grade 2, viable cancer cells account for less than one-third of the tumor tissue; grade 3, no viable cancer cells are apparent (pCR). Patients were divided into 2 groups (pCR and non-pCR) according to the pathological response. We analyzed these data using 39 cases. The samples of RNA 1, 4, 7, 10, 12, 17, 24, 29, 35, and 43 were pCR group. The samples of RNA 3, 5, 6, 8, 9, 11, 14, 15, 16, 18, 19, 20, 21, 22, 25, 26, 27, 28, 30, 31, 32, 33, 34, 36, 37, 38, 39, 41, and 42 were non-pCR group.\n", "Line 14: !Series_type = Expression profiling by array\n", "Line 15: !Series_contributor = Hajime,,Fujishima\n", "Line 16: !Series_contributor = Shoichi,,Fumoto\n", "Line 17: !Series_contributor = Tomotaka,,Shibata\n", "Line 18: !Series_contributor = Kohei,,Nishiki\n", "Line 19: !Series_contributor = Yoshiyuki,,Tsukamoto\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Gene annotation preview:\n", "{'ID': ['GE_BrightCorner', 'DarkCorner', 'A_21_P0014386', 'A_33_P3396872', 'A_33_P3267760'], 'CONTROL_TYPE': ['pos', 'pos', 'FALSE', 'FALSE', 'FALSE'], 'REFSEQ': [nan, nan, nan, 'NM_001105533', nan], 'GB_ACC': [nan, nan, nan, 'NM_001105533', nan], 'LOCUSLINK_ID': [nan, nan, nan, 79974.0, 54880.0], 'GENE_SYMBOL': [nan, nan, nan, 'CPED1', 'BCOR'], 'GENE_NAME': [nan, nan, nan, 'cadherin-like and PC-esterase domain containing 1', 'BCL6 corepressor'], 'UNIGENE_ID': [nan, nan, nan, 'Hs.189652', nan], 'ENSEMBL_ID': [nan, nan, nan, nan, 'ENST00000378463'], 'ACCESSION_STRING': [nan, nan, nan, 'ref|NM_001105533|gb|AK025639|gb|BC030538|tc|THC2601673', 'ens|ENST00000378463'], 'CHROMOSOMAL_LOCATION': [nan, nan, 'unmapped', 'chr7:120901888-120901947', 'chrX:39909128-39909069'], 'CYTOBAND': [nan, nan, nan, 'hs|7q31.31', 'hs|Xp11.4'], 'DESCRIPTION': [nan, nan, nan, 'Homo sapiens cadherin-like and PC-esterase domain containing 1 (CPED1), transcript variant 2, mRNA [NM_001105533]', 'BCL6 corepressor [Source:HGNC Symbol;Acc:HGNC:20893] [ENST00000378463]'], 'GO_ID': [nan, nan, nan, 'GO:0005783(endoplasmic reticulum)', 'GO:0000122(negative regulation of transcription from RNA polymerase II promoter)|GO:0000415(negative regulation of histone H3-K36 methylation)|GO:0003714(transcription corepressor activity)|GO:0004842(ubiquitin-protein ligase activity)|GO:0005515(protein binding)|GO:0005634(nucleus)|GO:0006351(transcription, DNA-dependent)|GO:0007507(heart development)|GO:0008134(transcription factor binding)|GO:0030502(negative regulation of bone mineralization)|GO:0031072(heat shock protein binding)|GO:0031519(PcG protein complex)|GO:0035518(histone H2A monoubiquitination)|GO:0042476(odontogenesis)|GO:0042826(histone deacetylase binding)|GO:0044212(transcription regulatory region DNA binding)|GO:0045892(negative regulation of transcription, DNA-dependent)|GO:0051572(negative regulation of histone H3-K4 methylation)|GO:0060021(palate development)|GO:0065001(specification of axis polarity)|GO:0070171(negative regulation of tooth mineralization)'], 'SEQUENCE': [nan, nan, 'AATACATGTTTTGGTAAACACTCGGTCAGAGCACCCTCTTTCTGTGGAATCAGACTGGCA', 'GCTTATCTCACCTAATACAGGGACTATGCAACCAAGAAACTGGAAATAAAAACAAAGATA', 'CATCAAAGCTACGAGAGATCCTACACACCCAGATTTAAAAAATAATAAAAACTTAAGGGC'], 'SPOT_ID': ['GE_BrightCorner', 'DarkCorner', 'A_21_P0014386', 'A_33_P3396872', 'A_33_P3267760']}\n" ] } ], "source": [ "# 1. Let's first examine the structure of the SOFT file before trying to parse it\n", "import gzip\n", "\n", "# Look at the first few lines of the SOFT file to understand its structure\n", "print(\"Examining SOFT file structure:\")\n", "try:\n", " with gzip.open(soft_file, 'rt') as file:\n", " # Read first 20 lines to understand the file structure\n", " for i, line in enumerate(file):\n", " if i < 20:\n", " print(f\"Line {i}: {line.strip()}\")\n", " else:\n", " break\n", "except Exception as e:\n", " print(f\"Error reading SOFT file: {e}\")\n", "\n", "# 2. Now let's try a more robust approach to extract the gene annotation\n", "# Instead of using the library function which failed, we'll implement a custom approach\n", "try:\n", " # First, look for the platform section which contains gene annotation\n", " platform_data = []\n", " with gzip.open(soft_file, 'rt') as file:\n", " in_platform_section = False\n", " for line in file:\n", " if line.startswith('^PLATFORM'):\n", " in_platform_section = True\n", " continue\n", " if in_platform_section and line.startswith('!platform_table_begin'):\n", " # Next line should be the header\n", " header = next(file).strip()\n", " platform_data.append(header)\n", " # Read until the end of the platform table\n", " for table_line in file:\n", " if table_line.startswith('!platform_table_end'):\n", " break\n", " platform_data.append(table_line.strip())\n", " break\n", " \n", " # If we found platform data, convert it to a DataFrame\n", " if platform_data:\n", " import pandas as pd\n", " import io\n", " platform_text = '\\n'.join(platform_data)\n", " gene_annotation = pd.read_csv(io.StringIO(platform_text), delimiter='\\t', \n", " low_memory=False, on_bad_lines='skip')\n", " print(\"\\nGene annotation preview:\")\n", " print(preview_df(gene_annotation))\n", " else:\n", " print(\"Could not find platform table in SOFT file\")\n", " \n", " # Try an alternative approach - extract mapping from other sections\n", " with gzip.open(soft_file, 'rt') as file:\n", " for line in file:\n", " if 'ANNOTATION information' in line or 'annotation information' in line:\n", " print(f\"Found annotation information: {line.strip()}\")\n", " if line.startswith('!Platform_title') or line.startswith('!platform_title'):\n", " print(f\"Platform title: {line.strip()}\")\n", " \n", "except Exception as e:\n", " print(f\"Error processing gene annotation: {e}\")\n" ] }, { "cell_type": "markdown", "id": "06f83946", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "d50729d5", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:11:52.532610Z", "iopub.status.busy": "2025-03-25T05:11:52.532478Z", "iopub.status.idle": "2025-03-25T05:11:58.507179Z", "shell.execute_reply": "2025-03-25T05:11:58.506768Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Successfully extracted gene annotation with 2742073 rows\n", "Created mapping dataframe with 48862 rows\n", "Sample of mapping dataframe:\n", " ID Gene\n", "3 A_33_P3396872 CPED1\n", "4 A_33_P3267760 BCOR\n", "5 A_32_P194264 CHAC2\n", "6 A_23_P153745 IFI30\n", "10 A_21_P0014180 GPR146\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Successfully mapped probe data to gene-level data with 29222 genes\n", "First few gene symbols in gene_data: Index(['A1BG', 'A1BG-AS1', 'A1CF', 'A1CF-2', 'A1CF-3'], dtype='object', name='Gene')\n", "After normalizing gene symbols, gene_data has 20778 genes\n", "First few normalized gene symbols: Index(['A1BG', 'A1BG-AS1', 'A1CF', 'A2M', 'A2M-AS1'], dtype='object', name='Gene')\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene expression data saved to ../../output/preprocess/Esophageal_Cancer/gene_data/GSE104958.csv\n" ] } ], "source": [ "# Based on the preview of gene annotation data, let's identify the relevant columns:\n", "# - 'ID' or 'SPOT_ID' contains the probe identifiers (like A_33_P3396872)\n", "# - 'GENE_SYMBOL' contains the gene symbols (like CPED1, BCOR)\n", "\n", "# 1. Decide which columns to use for mapping\n", "probe_col = 'ID' # The column containing probe IDs that match gene_data index\n", "gene_symbol_col = 'GENE_SYMBOL' # The column containing gene symbols\n", "\n", "# 2. Get a gene mapping dataframe\n", "# First, ensure we have the gene_annotation dataframe properly loaded\n", "# If the previous attempt worked, we should already have gene_annotation\n", "\n", "# Let's try to use the get_gene_annotation function again with proper error handling\n", "try:\n", " gene_annotation = get_gene_annotation(soft_file)\n", " print(f\"Successfully extracted gene annotation with {len(gene_annotation)} rows\")\n", "except Exception as e:\n", " print(f\"Error with get_gene_annotation: {e}\")\n", " # Use our previously created dataframe from the platform section\n", " # We assume it's already in the gene_annotation variable\n", "\n", "# Create the mapping dataframe\n", "mapping_df = get_gene_mapping(gene_annotation, probe_col, gene_symbol_col)\n", "print(f\"Created mapping dataframe with {len(mapping_df)} rows\")\n", "print(f\"Sample of mapping dataframe:\\n{mapping_df.head()}\")\n", "\n", "# 3. Apply gene mapping to convert from probe-level to gene-level expression\n", "gene_data = apply_gene_mapping(gene_data, mapping_df)\n", "print(f\"Successfully mapped probe data to gene-level data with {len(gene_data)} genes\")\n", "print(f\"First few gene symbols in gene_data: {gene_data.index[:5]}\")\n", "\n", "# Normalize gene symbols (optional but recommended)\n", "gene_data = normalize_gene_symbols_in_index(gene_data)\n", "print(f\"After normalizing gene symbols, gene_data has {len(gene_data)} genes\")\n", "print(f\"First few normalized gene symbols: {gene_data.index[:5]}\")\n", "\n", "# Saving the gene expression data to CSV\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": "f6cde561", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "77fdf2e0", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:11:58.508712Z", "iopub.status.busy": "2025-03-25T05:11:58.508593Z", "iopub.status.idle": "2025-03-25T05:12:10.244750Z", "shell.execute_reply": "2025-03-25T05:12:10.244409Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene data shape: (20778, 46)\n", "First few genes with their expression values after normalization:\n", " GSM2811122 GSM2811123 GSM2811124 GSM2811125 GSM2811126 \\\n", "Gene \n", "A1BG 0.103348 -0.582059 -1.208877 2.239748 0.195371 \n", "A1BG-AS1 -0.048602 -0.208037 -1.792347 1.689534 0.342461 \n", "A1CF -0.105821 -0.245147 -0.681063 -0.207984 -1.054633 \n", "A2M -0.015755 -0.460151 0.004467 -0.690533 1.742541 \n", "A2M-AS1 0.220449 -0.347176 -0.256770 -2.044582 0.581432 \n", "\n", " GSM2811127 GSM2811128 GSM2811129 GSM2811130 GSM2811131 ... \\\n", "Gene ... \n", "A1BG -0.619633 1.618708 0.673897 0.165190 -0.173507 ... \n", "A1BG-AS1 0.003299 1.232518 0.849790 -0.003299 0.348321 ... \n", "A1CF -0.714191 -1.024918 -0.998374 -0.243343 -1.165812 ... \n", "A2M -0.481196 0.437325 0.977062 0.388580 0.240284 ... \n", "A2M-AS1 -0.952485 -1.437210 0.430225 -0.264791 0.208688 ... \n", "\n", " GSM2811158 GSM2811159 GSM2811160 GSM2811161 GSM2811162 \\\n", "Gene \n", "A1BG 1.659499 -0.452680 -0.997692 2.674593 2.217539 \n", "A1BG-AS1 2.487921 -1.122222 -1.613949 2.723989 1.905098 \n", "A1CF -0.977084 2.490130 0.464486 0.669394 -0.019284 \n", "A2M 0.954518 -1.351378 -1.523800 0.252137 -0.419096 \n", "A2M-AS1 -1.661231 1.044748 -1.209105 1.416756 -0.706165 \n", "\n", " GSM2811163 GSM2811164 GSM2811165 GSM2811166 GSM2811167 \n", "Gene \n", "A1BG 0.317213 1.066660 -1.005837 0.129625 1.731336 \n", "A1BG-AS1 -0.396621 0.650781 0.858608 0.080313 1.560727 \n", "A1CF 0.544047 0.019284 1.531097 0.593118 0.459903 \n", "A2M -0.957097 -2.745299 -1.880650 -0.259982 0.428770 \n", "A2M-AS1 1.984238 1.528140 -0.580466 1.522639 0.775639 \n", "\n", "[5 rows x 46 columns]\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene data saved to ../../output/preprocess/Esophageal_Cancer/gene_data/GSE104958.csv\n", "Raw clinical data shape: (2, 47)\n", "Clinical features:\n", " GSM2811122 GSM2811123 GSM2811124 GSM2811125 GSM2811126 \\\n", "Esophageal_Cancer 1.0 1.0 1.0 1.0 1.0 \n", "\n", " GSM2811127 GSM2811128 GSM2811129 GSM2811130 GSM2811131 \\\n", "Esophageal_Cancer 1.0 1.0 1.0 1.0 1.0 \n", "\n", " ... GSM2811158 GSM2811159 GSM2811160 GSM2811161 \\\n", "Esophageal_Cancer ... 1.0 0.0 1.0 1.0 \n", "\n", " GSM2811162 GSM2811163 GSM2811164 GSM2811165 GSM2811166 \\\n", "Esophageal_Cancer 1.0 1.0 1.0 1.0 1.0 \n", "\n", " GSM2811167 \n", "Esophageal_Cancer 1.0 \n", "\n", "[1 rows x 46 columns]\n", "Clinical features saved to ../../output/preprocess/Esophageal_Cancer/clinical_data/GSE104958.csv\n", "Linked data shape: (46, 20779)\n", "Linked data preview (first 5 rows, first 5 columns):\n", " Esophageal_Cancer A1BG A1BG-AS1 A1CF A2M\n", "GSM2811122 1.0 0.103348 -0.048602 -0.105821 -0.015755\n", "GSM2811123 1.0 -0.582059 -0.208037 -0.245147 -0.460151\n", "GSM2811124 1.0 -1.208877 -1.792347 -0.681063 0.004467\n", "GSM2811125 1.0 2.239748 1.689534 -0.207984 -0.690533\n", "GSM2811126 1.0 0.195371 0.342461 -1.054633 1.742541\n", "Missing values before handling:\n", " Trait (Esophageal_Cancer) missing: 0 out of 46\n", " Genes with >20% missing: 0\n", " Samples with >5% missing genes: 0\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Data shape after handling missing values: (46, 20779)\n", "For the feature 'Esophageal_Cancer', the least common label is '0.0' with 5 occurrences. This represents 10.87% of the dataset.\n", "The distribution of the feature 'Esophageal_Cancer' in this dataset is fine.\n", "\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Linked data saved to ../../output/preprocess/Esophageal_Cancer/GSE104958.csv\n" ] } ], "source": [ "# 1. Normalize gene symbols in the gene expression data\n", "normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n", "print(f\"Normalized gene data shape: {normalized_gene_data.shape}\")\n", "print(\"First few genes with their expression values after normalization:\")\n", "print(normalized_gene_data.head())\n", "\n", "# Save the normalized gene data\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 data saved to {out_gene_data_file}\")\n", "\n", "# 2. Check if trait data is available before proceeding with clinical data extraction\n", "if trait_row is None:\n", " print(\"Trait row is None. Cannot extract trait information from clinical data.\")\n", " # Create an empty dataframe for clinical features\n", " clinical_features = pd.DataFrame()\n", " \n", " # Create an empty dataframe for linked data\n", " linked_data = pd.DataFrame()\n", " \n", " # Validate and save cohort info\n", " 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, # Trait data is not available\n", " is_biased=True, # Not applicable but required\n", " df=pd.DataFrame(), # Empty dataframe\n", " note=\"Dataset contains gene expression data but lacks clear trait indicators for Duchenne Muscular Dystrophy status.\"\n", " )\n", " print(\"Data was determined to be unusable due to missing trait indicators and was not saved\")\n", "else:\n", " try:\n", " # Get the file paths for the matrix file to extract clinical data\n", " _, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", " \n", " # Get raw clinical data from the matrix file\n", " _, clinical_raw = get_background_and_clinical_data(matrix_file)\n", " \n", " # Verify clinical data structure\n", " print(\"Raw clinical data shape:\", clinical_raw.shape)\n", " \n", " # Extract clinical features using the defined conversion functions\n", " clinical_features = geo_select_clinical_features(\n", " clinical_df=clinical_raw,\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(\"Clinical features:\")\n", " print(clinical_features)\n", " \n", " # Save clinical features to file\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " clinical_features.to_csv(out_clinical_data_file)\n", " print(f\"Clinical features saved to {out_clinical_data_file}\")\n", " \n", " # 3. Link clinical and genetic data\n", " linked_data = geo_link_clinical_genetic_data(clinical_features, normalized_gene_data)\n", " print(f\"Linked data shape: {linked_data.shape}\")\n", " print(\"Linked data preview (first 5 rows, first 5 columns):\")\n", " print(linked_data.iloc[:5, :5])\n", " \n", " # 4. Handle missing values\n", " print(\"Missing values before handling:\")\n", " print(f\" Trait ({trait}) missing: {linked_data[trait].isna().sum()} out of {len(linked_data)}\")\n", " if 'Age' in linked_data.columns:\n", " print(f\" Age missing: {linked_data['Age'].isna().sum()} out of {len(linked_data)}\")\n", " if 'Gender' in linked_data.columns:\n", " print(f\" Gender missing: {linked_data['Gender'].isna().sum()} out of {len(linked_data)}\")\n", " \n", " gene_cols = [col for col in linked_data.columns if col not in [trait, 'Age', 'Gender']]\n", " print(f\" Genes with >20% missing: {sum(linked_data[gene_cols].isna().mean() > 0.2)}\")\n", " print(f\" Samples with >5% missing genes: {sum(linked_data[gene_cols].isna().mean(axis=1) > 0.05)}\")\n", " \n", " cleaned_data = handle_missing_values(linked_data, trait)\n", " print(f\"Data shape after handling missing values: {cleaned_data.shape}\")\n", " \n", " # 5. Evaluate bias in trait and demographic features\n", " is_trait_biased = False\n", " if len(cleaned_data) > 0:\n", " trait_biased, cleaned_data = judge_and_remove_biased_features(cleaned_data, trait)\n", " is_trait_biased = trait_biased\n", " else:\n", " print(\"No data remains after handling missing values.\")\n", " is_trait_biased = True\n", " \n", " # 6. Final validation and save\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_trait_biased, \n", " df=cleaned_data,\n", " note=\"Dataset contains gene expression data comparing Duchenne muscular dystrophy vs healthy samples.\"\n", " )\n", " \n", " # 7. Save if usable\n", " if is_usable and len(cleaned_data) > 0:\n", " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n", " cleaned_data.to_csv(out_data_file)\n", " print(f\"Linked data saved to {out_data_file}\")\n", " else:\n", " print(\"Data was determined to be unusable or empty and was not saved\")\n", " \n", " except Exception as e:\n", " print(f\"Error processing data: {e}\")\n", " # Handle the error case by still recording cohort info\n", " 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, # Mark as not available due to processing issues\n", " is_biased=True, \n", " df=pd.DataFrame(), # Empty dataframe\n", " note=f\"Error processing data: {str(e)}\"\n", " )\n", " print(\"Data was determined to be unusable and was 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 }