{ "cells": [ { "cell_type": "code", "execution_count": null, "id": "4aa76e14", "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 = \"Obesity\"\n", "cohort = \"GSE99725\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Obesity\"\n", "in_cohort_dir = \"../../input/GEO/Obesity/GSE99725\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Obesity/GSE99725.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Obesity/gene_data/GSE99725.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Obesity/clinical_data/GSE99725.csv\"\n", "json_path = \"../../output/preprocess/Obesity/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "a31cf2fd", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": null, "id": "a0eaeff2", "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": "8d51bead", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "b51f8991", "metadata": {}, "outputs": [], "source": [ "import os\n", "import pandas as pd\n", "import numpy as np\n", "import json\n", "from typing import Callable, Optional, Dict, Any\n", "\n", "# Step 1: Gene Expression Data Availability\n", "# Based on the background info, this seems to be a study of whole-genome expression profiling\n", "# from peripheral blood, so gene expression data should be available\n", "is_gene_available = True\n", "\n", "# Step 2: Clinical Variable Analysis\n", "# 2.1 Data Availability\n", "# Analyzing the sample characteristics dictionary:\n", "# Key 0: Contains patient identifiers\n", "# Key 1: Shows time points (M0, M6) - Before and after bariatric surgery\n", "# Key 2: Shows MADRS (Montgomery-Asberg Depression Rating Scale) values - A and B likely indicate depression status\n", "# Key 3: Shows tissue type (Venous blood)\n", "\n", "# For trait (Obesity):\n", "# The study is about \"comorbid depression in obese patients\" and all patients are described as \"massively obese\"\n", "# However, the dataset doesn't seem to have BMI or obesity metrics, so all patients likely have the same obesity status\n", "# This makes obesity a constant feature, not suitable for our analysis\n", "\n", "# For depression (MADRS):\n", "# Key 2 contains MADRS values which indicate depression status (A/B likely mean depressed/non-depressed)\n", "# This can be our trait of interest\n", "\n", "trait_row = 2 # MADRS values in key 2\n", "age_row = None # Age not available in the sample characteristics\n", "gender_row = None # Gender not available in the sample characteristics\n", "\n", "# 2.2 Data Type Conversion\n", "def convert_trait(value):\n", " \"\"\"Convert MADRS values to binary depression status (0=non-depressed, 1=depressed)\"\"\"\n", " if not value or ':' not in value:\n", " return None\n", " \n", " value = value.split(':', 1)[1].strip()\n", " if value == 'A':\n", " return 1 # Depressed (assuming A means high MADRS score)\n", " elif value == 'B':\n", " return 0 # Non-depressed (assuming B means low MADRS score)\n", " else:\n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"Placeholder function as age data is not available\"\"\"\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"Placeholder function as gender data is not available\"\"\"\n", " return None\n", "\n", "# Step 3: Save Metadata\n", "is_trait_available = trait_row is not None\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", "# Step 4: Clinical Feature Extraction\n", "if trait_row is not None:\n", " # Create a DataFrame that has the same structure as what the geo_select_clinical_features function expects\n", " # Each column represents a characteristic type, and contains all possible values for that characteristic\n", " sample_chars = {\n", " 0: ['patient: CB291013', 'patient: TP100414', 'patient: JDF280314', 'patient: JA021214', \n", " 'patient: DC160914', 'patient: GMD170315', 'patient: MP220714', 'patient: SM260215', \n", " 'patient: MC261113', 'patient: SB091214', 'patient: CN220714', 'patient: AE170614', \n", " 'patient: AG121114', 'patient: SS150414', 'patient: TDC270115', 'patient: VF200115', \n", " 'patient: KP261113', 'patient: AC030215', 'patient: SM070415', 'patient: JMV220115', \n", " 'patient: NC130214', 'patient: SB221013', 'patient: MA021214', 'patient: DD101214', \n", " 'patient: LB141114', 'patient: CPP281113', 'patient: NR180314', 'patient: PP120315', \n", " 'patient: BB080414', 'patient: PM120914'],\n", " 1: ['time: M0', 'time: M6'],\n", " 2: ['MADRS: A', 'MADRS: B'],\n", " 3: ['tissue: Venous blood']\n", " }\n", " \n", " # Convert the dictionary to a format expected by geo_select_clinical_features\n", " # We need a DataFrame where each row corresponds to a feature type, not samples\n", " clinical_data = pd.DataFrame()\n", " for row_id, values in sample_chars.items():\n", " clinical_data[row_id] = values if row_id < len(clinical_data) else values + [None] * (len(clinical_data) - len(values))\n", " \n", " # Fill any missing values with None\n", " clinical_data = clinical_data.fillna(None)\n", " \n", " # Extract clinical features\n", " selected_clinical_df = geo_select_clinical_features(\n", " clinical_df=clinical_data,\n", " trait=trait, # Using the predefined trait variable\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_df(selected_clinical_df))\n", " \n", " # Create the directory if it doesn't exist\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" ] }, { "cell_type": "markdown", "id": "f87751be", "metadata": {}, "source": [ "### Step 3: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "b5b30ccd", "metadata": {}, "outputs": [], "source": [ "```python\n", "# 1. Import necessary libraries\n", "import pandas as pd\n", "import numpy as np\n", "import os\n", "import glob\n", "import re\n", "\n", "# 2. First, let's explore what files are available in the directory\n", "print(f\"Exploring directory: {in_cohort_dir}\")\n", "available_files = os.listdir(in_cohort_dir)\n", "print(f\"Available files: {available_files}\")\n", "\n", "# Load clinical/phenotype data if available\n", "clinical_data = None\n", "sample_characteristic_files = [f for f in available_files if 'characteristics' in f.lower() or 'phenotype' in f.lower() or 'clinical' in f.lower()]\n", "\n", "if sample_characteristic_files:\n", " clinical_data_path = os.path.join(in_cohort_dir, sample_characteristic_files[0])\n", " print(f\"Loading clinical data from: {clinical_data_path}\")\n", " clinical_data = pd.read_csv(clinical_data_path, sep=None, engine='python')\n", " print(\"Clinical data shape:\", clinical_data.shape)\n", " print(\"Sample from clinical data:\")\n", " print(clinical_data.head())\n", "\n", "# Load matrix data to check if gene expression data is available\n", "matrix_files = [f for f in available_files if 'matrix' in f.lower() or '.txt' in f.lower() or '.tsv' in f.lower() or '.csv' in f.lower()]\n", "is_gene_available = False\n", "\n", "for file in matrix_files:\n", " if 'matrix' in file.lower() or 'expression' in file.lower() or 'gene' in file.lower():\n", " # This is likely gene expression data\n", " is_gene_available = True\n", " break\n", "\n", "# Load background information if available\n", "background_info = \"\"\n", "background_files = [f for f in available_files if 'background' in f.lower() or 'readme' in f.lower() or 'info' in f.lower()]\n", "if background_files:\n", " background_path = os.path.join(in_cohort_dir, background_files[0])\n", " print(f\"Loading background information from: {background_path}\")\n", " try:\n", " with open(background_path, 'r') as f:\n", " background_info = f.read()\n", " print(\"Background information preview:\")\n", " print(background_info[:500] + \"...\" if len(background_info) > 500 else background_info)\n", " except Exception as e:\n", " print(f\"Error reading background file: {e}\")\n", "\n", "# If clinical data is available, analyze it to identify trait, age, and gender rows\n", "trait_row = None\n", "age_row = None\n", "gender_row = None\n", "is_trait_available = False\n", "\n", "if clinical_data is not None:\n", " print(\"\\nAnalyzing clinical data to identify variables...\")\n", " # Check unique values in each row to identify relevant variables\n", " for i in range(len(clinical_data)):\n", " try:\n", " row_description = str(clinical_data.iloc[i, 0]).lower() if clinical_data.shape[1] > 0 else \"\"\n", " row_values = clinical_data.iloc[i, 1:].astype(str) if clinical_data.shape[1] > 1 else pd.Series([])\n", " unique_vals = row_values.unique()\n", " \n", " if len(unique_vals) > 1: # Only consider rows with more than one unique value\n", " print(f\"Row {i}: {row_description}\")\n", " print(f\" Unique values: {unique_vals[:5]}{'...' if len(unique_vals) > 5 else ''}\")\n", " \n", " # Check for obesity-related trait (BMI, weight, obesity status)\n", " if any(term in row_description for term in ['bmi', 'body mass', 'weight', 'obes', 'adipos']):\n", " trait_row = i\n", " print(f\" Identified as trait row (Obesity)\")\n", " \n", " # Check for age\n", " elif any(term in row_description for term in ['age', 'year']):\n", " age_row = i\n", " print(f\" Identified as age row\")\n", " \n", " # Check for gender/sex\n", " elif any(term in row_description for term in ['gender', 'sex', 'male', 'female']):\n", " gender_row = i\n", " print(f\" Identified as gender row\")\n", " except Exception as e:\n", " print(f\"Error analyzing row {i}: {e}\")\n", "\n", " # Check if trait data is available\n", " is_trait_available = trait_row is not None\n", "\n", "# Define conversion functions for each variable\n", "def convert_trait(value):\n", " \"\"\"Convert obesity-related trait values to numeric.\"\"\"\n", " if pd.isna(value) or value is None:\n", " return None\n", " \n", " # Extract value after colon if present\n", " if isinstance(value, str) and ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # Try to convert to numeric (for BMI or weight values)\n", " try:\n", " return float(value)\n", " except (ValueError, TypeError):\n", " # Handle categorical values\n", " value_lower = str(value).lower()\n", " if 'obese' in value_lower or 'obesity' in value_lower:\n", " return 1\n", " elif 'normal' in value_lower or 'lean' in value_lower or 'control' in value_lower:\n", " return 0\n", " else:\n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age values to numeric.\"\"\"\n", " if pd.isna(value) or value is None:\n", " return None\n", " \n", " # Extract value after colon if present\n", " if isinstance(value, str) and ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # Try to extract numeric age\n", " try:\n", " # Remove non-numeric characters but keep decimals\n", " value_str = str(value).lower()\n", " if 'year' in value_str:\n", " value_str = value_str.split('year')[0].strip()\n", " \n", " # Extract numbers using regex\n", " matches = re.findall(r'\\d+\\.?\\d*', value_str)\n", " if matches:\n", " return float(matches[0])\n", " return None\n", " except (ValueError, TypeError):\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"Convert gender values to binary (0 for female, 1 for male).\"\"\"\n", " if pd.isna(value) or value is None:\n", " return None\n", " \n", " # Extract value after colon if present\n", " if isinstance(value, str) and ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " value_lower = str(value).lower()\n", " if any(term in value_lower for term in ['female', 'f', 'woman', 'women']):\n", " return 0\n", " elif any(term in value_lower for term in ['male', 'm', 'man', 'men']):\n", " return 1\n", " else:\n", " return None\n", "\n", "# Validate and save initial cohort info\n", "print(f\"\\nSaving initial cohort info...\")\n", "print(f\"is_gene_available: {is_gene_available}\")\n", "print(f\"is_trait_available: {is_trait_available}\")\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", "# Clinical Feature Extraction (if trait_row is not None and clinical_data is available)\n", "if trait_row is not None and clinical_data is not None:\n", " print(f\"\\nExtracting clinical features...\")\n", " # Extract clinical features using the provided function\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 if age_row is not None else None,\n", " gender_row=gender_row,\n", " convert_gender=convert_gender if gender_row is not None else None\n", " )\n", " \n", " # Preview the extracted clinical data\n", " print(\"Preview of extracted clinical data:\")\n", " preview_data = preview_df(selected_clinical_df)\n", " print(preview_data)\n", " \n", " # Save the\n" ] }, { "cell_type": "markdown", "id": "1ec92495", "metadata": {}, "source": [ "### Step 4: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "f6f402ae", "metadata": {}, "outputs": [], "source": [ "import pandas as pd\n", "import os\n", "import json\n", "from typing import Optional, Callable, Dict, Any\n", "\n", "# Let's load the available data first\n", "print(f\"Looking for data in: {in_cohort_dir}\")\n", "os.listdir(in_cohort_dir)\n", "\n", "# Try to load the sample characteristics data\n", "clinical_data_path = os.path.join(in_cohort_dir, \"clinical_data.pkl\")\n", "if os.path.exists(clinical_data_path):\n", " clinical_data = pd.read_pickle(clinical_data_path)\n", " print(\"Clinical data loaded\")\n", " print(clinical_data.shape)\n", " print(clinical_data.head())\n", "else:\n", " print(\"Clinical data not found\")\n", " clinical_data = None\n", "\n", "# Try to load background information if available\n", "info_path = os.path.join(in_cohort_dir, \"info.txt\")\n", "if os.path.exists(info_path):\n", " with open(info_path, 'r') as f:\n", " info_content = f.read()\n", " print(\"Background information loaded\")\n", " print(info_content)\n", "else:\n", " print(\"Background information not found\")\n", " info_content = \"\"\n", "\n", "# Display unique values in the clinical data to identify relevant rows\n", "if clinical_data is not None:\n", " for i in range(len(clinical_data.index)):\n", " unique_values = clinical_data.iloc[i].unique()\n", " if len(unique_values) <= 10: # Only show if the number of unique values is manageable\n", " print(f\"Row {i}: {clinical_data.index[i]}\")\n", " print(f\"Unique values: {unique_values}\")\n", " print(\"---\")\n", " else:\n", " print(f\"Row {i}: {clinical_data.index[i]} (too many unique values to display)\")\n", " print(\"---\")\n", "\n", "# 1. Determine if gene expression data is available\n", "# Set this to True if gene expression data is available, otherwise False\n", "is_gene_available = True # Assuming gene expression data is available unless we find evidence against it\n", "\n", "# 2.1 Identify rows containing trait, age, and gender data\n", "trait_row = None\n", "age_row = None\n", "gender_row = None\n", "\n", "if clinical_data is not None:\n", " # Look for obesity-related information\n", " obesity_keywords = ['obesity', 'bmi', 'weight', 'body mass index', 'body weight']\n", " for i in range(len(clinical_data.index)):\n", " row_name = str(clinical_data.index[i]).lower()\n", " unique_values = clinical_data.iloc[i].unique()\n", " \n", " # Check for obesity/BMI related rows\n", " if any(keyword in row_name for keyword in obesity_keywords) and len(unique_values) > 1:\n", " trait_row = i\n", " print(f\"Found potential trait row: {i} - {clinical_data.index[i]}\")\n", " print(f\"Unique values: {unique_values}\")\n", " \n", " # Check for age\n", " if 'age' in row_name and len(unique_values) > 1:\n", " age_row = i\n", " print(f\"Found potential age row: {i} - {clinical_data.index[i]}\")\n", " print(f\"Unique values: {unique_values}\")\n", " \n", " # Check for gender/sex\n", " if ('gender' in row_name or 'sex' in row_name) and len(unique_values) > 1:\n", " gender_row = i\n", " print(f\"Found potential gender row: {i} - {clinical_data.index[i]}\")\n", " print(f\"Unique values: {unique_values}\")\n", "\n", "# 2.2 Define conversion functions for each variable\n", "\n", "def convert_trait(value):\n", " \"\"\"Convert trait values to binary (0 for non-obese, 1 for obese)\"\"\"\n", " if pd.isna(value):\n", " return None\n", " \n", " value = str(value).lower()\n", " \n", " # Extract the value after colon if present\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # Common mappings for obesity\n", " if 'obese' in value or 'obesity' in value:\n", " return 1\n", " elif 'normal' in value or 'lean' in value or 'control' in value:\n", " return 0\n", " \n", " # Try to extract BMI value\n", " try:\n", " # If value contains digits, try to parse as BMI\n", " import re\n", " numbers = re.findall(r'\\d+\\.?\\d*', value)\n", " if numbers:\n", " bmi = float(numbers[0])\n", " return 1 if bmi >= 30 else 0 # Standard obesity threshold\n", " except:\n", " pass\n", " \n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age values to continuous numbers\"\"\"\n", " if pd.isna(value):\n", " return None\n", " \n", " value = str(value)\n", " \n", " # Extract the value after colon if present\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # Try to extract age value\n", " try:\n", " import re\n", " numbers = re.findall(r'\\d+\\.?\\d*', value)\n", " if numbers:\n", " return float(numbers[0])\n", " except:\n", " pass\n", " \n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"Convert gender values to binary (0 for female, 1 for male)\"\"\"\n", " if pd.isna(value):\n", " return None\n", " \n", " value = str(value).lower()\n", " \n", " # Extract the value after colon if present\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # Common mappings for gender\n", " if 'female' in value or 'f' == value.strip():\n", " return 0\n", " elif 'male' in value or 'm' == value.strip():\n", " return 1\n", " \n", " return None\n", "\n", "# 3. Save metadata with initial filtering\n", "is_trait_available = trait_row is not None\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. Extract clinical features if available\n", "if trait_row is not None:\n", " # Use the library function to 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", " print(\"Preview of selected clinical features:\")\n", " preview_result = preview_df(selected_clinical_df)\n", " print(preview_result)\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)\n", " print(f\"Clinical data saved to {out_clinical_data_file}\")\n", "else:\n", " print(\"No clinical features were extracted as trait data is not available.\")\n" ] }, { "cell_type": "markdown", "id": "50d071c9", "metadata": {}, "source": [ "### Step 5: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "2ef02e74", "metadata": {}, "outputs": [], "source": [ "# 1. First get the file paths again to access the matrix file\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 from the matrix_file\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(\"First 20 gene/probe identifiers:\")\n", "print(gene_data.index[:20])\n" ] }, { "cell_type": "markdown", "id": "1450f4d4", "metadata": {}, "source": [ "### Step 6: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": null, "id": "a4078f8a", "metadata": {}, "outputs": [], "source": [ "# Looking at the gene identifiers in the format 'A_19_P00315452', these appear to be Agilent microarray probe IDs\n", "# rather than standard human gene symbols. Agilent probe IDs typically use this format with 'A_' prefix.\n", "#\n", "# These identifiers need to be mapped to standard gene symbols for proper analysis.\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "a9174d20", "metadata": {}, "source": [ "### Step 7: Gene Annotation" ] }, { "cell_type": "code", "execution_count": null, "id": "4f4f9611", "metadata": {}, "outputs": [], "source": [ "# 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.\n", "gene_annotation = get_gene_annotation(soft_file)\n", "\n", "# 2. Use the 'preview_df' function from the library to preview the data and print out the results.\n", "print(\"Gene annotation preview:\")\n", "print(preview_df(gene_annotation))\n" ] }, { "cell_type": "markdown", "id": "9e04a42a", "metadata": {}, "source": [ "### Step 8: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": null, "id": "bd1787b0", "metadata": {}, "outputs": [], "source": [ "# 1. Identify the columns for gene identifiers and gene symbols\n", "# Looking at the gene expression data and gene annotation data:\n", "# - The gene expression data has index with identifiers like 'A_19_P00315452'\n", "# - The gene annotation data has similar identifiers in the 'ID' column\n", "# - The gene symbols are in the 'GENE_SYMBOL' column of the annotation data\n", "\n", "# 2. Extract the mapping between probe IDs and gene symbols\n", "prob_col = 'ID' # Column with probe identifiers \n", "gene_col = 'GENE_SYMBOL' # Column with gene symbols\n", "mapping_df = get_gene_mapping(gene_annotation, prob_col, gene_col)\n", "\n", "print(\"Mapping dataframe preview:\")\n", "print(preview_df(mapping_df))\n", "\n", "# 3. Apply the gene mapping to convert probe-level measurements to gene expression data\n", "gene_data = apply_gene_mapping(gene_data, mapping_df)\n", "\n", "print(\"Gene expression data after mapping:\")\n", "print(f\"Shape: {gene_data.shape}\")\n", "print(\"First 10 genes:\")\n", "print(gene_data.index[:10])\n" ] }, { "cell_type": "markdown", "id": "118ebe46", "metadata": {}, "source": [ "### Step 9: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": null, "id": "b5639df0", "metadata": {}, "outputs": [], "source": [ "# 1. First let's verify the file paths and get gene expression data\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "\n", "# 2. Load and process gene expression data\n", "gene_data = get_genetic_data(matrix_file)\n", "\n", "# 3. Get gene annotations and mapping\n", "gene_annotation = get_gene_annotation(soft_file)\n", "prob_col = 'ID' # Column with probe identifiers \n", "gene_col = 'GENE_SYMBOL' # Column with gene symbols\n", "mapping_df = get_gene_mapping(gene_annotation, prob_col, gene_col)\n", "\n", "# 4. Apply gene mapping to convert probe-level data to gene expression data\n", "mapped_gene_data = apply_gene_mapping(gene_data, mapping_df)\n", "\n", "# 5. Normalize gene symbols in the obtained gene expression data\n", "normalized_gene_data = normalize_gene_symbols_in_index(mapped_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", "# 6. Check if clinical data is available (based on previous steps, it's not)\n", "# We'll first get the soft_file and matrix_file again to obtain clinical_data\n", "background_info, clinical_data = get_background_and_clinical_data(matrix_file)\n", "\n", "if clinical_data is not None and trait_row is not None:\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 if age_row is not None else None,\n", " gender_row=gender_row,\n", " convert_gender=convert_gender if gender_row is not None else None\n", " )\n", " \n", " # Save 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", " \n", " # Link clinical and genetic data\n", " linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)\n", " print(f\"Shape of linked data before missing value handling: {linked_data.shape}\")\n", " \n", " # Handle missing values\n", " linked_data = handle_missing_values(linked_data, trait)\n", " print(f\"Shape of linked data after missing value handling: {linked_data.shape}\")\n", " \n", " # Check if the trait and demographic features are severely biased\n", " is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n", " \n", " # Validate and save metadata\n", " note = \"Dataset with gene expression data and clinical features.\"\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_biased,\n", " df=linked_data,\n", " note=note\n", " )\n", " \n", " # Save linked data if 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(\"Dataset is not usable for trait-gene association studies due to quality issues.\")\n", "else:\n", " # Clinical data is not available or trait row not found\n", " print(\"Clinical data or trait information not available - cannot proceed with linking or trait analysis\")\n", " \n", " # Create an empty DataFrame with the same structure that would be expected\n", " # This allows us to pass it to the validation function\n", " empty_df = pd.DataFrame(columns=[trait])\n", " \n", " # Save metadata indicating trait data is not available\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=False,\n", " is_biased=None,\n", " df=empty_df,\n", " note=\"Gene expression data available but no clinical data found for trait analysis.\"\n", " )\n", " print(\"Metadata saved indicating gene data available but trait data unavailable.\")\n" ] }, { "cell_type": "markdown", "id": "48394f17", "metadata": {}, "source": [ "### Step 10: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": null, "id": "cc7d274d", "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", "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. Extract clinical features using the function from tools.preprocess\n", "# Use the parameters defined in STEP 2 for the trait, age, and gender rows\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", "# 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)\n", "print(f\"Clinical data saved to {out_clinical_data_file}\")\n", "\n", "# 3. Link the clinical and genetic data\n", "linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)\n", "print(f\"Shape of linked data before missing value handling: {linked_data.shape}\")\n", "\n", "# 4. Handle missing values systematically\n", "linked_data = handle_missing_values(linked_data, trait)\n", "print(f\"Shape of linked data after missing value handling: {linked_data.shape}\")\n", "\n", "# 5. Check if the trait and demographic features are severely biased\n", "is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n", "\n", "# 6. Validate and save cohort information\n", "note = \"Dataset from NAFLD study with hypertension trait information available.\"\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_biased,\n", " df=linked_data,\n", " note=note\n", ")\n", "\n", "# 7. Save the linked data if it's 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(\"Dataset is not usable for trait-gene association studies due to quality issues.\")" ] } ], "metadata": {}, "nbformat": 4, "nbformat_minor": 5 }