{ "cells": [ { "cell_type": "code", "execution_count": null, "id": "fe5db780", "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 = \"Stomach_Cancer\"\n", "cohort = \"GSE161533\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Stomach_Cancer\"\n", "in_cohort_dir = \"../../input/GEO/Stomach_Cancer/GSE161533\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Stomach_Cancer/GSE161533.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Stomach_Cancer/gene_data/GSE161533.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Stomach_Cancer/clinical_data/GSE161533.csv\"\n", "json_path = \"../../output/preprocess/Stomach_Cancer/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "dd093a27", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": null, "id": "337ad9c6", "metadata": {}, "outputs": [], "source": [ "# 1. Let's first list the directory contents to understand what files are available\n", "import os\n", "\n", "print(\"Files in the cohort directory:\")\n", "files = os.listdir(in_cohort_dir)\n", "print(files)\n", "\n", "# Adapt file identification to handle different naming patterns\n", "soft_files = [f for f in files if 'soft' in f.lower() or '.soft' in f.lower() or '_soft' in f.lower()]\n", "matrix_files = [f for f in files if 'matrix' in f.lower() or '.matrix' in f.lower() or '_matrix' in f.lower()]\n", "\n", "# If no files with these patterns are found, look for alternative file types\n", "if not soft_files:\n", " soft_files = [f for f in files if f.endswith('.txt') or f.endswith('.gz')]\n", "if not matrix_files:\n", " matrix_files = [f for f in files if f.endswith('.txt') or f.endswith('.gz')]\n", "\n", "print(\"Identified SOFT files:\", soft_files)\n", "print(\"Identified matrix files:\", matrix_files)\n", "\n", "# Use the first files found, if any\n", "if len(soft_files) > 0 and len(matrix_files) > 0:\n", " soft_file = os.path.join(in_cohort_dir, soft_files[0])\n", " matrix_file = os.path.join(in_cohort_dir, matrix_files[0])\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(\"\\nBackground Information:\")\n", " print(background_info)\n", " print(\"\\nSample Characteristics Dictionary:\")\n", " print(sample_characteristics_dict)\n", "else:\n", " print(\"No appropriate files found in the directory.\")\n" ] }, { "cell_type": "markdown", "id": "71824a8b", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "c5b4067b", "metadata": {}, "outputs": [], "source": [ "# 1. Gene Expression Data Availability\n", "# The dataset uses Affymetrix Gene Chip Human Genome U133 plus 2.0 Array, which contains gene expression data\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "\n", "# For trait: Examining the tissue type which indicates stomach cancer status\n", "trait_row = 0 # 'tissue' field - has normal, paratumor, and tumor tissue types\n", "\n", "# For age: Age data is available in key 2\n", "age_row = 2 # 'age' field with multiple values\n", "\n", "# For gender: Gender data is available in key 3\n", "gender_row = 3 # 'gender' field with Male and Female values\n", "\n", "# 2.2 Data Type Conversion\n", "\n", "# Convert trait to binary (tumor vs non-tumor)\n", "def convert_trait(value):\n", " if not isinstance(value, str):\n", " return None\n", " value = value.lower().strip()\n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " if \"tumor tissue\" in value:\n", " return 1 # Tumor tissue (case)\n", " elif \"normal tissue\" in value:\n", " return 0 # Normal tissue (control)\n", " elif \"paratumor tissue\" in value:\n", " return None # We'll exclude paratumor tissue as it's neither case nor control\n", " return None\n", "\n", "# Convert age to continuous\n", "def convert_age(value):\n", " if not isinstance(value, str):\n", " return None\n", " value = value.lower().strip()\n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " try:\n", " return float(value)\n", " except ValueError:\n", " return None\n", "\n", "# Convert gender to binary (0=female, 1=male)\n", "def convert_gender(value):\n", " if not isinstance(value, str):\n", " return None\n", " value = value.lower().strip()\n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " if \"male\" in value:\n", " return 1\n", " elif \"female\" in value:\n", " return 0\n", " return None\n", "\n", "# 3. Save Metadata\n", "# Initial validation - checking if gene and trait data are available\n", "is_trait_available = trait_row is not None\n", "validate_and_save_cohort_info(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", "# 4. Clinical Feature Extraction\n", "if trait_row is not None:\n", " # Extract clinical features using the function from the library\n", " 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 data\n", " preview = preview_df(clinical_df)\n", " print(\"Preview of clinical data:\")\n", " print(preview)\n", " \n", " # Save clinical data to CSV\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " 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": "f000ac35", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "dd404382", "metadata": {}, "outputs": [], "source": [ "# Use the helper function to get the proper file paths\n", "soft_file_path, matrix_file_path = geo_get_relevant_filepaths(in_cohort_dir)\n", "\n", "# Extract gene expression data\n", "try:\n", " gene_data = get_genetic_data(matrix_file_path)\n", " \n", " # Print the first 20 row IDs (gene or probe identifiers)\n", " print(\"First 20 gene/probe identifiers:\")\n", " print(gene_data.index[:20])\n", " \n", " # Print shape to understand the dataset dimensions\n", " print(f\"\\nGene expression data shape: {gene_data.shape}\")\n", " \n", "except Exception as e:\n", " print(f\"Error extracting gene data: {e}\")\n" ] }, { "cell_type": "markdown", "id": "81ac5eed", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": null, "id": "de29d4e5", "metadata": {}, "outputs": [], "source": [ "# Examining the gene identifiers shown in the previous step\n", "# These identifiers (e.g., '1007_s_at', '1053_at') appear to be Affymetrix probe IDs\n", "# rather than standard human gene symbols (which would be like BRCA1, TP53, etc.)\n", "# Affymetrix probe IDs need to be mapped to official gene symbols for biological interpretation\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "7dfb6770", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": null, "id": "2fef7c0f", "metadata": {}, "outputs": [], "source": [ "# 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.\n", "try:\n", " # Use the correct variable name from previous steps\n", " gene_annotation = get_gene_annotation(soft_file_path)\n", " \n", " # 2. Preview the gene annotation dataframe\n", " print(\"Gene annotation preview:\")\n", " print(preview_df(gene_annotation))\n", " \n", "except UnicodeDecodeError as e:\n", " print(f\"Unicode decoding error: {e}\")\n", " print(\"Trying alternative approach...\")\n", " \n", " # Read the file with Latin-1 encoding which is more permissive\n", " import gzip\n", " import pandas as pd\n", " \n", " # Manually read the file line by line with error handling\n", " data_lines = []\n", " with gzip.open(soft_file_path, 'rb') as f:\n", " for line in f:\n", " # Skip lines starting with prefixes we want to filter out\n", " line_str = line.decode('latin-1')\n", " if not line_str.startswith('^') and not line_str.startswith('!') and not line_str.startswith('#'):\n", " data_lines.append(line_str)\n", " \n", " # Create dataframe from collected lines\n", " if data_lines:\n", " gene_data_str = '\\n'.join(data_lines)\n", " gene_annotation = pd.read_csv(pd.io.common.StringIO(gene_data_str), sep='\\t', low_memory=False)\n", " print(\"Gene annotation preview (alternative method):\")\n", " print(preview_df(gene_annotation))\n", " else:\n", " print(\"No valid gene annotation data found after filtering.\")\n", " gene_annotation = pd.DataFrame()\n", " \n", "except Exception as e:\n", " print(f\"Error extracting gene annotation data: {e}\")\n", " gene_annotation = pd.DataFrame()\n" ] }, { "cell_type": "markdown", "id": "0938a050", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": null, "id": "c1ad5024", "metadata": {}, "outputs": [], "source": [ "# 1. Identify the relevant columns in the gene annotation dataframe\n", "# The gene expression data uses identifiers like '1007_s_at', which matches the 'ID' column in the gene annotation\n", "# The gene symbols are stored in the 'Gene Symbol' column\n", "\n", "# 2. Create the gene mapping dataframe using the get_gene_mapping function\n", "mapping_df = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='Gene Symbol')\n", "print(\"\\nGene mapping dataframe (first 5 rows):\")\n", "print(mapping_df.head())\n", "print(f\"Shape of mapping dataframe: {mapping_df.shape}\")\n", "\n", "# 3. Apply the gene mapping to convert probe-level measurements to gene expression\n", "gene_data = apply_gene_mapping(gene_data, mapping_df)\n", "print(\"\\nConverted gene expression data (first 5 genes, 5 samples):\")\n", "if not gene_data.empty:\n", " print(gene_data.iloc[:5, :5])\n", " print(f\"\\nShape of gene expression data: {gene_data.shape}\")\n", "else:\n", " print(\"Gene expression data is empty after mapping.\")\n" ] }, { "cell_type": "markdown", "id": "e2d618be", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": null, "id": "c2e1f3d4", "metadata": {}, "outputs": [], "source": [ "# 1. Normalize gene symbols in the obtained 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. Load the clinical data created in Step 2\n", "# Inspect clinical data structure before manipulating\n", "clinical_df = pd.read_csv(out_clinical_data_file)\n", "print(f\"Loaded clinical data shape: {clinical_df.shape}\")\n", "print(f\"Loaded clinical data columns: {clinical_df.columns.tolist()}\")\n", "\n", "# Create clinical features DataFrame with proper structure \n", "# In this dataset, we know from step 2 that the first column is unnamed and contains feature names\n", "clinical_features = clinical_df.copy()\n", "# Set the first unnamed column as index if it exists\n", "if 'Unnamed: 0' in clinical_features.columns:\n", " clinical_features = clinical_features.set_index('Unnamed: 0') \n", "clinical_features = clinical_features.T # Transpose to get samples as rows and features as columns\n", "print(f\"Clinical features shape after format adjustment: {clinical_features.shape}\")\n", "\n", "# Link clinical and genetic data\n", "linked_data = geo_link_clinical_genetic_data(clinical_features.T, normalized_gene_data)\n", "print(f\"Linked data shape after linking: {linked_data.shape}\")\n", "\n", "# 3. Handle missing values\n", "linked_data = handle_missing_values(linked_data, trait)\n", "print(f\"Linked data shape after handling missing values: {linked_data.shape}\")\n", "\n", "# 4. Determine whether the trait and demographic features are biased\n", "is_trait_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n", "print(f\"Is trait biased: {is_trait_biased}\")\n", "print(f\"Linked data shape after removing biased features: {linked_data.shape}\")\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=linked_data,\n", " note=\"Dataset contains gene expression data from esophageal squamous cell carcinoma patients, with normal, paratumor, and tumor tissue samples.\"\n", ")\n", "\n", "# 6. Save the linked data if it's usable\n", "print(f\"Data quality check result: {'Usable' if is_usable else 'Not 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(f\"Data not saved due to quality issues.\")\n" ] }, { "cell_type": "markdown", "id": "9973ed83", "metadata": {}, "source": [ "### Step 8: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": null, "id": "3b202f75", "metadata": {}, "outputs": [], "source": [ "# 1. Normalize gene symbols in the obtained 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. Load the clinical data created in Step 2\n", "clinical_df = pd.read_csv(out_clinical_data_file)\n", "print(f\"Loaded clinical data shape: {clinical_df.shape}\")\n", "\n", "# Prepare clinical data properly, understanding the data structure from previous steps\n", "# The DataFrame needs to be transposed to have samples as rows and features as columns\n", "clinical_features = pd.DataFrame()\n", "for col in clinical_df.columns:\n", " if col != 'Unnamed: 0': # Skip the unnamed index column if it exists\n", " sample_id = col\n", " # Get trait, age, gender values for this sample\n", " values = clinical_df[col].values\n", " if len(values) >= 3: # Make sure we have enough values\n", " clinical_features.loc[sample_id, trait] = values[0] # Stomach_Cancer status\n", " clinical_features.loc[sample_id, 'Age'] = values[1] # Age\n", " clinical_features.loc[sample_id, 'Gender'] = values[2] # Gender\n", "\n", "print(f\"Prepared clinical features shape: {clinical_features.shape}\")\n", "print(clinical_features.head())\n", "\n", "# Link clinical and genetic data\n", "linked_data = pd.concat([clinical_features, normalized_gene_data.T], axis=1)\n", "print(f\"Linked data shape: {linked_data.shape}\")\n", "\n", "# 3. Handle missing values\n", "linked_data = handle_missing_values(linked_data, trait)\n", "print(f\"Linked data shape after handling missing values: {linked_data.shape}\")\n", "\n", "# 4. Determine whether the trait and demographic features are biased\n", "is_trait_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n", "print(f\"Is trait biased: {is_trait_biased}\")\n", "print(f\"Linked data shape after removing biased features: {linked_data.shape}\")\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=linked_data,\n", " note=\"Dataset contains gene expression data from esophageal squamous cell carcinoma patients, with normal, paratumor, and tumor tissue samples.\"\n", ")\n", "\n", "# 6. Save the linked data if it's usable\n", "print(f\"Data quality check result: {'Usable' if is_usable else 'Not 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(f\"Data not saved due to quality issues.\")" ] } ], "metadata": {}, "nbformat": 4, "nbformat_minor": 5 }