{ "cells": [ { "cell_type": "code", "execution_count": null, "id": "3adc507e", "metadata": {}, "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 = \"GSE139255\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Rectal_Cancer\"\n", "in_cohort_dir = \"../../input/GEO/Rectal_Cancer/GSE139255\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Rectal_Cancer/GSE139255.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Rectal_Cancer/gene_data/GSE139255.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Rectal_Cancer/clinical_data/GSE139255.csv\"\n", "json_path = \"../../output/preprocess/Rectal_Cancer/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "a2ed859d", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": null, "id": "a2c16f0e", "metadata": {}, "outputs": [], "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": "59563c58", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "025f5d41", "metadata": {}, "outputs": [], "source": [ "# Let's analyze the dataset and extract clinical features\n", "import pandas as pd\n", "import os\n", "import json\n", "import numpy as np\n", "from typing import Dict, Any, Optional, Callable\n", "\n", "# 1. Gene Expression Data Availability\n", "# From the background information, we can see that gene expression analysis was performed\n", "# using the nCounter PanCancer Pathway Panel that analyzed 770 genes\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "# From the Sample Characteristics Dictionary, we can see:\n", "# - trait (response to chemoradiotherapy) is in row 0\n", "# - age is not available \n", "# - gender is not available\n", "trait_row = 0 # Response to treatment is in row 0\n", "age_row = None # Age data is not available\n", "gender_row = None # Gender data is not available\n", "\n", "# 2.2 Data Type Conversion\n", "def convert_trait(value):\n", " \"\"\"Convert treatment response to binary values (0: Non-Response, 1: Good-Response)\"\"\"\n", " if value is None:\n", " return None\n", " # Extract the actual value after the colon if present\n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " if \"good-response\" in value.lower():\n", " return 1\n", " elif \"non-response\" in value.lower():\n", " return 0\n", " else:\n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"Placeholder function for age conversion\"\"\"\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"Placeholder function for gender conversion\"\"\"\n", " return None\n", "\n", "# 3. Save Metadata\n", "# Determine if trait data is available\n", "is_trait_available = trait_row is not None\n", "# Validate and save cohort info\n", "validate_and_save_cohort_info(\n", " is_final=False,\n", " cohort=cohort,\n", " info_path=json_path,\n", " is_gene_available=is_gene_available,\n", " is_trait_available=is_trait_available\n", ")\n", "\n", "# 4. Clinical Feature Extraction\n", "# Only proceed if trait data is available\n", "if trait_row is not None:\n", " # Using the sample characteristics dictionary directly provided in the previous step\n", " # Create a dataframe from the sample characteristics\n", " sample_chars = {0: ['histology: Non-Response', 'histology: Good-Response']}\n", " \n", " # Convert the sample characteristics to a proper DataFrame format\n", " # We need to create a DataFrame with columns for each sample and rows for each characteristic\n", " sample_data = []\n", " sample_ids = []\n", " \n", " # Assuming the values in sample_chars are the unique values across samples\n", " # Create mock data for demonstration (since we don't have actual sample assignments)\n", " for i, values in sample_chars.items():\n", " for val in values:\n", " sample_id = f\"Sample_{len(sample_ids) + 1}\"\n", " sample_ids.append(sample_id)\n", " sample_data.append([val])\n", " \n", " clinical_data = pd.DataFrame(sample_data, index=sample_ids)\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 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 to CSV\n", " selected_clinical_df.to_csv(out_clinical_data_file, index=False)\n", " print(f\"Clinical data saved to {out_clinical_data_file}\")\n", "else:\n", " print(\"No trait data available for clinical feature extraction\")\n" ] }, { "cell_type": "markdown", "id": "f42da576", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "eceb0c72", "metadata": {}, "outputs": [], "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": "3cfab2e6", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": null, "id": "db63b03f", "metadata": {}, "outputs": [], "source": [ "# Reviewing the gene identifiers\n", "# I see gene symbols like ABL1, AKT1, APC, AR, ARID1A which are standard human gene symbols\n", "# These are official HUGO gene symbols and don't need mapping to another format\n", "\n", "requires_gene_mapping = False\n" ] }, { "cell_type": "markdown", "id": "ae46f131", "metadata": {}, "source": [ "### Step 5: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": null, "id": "1fe0a33f", "metadata": {}, "outputs": [], "source": [ "# 1. Load the previously saved clinical data\n", "clinical_features = pd.read_csv(out_clinical_data_file)\n", "\n", "# Check the structure of the clinical data and rename columns if needed\n", "print(f\"Original clinical features columns: {clinical_features.columns}\")\n", "if '0' in clinical_features.columns:\n", " clinical_features = clinical_features.rename(columns={'0': trait})\n", "print(f\"Adjusted clinical features columns: {clinical_features.columns}\")\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", "# Verify the columns in linked data\n", "print(f\"Linked data columns: {linked_data.columns[:10]}\") # Show first 10 columns\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.\"\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.\")\n" ] }, { "cell_type": "markdown", "id": "8dd98f76", "metadata": {}, "source": [ "### Step 6: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": null, "id": "5d32a16b", "metadata": {}, "outputs": [], "source": [ "# 1. Let's extract clinical data from the matrix file again to get the correct format\n", "# First get the file paths\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "\n", "# Get background info and clinical 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", "# Extract clinical features properly\n", "clinical_features = geo_select_clinical_features(\n", " clinical_df=clinical_data,\n", " trait=trait,\n", " trait_row=0,\n", " convert_trait=lambda value: 1 if \"good-response\" in str(value).lower() else 0 if \"non-response\" in str(value).lower() else None,\n", " age_row=None,\n", " convert_age=None,\n", " gender_row=None,\n", " convert_gender=None\n", ")\n", "\n", "# Save clinical features again with proper format\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 shape: {clinical_features.shape}\")\n", "print(f\"Clinical features columns: {clinical_features.columns}\")\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", "# 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.\"\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": {}, "nbformat": 4, "nbformat_minor": 5 }