{ "cells": [ { "cell_type": "code", "execution_count": null, "id": "eb893ffd", "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 = \"Lung_Cancer\"\n", "cohort = \"GSE244117\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Lung_Cancer\"\n", "in_cohort_dir = \"../../input/GEO/Lung_Cancer/GSE244117\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Lung_Cancer/GSE244117.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Lung_Cancer/gene_data/GSE244117.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Lung_Cancer/clinical_data/GSE244117.csv\"\n", "json_path = \"../../output/preprocess/Lung_Cancer/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "47fb4015", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": null, "id": "f8598a70", "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": "c4358da7", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "663950e6", "metadata": {}, "outputs": [], "source": [ "import pandas as pd\n", "import numpy as np\n", "import os\n", "import json\n", "from typing import Optional, Callable, Dict, Any\n", "\n", "# 1. Gene Expression Data Availability\n", "# This dataset appears to be spatial transcriptomics data of olfactory neuroblastoma (ONB) samples\n", "# The description mentions transcriptomic profiling with the NanoString GeoMx platform\n", "# It's not miRNA or methylation data, but rather whole transcriptome analysis\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# Looking at the Sample Characteristics Dictionary\n", "\n", "# 2.1 Data Availability\n", "# For trait:\n", "# Row 1 contains 'grade' information which can be used as our trait\n", "# Grade indicates cancer severity/progression\n", "trait_row = 1\n", "\n", "# For age:\n", "# Row 5 contains age information\n", "age_row = 5\n", "\n", "# For gender:\n", "# Row 4 contains gender information as 'Sex: F' or 'Sex: M'\n", "gender_row = 4\n", "\n", "# 2.2 Data Type Conversion Functions\n", "def convert_trait(value):\n", " \"\"\"Convert grade information to binary cancer status.\"\"\"\n", " if pd.isna(value):\n", " return None\n", " \n", " # Extract the value after colon if present\n", " if ':' in str(value):\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # Convert to binary (normal=0, any grade=1)\n", " if value.lower() == 'normal':\n", " return 0\n", " elif value.upper() in ['I', 'II', 'III', 'IV']:\n", " return 1\n", " else:\n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age string to numerical value.\"\"\"\n", " if pd.isna(value):\n", " return None\n", " \n", " # Extract the value after colon if present\n", " if ':' in str(value):\n", " value = value.split(':', 1)[1].strip()\n", " \n", " try:\n", " return float(value)\n", " except (ValueError, TypeError):\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"Convert gender string to binary (F=0, M=1).\"\"\"\n", " if pd.isna(value):\n", " return None\n", " \n", " # Extract the value after colon if present\n", " if ':' in str(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", " else:\n", " return None\n", "\n", "# 3. Save Metadata\n", "# Determine trait data availability\n", "is_trait_available = trait_row is not None\n", "\n", "# Conduct initial filtering and save 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", "# Skip this step if trait_row is None\n", "if trait_row is not None:\n", " try:\n", " # Extract clinical features using the clinical_data variable that was mentioned in the instructions\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 features to a CSV file\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", " except NameError:\n", " print(\"The 'clinical_data' variable was not found. Please make sure it's properly defined.\")\n" ] }, { "cell_type": "markdown", "id": "b70e6e7f", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "f6072778", "metadata": {}, "outputs": [], "source": [ "# 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.\n", "gene_data = get_genetic_data(matrix_file)\n", "\n", "# 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.\n", "print(gene_data.index[:20])\n" ] }, { "cell_type": "markdown", "id": "be5f5428", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": null, "id": "60667a7e", "metadata": {}, "outputs": [], "source": [ "# Analyzing the gene identifiers shown in the output\n", "# These identifiers appear to be standard human gene symbols (HGNC symbols)\n", "# For example: A1BG (alpha-1-B glycoprotein), A2M (alpha-2-macroglobulin), AAAS (aladin WD repeat nucleoporin)\n", "# These are the standard official gene symbols for human genes, not probe IDs or other identifiers\n", "\n", "requires_gene_mapping = False\n" ] }, { "cell_type": "markdown", "id": "ba173d7b", "metadata": {}, "source": [ "### Step 5: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": null, "id": "7f7ea158", "metadata": {}, "outputs": [], "source": [ "# 1. Normalize the obtained gene data with the 'normalize_gene_symbols_in_index' function from the library.\n", "normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n", "print(f\"Shape of normalized gene data: {normalized_gene_data.shape}\")\n", "# Save to the gene data 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\"Saved normalized gene data to {out_gene_data_file}\")\n", "\n", "# 2. Link the clinical and genetic data with the 'geo_link_clinical_genetic_data' function from the library.\n", "# Need to load the saved clinical data - it's saved as T, so we need to transpose it back\n", "clinical_features = pd.read_csv(out_clinical_data_file, index_col=0)\n", "print(f\"Shape of clinical_features before transpose: {clinical_features.shape}\")\n", "print(f\"Columns in clinical_features: {clinical_features.columns.tolist()[:5]}...\") # Show first 5 columns\n", "\n", "# Convert the clinical dataframe to the expected format for linking\n", "# The index should be the feature names (Lung_Cancer, Age, Gender) and the columns should be sample IDs\n", "linked_data = geo_link_clinical_genetic_data(clinical_features, normalized_gene_data)\n", "print(f\"Shape of linked data: {linked_data.shape}\")\n", "print(f\"First few columns in linked_data: {linked_data.columns.tolist()[:5]}\")\n", "\n", "# 3. Handle missing values in the linked data\n", "# First check column names to ensure we're using the right trait name\n", "print(f\"Available columns in linked_data: {[col for col in linked_data.columns if col in [trait, 'Age', 'Gender', '0', '1']]}\")\n", "\n", "# The trait name in the linked data might be \"0\" (first row index from clinical_features)\n", "# We need to use the actual column name that exists in the linked data\n", "trait_col = \"0\" # This assumes the first row of clinical_features had the trait data\n", "linked_data = handle_missing_values(linked_data, trait_col)\n", "print(f\"Shape of linked data after handling missing values: {linked_data.shape}\")\n", "\n", "# Rename columns to ensure consistent naming\n", "if trait_col != trait:\n", " linked_data = linked_data.rename(columns={trait_col: trait})\n", "\n", "# 4. Determine whether the trait and some demographic features are severely biased, and remove biased features.\n", "is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, 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 from olfactory neuroblastoma patients relevant to lung cancer research\"\n", ")\n", "\n", "# 6. If the linked data is usable, save it as a CSV file to 'out_data_file'.\n", "if is_usable:\n", " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n", " unbiased_linked_data.to_csv(out_data_file)\n", " print(f\"Saved processed linked data to {out_data_file}\")\n", "else:\n", " print(\"Dataset validation failed. Data not saved.\")\n" ] }, { "cell_type": "markdown", "id": "768df867", "metadata": {}, "source": [ "### Step 6: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": null, "id": "12b871fe", "metadata": {}, "outputs": [], "source": [ "# 1. Normalize the obtained gene data with the 'normalize_gene_symbols_in_index' function from the library.\n", "normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n", "print(f\"Shape of normalized gene data: {normalized_gene_data.shape}\")\n", "# Save to the gene data 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\"Saved normalized gene data to {out_gene_data_file}\")\n", "\n", "# 2. Link the clinical and genetic data\n", "# Need to load the saved clinical data\n", "clinical_features = pd.read_csv(out_clinical_data_file)\n", "\n", "# Print clinical_features structure to debug\n", "print(f\"Clinical features columns: {clinical_features.columns.tolist()}\")\n", "print(f\"Clinical features shape: {clinical_features.shape}\")\n", "\n", "# Convert clinical features to the correct format for linking\n", "# First, we need to set the appropriate index\n", "if 'Unnamed: 0' in clinical_features.columns:\n", " clinical_features = clinical_features.set_index('Unnamed: 0')\n", "\n", "# Create a new DataFrame with the trait name as Lung_Cancer for clarity\n", "trait_row = clinical_features.iloc[0].rename(trait)\n", "age_row = clinical_features.iloc[1].rename('Age') if len(clinical_features) > 1 else None\n", "gender_row = clinical_features.iloc[2].rename('Gender') if len(clinical_features) > 2 else None\n", "\n", "# Combine rows into a new clinical dataframe with proper naming\n", "clinical_df_rows = [trait_row]\n", "if age_row is not None:\n", " clinical_df_rows.append(age_row)\n", "if gender_row is not None:\n", " clinical_df_rows.append(gender_row)\n", "\n", "named_clinical_df = pd.DataFrame(clinical_df_rows)\n", "print(f\"Named clinical dataframe shape: {named_clinical_df.shape}\")\n", "print(f\"Named clinical dataframe index: {named_clinical_df.index.tolist()}\")\n", "\n", "# Link the clinical and genetic data\n", "linked_data = geo_link_clinical_genetic_data(named_clinical_df, normalized_gene_data)\n", "print(f\"Shape of linked data: {linked_data.shape}\")\n", "print(f\"First few columns in linked_data: {linked_data.columns[:10].tolist()}\")\n", "\n", "# Check if the trait column exists in the dataframe\n", "if trait not in linked_data.columns:\n", " print(f\"Warning: '{trait}' column not found in linked data. Available columns: {linked_data.columns[:20].tolist()}\")\n", "\n", "# 3. Handle missing values in the linked data\n", "linked_data = handle_missing_values(linked_data, trait)\n", "print(f\"Shape of linked data after handling missing values: {linked_data.shape}\")\n", "\n", "# 4. Determine whether the trait and demographic features are biased, and remove biased features\n", "is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, 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 from olfactory neuroblastoma patients relevant to lung cancer research\"\n", ")\n", "\n", "# 6. If the linked data is usable, save it as a CSV file\n", "if is_usable:\n", " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n", " unbiased_linked_data.to_csv(out_data_file)\n", " print(f\"Saved processed linked data to {out_data_file}\")\n", "else:\n", " print(\"Dataset validation failed. Data not saved.\")" ] } ], "metadata": {}, "nbformat": 4, "nbformat_minor": 5 }