{ "cells": [ { "cell_type": "code", "execution_count": null, "id": "29d6485e", "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 = \"Longevity\"\n", "cohort = \"GSE44147\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Longevity\"\n", "in_cohort_dir = \"../../input/GEO/Longevity/GSE44147\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Longevity/GSE44147.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Longevity/gene_data/GSE44147.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Longevity/clinical_data/GSE44147.csv\"\n", "json_path = \"../../output/preprocess/Longevity/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "6898d13f", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": null, "id": "ed6e7b7d", "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": "be9fed2a", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "7a801a49", "metadata": {}, "outputs": [], "source": [ "# 1. Gene Expression Data Availability\n", "# Based on background information, this dataset contains transcriptome data from Affymetrix Gene Arrays\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 (Longevity), we can infer from 'age' data in row 2\n", "trait_row = 2\n", "# Age data is available in row 2\n", "age_row = 2\n", "# Gender data is not available in the sample characteristics\n", "gender_row = None\n", "\n", "# 2.2 Data Type Conversion\n", "def convert_trait(value):\n", " \"\"\"\n", " Convert age values to binary longevity status.\n", " Ages > 365 days (1 year) considered as longevity=1, otherwise longevity=0\n", " This threshold is appropriate for mice, as C57BL/6 mice typically live 2-3 years.\n", " \"\"\"\n", " if ':' in value:\n", " age_value = value.split(':')[1].strip()\n", " if 'days' in age_value:\n", " try:\n", " days = int(age_value.replace('days', '').strip())\n", " # Considering mice over 1 year as having longevity\n", " return 1 if days > 365 else 0\n", " except:\n", " return None\n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age values to continuous values in days.\"\"\"\n", " if ':' in value:\n", " age_value = value.split(':')[1].strip()\n", " if 'days' in age_value:\n", " try:\n", " return int(age_value.replace('days', '').strip())\n", " except:\n", " return None\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"\n", " Convert gender values to binary (0 for female, 1 for male).\n", " Not used in this dataset as gender information is not available.\n", " \"\"\"\n", " return None\n", "\n", "# 3. Save Metadata\n", "# Determine trait data availability - 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", " # Sample characteristics from the previous output\n", " sample_chars = {\n", " 0: ['strain: C57BL/6'],\n", " 1: ['tissue: prefrontal cortex of the brain'],\n", " 2: ['age: 2 days', 'age: 5 days', 'age: 11 days', 'age: 20 days', \n", " 'age: 32 days', 'age: 61 days', 'age: 122 days', 'age: 184 days', \n", " 'age: 365 days', 'age: 649 days', 'age: 904 days']\n", " }\n", " \n", " # Create a proper clinical DataFrame\n", " # First, determine the sample IDs from the age values (row 2)\n", " sample_ids = [f\"Sample_{i+1}\" for i in range(len(sample_chars[2]))]\n", " \n", " # Create a DataFrame with the proper structure for geo_select_clinical_features\n", " # Rows represent characteristic types, columns represent samples\n", " data = {}\n", " \n", " # Add sample_id column\n", " data['characteristic_id'] = list(sample_chars.keys()) \n", " \n", " # For each characteristic type, add a row\n", " for row_idx, values in sample_chars.items():\n", " if len(values) == 1: # Same value for all samples\n", " data[row_idx] = values * len(sample_ids)\n", " else: # Different values per sample\n", " data[row_idx] = values\n", " \n", " # Create the clinical DataFrame with the right structure\n", " clinical_data = pd.DataFrame()\n", " clinical_data['characteristic_id'] = list(sample_chars.keys())\n", " \n", " # Add each sample as a column\n", " for i, sample_id in enumerate(sample_ids):\n", " if i < len(sample_chars[2]): # Only add columns for available age data\n", " clinical_data[sample_id] = [\n", " sample_chars[0][0], # strain is the same for all\n", " sample_chars[1][0], # tissue is the same for all\n", " sample_chars[2][i] # age varies by sample\n", " ]\n", " \n", " # Now the clinical_data DataFrame has the right structure for geo_select_clinical_features\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 data\n", " preview = preview_df(selected_clinical_df)\n", " print(\"Clinical data preview:\")\n", " print(preview)\n", " \n", " # Save the extracted 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": "30a8f037", "metadata": {}, "source": [ "### Step 3: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "922cf167", "metadata": {}, "outputs": [], "source": [ "I understand the task is to fix the syntax issues in the previous attempt and implement the diagnostic and exploratory steps correctly.\n", "\n", "```python\n", "import pandas as pd\n", "import numpy as np\n", "import json\n", "import os\n", "from typing import Optional, Callable, Dict, Any\n", "\n", "# First, list all files in the directory to see what's available\n", "print(f\"Exploring directory: {in_cohort_dir}\")\n", "files = os.listdir(in_cohort_dir)\n", "print(f\"Files found: {files}\")\n", "\n", "# Let's check if there's any series matrix file or other data files\n", "series_files = [f for f in files if \"series_matrix\" in f.lower()]\n", "data_files = [f for f in files if f.endswith(\".txt\") or f.endswith(\".csv\") or f.endswith(\".tsv\")]\n", "\n", "print(f\"Series matrix files: {series_files}\")\n", "print(f\"Data files: {data_files}\")\n", "\n", "# Find a suitable file to extract clinical data from\n", "data_file_path = None\n", "if series_files:\n", " data_file_path = os.path.join(in_cohort_dir, series_files[0])\n", "elif data_files:\n", " data_file_path = os.path.join(in_cohort_dir, data_files[0])\n", "\n", "# Now examine the file content\n", "if data_file_path:\n", " print(f\"Examining file: {data_file_path}\")\n", " with open(data_file_path, 'r') as f:\n", " # Read first few lines to understand structure\n", " lines = []\n", " for i, line in enumerate(f):\n", " if i < 50: # Read first 50 lines\n", " lines.append(line.strip())\n", " \n", " # Print the first few lines to understand the file structure\n", " print(\"First few lines of the file:\")\n", " for i, line in enumerate(lines):\n", " print(f\"{i}: {line[:100]}...\") # Print first 100 chars of each line\n", " \n", " # Continue reading the entire file\n", " with open(data_file_path, 'r') as f:\n", " all_lines = f.readlines()\n", " \n", " # Look for sample characteristics or clinical data\n", " sample_char_lines = [i for i, line in enumerate(all_lines) if line.startswith(\"!Sample_characteristics_ch1\")]\n", " if sample_char_lines:\n", " print(f\"Found sample characteristics at lines: {sample_char_lines[:5]}...\")\n", " \n", " # Create a dictionary to store unique values for each sample characteristic\n", " sample_char_dict = {}\n", " for i in range(min(sample_char_lines), max(sample_char_lines) + 1):\n", " if all_lines[i].startswith(\"!Sample_characteristics_ch1\"):\n", " values = all_lines[i].strip().split('\\t')[1:]\n", " sample_char_dict[i - min(sample_char_lines)] = values\n", " \n", " # Print the dictionary to see the available sample characteristics\n", " print(\"Sample Characteristics Dictionary:\")\n", " for key, values in sample_char_dict.items():\n", " unique_values = set(values)\n", " print(f\"Row {key}: {unique_values}\")\n", " \n", " # Based on the sample characteristics, determine trait, age, and gender availability\n", " is_gene_available = True # Assuming gene expression data is available based on file inspection\n", " \n", " # Initialize as None, will be set based on examination of data\n", " trait_row = None\n", " age_row = None\n", " gender_row = None\n", " \n", " # Examine each row to identify trait, age, and gender\n", " for row, values in sample_char_dict.items():\n", " unique_values = list(set(values))\n", " sample_value = unique_values[0] if unique_values else \"\"\n", " \n", " # Look for longevity-related terms in the sample value\n", " if any(term in sample_value.lower() for term in ['long-lived', 'centenarian', 'control', 'survival', 'lifespan']):\n", " trait_row = row\n", " print(f\"Found trait data in row {row}: {unique_values}\")\n", " \n", " # Look for age-related terms\n", " elif any(term in sample_value.lower() for term in ['age', 'years', 'yr']):\n", " age_row = row\n", " print(f\"Found age data in row {row}: {unique_values}\")\n", " \n", " # Look for gender-related terms\n", " elif any(term in sample_value.lower() for term in ['gender', 'sex', 'male', 'female']):\n", " gender_row = row\n", " print(f\"Found gender data in row {row}: {unique_values}\")\n", " \n", " # Define conversion functions\n", " def convert_trait(value):\n", " if not value or ':' not in value:\n", " return None\n", " \n", " value = value.split(':', 1)[1].strip().lower()\n", " \n", " if 'long-lived' in value or 'centenarian' in value or 'll' in value:\n", " return 1 # Long-lived individuals\n", " elif 'control' in value or 'young' in value:\n", " return 0 # Control individuals\n", " else:\n", " return None\n", "\n", " def convert_age(value):\n", " if not value or ':' not in value:\n", " return None\n", " \n", " try:\n", " # Extract the age value after the colon\n", " age_str = value.split(':', 1)[1].strip()\n", " \n", " # Remove any non-numeric characters except for decimal point\n", " age_str = ''.join(c for c in age_str if c.isdigit() or c == '.')\n", " \n", " if age_str:\n", " return float(age_str)\n", " else:\n", " return None\n", " except:\n", " return None\n", "\n", " def convert_gender(value):\n", " if not value or ':' not in value:\n", " return None\n", " \n", " gender = value.split(':', 1)[1].strip().lower()\n", " \n", " if 'female' in gender or 'f' == gender:\n", " return 0\n", " elif 'male' in gender or 'm' == gender:\n", " return 1\n", " else:\n", " return None\n", " \n", " # Create a DataFrame from the sample characteristics dictionary\n", " clinical_data = pd.DataFrame(sample_char_dict).T\n", " \n", " # Validate and save cohort info\n", " is_trait_available = trait_row is not None\n", " \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_row is not None\n", " if trait_row is not None:\n", " # Use the geo_select_clinical_features function to extract 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 clinical features\n", " preview = preview_df(clinical_features)\n", " print(\"Clinical Features Preview:\")\n", " print(preview)\n", " \n", " # Save the clinical features to a CSV file\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", " else:\n", " print(\"No sample characteristics found in the file.\")\n", " is_gene_available = True # Assuming it contains gene data, but verify based on file content\n", " is_trait_available = False\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 suitable data files found in the directory.\")\n", " is_gene_available = False\n", " is_trait_available = False\n", " validate_and_save_cohort_info(\n", " is_final=False, \n", " cohort=cohort, \n", " info_path=\n" ] }, { "cell_type": "markdown", "id": "cedbaac1", "metadata": {}, "source": [ "### Step 4: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "74611853", "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", "# Add diagnostic code to check file content and structure\n", "print(\"Examining matrix file structure...\")\n", "with gzip.open(matrix_file, 'rt') as file:\n", " table_marker_found = False\n", " lines_read = 0\n", " for i, line in enumerate(file):\n", " lines_read += 1\n", " if '!series_matrix_table_begin' in line:\n", " table_marker_found = True\n", " print(f\"Found table marker at line {i}\")\n", " # Read a few lines after the marker to check data structure\n", " next_lines = [next(file, \"\").strip() for _ in range(5)]\n", " print(\"First few lines after marker:\")\n", " for next_line in next_lines:\n", " print(next_line)\n", " break\n", " if i < 10: # Print first few lines to see file structure\n", " print(f\"Line {i}: {line.strip()}\")\n", " if i > 100: # Don't read the entire file\n", " break\n", " \n", " if not table_marker_found:\n", " print(\"Table marker '!series_matrix_table_begin' not found in first 100 lines\")\n", " print(f\"Total lines examined: {lines_read}\")\n", "\n", "# 2. Try extracting gene expression data from the matrix file again with better diagnostics\n", "try:\n", " print(\"\\nAttempting to extract 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: {str(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", "\n", "# If data extraction failed, try an alternative approach using pandas directly\n", "if not is_gene_available:\n", " print(\"\\nTrying alternative approach to read gene expression data...\")\n", " try:\n", " with gzip.open(matrix_file, 'rt') as file:\n", " # Skip lines until we find the marker\n", " for line in file:\n", " if '!series_matrix_table_begin' in line:\n", " break\n", " \n", " # Try to read the data directly with pandas\n", " gene_data = pd.read_csv(file, sep='\\t', index_col=0)\n", " \n", " if not gene_data.empty:\n", " print(f\"Successfully extracted gene data with alternative method: {gene_data.shape}\")\n", " print(\"First 20 gene IDs:\")\n", " print(gene_data.index[:20])\n", " is_gene_available = True\n", " else:\n", " print(\"Alternative extraction method also produced empty data\")\n", " except Exception as e:\n", " print(f\"Alternative extraction failed: {str(e)}\")\n" ] }, { "cell_type": "markdown", "id": "29c0e913", "metadata": {}, "source": [ "### Step 5: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": null, "id": "e9ef5305", "metadata": {}, "outputs": [], "source": [ "# The gene identifiers appear to be numeric IDs (like 10344624, 10344637, etc.)\n", "# They are likely probe IDs from a microarray platform rather than human gene symbols\n", "# These will need to be mapped to standard gene symbols for analysis\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "b480e6fd", "metadata": {}, "source": [ "### Step 6: Gene Annotation" ] }, { "cell_type": "code", "execution_count": null, "id": "9f88ab4b", "metadata": {}, "outputs": [], "source": [ "# 1. Extract gene annotation data from the SOFT file\n", "print(\"Extracting gene annotation data from SOFT file...\")\n", "try:\n", " # Use the library function to extract gene annotation\n", " gene_annotation = get_gene_annotation(soft_file)\n", " print(f\"Successfully extracted gene annotation data with {len(gene_annotation.index)} rows\")\n", " \n", " # Preview the annotation DataFrame\n", " print(\"\\nGene annotation preview (first few rows):\")\n", " print(preview_df(gene_annotation))\n", " \n", " # Show column names to help identify which columns we need for mapping\n", " print(\"\\nColumn names in gene annotation data:\")\n", " print(gene_annotation.columns.tolist())\n", " \n", " # Check for relevant mapping columns\n", " if 'GB_ACC' in gene_annotation.columns:\n", " print(\"\\nThe dataset contains GenBank accessions (GB_ACC) that could be used for gene mapping.\")\n", " # Count non-null values in GB_ACC column\n", " non_null_count = gene_annotation['GB_ACC'].count()\n", " print(f\"Number of rows with GenBank accessions: {non_null_count} out of {len(gene_annotation)}\")\n", " \n", " if 'SPOT_ID' in gene_annotation.columns:\n", " print(\"\\nThe dataset contains genomic regions (SPOT_ID) that could be used for location-based gene mapping.\")\n", " print(\"Example SPOT_ID format:\", gene_annotation['SPOT_ID'].iloc[0])\n", " \n", "except Exception as e:\n", " print(f\"Error processing gene annotation data: {e}\")\n", " is_gene_available = False\n" ] }, { "cell_type": "markdown", "id": "de3be0ca", "metadata": {}, "source": [ "### Step 7: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": null, "id": "ded073ee", "metadata": {}, "outputs": [], "source": [ "# 1. Identify columns for mapping\n", "# The gene expression data has IDs in the index, and the annotation data has 'ID' column\n", "# The gene symbols are in 'gene_assignment' column which contains gene symbols in a specific format\n", "\n", "print(\"Preparing to map gene identifiers to gene symbols...\")\n", "\n", "# 2. Create the gene mapping dataframe from gene annotation\n", "# We need to extract ID and gene_assignment columns\n", "mapping_data = gene_annotation[['ID', 'gene_assignment']].copy()\n", "\n", "# Clean the mapping data\n", "# Remove rows where gene_assignment is missing or just \"---\"\n", "mapping_data = mapping_data[mapping_data['gene_assignment'].notna() & (mapping_data['gene_assignment'] != '---')]\n", "print(f\"Filtered mapping data to {len(mapping_data)} rows with gene assignments\")\n", "\n", "# Extract gene symbols from the gene_assignment format\n", "# The format is like \"NR_024005 // DDX11L2 // DEAD/H (Asp-Glu-Ala-Asp/His) box polypeptide 11 like 2 // 2q13 // 84771\"\n", "# We need to extract \"DDX11L2\" which is the gene symbol\n", "\n", "def extract_gene_symbols(assignment_text):\n", " \"\"\"Extract gene symbols from the gene_assignment column text\"\"\"\n", " if not isinstance(assignment_text, str) or '//' not in assignment_text:\n", " return []\n", " \n", " # Split by '//' and look for gene symbols (usually the second element after splitting)\n", " parts = [part.strip() for part in assignment_text.split('//')]\n", " \n", " # Extract gene symbols - these are usually the second elements in each group\n", " # A group format is typically: \"NR_024005 // DDX11L2 // description // location // ID\"\n", " symbols = []\n", " for i in range(1, len(parts), 5):\n", " if i < len(parts):\n", " symbol = parts[i]\n", " if symbol and symbol != '---':\n", " symbols.append(symbol)\n", " \n", " # If above method doesn't work, use the extract_human_gene_symbols function \n", " if not symbols:\n", " symbols = extract_human_gene_symbols(assignment_text)\n", " \n", " return symbols\n", "\n", "# Apply the extraction function and create a proper mapping dataframe\n", "mapping_data['Gene'] = mapping_data['gene_assignment'].apply(extract_gene_symbols)\n", "mapping_data = mapping_data[mapping_data['Gene'].apply(len) > 0] # Keep only rows with extracted symbols\n", "print(f\"Extracted gene symbols from {len(mapping_data)} rows\")\n", "\n", "# Preview the mapping data\n", "print(\"\\nMapping data preview (first few rows):\")\n", "mapping_preview = preview_df(mapping_data[['ID', 'Gene']])\n", "print(mapping_preview)\n", "\n", "# 3. Apply gene mapping to convert probe-level measurements to gene expression data\n", "# We'll use the apply_gene_mapping function from the library\n", "print(\"\\nApplying gene mapping to convert probe-level data to gene expression data...\")\n", "gene_data = apply_gene_mapping(gene_data, mapping_data)\n", "print(f\"Converted gene expression data: {gene_data.shape[0]} genes and {gene_data.shape[1]} samples\")\n", "\n", "# Preview the mapped gene expression data\n", "print(\"\\nMapped gene expression data preview (first few genes):\")\n", "gene_data_preview = preview_df(gene_data)\n", "print(gene_data_preview)\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}\")" ] } ], "metadata": {}, "nbformat": 4, "nbformat_minor": 5 }