{ "cells": [ { "cell_type": "code", "execution_count": null, "id": "974f36c8", "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 = \"Depression\"\n", "cohort = \"GSE201332\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Depression\"\n", "in_cohort_dir = \"../../input/GEO/Depression/GSE201332\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Depression/GSE201332.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Depression/gene_data/GSE201332.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Depression/clinical_data/GSE201332.csv\"\n", "json_path = \"../../output/preprocess/Depression/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "388a3634", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": null, "id": "0d3fa7c1", "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": "f5a442f1", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "4353b83a", "metadata": {}, "outputs": [], "source": [ "import pandas as pd\n", "import numpy as np\n", "import os\n", "import json\n", "from typing import Callable, Optional, Dict, Any\n", "\n", "# 1. Gene Expression Data Availability\n", "# Based on the background information, this study involves transcriptional profiling\n", "# in whole blood samples, which indicates gene expression data is available\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "# From the Sample Characteristics Dictionary:\n", "# Row 1 contains subject status (healthy controls vs MDD patients) -> trait_row\n", "# Row 3 contains age information -> age_row\n", "# Row 2 contains gender information -> gender_row\n", "trait_row = 1\n", "age_row = 3\n", "gender_row = 2\n", "\n", "# 2.2 Data Type Conversion Functions\n", "def convert_trait(value):\n", " \"\"\"Convert trait value to binary (0 for healthy, 1 for depression)\"\"\"\n", " if not isinstance(value, str):\n", " return None\n", " value = value.lower().strip()\n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " if \"healthy\" in value or \"control\" in value:\n", " return 0\n", " elif \"mdd\" in value or \"depress\" in value:\n", " return 1\n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age value to continuous integer\"\"\"\n", " if not isinstance(value, str):\n", " return None\n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " # Extract numeric part and remove 'y' (years)\n", " if 'y' in value:\n", " try:\n", " return int(value.replace('y', '').strip())\n", " except ValueError:\n", " return None\n", " try:\n", " return int(value)\n", " except ValueError:\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"Convert gender value to binary (0 for female, 1 for male)\"\"\"\n", " if not isinstance(value, str):\n", " return None\n", " value = value.lower().strip()\n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " if \"female\" in value:\n", " return 0\n", " elif \"male\" in value:\n", " return 1\n", " return None\n", "\n", "# 3. Save Metadata - Initial Filtering\n", "# trait_row is not None, so trait data is available\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", "# Since trait_row is not None, we need to extract clinical features\n", "if trait_row is not None:\n", " # Create a clinical data DataFrame from the sample characteristics dictionary\n", " sample_characteristics = {\n", " 0: ['tissue: whole blood'], \n", " 1: ['subject status: heathy controls', 'subject status: MDD patients'], \n", " 2: ['gender: male', 'gender: female'], \n", " 3: ['age: 48y', 'age: 33y', 'age: 43y', 'age: 24y', 'age: 45y', 'age: 36y', 'age: 59y', \n", " 'age: 51y', 'age: 26y', 'age: 25y', 'age: 32y', 'age: 39y', 'age: 41y', 'age: 52y', \n", " 'age: 53y', 'age: 44y', 'age: 22y', 'age: 47y', 'age: 54y', 'age: 28y', 'age: 30y']\n", " }\n", " \n", " # Convert the dictionary to a DataFrame format that can be used with geo_select_clinical_features\n", " clinical_data = pd.DataFrame(sample_characteristics)\n", " \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,\n", " gender_row=gender_row,\n", " convert_gender=convert_gender\n", " )\n", " \n", " # Preview the extracted features\n", " clinical_preview = preview_df(selected_clinical_df)\n", " print(\"Clinical Data Preview:\")\n", " print(clinical_preview)\n", " \n", " # Save the processed 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" ] }, { "cell_type": "markdown", "id": "b8a39ddd", "metadata": {}, "source": [ "### Step 3: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "99b99a5e", "metadata": {}, "outputs": [], "source": [ "I'll implement code specifically to handle GEO compressed files and extract sample characteristics from the series matrix file format.\n", "\n", "```python\n", "import os\n", "import pandas as pd\n", "import json\n", "import numpy as np\n", "import gzip\n", "import re\n", "from typing import Callable, Optional, Dict, Any, List, Tuple\n", "\n", "# Function to extract sample characteristics from GEO series matrix file\n", "def extract_geo_characteristics(matrix_file_path: str) -> Tuple[Dict[str, List[str]], pd.DataFrame]:\n", " \"\"\"Extract sample characteristics and data from a GEO series matrix file.\"\"\"\n", " # Initialize variables\n", " characteristics = {}\n", " sample_ids = []\n", " char_indices = {}\n", " in_characteristics = False\n", " series_matrix_lines = []\n", " data_lines = []\n", " \n", " # Read the gzipped file\n", " with gzip.open(matrix_file_path, 'rt') as f:\n", " for line in f:\n", " line = line.strip()\n", " series_matrix_lines.append(line)\n", " \n", " # Detect sample characteristics lines\n", " if line.startswith('!Sample_characteristics_ch'):\n", " in_characteristics = True\n", " parts = line.split('\\t')\n", " key = parts[0].replace('!Sample_characteristics_ch', '').strip()\n", " if key not in char_indices:\n", " char_indices[key] = len(char_indices)\n", " characteristics[str(char_indices[key])] = []\n", " \n", " # Add sample characteristic values for each sample\n", " for value in parts[1:]:\n", " characteristics[str(char_indices[key])].append(value)\n", " \n", " # Collect sample IDs\n", " elif line.startswith('!Sample_geo_accession'):\n", " sample_ids = line.split('\\t')[1:]\n", " \n", " # Detect the beginning of data section\n", " elif line.startswith('!series_matrix_table_begin'):\n", " in_characteristics = False\n", " in_data = True\n", " \n", " # Collect data lines\n", " elif in_data and not line.startswith('!series_matrix_table_end'):\n", " data_lines.append(line)\n", " \n", " # End of data section\n", " elif line.startswith('!series_matrix_table_end'):\n", " break\n", " \n", " # Extract relevant background information for gene availability check\n", " background_info = \"\\n\".join([line for line in series_matrix_lines \n", " if line.startswith('!Series_summary') or \n", " line.startswith('!Series_title') or\n", " line.startswith('!Series_type')])\n", " \n", " # Create a DataFrame if data section is found\n", " clinical_data = None\n", " if data_lines:\n", " # First line contains column headers\n", " headers = data_lines[0].split('\\t')\n", " # Data starts from second line\n", " data = [line.split('\\t') for line in data_lines[1:]]\n", " \n", " # Create a DataFrame with gene expression data\n", " gene_data = pd.DataFrame(data, columns=headers)\n", " \n", " # Create a transposed version as clinical data\n", " # Here we assume samples are columns in the original data\n", " clinical_data = pd.DataFrame(index=sample_ids)\n", " \n", " return characteristics, clinical_data, background_info\n", "\n", "# Find and process GEO series matrix file\n", "matrix_file = os.path.join(in_cohort_dir, \"GSE201332_series_matrix.txt.gz\")\n", "\n", "if os.path.exists(matrix_file):\n", " print(f\"Found matrix file: {matrix_file}\")\n", " sample_characteristics, clinical_data, background_info = extract_geo_characteristics(matrix_file)\n", " \n", " # Print sample characteristics to understand the data structure\n", " for key, values in sample_characteristics.items():\n", " if len(values) > 0:\n", " unique_values = set(values)\n", " print(f\"Key {key}, Example value: {values[0]}\")\n", " print(f\"Key {key}, Unique values: {unique_values if len(unique_values) < 5 else list(unique_values)[:5]}\")\n", "else:\n", " print(\"Matrix file not found!\")\n", " sample_characteristics = {}\n", " clinical_data = None\n", " background_info = \"\"\n", "\n", "# 1. Check for gene expression data availability\n", "is_gene_available = True # Default to True unless we find evidence otherwise\n", "\n", "if \"miRNA\" in background_info and \"gene expression\" not in background_info.lower():\n", " is_gene_available = False\n", "if \"methylation\" in background_info and \"gene expression\" not in background_info.lower():\n", " is_gene_available = False\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "trait_row = None\n", "age_row = None\n", "gender_row = None\n", "\n", "# Examine sample characteristics to identify rows for trait, age, and gender\n", "if sample_characteristics:\n", " for key, values in sample_characteristics.items():\n", " if not values: # Skip empty lists\n", " continue\n", " \n", " value_str = \" \".join(values).lower()\n", " \n", " # Look for depression-related indicators in values\n", " depression_keywords = [\"depression\", \"depressive\", \"mdd\", \"major depression\", \"depressed\", \"patient: \"]\n", " if any(keyword.lower() in value_str for keyword in depression_keywords):\n", " trait_row = int(key)\n", " \n", " # Look for age indicators\n", " if any((\"age:\" in val.lower() or \"age :\" in val.lower() or \"years\" in val.lower()) for val in values):\n", " age_row = int(key)\n", " \n", " # Look for gender indicators\n", " if any((\"gender:\" in val.lower() or \"gender :\" in val.lower() or \n", " \"sex:\" in val.lower() or \"sex :\" in val.lower() or\n", " \"male\" in val.lower() or \"female\" in val.lower()) for val in values):\n", " gender_row = int(key)\n", "\n", "# Define conversion functions\n", "def convert_trait(value: str) -> Optional[int]:\n", " if pd.isna(value) or value is None:\n", " return None\n", " \n", " value = str(value).lower()\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " if \"depression\" in value or \"depressive\" in value or \"mdd\" in value or \"patient\" in value:\n", " return 1\n", " elif \"control\" in value or \"healthy\" in value or \"non-depression\" in value or \"normal\" in value:\n", " return 0\n", " return None\n", "\n", "def convert_age(value: str) -> Optional[float]:\n", " if pd.isna(value) or value is None:\n", " return None\n", " \n", " value = str(value)\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # Extract numeric value (age in years)\n", " age_match = re.search(r'(\\d+(?:\\.\\d+)?)', value)\n", " if age_match:\n", " try:\n", " return float(age_match.group(1))\n", " except ValueError:\n", " return None\n", " return None\n", "\n", "def convert_gender(value: str) -> Optional[int]:\n", " if pd.isna(value) or value is None:\n", " return None\n", " \n", " value = str(value).lower()\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " if \"female\" in value or \"f\" == value.strip() or \"woman\" in value:\n", " return 0\n", " elif \"male\" in value or \"m\" == value.strip() or \"man\" in value:\n", " return 1\n", " return None\n", "\n", "# 3. Save Metadata\n", "# Determine trait data availability\n", "is_trait_available = trait_row is not None\n", "\n", "print(f\"Gene 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", "# Conduct initial filtering and save metadata\n", "validate_and_save_cohort_info(\n", " is_final=False,\n", " cohort=cohort,\n", " info_path=json_path,\n", " is_gene_available=is_gene_available,\n", " is_trait_available=is_trait_available\n", ")\n", "\n", "# 4. Clinical Feature Extraction\n", "# If trait data is available and clinical data exists, extract clinical features\n", "if trait_row is not\n" ] }, { "cell_type": "markdown", "id": "f20ce7a6", "metadata": {}, "source": [ "### Step 4: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "e981ccd9", "metadata": {}, "outputs": [], "source": [ "# Task: Dataset Analysis and Clinical Feature Extraction\n", "\n", "import os\n", "import pandas as pd\n", "import json\n", "import gzip\n", "from typing import Optional, Callable, Dict, Any\n", "\n", "# 1. First, let's examine the available data files in the cohort directory\n", "available_files = os.listdir(in_cohort_dir)\n", "print(f\"Available files in the cohort directory: {available_files}\")\n", "\n", "# Let's load the series matrix file which contains both gene expression and clinical data\n", "matrix_file = os.path.join(in_cohort_dir, 'GSE201332_series_matrix.txt.gz')\n", "\n", "# Function to extract sample characteristics from series matrix file\n", "def extract_characteristics(file_path):\n", " characteristics_data = []\n", " sample_titles = None\n", " \n", " with gzip.open(file_path, 'rt') as f:\n", " for line in f:\n", " line = line.strip()\n", " if line.startswith('!Sample_geo_accession'):\n", " sample_titles = line.split('\\t')[1:]\n", " elif line.startswith('!Sample_characteristics_ch'):\n", " parts = line.split('\\t')\n", " row_name = parts[0]\n", " values = parts[1:]\n", " characteristics_data.append((row_name, values))\n", " elif line.startswith('!series_matrix_table_begin'):\n", " break\n", " \n", " # Create DataFrame from characteristics\n", " if sample_titles and characteristics_data:\n", " df = pd.DataFrame({i: values for i, (_, values) in enumerate(characteristics_data)})\n", " df.index = sample_titles\n", " return df.transpose()\n", " \n", " return pd.DataFrame()\n", "\n", "# Extract clinical data\n", "clinical_data = extract_characteristics(matrix_file)\n", "print(\"\\nClinical data preview:\")\n", "print(clinical_data.head())\n", "print(f\"Clinical data shape: {clinical_data.shape}\")\n", "\n", "# Check if gene expression data exists\n", "is_gene_available = True # Default assumption based on the file being a series matrix\n", "\n", "# Now examine each row to find trait, age, and gender information\n", "row_descriptions = []\n", "for i, row in clinical_data.iterrows():\n", " unique_values = set(row)\n", " row_descriptions.append((i, unique_values))\n", " print(f\"Row {i}: {list(unique_values)[:3]}{'...' if len(unique_values) > 3 else ''}\")\n", "\n", "# Based on the row contents, identify trait_row, age_row, and gender_row\n", "trait_row = None\n", "age_row = None\n", "gender_row = None\n", "\n", "# Define conversion functions\n", "def convert_trait(value):\n", " if pd.isna(value):\n", " return None\n", " \n", " value = str(value).lower() if value is not None else \"\"\n", " \n", " # Extract the actual value if there's a colon\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # Convert to binary: 1 for depression, 0 for control\n", " if any(term in value for term in ['depression', 'mdd', 'major depressive disorder']):\n", " return 1\n", " elif any(term in value for term in ['control', 'healthy', 'normal']):\n", " return 0\n", " return None\n", "\n", "def convert_age(value):\n", " if pd.isna(value):\n", " return None\n", " \n", " value = str(value)\n", " \n", " # Extract the actual value if there's a colon\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # Try to extract numeric age\n", " import re\n", " age_match = re.search(r'(\\d+(?:\\.\\d+)?)', value)\n", " if age_match:\n", " return float(age_match.group(1))\n", " \n", " return None\n", "\n", "def convert_gender(value):\n", " if pd.isna(value):\n", " return None\n", " \n", " value = str(value).lower()\n", " \n", " # Extract the actual value if there's a colon\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # Female: 0, Male: 1\n", " if any(term in value for term in ['f', 'female', 'women', 'woman']):\n", " return 0\n", " elif any(term in value for term in ['m', 'male', 'men', 'man']):\n", " return 1\n", " \n", " return None\n", "\n", "# Search for trait, age, and gender rows by examining values\n", "for i, values in row_descriptions:\n", " values_str = ' '.join([str(v).lower() for v in values])\n", " \n", " # Look for depression/MDD indicators\n", " if trait_row is None and ('depression' in values_str or 'mdd' in values_str or 'control' in values_str):\n", " trait_row = i\n", " print(f\"Found trait row at index {i}\")\n", " \n", " # Look for age indicators\n", " if age_row is None and ('age' in values_str or 'years' in values_str):\n", " age_row = i\n", " print(f\"Found age row at index {i}\")\n", " \n", " # Look for gender indicators\n", " if gender_row is None and ('gender' in values_str or 'sex' in values_str or 'male' in values_str or 'female' in values_str):\n", " gender_row = i\n", " print(f\"Found gender row at index {i}\")\n", "\n", "# Check trait availability\n", "is_trait_available = trait_row is not None\n", "\n", "# Initial validation to check if this dataset is worth processing further\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 and trait_row is identified, extract and save features\n", "if is_trait_available and clinical_data is not None:\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 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 features\n", " preview = preview_df(clinical_features)\n", " print(\"\\nClinical features preview:\")\n", " print(preview)\n", " \n", " # Save clinical features to CSV\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 features saved to {out_clinical_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "c17bb83c", "metadata": {}, "source": [ "### Step 5: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "58437d7e", "metadata": {}, "outputs": [], "source": [ "# 1. Get the SOFT and matrix file paths again \n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "print(f\"Matrix file found: {matrix_file}\")\n", "\n", "# 2. Use the get_genetic_data function from the library to get the gene_data\n", "try:\n", " gene_data = get_genetic_data(matrix_file)\n", " print(f\"Gene data shape: {gene_data.shape}\")\n", " \n", " # 3. Print the first 20 row IDs (gene or probe identifiers)\n", " print(\"First 20 gene/probe identifiers:\")\n", " print(gene_data.index[:20])\n", "except Exception as e:\n", " print(f\"Error extracting gene data: {e}\")\n" ] }, { "cell_type": "markdown", "id": "9ee549f5", "metadata": {}, "source": [ "### Step 6: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": null, "id": "8b6faf74", "metadata": {}, "outputs": [], "source": [ "# Evaluating gene identifiers\n", "# The identifiers shown (1, 2, 3, etc.) are numeric indices, not human gene symbols\n", "# These are likely probe IDs or feature IDs from a microarray or sequencing platform\n", "# They need to be mapped to proper gene symbols for biological interpretation\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "eb01dc47", "metadata": {}, "source": [ "### Step 7: Gene Annotation" ] }, { "cell_type": "code", "execution_count": null, "id": "8008789d", "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", "# Check if there are any platforms defined in the SOFT file that might contain annotation data\n", "with gzip.open(soft_file, 'rt') as f:\n", " soft_content = f.read()\n", "\n", "# Look for platform sections in the SOFT file\n", "platform_sections = re.findall(r'^!Platform_title\\s*=\\s*(.+)$', soft_content, re.MULTILINE)\n", "if platform_sections:\n", " print(f\"Platform title found: {platform_sections[0]}\")\n", "\n", "# Try to extract more annotation data by reading directly from the SOFT file\n", "# Look for lines that might contain gene symbol mappings\n", "symbol_pattern = re.compile(r'ID_REF\\s+Symbol|ID\\s+Gene Symbol', re.IGNORECASE)\n", "annotation_lines = []\n", "with gzip.open(soft_file, 'rt') as f:\n", " for line in f:\n", " if symbol_pattern.search(line):\n", " annotation_lines.append(line)\n", " # Collect the next few lines to see the annotation structure\n", " for _ in range(10):\n", " annotation_lines.append(next(f, ''))\n", "\n", "if annotation_lines:\n", " print(\"Found potential gene symbol mappings:\")\n", " for line in annotation_lines:\n", " print(line.strip())\n", "\n", "# 2. Use the 'preview_df' function from the library to preview the data and print out the results.\n", "print(\"\\nGene annotation preview:\")\n", "print(preview_df(gene_annotation, n=10))\n", "\n", "# If we need an alternative source of mapping, check if there are any other annotation files in the cohort directory\n", "cohort_files = os.listdir(in_cohort_dir)\n", "annotation_files = [f for f in cohort_files if 'annotation' in f.lower() or 'platform' in f.lower()]\n", "if annotation_files:\n", " print(\"\\nAdditional annotation files found in the cohort directory:\")\n", " for file in annotation_files:\n", " print(file)\n" ] }, { "cell_type": "markdown", "id": "38803b07", "metadata": {}, "source": [ "### Step 8: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": null, "id": "5888cd8e", "metadata": {}, "outputs": [], "source": [ "# Examine gene_annotation to find the column containing gene symbols\n", "print(\"Gene annotation columns:\", gene_annotation.columns.tolist())\n", "\n", "# After examining the annotation data and the first few rows, I need to determine which\n", "# columns contain the gene identifiers and gene symbols\n", "\n", "# Check if 'GENE_SYMBOL' column exists in the annotation\n", "if 'GENE_SYMBOL' in gene_annotation.columns:\n", " gene_col = 'GENE_SYMBOL'\n", "elif 'GENE' in gene_annotation.columns:\n", " gene_col = 'GENE'\n", "elif 'SYMBOL' in gene_annotation.columns:\n", " gene_col = 'SYMBOL'\n", "else:\n", " # If no obvious gene symbol column is found, check if gene symbol information\n", " # might be embedded in another column like NAME or SPOT_ID\n", " # For Agilent platforms, sometimes gene info is in the SEQUENCE column\n", " sample_rows = gene_annotation.iloc[100:120] # Check rows after control probes\n", " print(\"Sample rows to look for gene symbols:\")\n", " print(sample_rows[['ID', 'NAME', 'SPOT_ID']].head())\n", " \n", " # Default to NAME column which often contains gene information\n", " gene_col = 'NAME'\n", "\n", "# The ID column should be the probe identifier that matches the gene expression data\n", "id_col = 'ID'\n", "\n", "print(f\"Using {id_col} for probe identifiers and {gene_col} for gene symbols\")\n", "\n", "# Get mapping between probe IDs and gene symbols\n", "mapping_df = get_gene_mapping(gene_annotation, id_col, gene_col)\n", "print(f\"Mapping dataframe shape: {mapping_df.shape}\")\n", "print(\"Mapping preview:\")\n", "print(mapping_df.head(10))\n", "\n", "# Apply the mapping to convert probe-level data to gene-level data\n", "gene_data = apply_gene_mapping(gene_data, mapping_df)\n", "print(f\"Gene expression data shape after mapping: {gene_data.shape}\")\n", "print(\"First 10 gene symbols:\")\n", "print(gene_data.index[:10].tolist())\n", "\n", "# Save the gene expression data\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" ] }, { "cell_type": "markdown", "id": "f722ce84", "metadata": {}, "source": [ "### Step 9: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": null, "id": "16ba7ece", "metadata": {}, "outputs": [], "source": [ "# 1. Normalize gene symbols in the gene expression data\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\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", " normalized_gene_data = gene_data # Use original data if normalization fails\n", " \n", "# 2. Recreate clinical data using correct row indices from step 2\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", "# Extract clinical features using correct row indices and conversion functions\n", "def convert_trait(value):\n", " \"\"\"Convert depression history data to binary format (0 = no, 1 = yes)\"\"\"\n", " if not isinstance(value, str):\n", " return None\n", " \n", " # Extract value after colon if present\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip().lower()\n", " else:\n", " value = value.strip().lower()\n", " \n", " if value == 'yes':\n", " return 1\n", " elif value == 'no':\n", " return 0\n", " else:\n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age data to continuous format\"\"\"\n", " if not isinstance(value, str):\n", " return None\n", " \n", " # Extract value after colon if present\n", " if ':' in value:\n", " age_str = value.split(':', 1)[1].strip()\n", " else:\n", " age_str = value.strip()\n", " \n", " try:\n", " return float(age_str)\n", " except ValueError:\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"Convert gender data to binary format (0 = female, 1 = male)\"\"\"\n", " if not isinstance(value, str):\n", " return None\n", " \n", " # Extract value after colon if present\n", " if ':' in value:\n", " gender = value.split(':', 1)[1].strip().lower()\n", " else:\n", " gender = value.strip().lower()\n", " \n", " if gender == 'female':\n", " return 0\n", " elif gender == 'male':\n", " return 1\n", " else:\n", " return None\n", "\n", "# Use correct row indices identified in step 2\n", "selected_clinical_df = geo_select_clinical_features(\n", " clinical_df=clinical_data,\n", " trait=trait, # Using the trait variable from context (Depression)\n", " trait_row=9, # Using row 9 for depression history as identified in step 2\n", " convert_trait=convert_trait,\n", " age_row=1, # Age data is in row 1\n", " convert_age=convert_age,\n", " gender_row=2, # Gender data is in row 2\n", " convert_gender=convert_gender\n", ")\n", "\n", "print(f\"Selected clinical data shape: {selected_clinical_df.shape}\")\n", "print(\"Clinical data preview:\")\n", "print(preview_df(selected_clinical_df))\n", "\n", "# Save clinical data for future reference\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", "# 2. Link clinical and genetic data\n", "linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)\n", "print(f\"Linked data shape: {linked_data.shape}\")\n", "print(\"Linked data preview (first 5 rows, 5 columns):\")\n", "print(linked_data.iloc[:5, :5] if not linked_data.empty else \"Linked data is empty\")\n", "\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. Check for bias in features\n", "is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n", "\n", "# 5. 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=True,\n", " is_trait_available=True,\n", " is_biased=is_biased,\n", " df=linked_data,\n", " note=\"Dataset contains gene expression data from peripheral blood mononuclear cells of older adults with and without depression history, from a study on insomnia disorder.\"\n", ")\n", "\n", "# 6. 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(\"Dataset is not usable for analysis. No linked data file saved.\")" ] } ], "metadata": {}, "nbformat": 4, "nbformat_minor": 5 }