{ "cells": [ { "cell_type": "code", "execution_count": null, "id": "bc2f887d", "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 = \"Amyotrophic_Lateral_Sclerosis\"\n", "cohort = \"GSE68608\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Amyotrophic_Lateral_Sclerosis\"\n", "in_cohort_dir = \"../../input/GEO/Amyotrophic_Lateral_Sclerosis/GSE68608\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Amyotrophic_Lateral_Sclerosis/GSE68608.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Amyotrophic_Lateral_Sclerosis/gene_data/GSE68608.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Amyotrophic_Lateral_Sclerosis/clinical_data/GSE68608.csv\"\n", "json_path = \"../../output/preprocess/Amyotrophic_Lateral_Sclerosis/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "e12b2c02", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": null, "id": "b7336d49", "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": "734e077b", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "d18c70b5", "metadata": {}, "outputs": [], "source": [ "# 1. Gene Expression Data Availability\n", "# Based on the background information about C9ORF72 ALS study with motor neurons\n", "# This is likely a gene expression dataset looking at splicing dysregulation\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "# Looking at the sample characteristics dictionary\n", "# For trait (ALS), row 1 contains \"patient group\" information\n", "trait_row = 1\n", "\n", "# There's no information about age in the sample characteristics\n", "age_row = None\n", "\n", "# No gender information in the sample characteristics\n", "gender_row = None\n", "\n", "# 2.2 Data Type Conversion Functions\n", "def convert_trait(value):\n", " \"\"\"Convert ALS trait value to binary (1 for ALS, 0 for control)\"\"\"\n", " if value is None:\n", " return None\n", " \n", " # Extract the value after colon if present\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # Convert to binary\n", " if 'ALS' in value or 'mutated C9ORF72' in value:\n", " return 1\n", " elif 'control' in value or 'healthy' in value:\n", " return 0\n", " else:\n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age value to continuous\"\"\"\n", " # Not applicable as age data is not available\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"Convert gender value to binary (0 for female, 1 for male)\"\"\"\n", " # Not applicable as gender data is not available\n", " return None\n", "\n", "# 3. Save Metadata\n", "# Check trait data availability\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. Clinical Feature Extraction\n", "if trait_row is not None:\n", " # Extract information from sample characteristics dictionary\n", " sample_ids = []\n", " for item in [s.split(\": \")[1] for s in sample_chars[0]]:\n", " sample_ids.append(item)\n", " \n", " # Create a DataFrame with appropriate structure for geo_select_clinical_features\n", " data = []\n", " for sample_id in sample_ids:\n", " if 'Patient' in sample_id:\n", " # For patients\n", " data.append({\n", " 'ID_REF': sample_id,\n", " trait_row: 'patient group: ALS due to mutated C9ORF72'\n", " })\n", " else:\n", " # For controls\n", " data.append({\n", " 'ID_REF': sample_id,\n", " trait_row: 'patient group: Neurologically healthy, non-disease control'\n", " })\n", " \n", " # Create DataFrame\n", " clinical_df = pd.DataFrame(data)\n", " \n", " # Extract clinical features\n", " selected_clinical_df = geo_select_clinical_features(\n", " clinical_df=clinical_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=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 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, index=False)\n", " print(f\"Clinical data saved to {out_clinical_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "8cbce638", "metadata": {}, "source": [ "### Step 3: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "6e7b5886", "metadata": {}, "outputs": [], "source": [ "I'll implement the code for the current step with corrections to address the file parsing issue:\n", "\n", "```python\n", "import pandas as pd\n", "import numpy as np\n", "import os\n", "import json\n", "import glob\n", "import gzip\n", "from typing import Optional, Callable, Dict, Any, List, Union\n", "\n", "# Initialize variables for validation\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:\n", " # Look for any series matrix file (compressed or not)\n", " matrix_files = glob.glob(os.path.join(in_cohort_dir, \"*series_matrix*.txt*\"))\n", " \n", " if not matrix_files:\n", " print(f\"No series matrix file found in {in_cohort_dir}\")\n", " clinical_data = pd.DataFrame() # Empty DataFrame if no file found\n", " else:\n", " matrix_file = matrix_files[0] # Take the first matching file\n", " print(f\"Found matrix file: {matrix_file}\")\n", " \n", " # First, let's examine the file structure\n", " if matrix_file.endswith('.gz'):\n", " with gzip.open(matrix_file, 'rt') as f:\n", " header_lines = [next(f) for _ in range(40) if f]\n", " else:\n", " with open(matrix_file, 'rt') as f:\n", " header_lines = [next(f) for _ in range(40) if f]\n", " \n", " # Print a few header lines to understand the structure\n", " print(\"First few lines of the file:\")\n", " for i, line in enumerate(header_lines[:5]):\n", " print(f\"Line {i+1}: {line.strip()}\")\n", " \n", " # Read the file with flexible parsing to handle potential formatting issues\n", " clinical_data = pd.read_csv(matrix_file, sep='\\t', comment='#', nrows=70, \n", " on_bad_lines='skip', engine='python')\n", " \n", " # Check if the file has content\n", " if clinical_data.empty:\n", " print(\"Warning: The matrix file is empty or couldn't be parsed properly\")\n", " else:\n", " # Print the shape and first few columns to understand the structure\n", " print(f\"Clinical data shape: {clinical_data.shape}\")\n", " print(\"First column names:\", clinical_data.columns[:5].tolist())\n", " \n", " # Examine the first column which typically contains metadata identifiers\n", " first_col = clinical_data.iloc[:,0].dropna().tolist()\n", " print(\"\\nMetadata identifiers in first column:\")\n", " for i, item in enumerate(first_col[:10]): # Print first 10 items\n", " print(f\"{i}: {item}\")\n", " \n", " # Check if this contains gene expression data\n", " # Look for platform information and other indicators\n", " platform_entries = [item for item in first_col if 'platform' in str(item).lower()]\n", " if platform_entries:\n", " print(\"\\nPlatform information:\")\n", " for entry in platform_entries:\n", " print(entry)\n", " # Typical gene expression platforms start with GPL\n", " if any('GPL' in str(entry) for entry in platform_entries):\n", " is_gene_available = True\n", " print(\"This appears to be gene expression data based on platform information\")\n", " \n", " # Look for sample characteristics entries to identify clinical features\n", " sample_char_entries = [i for i, item in enumerate(first_col) \n", " if 'sample_char' in str(item).lower()]\n", " \n", " if sample_char_entries:\n", " print(\"\\nSample characteristic entries found at rows:\", sample_char_entries)\n", " \n", " # Examine each sample characteristic row\n", " for idx in sample_char_entries:\n", " row_content = str(clinical_data.iloc[idx, 0])\n", " unique_values = set(clinical_data.iloc[idx, 1:].dropna())\n", " print(f\"Row {idx}: {row_content}\")\n", " print(f\"Unique values: {unique_values}\")\n", " \n", " # Identify trait, age, and gender information\n", " row_content_lower = row_content.lower()\n", " if ('disease' in row_content_lower or 'status' in row_content_lower or \n", " 'diagnosis' in row_content_lower or 'als' in row_content_lower or\n", " 'amyotrophic' in row_content_lower or 'control' in row_content_lower):\n", " if trait_row is None and len(unique_values) > 1: # Ensure it's not a constant feature\n", " trait_row = idx\n", " print(f\"Identified trait row at {idx}\")\n", " elif 'age' in row_content_lower:\n", " if age_row is None and len(unique_values) > 1:\n", " age_row = idx\n", " print(f\"Identified age row at {idx}\")\n", " elif 'gender' in row_content_lower or 'sex' in row_content_lower:\n", " if gender_row is None and len(unique_values) > 1:\n", " gender_row = idx\n", " print(f\"Identified gender row at {idx}\")\n", " \n", " is_trait_available = trait_row is not None\n", " \n", " # Print final determinations\n", " print(f\"\\nFinal determinations:\")\n", " print(f\"Gene expression data available: {is_gene_available}\")\n", " print(f\"Trait data available: {is_trait_available}\")\n", " print(f\"Trait row: {trait_row}\")\n", " print(f\"Age row: {age_row}\")\n", " print(f\"Gender row: {gender_row}\")\n", "\n", "except Exception as e:\n", " print(f\"Error processing file: {str(e)}\")\n", " clinical_data = pd.DataFrame() # Empty DataFrame on error\n", "\n", "# Define conversion functions\n", "def convert_trait(value: str) -> int:\n", " \"\"\"Convert trait value to binary (0 for Control, 1 for ALS)\"\"\"\n", " if value is None or pd.isna(value):\n", " return None\n", " value = value.lower() if isinstance(value, str) else str(value).lower()\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " if 'als' in value or 'amyotrophic lateral sclerosis' in value or 'patient' in value:\n", " return 1\n", " elif 'control' in value or 'normal' in value or 'healthy' in value:\n", " return 0\n", " return None\n", "\n", "def convert_age(value: str) -> float:\n", " \"\"\"Convert age value to float\"\"\"\n", " if value is None or pd.isna(value):\n", " return None\n", " value = str(value)\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " try:\n", " # Extract numeric part if it contains non-numeric characters\n", " import re\n", " numeric_part = re.search(r'\\d+(\\.\\d+)?', value)\n", " if numeric_part:\n", " return float(numeric_part.group())\n", " return None\n", " except:\n", " return None\n", "\n", "def convert_gender(value: str) -> int:\n", " \"\"\"Convert gender value to binary (0 for Female, 1 for Male)\"\"\"\n", " if value is None or pd.isna(value):\n", " return None\n", " value = value.lower() if isinstance(value, str) else str(value).lower()\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " if 'female' in value or 'f' == value or value.strip() == 'f':\n", " return 0\n", " elif 'male' in value or 'm' == value or value.strip() == 'm':\n", " return 1\n", " return None\n", "\n", "# 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", "# Clinical Feature Extraction\n", "if trait_row is not None and not clinical_data.empty:\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" ] }, { "cell_type": "markdown", "id": "330002a0", "metadata": {}, "source": [ "### Step 4: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "8cf8cea3", "metadata": {}, "outputs": [], "source": [ "I'll debug the code by addressing the syntax errors and completing the implementation properly.\n", "\n", "```python\n", "import os\n", "import pandas as pd\n", "import numpy as np\n", "import json\n", "from typing import Dict, Any, Optional, Callable\n", "import glob\n", "\n", "# Check if this dataset contains gene expression data\n", "# Look for gene expression files in the directory\n", "gene_expression_patterns = ['*_series_matrix.txt', '*gene*', '*expr*', '*.txt', '*.csv', '*.tsv', '*.gz']\n", "gene_files = []\n", "for pattern in gene_expression_patterns:\n", " gene_files.extend(glob.glob(os.path.join(in_cohort_dir, pattern)))\n", "\n", "# Filter out files that might be clinical data\n", "gene_files = [f for f in gene_files if 'clinical' not in f.lower() and 'phenotype' not in f.lower()]\n", "is_gene_available = len(gene_files) > 0\n", "\n", "# Try to identify clinical data files using different patterns\n", "clinical_data = None\n", "clinical_file_patterns = ['*clinical*', '*phenotype*', '*meta*', '*sample*', '*char*', '*series_matrix.txt']\n", "clinical_files = []\n", "for pattern in clinical_file_patterns:\n", " clinical_files.extend(glob.glob(os.path.join(in_cohort_dir, pattern)))\n", "\n", "# Load the first available clinical data file\n", "for file_path in clinical_files:\n", " try:\n", " if file_path.endswith('.txt'):\n", " # For series matrix files, we need to extract the sample characteristics\n", " with open(file_path, 'r') as f:\n", " lines = f.readlines()\n", " \n", " # Extract sample characteristic lines\n", " sample_chars = []\n", " for i, line in enumerate(lines):\n", " if line.startswith('!Sample_characteristics_ch1'):\n", " sample_chars.append(line.strip())\n", " \n", " if sample_chars:\n", " # Process sample characteristics into a DataFrame\n", " char_data = {}\n", " for i, char in enumerate(sample_chars):\n", " parts = char.split('\\t')\n", " if i == 0:\n", " # Initialize columns with sample IDs\n", " samples = [p.replace('\"', '') for p in parts[1:]]\n", " for sample in samples:\n", " char_data[sample] = []\n", " \n", " # Add characteristics for each sample\n", " values = [p.replace('\"', '').replace('!Sample_characteristics_ch1: ', '') for p in parts[1:]]\n", " \n", " # Check if this is a new type of characteristic\n", " if len(values) > 0:\n", " characteristic_type = values[0].split(':')[0] if ':' in values[0] else f'characteristic_{i}'\n", " if characteristic_type not in char_data:\n", " char_data[characteristic_type] = []\n", " \n", " # Add this characteristic to each sample\n", " for j, value in enumerate(values):\n", " if j < len(samples):\n", " char_data[samples[j]].append(value)\n", " \n", " # Convert to DataFrame\n", " clinical_data = pd.DataFrame(char_data)\n", " break\n", " else:\n", " # Try standard CSV loading for other file types\n", " clinical_data = pd.read_csv(file_path)\n", " break\n", " except Exception as e:\n", " print(f\"Could not load {file_path}: {e}\")\n", " continue\n", "\n", "# Display what we found for debugging\n", "if clinical_data is not None:\n", " print(\"Clinical data preview:\")\n", " print(clinical_data.head())\n", " print(\"\\nColumn names:\", clinical_data.columns.tolist())\n", " \n", " # Check for trait, age, and gender information\n", " trait_row = None\n", " age_row = None\n", " gender_row = None\n", " \n", " # Analyze each column for clinical information\n", " for col in clinical_data.columns:\n", " values = clinical_data[col].astype(str).str.lower()\n", " unique_values = values.unique()\n", " \n", " # Look for trait information (ALS vs control)\n", " if (any(['als' in str(v) for v in unique_values]) or \n", " any(['amyotrophic' in str(v) for v in unique_values])) and \\\n", " (any(['control' in str(v) for v in unique_values]) or \n", " any(['healthy' in str(v) for v in unique_values])):\n", " print(f\"Found trait information in column: {col}\")\n", " print(f\"Unique values: {unique_values}\")\n", " trait_row = clinical_data.columns.get_loc(col)\n", " \n", " # Look for age information\n", " if any(['age' in str(v) for v in unique_values]) or \\\n", " any([str(v).replace('.', '', 1).isdigit() for v in unique_values if v != 'nan']):\n", " print(f\"Found potential age information in column: {col}\")\n", " print(f\"Unique values: {unique_values}\")\n", " age_row = clinical_data.columns.get_loc(col)\n", " \n", " # Look for gender information\n", " if any(['male' in str(v) for v in unique_values]) or \\\n", " any(['female' in str(v) for v in unique_values]) or \\\n", " any(['gender' in str(v) for v in unique_values]) or \\\n", " any(['sex' in str(v) for v in unique_values]):\n", " print(f\"Found gender information in column: {col}\")\n", " print(f\"Unique values: {unique_values}\")\n", " gender_row = clinical_data.columns.get_loc(col)\n", "else:\n", " print(\"No clinical data found in the directory.\")\n", " trait_row = None\n", " age_row = None\n", " gender_row = None\n", "\n", "# Define conversion functions based on observed data patterns\n", "def convert_trait(value):\n", " if value is None:\n", " return None\n", " if isinstance(value, str) and \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " value = str(value).lower() if value is not None else \"\"\n", " if \"als\" in value or \"amyotrophic\" in value or \"disease\" in value:\n", " return 1\n", " elif \"control\" in value or \"healthy\" in value or \"normal\" in value:\n", " return 0\n", " return None\n", "\n", "def convert_age(value):\n", " if value is None:\n", " return None\n", " if isinstance(value, str) and \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " # Try to extract the numeric age\n", " if isinstance(value, str):\n", " # Extract digits from the string\n", " import re\n", " digits = re.findall(r'\\d+\\.?\\d*', value)\n", " if digits:\n", " return float(digits[0])\n", " elif isinstance(value, (int, float)):\n", " return float(value)\n", " return None\n", "\n", "def convert_gender(value):\n", " if value is None:\n", " return None\n", " if isinstance(value, str) and \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " value = str(value).lower() if value is not None else \"\"\n", " if \"female\" in value or \"f\" == value:\n", " return 0\n", " elif \"male\" in value or \"m\" == value:\n", " return 1\n", " return None\n", "\n", "# Save initial 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", "# Extract clinical features if trait data is available\n", "if is_trait_available and clinical_data is not None:\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 selected clinical data\n", " print(\"Selected clinical data preview:\")\n", " preview = preview_df(selected_clinical_df)\n", " print(preview)\n", " \n", " # Save to file\n", " os.makedirs(os.path.dirname(out\n" ] }, { "cell_type": "markdown", "id": "6096451a", "metadata": {}, "source": [ "### Step 5: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "68426b85", "metadata": {}, "outputs": [], "source": [ "# 1. Re-identify the SOFT and matrix files to ensure we have the correct paths\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "\n", "# 2. Extract the gene expression 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)\n", "print(\"\\nFirst 20 gene/probe identifiers:\")\n", "print(gene_data.index[:20])\n", "\n", "# 4. Print the dimensions of the gene expression data\n", "print(f\"\\nGene data dimensions: {gene_data.shape[0]} genes × {gene_data.shape[1]} samples\")\n", "\n", "# Note: we keep is_gene_available as True since we successfully extracted gene expression data\n", "is_gene_available = True\n" ] }, { "cell_type": "markdown", "id": "4be61ba5", "metadata": {}, "source": [ "### Step 6: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": null, "id": "a6c8c199", "metadata": {}, "outputs": [], "source": [ "# These identifiers are in Affymetrix HG-U133 Plus 2.0 format (e.g., \"1007_s_at\"), \n", "# which are probe IDs rather than human gene symbols. \n", "# They need to be mapped to standard gene symbols.\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "501900bd", "metadata": {}, "source": [ "### Step 7: Gene Annotation" ] }, { "cell_type": "code", "execution_count": null, "id": "b0fff948", "metadata": {}, "outputs": [], "source": [ "# 1. First get the file paths using geo_get_relevant_filepaths function\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "\n", "# 2. 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", "# 3. 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": "ac9afc3b", "metadata": {}, "source": [ "### Step 8: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": null, "id": "8a0c335c", "metadata": {}, "outputs": [], "source": [ "# 1. Identify the appropriate columns for gene identifiers and gene symbols\n", "# From the preview, we can see:\n", "# - The 'ID' column contains probe identifiers (e.g., '1007_s_at') matching the gene expression data\n", "# - The 'Gene Symbol' column contains the human gene symbols we need to map to\n", "\n", "# 2. Get the gene mapping dataframe using the library function\n", "gene_mapping = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='Gene Symbol')\n", "\n", "# Print a preview of the mapping\n", "print(\"\\nGene mapping preview (first 5 rows):\")\n", "print(gene_mapping.head())\n", "\n", "# 3. Apply the gene mapping to convert probe-level data to gene-level data\n", "gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=gene_mapping)\n", "\n", "# Print information about the result\n", "print(f\"\\nAfter mapping: {gene_data.shape[0]} genes × {gene_data.shape[1]} samples\")\n", "print(\"\\nFirst 10 gene symbols after mapping:\")\n", "print(gene_data.index[:10])\n", "\n", "# Normalize gene symbols to handle synonyms and aggregate duplicate genes\n", "gene_data = normalize_gene_symbols_in_index(gene_data)\n", "print(f\"\\nAfter normalization: {gene_data.shape[0]} genes × {gene_data.shape[1]} samples\")\n", "\n", "# Save the gene expression data to a file\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\"\\nGene expression data saved to {out_gene_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "86ae4c11", "metadata": {}, "source": [ "### Step 9: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": null, "id": "e23178e2", "metadata": {}, "outputs": [], "source": [ "# 1. Normalize gene symbols in the index of gene expression data\n", "normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n", "print(f\"Gene data shape after normalization: {normalized_gene_data.shape}\")\n", "print(f\"First 5 gene symbols after normalization: {normalized_gene_data.index[:5]}\")\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. Check if clinical data was properly loaded\n", "# First, reload the clinical_data to make sure we're using the original data\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "background_info, clinical_data = get_background_and_clinical_data(matrix_file)\n", "\n", "# Print the sample IDs to understand the data structure\n", "print(\"Sample IDs in clinical data:\")\n", "print(clinical_data.columns[:5], \"...\") # Show first 5 sample IDs\n", "\n", "# Print the sample IDs in gene expression data\n", "print(\"Sample IDs in gene expression data:\")\n", "print(normalized_gene_data.columns[:5], \"...\") # Show first 5 sample IDs\n", "\n", "# Extract clinical features using the actual sample IDs\n", "is_trait_available = trait_row is not None\n", "linked_data = None\n", "\n", "if is_trait_available:\n", " # Extract clinical features with proper sample IDs\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", " print(f\"Clinical data shape: {selected_clinical_df.shape}\")\n", " print(f\"Clinical data preview: {preview_df(selected_clinical_df, n=3)}\")\n", " \n", " # Save the 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", " # Make sure both dataframes have compatible indices/columns\n", " linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)\n", " print(f\"Linked data shape before handling missing values: {linked_data.shape}\")\n", " \n", " if linked_data.shape[0] == 0:\n", " print(\"WARNING: No samples matched between clinical and genetic data!\")\n", " # Create a sample dataset for demonstration\n", " print(\"Using gene data with artificial trait values for demonstration\")\n", " is_trait_available = False\n", " is_biased = True\n", " linked_data = pd.DataFrame(index=normalized_gene_data.columns)\n", " linked_data[trait] = 1 # Placeholder\n", " else:\n", " # 3. Handle missing values\n", " linked_data = handle_missing_values(linked_data, trait)\n", " print(f\"Data shape after handling missing values: {linked_data.shape}\")\n", " \n", " # 4. Determine 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", "else:\n", " print(\"Trait data was determined to be unavailable in previous steps.\")\n", " is_biased = True # Set to True since we can't evaluate without trait data\n", " linked_data = pd.DataFrame(index=normalized_gene_data.columns)\n", " linked_data[trait] = 1 # Add a placeholder trait column\n", " print(f\"Using placeholder data due to missing trait information, shape: {linked_data.shape}\")\n", "\n", "# 5. Validate and save cohort info\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=is_trait_available,\n", " is_biased=is_biased,\n", " df=linked_data,\n", " note=\"Dataset contains gene expression data from multiple sclerosis patients, but there were issues linking clinical and genetic data.\"\n", ")\n", "\n", "# 6. 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 deemed not usable for associational studies.\")" ] } ], "metadata": {}, "nbformat": 4, "nbformat_minor": 5 }