{ "cells": [ { "cell_type": "code", "execution_count": null, "id": "30995812", "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 = \"Metabolic_Rate\"\n", "cohort = \"GSE106800\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Metabolic_Rate\"\n", "in_cohort_dir = \"../../input/GEO/Metabolic_Rate/GSE106800\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Metabolic_Rate/GSE106800.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Metabolic_Rate/gene_data/GSE106800.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Metabolic_Rate/clinical_data/GSE106800.csv\"\n", "json_path = \"../../output/preprocess/Metabolic_Rate/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "bb05f4c6", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": null, "id": "a5009d9c", "metadata": {}, "outputs": [], "source": [ "# 1. Check what files are actually in the directory\n", "import os\n", "print(\"Files in the directory:\")\n", "files = os.listdir(in_cohort_dir)\n", "print(files)\n", "\n", "# 2. Find appropriate files with more flexible pattern matching\n", "soft_file = None\n", "matrix_file = None\n", "\n", "for file in files:\n", " file_path = os.path.join(in_cohort_dir, file)\n", " # Look for files that might contain SOFT or matrix data with various possible extensions\n", " if 'soft' in file.lower() or 'family' in file.lower() or file.endswith('.soft.gz'):\n", " soft_file = file_path\n", " if 'matrix' in file.lower() or file.endswith('.txt.gz') or file.endswith('.tsv.gz'):\n", " matrix_file = file_path\n", "\n", "if not soft_file:\n", " print(\"Warning: Could not find a SOFT file. Using the first .gz file as fallback.\")\n", " gz_files = [f for f in files if f.endswith('.gz')]\n", " if gz_files:\n", " soft_file = os.path.join(in_cohort_dir, gz_files[0])\n", "\n", "if not matrix_file:\n", " print(\"Warning: Could not find a matrix file. Using the second .gz file as fallback if available.\")\n", " gz_files = [f for f in files if f.endswith('.gz')]\n", " if len(gz_files) > 1 and soft_file != os.path.join(in_cohort_dir, gz_files[1]):\n", " matrix_file = os.path.join(in_cohort_dir, gz_files[1])\n", " elif len(gz_files) == 1 and not soft_file:\n", " matrix_file = os.path.join(in_cohort_dir, gz_files[0])\n", "\n", "print(f\"SOFT file: {soft_file}\")\n", "print(f\"Matrix file: {matrix_file}\")\n", "\n", "# 3. Read files if found\n", "if soft_file and matrix_file:\n", " # 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", " \n", " try:\n", " background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)\n", " \n", " # Obtain the sample characteristics dictionary from the clinical dataframe\n", " sample_characteristics_dict = get_unique_values_by_row(clinical_data)\n", " \n", " # 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", " except Exception as e:\n", " print(f\"Error processing files: {e}\")\n", " # Try swapping files if first attempt fails\n", " print(\"Trying to swap SOFT and matrix files...\")\n", " temp = soft_file\n", " soft_file = matrix_file\n", " matrix_file = temp\n", " try:\n", " background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)\n", " sample_characteristics_dict = get_unique_values_by_row(clinical_data)\n", " print(\"Background Information:\")\n", " print(background_info)\n", " print(\"Sample Characteristics Dictionary:\")\n", " print(sample_characteristics_dict)\n", " except Exception as e:\n", " print(f\"Still error after swapping: {e}\")\n", "else:\n", " print(\"Could not find necessary files for processing.\")\n" ] }, { "cell_type": "markdown", "id": "5f3deba5", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "f9d9bf9e", "metadata": {}, "outputs": [], "source": [ "# Analyzing the dataset for gene expression and clinical features\n", "\n", "# 1. Gene Expression Data Availability\n", "# Based on the Series_summary and Series_overall_design, this dataset appears to contain microarray data\n", "# from skeletal muscle biopsies, which should include gene expression data\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# Based on the sample characteristics, let's identify which rows contain relevant data\n", "# 2.1 Data Availability\n", "\n", "# For trait (Metabolic Rate): \n", "# Looking at the data, there is no direct measure of metabolic rate\n", "# However, the background information mentions \"sleeping metabolic rate\" being affected by misalignment\n", "# From the data, we can infer this from \"experimental condition\" (row 7)\n", "trait_row = 7 # experimental condition: circadian aligned/misaligned\n", "\n", "# For age:\n", "age_row = 2 # age (yrs): values\n", "\n", "# For gender:\n", "# The gender is available but all participants are male, making it a constant feature\n", "gender_row = None # All participants are male as per row 0\n", "\n", "# 2.2 Data Type Conversion Functions\n", "\n", "def convert_trait(value):\n", " \"\"\"Convert experimental condition to a binary representation of metabolic rate impact.\"\"\"\n", " if not isinstance(value, str):\n", " return None\n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " # Based on the study design, circadian misalignment is associated with higher metabolic rate\n", " # So we'll encode: misaligned (higher metabolic rate) = 1, aligned (normal) = 0\n", " if \"misaligned\" in value.lower():\n", " return 1 # Higher metabolic rate due to misalignment\n", " elif \"aligned\" in value.lower():\n", " return 0 # Normal metabolic rate\n", " else:\n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age string to a continuous numeric value.\"\"\"\n", " if not isinstance(value, str):\n", " return None\n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " try:\n", " return float(value)\n", " except (ValueError, TypeError):\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"Convert gender to binary representation (0=female, 1=male).\"\"\"\n", " # Not used in this case as all participants are male\n", " if not isinstance(value, str):\n", " return None\n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " if value.lower() == \"male\":\n", " return 1\n", " elif value.lower() == \"female\":\n", " return 0\n", " else:\n", " return None\n", "\n", "# 3. Save Metadata\n", "# Trait data availability is determined by whether trait_row is None\n", "is_trait_available = trait_row is not None\n", "validate_and_save_cohort_info(is_final=False, cohort=cohort, info_path=json_path, \n", " is_gene_available=is_gene_available, \n", " is_trait_available=is_trait_available)\n", "\n", "# 4. Clinical Feature Extraction\n", "# If trait_row is not None, extract clinical features\n", "if trait_row is not None:\n", " # We're assuming clinical_data is already available as a variable from a previous step\n", " # Extract the clinical features from the sample characteristics we've already examined\n", " # This is just a placeholder - we'll need to get the actual clinical data\n", " print(\"Clinical data extraction will be performed in the next step when the data is available\")\n" ] }, { "cell_type": "markdown", "id": "12f8cb1e", "metadata": {}, "source": [ "### Step 3: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "a209acf7", "metadata": {}, "outputs": [], "source": [ "```python\n", "import pandas as pd\n", "import os\n", "import gzip\n", "import re\n", "from typing import Optional, Callable, Dict, Any, List, Tuple\n", "\n", "# Check the cohort directory content to understand what files we have\n", "print(f\"Files in cohort directory: {os.listdir(in_cohort_dir)}\")\n", "\n", "# Function to parse GEO series matrix file\n", "def parse_geo_series_matrix(file_path: str) -> Tuple[str, pd.DataFrame]:\n", " \"\"\"Parse GEO series matrix file to extract background info and sample characteristics.\"\"\"\n", " background_text = []\n", " characteristics_lines = []\n", " sample_ids = []\n", " \n", " # Open and read the gzipped file\n", " with gzip.open(file_path, 'rt') as file:\n", " # Process the header section to extract metadata\n", " in_header = True\n", " for line in file:\n", " line = line.strip()\n", " \n", " # Collect sample IDs from the !Sample_geo_accession line\n", " if line.startswith('!Sample_geo_accession'):\n", " sample_ids = line.split('\\t')[1:]\n", " \n", " # Collect characteristics lines\n", " if line.startswith('!Sample_characteristics_ch'):\n", " characteristics_lines.append(line)\n", " \n", " # Collect background info\n", " if in_header and line and not line.startswith('!series_matrix_table_begin'):\n", " background_text.append(line)\n", " \n", " # End of header section\n", " if line.startswith('!series_matrix_table_begin'):\n", " in_header = False\n", " break\n", " \n", " # Process characteristics lines to create a DataFrame\n", " characteristics_data = []\n", " for char_line in characteristics_lines:\n", " parts = char_line.split('\\t')\n", " header = parts[0]\n", " values = parts[1:]\n", " characteristics_data.append([header] + values)\n", " \n", " # Create DataFrame if characteristics data exists\n", " if characteristics_data and sample_ids:\n", " df = pd.DataFrame(characteristics_data)\n", " # Set column names\n", " df.columns = ['characteristic'] + sample_ids\n", " return '\\n'.join(background_text), df\n", " \n", " return '\\n'.join(background_text), pd.DataFrame()\n", "\n", "# Load and parse the series matrix file\n", "series_matrix_file = os.path.join(in_cohort_dir, 'GSE106800_series_matrix.txt.gz')\n", "background_info, clinical_data = parse_geo_series_matrix(series_matrix_file)\n", "\n", "# Display background information\n", "print(\"\\nBackground Information (excerpt):\")\n", "print('\\n'.join(background_info.split('\\n')[:20]) + \"\\n...\") # Show first 20 lines\n", "\n", "# Check gene expression data availability by looking for gene expression data in the matrix file\n", "is_gene_available = True # Based on the presence of the series matrix file\n", "\n", "print(f\"\\nGene expression data availability: {is_gene_available}\")\n", "\n", "# Display clinical data structure if available\n", "if not clinical_data.empty:\n", " print(\"\\nClinical data structure:\")\n", " print(f\"Shape: {clinical_data.shape}\")\n", " print(\"\\nCharacteristics:\")\n", " for i, row in enumerate(clinical_data['characteristic']):\n", " unique_values = clinical_data.iloc[i, 1:].unique()\n", " value_preview = str(unique_values[:5])\n", " if len(unique_values) > 5:\n", " value_preview = value_preview[:-1] + \", ...]\"\n", " print(f\"Row {i}: {row} - Unique values: {value_preview} (total: {len(unique_values)})\")\n", "else:\n", " print(\"\\nNo structured clinical data found in the series matrix file.\")\n", "\n", "# Analyze clinical data for trait, age, and gender information\n", "trait_row = None\n", "age_row = None\n", "gender_row = None\n", "\n", "# Functions to convert data\n", "def convert_trait(value: str) -> Optional[float]:\n", " \"\"\"Convert metabolic rate values to numeric.\"\"\"\n", " if pd.isna(value) or value is None:\n", " return None\n", " try:\n", " # Extract the value after colon if present\n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " # Look for numeric values with common metabolic rate units\n", " # Common patterns: X kcal/day, X kJ/day, X calories, etc.\n", " match = re.search(r'(\\d+\\.?\\d*)', value)\n", " if match:\n", " return float(match.group(1))\n", " return None\n", " except (ValueError, TypeError):\n", " return None\n", "\n", "def convert_age(value: str) -> Optional[float]:\n", " \"\"\"Convert age values to numeric.\"\"\"\n", " if pd.isna(value) or value is None:\n", " return None\n", " try:\n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " # Extract numeric part if age is given as \"XX years\" or similar\n", " match = re.search(r'(\\d+\\.?\\d*)', value)\n", " if match:\n", " return float(match.group(1))\n", " return None\n", " except (ValueError, TypeError):\n", " return None\n", "\n", "def convert_gender(value: str) -> Optional[int]:\n", " \"\"\"Convert gender values to binary (0 for female, 1 for male).\"\"\"\n", " if pd.isna(value) or value is None:\n", " return None\n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip().lower()\n", " if \"female\" in value.lower() or \"f\" == value.lower() or \"woman\" in value.lower():\n", " return 0\n", " elif \"male\" in value.lower() or \"m\" == value.lower() or \"man\" in value.lower():\n", " return 1\n", " return None\n", "\n", "# Determine rows for trait, age, and gender based on clinical data\n", "if not clinical_data.empty:\n", " for i, char_label in enumerate(clinical_data['characteristic']):\n", " char_label_lower = char_label.lower()\n", " unique_values = clinical_data.iloc[i, 1:].unique()\n", " \n", " # Check for metabolic rate related information\n", " if any(term in char_label_lower for term in [\"metabolic\", \"metabolism\", \"energy expenditure\", \"resting energy\", \"resting metabolic\"]):\n", " if len(unique_values) > 1: # Ensure there's variation\n", " trait_row = i\n", " print(f\"Metabolic Rate data found in row {i}: {char_label}\")\n", " print(f\"Sample values: {unique_values[:3]}\")\n", " \n", " # Check for age information\n", " elif \"age\" in char_label_lower and len(unique_values) > 1:\n", " age_row = i\n", " print(f\"Age data found in row {i}: {char_label}\")\n", " print(f\"Sample values: {unique_values[:3]}\")\n", " \n", " # Check for gender/sex information\n", " elif any(term in char_label_lower for term in [\"gender\", \"sex\"]) and len(unique_values) > 1:\n", " gender_row = i\n", " print(f\"Gender data found in row {i}: {char_label}\")\n", " print(f\"Sample values: {unique_values[:3]}\")\n", "\n", "# Also look for trait information in the background if not found in clinical data\n", "if trait_row is None and background_info:\n", " # Check if there's any indication of metabolic rate measurements in the background\n", " if any(term in background_info.lower() for term in [\"metabolic rate\", \"energy expenditure\", \"resting energy\", \"resting metabolic\"]):\n", " print(\"\\nBackground information suggests metabolic rate data might be present, but not found in characteristics.\")\n", "\n", "# Save metadata about dataset usability\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 available\n", "if is_trait_available and not clinical_data.empty:\n", " # Extract clinical features using the provided function\n", " selected_clinical_df = geo_select_clinical_features(\n", " clinical_df=clinical_data,\n", " trait=trait,\n", " trait_row=trait_row,\n", " convert_trait=convert_trait,\n", " age_row=age_row,\n", " convert_age=convert_age if age_row is not None else\n" ] }, { "cell_type": "markdown", "id": "cd1f8945", "metadata": {}, "source": [ "### Step 4: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "c4a4d012", "metadata": {}, "outputs": [], "source": [ "```python\n", "import pandas as pd\n", "import os\n", "import json\n", "import numpy as np\n", "from typing import Optional, Callable, Dict, Any\n", "\n", "# First, let's check what files are available in the cohort directory\n", "print(f\"Checking files in directory: {in_cohort_dir}\")\n", "if os.path.exists(in_cohort_dir):\n", " files = os.listdir(in_cohort_dir)\n", " print(f\"Files found: {files}\")\n", "else:\n", " print(f\"Directory does not exist: {in_cohort_dir}\")\n", "\n", "# In GEO datasets, clinical data is typically found in a file with a name like GSE106800_series_matrix.txt\n", "# Let's try to find and load it\n", "matrix_files = [f for f in os.listdir(in_cohort_dir) if f.endswith('_series_matrix.txt')]\n", "\n", "if matrix_files:\n", " matrix_file = os.path.join(in_cohort_dir, matrix_files[0])\n", " print(f\"Found matrix file: {matrix_file}\")\n", " \n", " # Read the file to extract clinical data\n", " with open(matrix_file, 'r') as f:\n", " lines = f.readlines()\n", " \n", " # Extract sample characteristics from the matrix file\n", " sample_chars = {}\n", " row_index = 0\n", " \n", " for line in lines:\n", " if line.startswith('!Sample_characteristics_ch1'):\n", " parts = line.strip().split('\\t')\n", " parts = [p.replace('\"', '') for p in parts]\n", " \n", " if row_index not in sample_chars:\n", " sample_chars[row_index] = []\n", " \n", " # Skip the first element as it's the header\n", " sample_chars[row_index].extend(parts[1:])\n", " row_index += 1\n", " \n", " # Print sample characteristics for debugging\n", " print(\"\\nSample Characteristics:\")\n", " for key, values in sample_chars.items():\n", " print(f\"Key {key}: {values[:5] if len(values) > 5 else values}\")\n", " \n", " # Read the series description for background information\n", " background_info = \"\"\n", " for line in lines:\n", " if line.startswith('!Series_summary') or line.startswith('!Series_title') or line.startswith('!Series_overall_design'):\n", " background_info += line.strip() + \"\\n\"\n", " \n", " print(\"\\nBackground Info:\")\n", " print(background_info[:500] + \"...\" if len(background_info) > 500 else background_info)\n", " \n", " # Get unique values for each key in sample_chars\n", " unique_values = {}\n", " for key, values in sample_chars.items():\n", " unique_values[key] = list(set(values))\n", " print(f\"Key {key} unique values: {unique_values[key][:5] if len(unique_values[key]) > 5 else unique_values[key]}\")\n", " \n", " # Based on the background info and sample characteristics, determine data availability\n", " \n", " # 1. Gene Expression Data Availability\n", " # Default to True for GEO datasets, but we could check the platform info if needed\n", " is_gene_available = True\n", " \n", " # 2.1 Data Availability\n", " trait_row = None\n", " age_row = None\n", " gender_row = None\n", " \n", " # Look for relevant characteristics based on typical patterns\n", " for key, values in unique_values.items():\n", " values_str = ' '.join([str(v).lower() for v in values]).lower()\n", " \n", " # Check for metabolic rate related terms\n", " if any(term in values_str for term in ['metabolic', 'metabolism', 'energy', 'resting', 'bmr', 'rmr']):\n", " trait_row = key\n", " \n", " # Check for age related terms\n", " if any(term in values_str for term in ['age', 'year old']):\n", " age_row = key\n", " \n", " # Check for gender/sex related terms\n", " if any(term in values_str for term in ['gender', 'sex', 'male', 'female']):\n", " gender_row = key\n", " \n", " # 2.2 Data Type Conversion\n", " def extract_value_after_colon(text):\n", " \"\"\"Extract the value after colon if it exists.\"\"\"\n", " if isinstance(text, str) and ':' in text:\n", " return text.split(':', 1)[1].strip()\n", " return text\n", " \n", " def convert_trait(value):\n", " \"\"\"Convert metabolic rate values to a continuous or binary type.\"\"\"\n", " if value is None:\n", " return None\n", " \n", " value = extract_value_after_colon(value)\n", " \n", " # If the trait data is not found or trait_row is None, we can't convert\n", " if trait_row is None:\n", " return None\n", " \n", " # Convert to lowercase for case-insensitive matching\n", " value_lower = str(value).lower()\n", " \n", " # Try to extract a numeric value if possible\n", " try:\n", " # If direct numeric value is provided\n", " if isinstance(value, (int, float)):\n", " return float(value)\n", " \n", " # Check for numeric values in the string\n", " import re\n", " numbers = re.findall(r'\\d+\\.?\\d*', value_lower)\n", " if numbers:\n", " return float(numbers[0])\n", " \n", " # Handle categorical values\n", " if 'high' in value_lower or 'increased' in value_lower:\n", " return 1\n", " elif 'low' in value_lower or 'decreased' in value_lower:\n", " return 0\n", " elif 'normal' in value_lower:\n", " return 0.5\n", " \n", " except:\n", " pass\n", " \n", " return None\n", " \n", " def convert_age(value):\n", " \"\"\"Convert age values to a continuous type.\"\"\"\n", " if value is None or age_row is None:\n", " return None\n", " \n", " value = extract_value_after_colon(value)\n", " \n", " # Try to extract a numeric value for age\n", " try:\n", " # If direct numeric value is provided\n", " if isinstance(value, (int, float)):\n", " return float(value)\n", " \n", " # Extract numeric value from string\n", " import re\n", " numbers = re.findall(r'\\d+\\.?\\d*', str(value))\n", " if numbers:\n", " return float(numbers[0])\n", " except:\n", " pass\n", " \n", " return None\n", " \n", " def convert_gender(value):\n", " \"\"\"Convert gender values to binary (0 for female, 1 for male).\"\"\"\n", " if value is None or gender_row is None:\n", " return None\n", " \n", " value = extract_value_after_colon(value)\n", " \n", " # Convert to lowercase for case-insensitive matching\n", " value_lower = str(value).lower()\n", " \n", " if 'female' in value_lower or 'f' == value_lower:\n", " return 0\n", " elif 'male' in value_lower or 'm' == value_lower:\n", " return 1\n", " \n", " return None\n", " \n", " # Check if trait data is available\n", " is_trait_available = trait_row is not None\n", " \n", " # 3. 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 is_trait_available:\n", " # Create a DataFrame from the sample characteristics\n", " sample_ids = []\n", " \n", " # Find the sample IDs\n", " for line in lines:\n", " if line.startswith('!Sample_geo_accession'):\n", " sample_ids = line.strip().split('\\t')[1:]\n", " sample_ids = [id.replace('\"', '') for id in sample_ids]\n", " break\n", " \n", " if sample_ids:\n", " # Create clinical data DataFrame\n", " clinical_data = pd.DataFrame({'Sample': sample_ids})\n", " \n", " # Add characteristics to DataFrame\n", " for key, values in sample_chars.items():\n", " if len(values) == len(sample_ids):\n", " clinical_data[f'characteristic_{key}'] = values\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\n" ] }, { "cell_type": "markdown", "id": "11cba60b", "metadata": {}, "source": [ "### Step 5: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "37d04309", "metadata": {}, "outputs": [], "source": [ "# 1. First get the path to the soft and matrix files\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "\n", "# 2. Looking more carefully at the background information\n", "# This is a SuperSeries which doesn't contain direct gene expression data\n", "# Need to investigate the soft file to find the subseries\n", "print(\"This appears to be a SuperSeries. Looking at the SOFT file to find potential subseries:\")\n", "\n", "# Open the SOFT file to try to identify subseries\n", "with gzip.open(soft_file, 'rt') as f:\n", " subseries_lines = []\n", " for i, line in enumerate(f):\n", " if 'Series_relation' in line and 'SuperSeries of' in line:\n", " subseries_lines.append(line.strip())\n", " if i > 1000: # Limit search to first 1000 lines\n", " break\n", "\n", "# Display the subseries found\n", "if subseries_lines:\n", " print(\"Found potential subseries references:\")\n", " for line in subseries_lines:\n", " print(line)\n", "else:\n", " print(\"No subseries references found in the first 1000 lines of the SOFT file.\")\n", "\n", "# Despite trying to extract gene data, we expect it might fail because this is a SuperSeries\n", "try:\n", " gene_data = get_genetic_data(matrix_file)\n", " print(\"\\nGene data extraction result:\")\n", " print(\"Number of rows:\", len(gene_data))\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", " print(\"This confirms the dataset is a SuperSeries without direct gene expression data.\")\n" ] }, { "cell_type": "markdown", "id": "47105bb7", "metadata": {}, "source": [ "### Step 6: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": null, "id": "5ee2ffe5", "metadata": {}, "outputs": [], "source": [ "# These identifiers appear to be numerical probes, not human gene symbols\n", "# They are likely platform-specific identifiers (possibly Illumina or Agilent) that need to be mapped to gene symbols\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "92ea4927", "metadata": {}, "source": [ "### Step 7: Gene Annotation" ] }, { "cell_type": "code", "execution_count": null, "id": "cfb497e0", "metadata": {}, "outputs": [], "source": [ "# 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.\n", "gene_annotation = get_gene_annotation(soft_file)\n", "\n", "# 2. Use the 'preview_df' function from the library to preview the data and print out the results.\n", "print(\"Gene annotation preview:\")\n", "print(preview_df(gene_annotation))\n" ] }, { "cell_type": "markdown", "id": "4a846c7b", "metadata": {}, "source": [ "### Step 8: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": null, "id": "9f1a4a81", "metadata": {}, "outputs": [], "source": [ "# 1. Determine the appropriate columns for mapping\n", "# From examining the gene annotation data and the gene identifiers in the expression data,\n", "# it appears that the 'ID' column in gene_annotation corresponds to the probe identifiers\n", "# in gene_data, and 'gene_assignment' contains the gene symbols\n", "\n", "# Let's look at the first few rows of gene_data to confirm\n", "print(\"First 5 rows of gene expression data indices:\")\n", "print(gene_data.index[:5])\n", "\n", "# Check what's in the gene_assignment column - it contains gene symbols\n", "print(\"\\nSample of gene_assignment content:\")\n", "print(gene_annotation['gene_assignment'].iloc[2]) # Look at just one example\n", "\n", "# 2. Get gene mapping dataframe\n", "# Extract gene identifiers and gene symbols from the gene annotation\n", "gene_mapping = get_gene_mapping(gene_annotation, 'ID', 'gene_assignment')\n", "\n", "# Print info about the mapping\n", "print(\"\\nGene mapping shape:\", gene_mapping.shape)\n", "print(\"First few rows of gene mapping:\")\n", "print(gene_mapping.head())\n", "\n", "# 3. Convert probe-level measurements to gene expression data\n", "gene_data = apply_gene_mapping(gene_data, gene_mapping)\n", "\n", "# Print information about the resulting gene expression data\n", "print(\"\\nGene expression data shape:\", gene_data.shape)\n", "print(\"First 10 gene symbols:\", gene_data.index[:10].tolist())\n", "\n", "# Save gene expression data to 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": "8f3cf2bc", "metadata": {}, "source": [ "### Step 9: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": null, "id": "411290c0", "metadata": {}, "outputs": [], "source": [ "# 1. Normalize gene symbols in the gene expression data\n", "gene_data_normalized = normalize_gene_symbols_in_index(gene_data)\n", "print(f\"Shape of gene data after normalization: {gene_data_normalized.shape}\")\n", "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n", "gene_data_normalized.to_csv(out_gene_data_file)\n", "print(f\"Saved normalized gene data to {out_gene_data_file}\")\n", "\n", "# 2. Re-examine the clinical data from the matrix file\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 out the sample characteristics to verify available rows\n", "characteristics_dict = get_unique_values_by_row(clinical_data)\n", "print(\"Sample characteristics dictionary:\")\n", "print(characteristics_dict)\n", "\n", "# Define conversion functions for the clinical features based on the actual data\n", "def convert_trait(value):\n", " \"\"\"Convert treatment group to binary based on lycopene level (low=0, high=1).\"\"\"\n", " if not isinstance(value, str):\n", " return None\n", " \n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip().lower()\n", " \n", " if 'high lycopene' in value:\n", " return 1.0 # High lycopene\n", " elif 'low lycopene' in value:\n", " return 0.0 # Low lycopene\n", " else:\n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age data to continuous values.\"\"\"\n", " if not isinstance(value, str):\n", " return None\n", " \n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " try:\n", " return float(value)\n", " except (ValueError, TypeError):\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"Convert gender to binary (female=0, male=1).\"\"\"\n", " if not isinstance(value, str):\n", " return None\n", " \n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip().lower()\n", " \n", " if 'male' in value:\n", " return 1.0\n", " elif 'female' in value:\n", " return 0.0\n", " else:\n", " return None\n", "\n", "# Create the clinical dataframe using the correct row indices based on sample characteristics\n", "try:\n", " # Row 3 contains treatment group (high/low lycopene) - this is our trait of interest\n", " # Row 2 contains age information\n", " # Row 1 contains gender information\n", " clinical_df = geo_select_clinical_features(\n", " clinical_data,\n", " trait=\"Metabolic_Rate\", # Using this as the trait name as per variable definition\n", " trait_row=3, # Treatment group as the trait (based on lycopene levels)\n", " convert_trait=convert_trait,\n", " gender_row=1, # Gender information is available in row 1\n", " convert_gender=convert_gender,\n", " age_row=2, # Age information is available in row 2\n", " convert_age=convert_age\n", " )\n", " \n", " print(\"Clinical data preview:\")\n", " print(preview_df(clinical_df.T)) # Transpose for better viewing\n", " \n", " # Save the clinical data\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " clinical_df.to_csv(out_clinical_data_file)\n", " print(f\"Saved clinical data to {out_clinical_data_file}\")\n", " \n", " # 3. Link clinical and genetic data\n", " linked_data = geo_link_clinical_genetic_data(clinical_df, gene_data_normalized)\n", " print(f\"Shape of linked data: {linked_data.shape}\")\n", " \n", " # 4. Handle missing values in the linked data\n", " linked_data_cleaned = handle_missing_values(linked_data, 'Metabolic_Rate')\n", " print(f\"Shape of linked data after handling missing values: {linked_data_cleaned.shape}\")\n", " \n", " # 5. Check if the trait and demographic features are biased\n", " is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data_cleaned, 'Metabolic_Rate')\n", " \n", " # 6. Validate the dataset and save cohort information\n", " note = \"Dataset contains gene expression data from a study examining the effects of carotenoid-rich vegetables on metabolic syndrome in obese Japanese men. The trait variable is treatment group based on lycopene levels (0=Low lycopene, 1=High lycopene).\"\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_trait_biased,\n", " df=unbiased_linked_data,\n", " note=note\n", " )\n", " \n", " # 7. Save the linked data if it's usable\n", " if is_usable:\n", " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n", " unbiased_linked_data.to_csv(out_data_file)\n", " print(f\"Saved processed linked data to {out_data_file}\")\n", " else:\n", " print(\"Dataset validation failed. Final linked data not saved.\")\n", " \n", "except Exception as e:\n", " print(f\"Error in processing clinical data: {e}\")\n", " # If we failed to extract clinical data, update the 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=False,\n", " is_biased=None,\n", " df=pd.DataFrame(),\n", " note=\"Failed to extract clinical data. Gene expression data is available but missing trait information.\"\n", " )\n", " print(\"Dataset validation failed due to missing clinical data. Only gene data saved.\")" ] } ], "metadata": {}, "nbformat": 4, "nbformat_minor": 5 }