{ "cells": [ { "cell_type": "code", "execution_count": null, "id": "906a1344", "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 = \"Hemochromatosis\"\n", "cohort = \"GSE50579\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Hemochromatosis\"\n", "in_cohort_dir = \"../../input/GEO/Hemochromatosis/GSE50579\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Hemochromatosis/GSE50579.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Hemochromatosis/gene_data/GSE50579.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Hemochromatosis/clinical_data/GSE50579.csv\"\n", "json_path = \"../../output/preprocess/Hemochromatosis/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "7b8dd8ca", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": null, "id": "9bea7379", "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": "4f75058e", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "3cfd369f", "metadata": {}, "outputs": [], "source": [ "# 1. Gene Expression Data Availability\n", "# Based on the background information, this dataset contains gene expression data\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "# Trait (Hemochromatosis) appears in row 1 under \"etiology: genetic hemochromatosis\"\n", "trait_row = 1\n", "# Age appears in row 5\n", "age_row = 5\n", "# Gender appears in row 3\n", "gender_row = 3\n", "\n", "# 2.2 Data Type Conversion\n", "def convert_trait(value):\n", " \"\"\"Convert trait values to binary (0 or 1).\"\"\"\n", " if value is None or 'n.d.' in value:\n", " return None\n", " # Extract the value after ':'\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # If the value indicates genetic hemochromatosis, return 1, otherwise return 0\n", " if 'genetic hemochromatosis' in value.lower():\n", " return 1\n", " return 0\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age values to continuous numeric values.\"\"\"\n", " if value is None or 'n.d.' in value:\n", " return None\n", " # Extract the value after ':'\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " try:\n", " # Convert to integer\n", " return int(value)\n", " except ValueError:\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"Convert gender values to binary (0 for female, 1 for male).\"\"\"\n", " if value is None or 'n.d.' in value:\n", " return None\n", " # Extract the value after ':'\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " if 'female' in value.lower():\n", " return 0\n", " elif 'male' in value.lower():\n", " return 1\n", " return None\n", "\n", "# 3. Save Metadata\n", "# Determine trait availability\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", "# We're skipping this step for now as the required clinical_data.csv file \n", "# is not yet available in the input directory.\n", "# This will be handled in a subsequent step when the clinical data is ready.\n" ] }, { "cell_type": "markdown", "id": "dfbe9894", "metadata": {}, "source": [ "### Step 3: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "35a9fdf3", "metadata": {}, "outputs": [], "source": [ "I'll correct the code for the current step to properly explore available files and handle the clinical data.\n", "\n", "```python\n", "import pandas as pd\n", "import json\n", "import os\n", "from typing import Callable, Optional, Dict, Any\n", "import numpy as np\n", "import glob\n", "\n", "# Let's first explore the directory to find what files are available\n", "print(f\"Exploring directory: {in_cohort_dir}\")\n", "available_files = glob.glob(os.path.join(in_cohort_dir, \"*\"))\n", "print(f\"Available files: {available_files}\")\n", "\n", "# Look for series matrix files which typically contain clinical data in GEO datasets\n", "series_matrix_files = glob.glob(os.path.join(in_cohort_dir, \"*series_matrix*\"))\n", "print(f\"Series matrix files: {series_matrix_files}\")\n", "\n", "# Check for any other files that might contain clinical data\n", "clinical_files = [f for f in available_files if 'clinical' in f.lower() or 'sample' in f.lower()]\n", "print(f\"Potential clinical files: {clinical_files}\")\n", "\n", "# Initialize variables\n", "clinical_data = None\n", "sample_characteristics = {}\n", "is_gene_available = False\n", "is_trait_available = False\n", "trait_row = None\n", "age_row = None\n", "gender_row = None\n", "\n", "# Try to load clinical data from various potential sources\n", "if series_matrix_files:\n", " try:\n", " # Try to parse series matrix file which often contains clinical data\n", " with open(series_matrix_files[0], 'r') as file:\n", " lines = file.readlines()\n", " \n", " # Extract sample characteristics sections from series matrix\n", " for i, line in enumerate(lines):\n", " if line.startswith('!Sample_title') or line.startswith('!Sample_geo_accession'):\n", " # Get sample identifiers\n", " parts = line.strip().split('\\t')\n", " sample_ids = parts[1:]\n", " \n", " if line.startswith('!Sample_characteristics_ch1'):\n", " # Get sample characteristics\n", " parts = line.strip().split('\\t')\n", " values = parts[1:]\n", " \n", " # Store in sample_characteristics with index as key\n", " if i not in sample_characteristics:\n", " sample_characteristics[i] = values\n", " \n", " # Check if the file contains gene expression data\n", " for line in lines:\n", " if '!Series_platform_id' in line or '!Platform_title' in line:\n", " platform = line.lower()\n", " # Most common gene expression platforms\n", " if ('illumina' in platform or 'affymetrix' in platform or \n", " 'agilent' in platform or 'gene expression' in platform or \n", " 'transcriptome' in platform or 'rna' in platform):\n", " is_gene_available = True\n", " break\n", " except Exception as e:\n", " print(f\"Error parsing series matrix file: {e}\")\n", "\n", "# If we couldn't load clinical data from series matrix, try other approaches\n", "if not sample_characteristics and clinical_files:\n", " try:\n", " # Try to read other clinical files\n", " for file_path in clinical_files:\n", " if file_path.endswith('.csv'):\n", " df = pd.read_csv(file_path)\n", " elif file_path.endswith('.txt') or file_path.endswith('.tsv'):\n", " df = pd.read_csv(file_path, sep='\\t')\n", " \n", " # Check if this file contains relevant clinical data\n", " if 'characteristic' in ' '.join(df.columns).lower():\n", " clinical_data = df\n", " break\n", " except Exception as e:\n", " print(f\"Error loading alternative clinical files: {e}\")\n", "\n", "# If we still don't have clinical data, make a best-guess about gene availability\n", "if not is_gene_available:\n", " # If there are any files that might contain gene expression data\n", " gene_expr_files = [f for f in available_files if 'expr' in f.lower() or 'gene' in f.lower()]\n", " is_gene_available = len(gene_expr_files) > 0\n", "\n", "# Print sample characteristics for analysis\n", "print(\"Sample Characteristics:\")\n", "for key, value in sample_characteristics.items():\n", " if isinstance(value, list) and len(value) > 0:\n", " print(f\"{key}: {value[:5]}...\") # Show first 5 values\n", " else:\n", " print(f\"{key}: {value}\")\n", "\n", "# Look for keys that might contain trait, age, and gender information\n", "for key, values in sample_characteristics.items():\n", " if isinstance(values, list) and len(values) > 0:\n", " unique_values = set(values)\n", " values_str = str(values)\n", " \n", " # Check for trait-related information (Hemochromatosis)\n", " if any(term in values_str.lower() for term in [\"hemochromatosis\", \"iron\", \"hfe\", \"patient\", \"disease\"]):\n", " if len(unique_values) > 1: # Ensure it's not a constant feature\n", " trait_row = key\n", " is_trait_available = True\n", " \n", " # Check for age information\n", " if \"age\" in values_str.lower():\n", " if len(unique_values) > 1: # Ensure it's not a constant feature\n", " age_row = key\n", " \n", " # Check for gender/sex information\n", " if any(term in values_str.lower() for term in [\"gender\", \"sex\", \"male\", \"female\"]):\n", " if len(unique_values) > 1: # Ensure it's not a constant feature\n", " gender_row = key\n", "\n", "# Define conversion functions\n", "def convert_trait(value):\n", " if 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", " \n", " # Identify cases\n", " if any(term in value_lower for term in [\"hemochromatosis\", \"hfe\", \"patient\", \"disease\", \"case\"]):\n", " return 1\n", " # Identify controls\n", " elif any(term in value_lower for term in [\"control\", \"normal\", \"healthy\"]):\n", " return 0\n", " else:\n", " return None\n", "\n", "def convert_age(value):\n", " if 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 age as a number\n", " value_str = str(value).lower()\n", " try:\n", " # Extract numbers from the string\n", " import re\n", " numbers = re.findall(r'\\d+', value_str)\n", " if numbers:\n", " age = int(numbers[0])\n", " return age\n", " else:\n", " return None\n", " except:\n", " return None\n", "\n", "def convert_gender(value):\n", " if 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", " \n", " if any(term == value_lower for term in [\"female\", \"f\"]):\n", " return 0\n", " elif any(term == value_lower for term in [\"male\", \"m\"]):\n", " return 1\n", " else:\n", " return None\n", "\n", "# Save metadata - initial filtering\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", "# If clinical data is available, extract and save clinical features\n", "if is_trait_available and trait_row is not None and sample_characteristics:\n", " # Create a DataFrame from sample_characteristics for geo_select_clinical_features\n", " sample_df = pd.DataFrame()\n", " for key, values in sample_characteristics.items():\n", " if isinstance(values, list):\n", " sample_df[key] = values\n", " \n", " # Extract clinical features using the library function\n", " try:\n", " selected_clinical_df = geo_select_clinical_features(\n", " clinical_df=sample_df,\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\n" ] }, { "cell_type": "markdown", "id": "fd075b41", "metadata": {}, "source": [ "### Step 4: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "1e965f02", "metadata": {}, "outputs": [], "source": [ "import pandas as pd\n", "import os\n", "import json\n", "import gzip\n", "from typing import Optional, Callable, Dict, Any\n", "\n", "# For GSE50579, the clinical data is embedded in the series matrix file\n", "series_matrix_path = os.path.join(in_cohort_dir, \"GSE50579_series_matrix.txt.gz\")\n", "\n", "# Extract clinical data from series matrix file\n", "clinical_data = pd.DataFrame()\n", "sample_chars = []\n", "sample_ids = []\n", "\n", "try:\n", " with gzip.open(series_matrix_path, 'rt') as f:\n", " # Process the file line by line to extract sample characteristics\n", " for line in f:\n", " if line.startswith('!Sample_geo_accession'):\n", " # Extract sample IDs\n", " sample_ids = line.strip().split('\\t')[1:]\n", " elif line.startswith('!Sample_characteristics_ch1'):\n", " # Extract sample characteristics\n", " chars = line.strip().split('\\t')[1:]\n", " sample_chars.append(chars)\n", " elif line.startswith('!Sample_title'):\n", " # Extract sample titles for possible trait information\n", " sample_titles = line.strip().split('\\t')[1:]\n", " # Once we've passed the header section, we can stop\n", " elif line.startswith('!series_matrix_table_begin'):\n", " break\n", " \n", " # Create a DataFrame from the extracted characteristics\n", " if sample_chars and sample_ids:\n", " clinical_data = pd.DataFrame(sample_chars, columns=sample_ids)\n", " # Transpose so that each row represents a characteristic and each column a sample\n", " clinical_data = clinical_data.T\n", " \n", " print(\"Clinical data shape:\", clinical_data.shape)\n", " print(\"Clinical data preview:\")\n", " print(clinical_data.head())\n", " \n", " # Check unique values for each row to identify relevant information\n", " for i in range(len(clinical_data.columns)):\n", " unique_values = clinical_data.iloc[:, i].unique()\n", " print(f\"Row {i}: {len(unique_values)} unique values\")\n", " print(f\"Sample values: {unique_values[:5] if len(unique_values) > 5 else unique_values}\")\n", " \n", "except Exception as e:\n", " print(f\"Error loading clinical data from series matrix: {e}\")\n", " clinical_data = pd.DataFrame()\n", "\n", "# Confirm gene expression data is available from series matrix file\n", "is_gene_available = os.path.exists(series_matrix_path)\n", "print(f\"Gene expression data available: {is_gene_available}\")\n", "\n", "# Based on examination of the data, set trait_row, age_row, gender_row\n", "# These values would be set based on the actual data review\n", "trait_row = None\n", "age_row = None\n", "gender_row = None\n", "\n", "# After reviewing the unique values in each row, identify the appropriate rows\n", "# This is sample code - in an actual implementation, these would be determined after examining the data\n", "if not clinical_data.empty:\n", " # Look for disease status in sample characteristics\n", " for i in range(len(clinical_data.columns)):\n", " col_values = [str(val).lower() for val in clinical_data.iloc[:, i].unique()]\n", " col_values_str = ' '.join(col_values)\n", " \n", " # Look for trait-related information (hemochromatosis)\n", " if any(term in col_values_str for term in ['hemochromatosis', 'iron overload', 'hfe', 'disease', 'status', 'diagnosis', 'condition']):\n", " trait_row = i\n", " print(f\"Found potential trait row: {i}\")\n", " print(f\"Values: {clinical_data.iloc[:, i].unique()}\")\n", " \n", " # Look for age information\n", " elif any(term in col_values_str for term in ['age', 'years']):\n", " age_row = i\n", " print(f\"Found potential age row: {i}\")\n", " print(f\"Values: {clinical_data.iloc[:, i].unique()}\")\n", " \n", " # Look for gender/sex information\n", " elif any(term in col_values_str for term in ['gender', 'sex', 'male', 'female']):\n", " gender_row = i\n", " print(f\"Found potential gender row: {i}\")\n", " print(f\"Values: {clinical_data.iloc[:, i].unique()}\")\n", "\n", "# Define conversion functions with proper value extraction\n", "def extract_value(value_str):\n", " if isinstance(value_str, str) and ':' in value_str:\n", " return value_str.split(':', 1)[1].strip()\n", " return value_str\n", "\n", "def convert_trait(value):\n", " if not isinstance(value, str):\n", " return None\n", " \n", " value = extract_value(value).lower()\n", " # Convert hemochromatosis-related terms to binary\n", " if any(term in value for term in ['control', 'normal', 'healthy', 'wild type', 'wt']):\n", " return 0\n", " elif any(term in value for term in ['hemochromatosis', 'iron overload', 'hfe', 'patient', 'homozygous', 'c282y']):\n", " return 1\n", " else:\n", " return None\n", "\n", "def convert_age(value):\n", " if not isinstance(value, str):\n", " return None\n", " \n", " value = extract_value(value)\n", " try:\n", " # Extract numeric value from string like \"age: 45 years\"\n", " import re\n", " match = re.search(r'(\\d+)', value)\n", " if match:\n", " return float(match.group(1))\n", " return float(value)\n", " except:\n", " return None\n", "\n", "def convert_gender(value):\n", " if not isinstance(value, str):\n", " return None\n", " \n", " value = extract_value(value).lower()\n", " if any(term in value for term in ['female', 'f']):\n", " return 0\n", " elif any(term in value for term in ['male', 'm']):\n", " return 1\n", " else:\n", " return None\n", "\n", "# Determine trait availability\n", "is_trait_available = trait_row is not None\n", "\n", "# Save metadata about the dataset\n", "initial_validation = 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", "# Extract clinical features if trait_row is not None\n", "if is_trait_available:\n", " try:\n", " # Extract clinical features\n", " clinical_features = 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(clinical_features)\n", " print(\"\\nClinical Features Preview:\")\n", " for key, values in preview.items():\n", " print(f\"{key}: {values}\")\n", " \n", " # Save the clinical data\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " clinical_features.to_csv(out_clinical_data_file, index=False)\n", " print(f\"Clinical data saved to {out_clinical_data_file}\")\n", " except Exception as e:\n", " print(f\"Error extracting clinical features: {e}\")\n", " is_trait_available = False\n", " # Re-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", "else:\n", " print(\"No trait data available, skipping clinical feature extraction\")\n" ] }, { "cell_type": "markdown", "id": "cbc29f4e", "metadata": {}, "source": [ "### Step 5: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "bb862b42", "metadata": {}, "outputs": [], "source": [ "# 1. Get the file paths for the SOFT file and matrix file\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "\n", "# 2. Extract gene expression data from the matrix file\n", "try:\n", " print(\"Extracting gene data from matrix file:\")\n", " gene_data = get_genetic_data(matrix_file)\n", " if gene_data.empty:\n", " print(\"Extracted gene expression data is empty\")\n", " is_gene_available = False\n", " else:\n", " print(f\"Successfully extracted gene data with {len(gene_data.index)} rows\")\n", " print(\"First 20 gene IDs:\")\n", " print(gene_data.index[:20])\n", " is_gene_available = True\n", "except Exception as e:\n", " print(f\"Error extracting gene data: {e}\")\n", " print(\"This dataset appears to have an empty or malformed gene expression matrix\")\n", " is_gene_available = False\n", "\n", "print(f\"\\nGene expression data available: {is_gene_available}\")\n" ] }, { "cell_type": "markdown", "id": "494a2203", "metadata": {}, "source": [ "### Step 6: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": null, "id": "1e38fccb", "metadata": {}, "outputs": [], "source": [ "# Reviewing gene identifiers\n", "# Based on the identifiers displayed (like \"(+)E1A_r60_1\", \"A_19_P00315452\"), these appear to be \n", "# microarray probe IDs rather than standard human gene symbols.\n", "# Standard human gene symbols would look like \"BRCA1\", \"TP53\", \"HFE\", etc.\n", "# These probe IDs will need to be mapped to actual gene symbols.\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "93f1bbfc", "metadata": {}, "source": [ "### Step 7: Gene Annotation" ] }, { "cell_type": "code", "execution_count": null, "id": "aeccf07b", "metadata": {}, "outputs": [], "source": [ "# 1. Let's first examine the structure of the SOFT file before trying to parse it\n", "import gzip\n", "\n", "# Look at the first few lines of the SOFT file to understand its structure\n", "print(\"Examining SOFT file structure:\")\n", "try:\n", " with gzip.open(soft_file, 'rt') as file:\n", " # Read first 20 lines to understand the file structure\n", " for i, line in enumerate(file):\n", " if i < 20:\n", " print(f\"Line {i}: {line.strip()}\")\n", " else:\n", " break\n", "except Exception as e:\n", " print(f\"Error reading SOFT file: {e}\")\n", "\n", "# 2. Now let's try a more robust approach to extract the gene annotation\n", "# Instead of using the library function which failed, we'll implement a custom approach\n", "try:\n", " # First, look for the platform section which contains gene annotation\n", " platform_data = []\n", " with gzip.open(soft_file, 'rt') as file:\n", " in_platform_section = False\n", " for line in file:\n", " if line.startswith('^PLATFORM'):\n", " in_platform_section = True\n", " continue\n", " if in_platform_section and line.startswith('!platform_table_begin'):\n", " # Next line should be the header\n", " header = next(file).strip()\n", " platform_data.append(header)\n", " # Read until the end of the platform table\n", " for table_line in file:\n", " if table_line.startswith('!platform_table_end'):\n", " break\n", " platform_data.append(table_line.strip())\n", " break\n", " \n", " # If we found platform data, convert it to a DataFrame\n", " if platform_data:\n", " import pandas as pd\n", " import io\n", " platform_text = '\\n'.join(platform_data)\n", " gene_annotation = pd.read_csv(io.StringIO(platform_text), delimiter='\\t', \n", " low_memory=False, on_bad_lines='skip')\n", " print(\"\\nGene annotation preview:\")\n", " print(preview_df(gene_annotation))\n", " else:\n", " print(\"Could not find platform table in SOFT file\")\n", " \n", " # Try an alternative approach - extract mapping from other sections\n", " with gzip.open(soft_file, 'rt') as file:\n", " for line in file:\n", " if 'ANNOTATION information' in line or 'annotation information' in line:\n", " print(f\"Found annotation information: {line.strip()}\")\n", " if line.startswith('!Platform_title') or line.startswith('!platform_title'):\n", " print(f\"Platform title: {line.strip()}\")\n", " \n", "except Exception as e:\n", " print(f\"Error processing gene annotation: {e}\")\n" ] }, { "cell_type": "markdown", "id": "bc422189", "metadata": {}, "source": [ "### Step 8: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": null, "id": "6cb3992d", "metadata": {}, "outputs": [], "source": [ "# 1. Identify the appropriate columns for gene mapping\n", "# Based on the gene annotation preview, 'ID' contains the probe identifiers\n", "# and 'GENE_SYMBOL' likely contains the corresponding gene symbols\n", "probe_id_col = 'ID'\n", "gene_symbol_col = 'GENE_SYMBOL'\n", "\n", "print(f\"Using columns for mapping: Probe ID = '{probe_id_col}', Gene Symbol = '{gene_symbol_col}'\")\n", "\n", "# 2. Create a gene mapping dataframe by extracting these two columns\n", "try:\n", " # Extract the mapping between probe IDs and gene symbols\n", " mapping_df = get_gene_mapping(gene_annotation, probe_id_col, gene_symbol_col)\n", " print(f\"Created mapping with {len(mapping_df)} rows\")\n", " print(\"Sample of mapping data:\")\n", " print(mapping_df.head())\n", " \n", " # Check for any issues with the mapping data\n", " num_mapped_probes = len(mapping_df['ID'].unique())\n", " num_mapped_genes = len(mapping_df['Gene'].unique())\n", " print(f\"Number of unique probes with gene mapping: {num_mapped_probes}\")\n", " print(f\"Number of unique genes in mapping: {num_mapped_genes}\")\n", " \n", " # 3. Apply the gene mapping to convert probe-level expression to gene-level expression\n", " gene_data = apply_gene_mapping(gene_data, mapping_df)\n", " print(f\"Converted probe-level data to gene-level data\")\n", " print(f\"Number of genes in final expression matrix: {len(gene_data)}\")\n", " \n", " # Save the gene expression data to CSV\n", " os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n", " gene_data.to_csv(out_gene_data_file)\n", " print(f\"Gene expression data saved to {out_gene_data_file}\")\n", " \n", "except Exception as e:\n", " print(f\"Error during gene mapping: {e}\")\n", " # If mapping fails, attempt to extract using other common gene-related columns\n", " try:\n", " print(\"Attempting alternative mapping approach...\")\n", " # Some platforms use different column names for gene symbols\n", " alternative_gene_cols = ['GENE_SYMBOL', 'GENE', 'SYMBOL', 'GeneSymbol', 'Gene_Symbol', 'GENE NAME', 'GENE_NAME']\n", " \n", " for gene_col in alternative_gene_cols:\n", " if gene_col in gene_annotation.columns:\n", " print(f\"Trying alternative gene symbol column: {gene_col}\")\n", " mapping_df = get_gene_mapping(gene_annotation, probe_id_col, gene_col)\n", " if not mapping_df.empty and mapping_df['Gene'].notna().any():\n", " gene_data = apply_gene_mapping(gene_data, mapping_df)\n", " print(f\"Alternative mapping successful with column {gene_col}\")\n", " print(f\"Number of genes in final expression matrix: {len(gene_data)}\")\n", " break\n", " \n", " # If we successfully mapped with an alternative column, save the data\n", " if 'gene_data' in locals() and not gene_data.empty:\n", " os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n", " gene_data.to_csv(out_gene_data_file)\n", " print(f\"Gene expression data saved to {out_gene_data_file}\")\n", " except Exception as e2:\n", " print(f\"Alternative mapping also failed: {e2}\")\n", " print(\"Unable to map probes to gene symbols\")\n" ] }, { "cell_type": "markdown", "id": "51a8c4b0", "metadata": {}, "source": [ "### Step 9: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": null, "id": "c9f43690", "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", "\n", "# Define the conversion functions that were defined in a previous step\n", "def convert_trait(value):\n", " \"\"\"Convert trait values to binary (0 or 1).\"\"\"\n", " if value is None or 'n.d.' in value:\n", " return None\n", " # Extract the value after ':'\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # If the value indicates genetic hemochromatosis, return 1, otherwise return 0\n", " if 'genetic hemochromatosis' in value.lower():\n", " return 1\n", " return 0\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age values to continuous numeric values.\"\"\"\n", " if value is None or 'n.d.' in value:\n", " return None\n", " # Extract the value after ':'\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " try:\n", " # Convert to integer\n", " return int(value)\n", " except ValueError:\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"Convert gender values to binary (0 for female, 1 for male).\"\"\"\n", " if value is None or 'n.d.' in value:\n", " return None\n", " # Extract the value after ':'\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " if 'female' in value.lower():\n", " return 0\n", " elif 'male' in value.lower():\n", " return 1\n", " return None\n", "\n", "# 1. Normalize gene symbols in the gene expression data\n", "try:\n", " # Load the gene expression data that was saved in a previous step\n", " gene_data = pd.read_csv(out_gene_data_file, index_col=0)\n", " print(f\"Loaded gene data shape before normalization: {gene_data.shape}\")\n", " \n", " # Check if gene data is empty\n", " if gene_data.shape[0] == 0:\n", " print(\"Warning: Gene data is empty. Attempting to load from matrix file directly.\")\n", " # Extract gene expression data directly from matrix file as a fallback\n", " gene_data = get_genetic_data(matrix_file)\n", " \n", " # Normalize gene symbols using the NCBI Gene database information\n", " normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n", " print(f\"Gene data shape after normalization: {normalized_gene_data.shape}\")\n", " \n", " # Check if normalization retained any genes\n", " if normalized_gene_data.shape[0] == 0:\n", " print(\"Warning: Gene symbol normalization resulted in zero genes. Using original gene data instead.\")\n", " normalized_gene_data = gene_data\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\"Gene data saved to {out_gene_data_file}\")\n", " \n", " is_gene_available = normalized_gene_data.shape[0] > 0\n", " print(f\"Gene data available: {is_gene_available}\")\n", "except Exception as e:\n", " print(f\"Error loading or normalizing gene data: {e}\")\n", " is_gene_available = False\n", "\n", "# 2. Load the clinical data\n", "try:\n", " # First we need to get the clinical data from the original source\n", " soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", " background_info, clinical_df = get_background_and_clinical_data(matrix_file)\n", " \n", " # Create clinical features dataframe\n", " clinical_features = geo_select_clinical_features(\n", " clinical_df=clinical_df,\n", " trait=trait,\n", " trait_row=1, # etiology info is in row 1\n", " convert_trait=convert_trait,\n", " age_row=5, # age info is in row 5\n", " convert_age=convert_age,\n", " gender_row=3, # gender info is in row 3\n", " convert_gender=convert_gender\n", " )\n", " \n", " # Check if we have trait data\n", " is_trait_available = trait in clinical_features.index\n", " print(f\"Trait '{trait}' available: {is_trait_available}\")\n", " \n", " # Save the properly extracted clinical features\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 saved to {out_clinical_data_file}\")\n", " \n", "except Exception as e:\n", " print(f\"Error processing clinical data: {e}\")\n", " clinical_features = pd.DataFrame()\n", " is_trait_available = False\n", "\n", "# 3. Link clinical and genetic data\n", "if is_gene_available and is_trait_available:\n", " try:\n", " # Link clinical features with gene expression data\n", " linked_data = geo_link_clinical_genetic_data(clinical_features, normalized_gene_data)\n", " print(f\"Linked data shape: {linked_data.shape}\")\n", " \n", " # 4. Handle missing values systematically\n", " linked_data = handle_missing_values(linked_data, trait)\n", " print(f\"Data shape after handling missing values: {linked_data.shape}\")\n", " \n", " # 5. Check if trait and demographic features are biased\n", " is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n", " print(f\"Data shape after removing biased features: {linked_data.shape}\")\n", " print(f\"Is dataset biased for {trait}: {is_biased}\")\n", " \n", " # Additional note about the dataset\n", " note = f\"Dataset contains gene expression data with {linked_data.shape[0]} samples and {linked_data.shape[1] - (3 if 'Age' in linked_data.columns and 'Gender' in linked_data.columns else 2 if 'Age' in linked_data.columns or 'Gender' in linked_data.columns else 1)} genes.\"\n", " \n", " except Exception as e:\n", " print(f\"Error processing linked data: {e}\")\n", " is_biased = True\n", " linked_data = pd.DataFrame({trait: [np.nan]})\n", " note = f\"Error during data processing: {e}\"\n", "else:\n", " # If either gene or trait data is unavailable, set up minimal data for validation\n", " is_biased = True\n", " if is_gene_available:\n", " note = f\"Dataset contains gene expression data but no {trait} measurements. Not usable for studying {trait} associations.\"\n", " elif is_trait_available:\n", " note = f\"Dataset contains {trait} data but no gene expression data. Not usable for genetic associations.\"\n", " else:\n", " note = f\"Dataset contains neither {trait} data nor gene expression data. Not usable for association studies.\"\n", " \n", " # Create a minimal dataframe for validation\n", " linked_data = pd.DataFrame({trait: [np.nan]})\n", "\n", "# 6. Validate and save 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=is_gene_available, \n", " is_trait_available=is_trait_available, \n", " is_biased=is_biased if 'is_biased' in locals() else True,\n", " df=linked_data if 'linked_data' in locals() else pd.DataFrame({trait: [np.nan]}),\n", " note=note if 'note' in locals() else \"Error during data processing\"\n", ")\n", "\n", "# Save the 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(f\"Dataset not usable for {trait} association studies. Linked data not saved.\")\n" ] }, { "cell_type": "markdown", "id": "a59f2275", "metadata": {}, "source": [ "### Step 10: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": null, "id": "0ed61df3", "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", "import os\n", "import gzip\n", "\n", "# 1. Extract gene expression data using the alternative approach that worked in Step 3\n", "with gzip.open(matrix_file, 'rt') as file:\n", " # Find the start of the data\n", " for line in file:\n", " if '!series_matrix_table_begin' in line:\n", " break\n", " \n", " # Read the headers and data\n", " gene_data = pd.read_csv(file, sep='\\t', index_col=0)\n", "\n", "# Check if we have gene data before proceeding\n", "if gene_data.empty:\n", " print(\"No gene expression data found in the matrix file.\")\n", " is_gene_available = False\n", "else:\n", " is_gene_available = True\n", " print(f\"Gene data shape before normalization: {gene_data.shape}\")\n", "\n", " # Normalize gene symbols using the NCBI Gene database information\n", " try:\n", " normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n", " print(f\"Gene data shape after normalization: {normalized_gene_data.shape}\")\n", " \n", " # Save the normalized gene data to the output 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\"Normalized gene data saved to {out_gene_data_file}\")\n", " except Exception as e:\n", " print(f\"Error normalizing gene data: {e}\")\n", " is_gene_available = False\n", " normalized_gene_data = gene_data # Use original data if normalization fails\n", "\n", "# 2. Link clinical and genetic data\n", "# In Step 2, we determined that Height data is not available in this dataset (trait_row = None)\n", "# Create a minimal clinical dataframe with the trait column (containing NaNs)\n", "if is_gene_available:\n", " sample_ids = gene_data.columns\n", " minimal_clinical_df = pd.DataFrame(index=sample_ids)\n", " minimal_clinical_df[trait] = np.nan # Add the trait column with NaN values\n", "\n", " # If we have age and gender data from Step 2, add those columns\n", " if age_row is not None:\n", " minimal_clinical_df['Age'] = get_feature_data(clinical_data, age_row, 'Age', convert_age).iloc[0]\n", "\n", " if gender_row is not None:\n", " minimal_clinical_df['Gender'] = get_feature_data(clinical_data, gender_row, 'Gender', convert_gender).iloc[0]\n", "\n", " minimal_clinical_df.index.name = 'Sample'\n", "\n", " # Save this minimal clinical data for reference\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " minimal_clinical_df.to_csv(out_clinical_data_file)\n", " print(f\"Clinical data saved to {out_clinical_data_file}\")\n", "\n", " # Create a linked dataset \n", " if is_gene_available and normalized_gene_data is not None:\n", " linked_data = pd.concat([minimal_clinical_df, normalized_gene_data.T], axis=1)\n", " linked_data.index.name = 'Sample'\n", " print(f\"Linked data shape: {linked_data.shape}\")\n", " else:\n", " linked_data = minimal_clinical_df\n", " print(\"No gene data to link with clinical data.\")\n", "else:\n", " # Create a minimal dataframe with just the trait for the validation step\n", " linked_data = pd.DataFrame({trait: [np.nan]})\n", " print(\"No gene data available, creating minimal dataframe for validation.\")\n", "\n", "# 4 & 5. Validate and save cohort information\n", "# Since trait_row was None in Step 2, we know Height data is not available\n", "is_trait_available = False # Height data is not available\n", "\n", "note = \"Dataset contains gene expression data but no Height measurements. This dataset is not usable for studying Height associations.\"\n", "\n", "# For datasets without trait data, we set is_biased to False\n", "# This indicates the dataset is not usable due to missing trait data, not due to bias\n", "is_biased = False\n", "\n", "# Final validation\n", "is_usable = validate_and_save_cohort_info(\n", " is_final=True, \n", " cohort=cohort, \n", " info_path=json_path, \n", " is_gene_available=is_gene_available, \n", " is_trait_available=is_trait_available, \n", " is_biased=is_biased,\n", " df=linked_data,\n", " note=note\n", ")\n", "\n", "# 6. Since there is no trait data, the dataset is not usable for our association study\n", "# So we should not save it to out_data_file\n", "print(f\"Dataset usability: {is_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 does not contain Height data and cannot be used for association studies.\")" ] } ], "metadata": {}, "nbformat": 4, "nbformat_minor": 5 }