{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "a122cdba", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T03:47:09.361650Z", "iopub.status.busy": "2025-03-25T03:47:09.361416Z", "iopub.status.idle": "2025-03-25T03:47:09.529994Z", "shell.execute_reply": "2025-03-25T03:47:09.529612Z" } }, "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 = \"Rectal_Cancer\"\n", "cohort = \"GSE145037\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Rectal_Cancer\"\n", "in_cohort_dir = \"../../input/GEO/Rectal_Cancer/GSE145037\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Rectal_Cancer/GSE145037.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Rectal_Cancer/gene_data/GSE145037.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Rectal_Cancer/clinical_data/GSE145037.csv\"\n", "json_path = \"../../output/preprocess/Rectal_Cancer/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "78844ed8", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "206a32b2", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T03:47:09.531481Z", "iopub.status.busy": "2025-03-25T03:47:09.531334Z", "iopub.status.idle": "2025-03-25T03:47:09.597226Z", "shell.execute_reply": "2025-03-25T03:47:09.596896Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Hypermethylation and downregulation of UTP6 are associated with stemness properties, chemoradiotherapy resistance and prognosis in rectal cancer: A co-expression network analysis\"\n", "!Series_summary\t\"To measure global gene expression in primary locally advanced rectal cancer patients who have undergone CRT and screen valuable biomarkers to predict the effects of CRT.Samples fromprimary locally advanced rectal cancer patients were collected. The effects of chemoradiotherapy were evaluated.\"\n", "!Series_overall_design\t\"All patients underwent standard CRT after signing the chemoradiotherapy agreement; subsequently, they were evaluated in accordance with the AJCC tumor regression grade (TRG).Each samplewas collected before CRT. Each sample was stored in liquid nitrogen until total RNA extraction.\"\n", "Sample Characteristics Dictionary:\n", "{0: ['tissue: primary rectalcancer'], 1: ['Sex: Male', 'Sex: Female'], 2: ['age: 34', 'age: 66', 'age: 69', 'age: 65', 'age: 72', 'age: 64', 'age: 53', 'age: 60', 'age: 44', 'age: 58', 'age: 41', 'age: 52', 'age: 48', 'age: 49', 'age: 61', 'age: 63', 'age: 75', 'age: 46', 'age: 59', 'age: 70', 'age: 68', 'age: 73'], 3: ['response to the crt: non-response', 'response to the crt: response'], 4: ['clincal t stage: 4', 'clincal t stage: 3', 'clincal t stage: 2'], 5: ['clincal n positive: 1', 'clincal n positive: 0']}\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": "f5cf823f", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "e30fe2ec", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T03:47:09.598389Z", "iopub.status.busy": "2025-03-25T03:47:09.598279Z", "iopub.status.idle": "2025-03-25T03:47:09.609388Z", "shell.execute_reply": "2025-03-25T03:47:09.609083Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Preview of selected clinical features:\n", "{0: [0.0, 34.0, 1.0], 1: [1.0, 66.0, 0.0], 2: [nan, 69.0, nan], 3: [nan, 65.0, nan], 4: [nan, 72.0, nan], 5: [nan, 64.0, nan], 6: [nan, 53.0, nan], 7: [nan, 60.0, nan], 8: [nan, 44.0, nan], 9: [nan, 58.0, nan], 10: [nan, 41.0, nan], 11: [nan, 52.0, nan], 12: [nan, 48.0, nan], 13: [nan, 49.0, nan], 14: [nan, 61.0, nan], 15: [nan, 63.0, nan], 16: [nan, 75.0, nan], 17: [nan, 46.0, nan], 18: [nan, 59.0, nan], 19: [nan, 70.0, nan], 20: [nan, 68.0, nan], 21: [nan, 73.0, nan]}\n", "Clinical data saved to ../../output/preprocess/Rectal_Cancer/clinical_data/GSE145037.csv\n" ] } ], "source": [ "# 1. Gene Expression Data Availability\n", "# Based on the series title and design mentioning \"gene expression\", this appears to be gene expression data\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "# For trait - response to CRT is available in row 3\n", "trait_row = 3\n", "\n", "# For gender - available in row 1\n", "gender_row = 1\n", "\n", "# For age - available in row 2\n", "age_row = 2\n", "\n", "# 2.2 Data Type Conversion Functions\n", "def convert_trait(value):\n", " \"\"\"Convert treatment response to binary: 1 for response, 0 for non-response\"\"\"\n", " if not isinstance(value, str):\n", " return None\n", " value = value.lower()\n", " if 'response to the crt:' in value:\n", " value = value.split('response to the crt:')[1].strip()\n", " if 'response' == value:\n", " return 1\n", " elif 'non-response' == value:\n", " return 0\n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age to a continuous value\"\"\"\n", " if not isinstance(value, str):\n", " return None\n", " if 'age:' in value:\n", " try:\n", " age = int(value.split('age:')[1].strip())\n", " return age\n", " except:\n", " pass\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", " value = value.lower()\n", " if 'sex:' in value:\n", " value = value.split('sex:')[1].strip().lower()\n", " if 'female' in value:\n", " return 0\n", " elif 'male' in value:\n", " return 1\n", " return None\n", "\n", "# 3. Save Metadata\n", "# Trait data is available (trait_row is not None)\n", "is_trait_available = trait_row is not None\n", "validate_and_save_cohort_info(is_final=False, cohort=cohort, \n", " info_path=json_path, \n", " is_gene_available=is_gene_available, \n", " is_trait_available=is_trait_available)\n", "\n", "# 4. Clinical Feature Extraction\n", "if trait_row is not None:\n", " # Create a DataFrame from the sample characteristics dictionary\n", " # The dictionary format suggests rows are indexed by integers (0-5)\n", " # and each row contains a list of values\n", " sample_char_dict = {\n", " 0: ['tissue: primary rectalcancer'],\n", " 1: ['Sex: Male', 'Sex: Female'],\n", " 2: ['age: 34', 'age: 66', 'age: 69', 'age: 65', 'age: 72', 'age: 64', 'age: 53', 'age: 60', 'age: 44', \n", " 'age: 58', 'age: 41', 'age: 52', 'age: 48', 'age: 49', 'age: 61', 'age: 63', 'age: 75', 'age: 46', \n", " 'age: 59', 'age: 70', 'age: 68', 'age: 73'],\n", " 3: ['response to the crt: non-response', 'response to the crt: response'],\n", " 4: ['clincal t stage: 4', 'clincal t stage: 3', 'clincal t stage: 2'],\n", " 5: ['clincal n positive: 1', 'clincal n positive: 0']\n", " }\n", " \n", " # Convert to DataFrame format suitable for geo_select_clinical_features\n", " clinical_data = pd.DataFrame.from_dict(sample_char_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 extracted clinical features\n", " preview = preview_df(selected_clinical_df)\n", " print(\"Preview of selected clinical features:\")\n", " print(preview)\n", " \n", " # Save the extracted clinical data\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " selected_clinical_df.to_csv(out_clinical_data_file)\n", " print(f\"Clinical data saved to {out_clinical_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "a3c531dd", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "7b8a7f72", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T03:47:09.610471Z", "iopub.status.busy": "2025-03-25T03:47:09.610362Z", "iopub.status.idle": "2025-03-25T03:47:09.690115Z", "shell.execute_reply": "2025-03-25T03:47:09.689634Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Index(['A1BG', 'A1CF', 'A2M', 'A2ML1', 'A3GALT2', 'A4GALT', 'A4GNT', 'AAAS',\n", " 'AACS', 'AADAC', 'AADACL2', 'AADACL3', 'AADACL4', 'AADAT', 'AAGAB',\n", " 'AAK1', 'AAMDC', 'AAMP', 'AANAT', 'AAR2'],\n", " dtype='object', name='ID')\n" ] } ], "source": [ "# 1. First get the file paths\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "\n", "# 2. Use the get_genetic_data function from the library to get the gene_data\n", "gene_data = get_genetic_data(matrix_file)\n", "\n", "# 3. Print the first 20 row IDs (gene or probe identifiers) for future observation\n", "print(gene_data.index[:20])\n" ] }, { "cell_type": "markdown", "id": "2cd28dc2", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "9a4e5972", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T03:47:09.691615Z", "iopub.status.busy": "2025-03-25T03:47:09.691501Z", "iopub.status.idle": "2025-03-25T03:47:09.693632Z", "shell.execute_reply": "2025-03-25T03:47:09.693263Z" } }, "outputs": [], "source": [ "# The gene identifiers shown in the output are human gene symbols.\n", "# These are standard HUGO Gene Nomenclature Committee (HGNC) gene symbols,\n", "# including known genes like A1BG (alpha-1-B glycoprotein), A2M (alpha-2-macroglobulin),\n", "# and AANAT (aralkylamine N-acetyltransferase).\n", "# No mapping is required as these are already in the proper gene symbol format.\n", "\n", "requires_gene_mapping = False\n" ] }, { "cell_type": "markdown", "id": "032f0724", "metadata": {}, "source": [ "### Step 5: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 6, "id": "b04d49e0", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T03:47:09.694838Z", "iopub.status.busy": "2025-03-25T03:47:09.694740Z", "iopub.status.idle": "2025-03-25T03:47:10.141118Z", "shell.execute_reply": "2025-03-25T03:47:10.140635Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Loaded clinical data shape: (3, 22)\n", "Normalized gene data shape: (18404, 31)\n", "First few normalized gene symbols: ['A1BG', 'A1CF', 'A2M', 'A2ML1', 'A3GALT2', 'A4GALT', 'A4GNT', 'AAAS', 'AACS', 'AADAC']\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene data saved to ../../output/preprocess/Rectal_Cancer/gene_data/GSE145037.csv\n", "Linked data shape: (53, 18407)\n", " Rectal_Cancer Age Gender A1BG A1CF A2M A2ML1 A3GALT2 A4GALT \\\n", "0 0.0 34.0 1.0 NaN NaN NaN NaN NaN NaN \n", "1 1.0 66.0 0.0 NaN NaN NaN NaN NaN NaN \n", "2 NaN 69.0 NaN NaN NaN NaN NaN NaN NaN \n", "3 NaN 65.0 NaN NaN NaN NaN NaN NaN NaN \n", "4 NaN 72.0 NaN NaN NaN NaN NaN NaN NaN \n", "\n", " A4GNT ... ZW10 ZWILCH ZWINT ZXDA ZXDB ZXDC ZYG11A ZYG11B ZYX \\\n", "0 NaN ... NaN NaN NaN NaN NaN NaN NaN NaN NaN \n", "1 NaN ... NaN NaN NaN NaN NaN NaN NaN NaN NaN \n", "2 NaN ... NaN NaN NaN NaN NaN NaN NaN NaN NaN \n", "3 NaN ... NaN NaN NaN NaN NaN NaN NaN NaN NaN \n", "4 NaN ... NaN NaN NaN NaN NaN NaN NaN NaN NaN \n", "\n", " ZZEF1 \n", "0 NaN \n", "1 NaN \n", "2 NaN \n", "3 NaN \n", "4 NaN \n", "\n", "[5 rows x 18407 columns]\n", "Missing values in trait column: 51/53\n", "Missing values in Age column: 31/53\n", "Missing values in Gender column: 51/53\n", "Shape after handling missing values: (0, 2)\n", "No samples remain after handling missing values. The dataset cannot be processed further.\n", "Abnormality detected in the cohort: GSE145037. Preprocessing failed.\n", "Data quality check failed. The dataset is not suitable for association studies.\n" ] } ], "source": [ "# 1. Load the previously saved clinical data instead of re-extracting\n", "clinical_features = pd.read_csv(out_clinical_data_file, index_col=0)\n", "print(f\"Loaded clinical data shape: {clinical_features.shape}\")\n", "\n", "# 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(f\"First few normalized gene symbols: {list(normalized_gene_data.index[:10])}\")\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. Link the 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.head())\n", "\n", "# Inspect the data for missing values before handling them\n", "print(f\"Missing values in trait column: {linked_data[trait].isna().sum()}/{len(linked_data)}\")\n", "print(f\"Missing values in Age column: {linked_data['Age'].isna().sum()}/{len(linked_data)}\")\n", "print(f\"Missing values in Gender column: {linked_data['Gender'].isna().sum()}/{len(linked_data)}\")\n", "\n", "# 3. Handle missing values in the linked data\n", "linked_data_processed = handle_missing_values(linked_data, trait)\n", "print(f\"Shape after handling missing values: {linked_data_processed.shape}\")\n", "\n", "# Add validation check - if no samples remain, note the issue\n", "if linked_data_processed.shape[0] == 0:\n", " print(\"No samples remain after handling missing values. The dataset cannot be processed further.\")\n", " is_trait_biased = True # Mark as biased since we can't use it\n", " unbiased_linked_data = linked_data_processed\n", "else:\n", " # 4. Determine whether the trait and demographic features are severely biased\n", " is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data_processed, trait)\n", "\n", "# 5. Conduct quality check and save the 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,\n", " is_biased=is_trait_biased, \n", " df=unbiased_linked_data,\n", " note=\"Dataset contains gene expression data from rectal cancer patients, focusing on response to chemoradiotherapy. However, high levels of missing trait values make it unsuitable for association studies.\"\n", ")\n", "\n", "# 6. Save the data if it's usable\n", "if is_usable:\n", " # Create directory if it doesn't exist\n", " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n", " # Save the data\n", " unbiased_linked_data.to_csv(out_data_file)\n", " print(f\"Linked data saved to {out_data_file}\")\n", "else:\n", " print(f\"Data quality check failed. The dataset is not suitable for association studies.\")" ] } ], "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 }