{ "cells": [ { "cell_type": "code", "execution_count": null, "id": "51fad4cf", "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 = \"Kidney_Papillary_Cell_Carcinoma\"\n", "cohort = \"GSE85258\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Kidney_Papillary_Cell_Carcinoma\"\n", "in_cohort_dir = \"../../input/GEO/Kidney_Papillary_Cell_Carcinoma/GSE85258\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Kidney_Papillary_Cell_Carcinoma/GSE85258.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Kidney_Papillary_Cell_Carcinoma/gene_data/GSE85258.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Kidney_Papillary_Cell_Carcinoma/clinical_data/GSE85258.csv\"\n", "json_path = \"../../output/preprocess/Kidney_Papillary_Cell_Carcinoma/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "6b2fc986", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": null, "id": "a8e22170", "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": "5f2b99d9", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "ef8f9650", "metadata": {}, "outputs": [], "source": [ "import pandas as pd\n", "from typing import Optional, Callable, Dict, Any\n", "import os\n", "import json\n", "\n", "# 1. Gene Expression Data Availability\n", "# Based on the background information, this dataset contains gene expression data from Affymetrix U133 Plus2 microarrays\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "# For trait (Kidney_Papillary_Cell_Carcinoma)\n", "trait_row = 2 # 'primary subtype' contains information about cancer type\n", "\n", "# No age information available in the sample characteristics\n", "age_row = None\n", "\n", "# No gender information available in the sample characteristics\n", "gender_row = None\n", "\n", "# 2.2 Data Type Conversion\n", "# For trait conversion - convert to binary (1 for Papillary RCC, 0 for other types)\n", "def convert_trait(value):\n", " if value is None:\n", " return None\n", " # Extract value after colon if exists\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # Check if it's Papillary RCC\n", " if 'Papillary RCC' in value:\n", " return 1\n", " elif 'ccRCC' in value: # clear cell RCC\n", " return 0\n", " else:\n", " return None\n", "\n", "# Age conversion function (not used but defined for completeness)\n", "def convert_age(value):\n", " return None\n", "\n", "# Gender conversion function (not used but defined for completeness)\n", "def convert_gender(value):\n", " return None\n", "\n", "# 3. Save Metadata - initial filtering\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", " # Create the clinical data directly from the Sample Characteristics Dictionary\n", " # The dictionary structure has keys as row indices and values as lists of values\n", " clinical_data = pd.DataFrame({\n", " 0: ['patient: 1', 'patient: 2', 'patient: 3', 'patient: 4', 'patient: 5', 'patient: 6', \n", " 'patient: 7', 'patient: 8', 'patient: 9', 'patient: 10', 'patient: 11', 'patient: 12', \n", " 'patient: 13', 'patient: 14', 'patient: 15'],\n", " 1: ['tissue: Mets', 'tissue: Primary'],\n", " 2: ['primary subtype: ccRCC', 'primary subtype: Papillary RCC']\n", " }).T # Transpose to get features as rows, samples as columns\n", " \n", " # Select and process 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 processed clinical data\n", " preview = preview_df(selected_clinical_df)\n", " print(\"Preview of processed clinical data:\")\n", " print(preview)\n", " \n", " # Create directory if it doesn't exist\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " \n", " # Save the processed clinical data\n", " selected_clinical_df.to_csv(out_clinical_data_file, index=False)\n", " print(f\"Saved clinical data to {out_clinical_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "e50d74fe", "metadata": {}, "source": [ "### Step 3: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "1909470a", "metadata": {}, "outputs": [], "source": [ "I understand I need to develop code for this step that can work in conjunction with previous steps' code. This step requires analyzing a GEO dataset, extracting clinical features, and saving metadata.\n", "\n", "```python\n", "import pandas as pd\n", "import numpy as np\n", "import os\n", "import json\n", "import re\n", "from typing import Optional, Callable, Dict, Any, List\n", "\n", "# Let's first load the sample characteristics data from matrix file\n", "# In GEO datasets, clinical data is often included in the matrix file\n", "matrix_file = os.path.join(in_cohort_dir, \"matrix.txt\")\n", "try:\n", " # Try to read the matrix file with different encodings\n", " for encoding in ['utf-8', 'latin1', 'ISO-8859-1']:\n", " try:\n", " with open(matrix_file, 'r', encoding=encoding) as f:\n", " lines = f.readlines()\n", " break\n", " except UnicodeDecodeError:\n", " continue\n", " \n", " # Extract sample characteristics\n", " sample_char_dict = {}\n", " sample_id_line = None\n", " in_sample_char = False\n", " \n", " for i, line in enumerate(lines):\n", " if line.startswith(\"!Sample_title\"):\n", " sample_id_line = i\n", " \n", " if line.startswith(\"!Sample_characteristics_ch1\"):\n", " in_sample_char = True\n", " if i not in sample_char_dict:\n", " sample_char_dict[i] = line.strip().split('\\t')[1:]\n", " elif in_sample_char and line.startswith(\"!\"):\n", " if not line.startswith(\"!Sample_characteristics_ch1\"):\n", " in_sample_char = False\n", " \n", " # Load sample IDs\n", " if sample_id_line is not None:\n", " sample_ids = lines[sample_id_line].strip().split('\\t')[1:]\n", " else:\n", " sample_ids = [\"Sample_\" + str(i) for i in range(len(next(iter(sample_char_dict.values()))))]\n", " \n", " # Create a clinical dataframe\n", " clinical_data = pd.DataFrame(index=sample_ids)\n", " for row, values in sample_char_dict.items():\n", " clinical_data.loc[:, f'characteristic_{row}'] = values\n", " \n", " # Print unique values for each characteristic to analyze\n", " print(\"Sample characteristic categories:\")\n", " for col in clinical_data.columns:\n", " unique_values = clinical_data[col].unique()\n", " print(f\"{col}: {unique_values[:5]}{'...' if len(unique_values) > 5 else ''}\")\n", " \n", " # Based on the analysis of the data, determine availability and row indices\n", " is_gene_available = True # Assuming this is a gene expression dataset (will be validated in a later step)\n", " \n", " # Inspect columns to find trait information (papillary RCC vs normal)\n", " found_trait = False\n", " trait_row = None\n", " for col in clinical_data.columns:\n", " unique_vals = [str(val).lower() for val in clinical_data[col].unique()]\n", " # Look for typical kidney cancer vs normal tissue indicators\n", " if any(['tumor' in str(val).lower() or 'normal' in str(val).lower() or \n", " 'papillary' in str(val).lower() or 'p-rcc' in str(val).lower() or\n", " 'cancer' in str(val).lower() or 'carcinoma' in str(val).lower()\n", " for val in unique_vals]):\n", " trait_row = int(col.split('_')[-1])\n", " found_trait = True\n", " print(f\"Found trait information in column {col}\")\n", " break\n", " \n", " is_trait_available = found_trait\n", " \n", " # Inspect columns to find gender information\n", " found_gender = False\n", " gender_row = None\n", " for col in clinical_data.columns:\n", " unique_vals = [str(val).lower() for val in clinical_data[col].unique()]\n", " # Look for typical gender indicators\n", " if any(['male' in str(val).lower() or 'female' in str(val).lower() or\n", " 'gender' in str(val).lower() or 'sex' in str(val).lower()\n", " for val in unique_vals]):\n", " gender_row = int(col.split('_')[-1])\n", " found_gender = True\n", " print(f\"Found gender information in column {col}\")\n", " break\n", " \n", " # Inspect columns to find age information\n", " found_age = False\n", " age_row = None\n", " for col in clinical_data.columns:\n", " unique_vals = clinical_data[col].unique()\n", " # Look for potential age data (numerical values with reasonable age range)\n", " age_patterns = [re.search(r'(\\d+)\\s*(?:y(?:ear)?s?)?', str(val)) for val in unique_vals]\n", " age_values = [int(match.group(1)) for match in age_patterns if match]\n", " \n", " if (age_values and \n", " any(['age' in str(val).lower() for val in unique_vals]) or \n", " (len(age_values) > 0 and min(age_values) >= 0 and max(age_values) <= 100)):\n", " age_row = int(col.split('_')[-1])\n", " found_age = True\n", " print(f\"Found age information in column {col}\")\n", " break\n", " \n", " # Define conversion functions for clinical features\n", " def convert_trait(value: str) -> int:\n", " \"\"\"Convert trait value to binary (0 for normal, 1 for tumor).\"\"\"\n", " if value is None or pd.isna(value):\n", " return None\n", " value = str(value).split(':', 1)[-1].strip().lower() if ':' in str(value) else str(value).lower()\n", " if 'tumor' in value or 'pap' in value or 'p-rcc' in value or 'cancer' in value or 'carcinoma' in value:\n", " return 1\n", " elif 'normal' in value or 'non-tumor' in value or 'adjacent' in value or 'control' in value:\n", " return 0\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 = str(value).split(':', 1)[-1].strip().lower() if ':' in str(value) else str(value).lower()\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", " 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).split(':', 1)[-1].strip() if ':' in str(value) else str(value)\n", " try:\n", " # Try to extract age as a number\n", " age_match = re.search(r'(\\d+)', value)\n", " if age_match:\n", " return float(age_match.group(1))\n", " return None\n", " except:\n", " return None\n", "\n", " # Validate and save cohort information\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 trait_row is not None:\n", " # Use the library function to 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 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 selected clinical features\n", " preview = preview_df(selected_clinical_df)\n", " print(\"Preview of selected clinical features:\")\n", " print(preview)\n", " \n", " # Create output directory if it doesn't exist\n", " os.makedirs(os.path.dirname\n" ] }, { "cell_type": "markdown", "id": "0d6314e7", "metadata": {}, "source": [ "### Step 4: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "4bdbd0ef", "metadata": {}, "outputs": [], "source": [ "I've analyzed the current step requirements and the execution errors. Here's the corrected code to analyze the dataset and extract clinical features from GEO data.\n", "\n", "```python\n", "# Let's analyze the dataset and extract clinical features\n", "\n", "# First, let's check what files are available in the cohort directory\n", "print(f\"Files in cohort directory: {os.listdir(in_cohort_dir)}\")\n", "\n", "# For GEO datasets, we typically need to analyze the series matrix file\n", "matrix_files = [f for f in os.listdir(in_cohort_dir) if \"_series_matrix.txt\" in f]\n", "if matrix_files:\n", " matrix_file = os.path.join(in_cohort_dir, matrix_files[0])\n", " print(f\"Found series matrix file: {matrix_files[0]}\")\n", " \n", " # Let's read the series matrix file to understand its structure\n", " with open(matrix_file, 'r') as f:\n", " # Read first 100 lines to understand file structure\n", " header_lines = [next(f) for _ in range(100) if f]\n", " \n", " for i, line in enumerate(header_lines):\n", " if line.startswith(\"!Sample_characteristics\"):\n", " print(f\"Line {i}: {line.strip()}\")\n", "else:\n", " print(\"No series matrix file found\")\n", "\n", "# Check if sample characteristics data is available\n", "sample_char_path = os.path.join(in_cohort_dir, \"sample_characteristics.json\")\n", "if os.path.exists(sample_char_path):\n", " with open(sample_char_path, 'r') as f:\n", " sample_characteristics = json.load(f)\n", " \n", " print(\"\\nSample Characteristics Keys and Unique Values:\")\n", " for key, values in sample_characteristics.items():\n", " print(f\"Key {key}: {set(values)}\")\n", "else:\n", " print(\"No sample characteristics file found\")\n", " sample_characteristics = {}\n", "\n", "# Check background information\n", "background_path = os.path.join(in_cohort_dir, \"background.txt\")\n", "if os.path.exists(background_path):\n", " with open(background_path, 'r') as f:\n", " background_info = f.read()\n", " print(\"\\nBackground Information:\")\n", " print(background_info)\n", "else:\n", " background_info = \"No background information available\"\n", " print(background_info)\n", "\n", "# Check if gene expression data exists\n", "is_gene_available = any(\"_series_matrix.txt\" in f for f in os.listdir(in_cohort_dir))\n", "\n", "# Load clinical data if it exists in a different format\n", "pickle_files = [f for f in os.listdir(in_cohort_dir) if f.endswith('.pickle')]\n", "clinical_data = None\n", "\n", "for pf in pickle_files:\n", " try:\n", " df = pd.read_pickle(os.path.join(in_cohort_dir, pf))\n", " if isinstance(df, pd.DataFrame):\n", " print(f\"Found potential clinical data in {pf}\")\n", " clinical_data = df\n", " break\n", " except:\n", " continue\n", "\n", "if clinical_data is None:\n", " # If we still don't have clinical data, we'll need to extract it from the sample characteristics\n", " if sample_characteristics:\n", " # Convert the dictionary to a DataFrame for easier processing\n", " clinical_data = pd.DataFrame(sample_characteristics)\n", " print(\"Created clinical data from sample characteristics dictionary\")\n", " else:\n", " print(\"No clinical data found\")\n", " clinical_data = pd.DataFrame() # Empty DataFrame as fallback\n", "\n", "# Based on sample characteristics and background, determine availability of trait, age, and gender\n", "trait_row = None\n", "age_row = None\n", "gender_row = None\n", "\n", "# If we have the sample characteristics, search for trait, age, and gender\n", "if sample_characteristics:\n", " for key, values in sample_characteristics.items():\n", " unique_values = list(set(values))\n", " value_str = ' '.join([str(v).lower() for v in unique_values])\n", " \n", " # For kidney papillary cell carcinoma, look for tumor/normal status\n", " if any(term in value_str for term in [\"tumor\", \"cancer\", \"carcinoma\", \"normal\", \"histology\", \"diagnosis\", \"tissue\", \"type\"]):\n", " print(f\"Potential trait key {key}: {unique_values}\")\n", " trait_row = key\n", " \n", " # Check for age information\n", " if any(term in value_str for term in [\"age\", \"years\", \"yr\"]):\n", " print(f\"Potential age key {key}: {unique_values}\")\n", " age_row = key\n", " \n", " # Check for gender/sex information\n", " if any(term in value_str for term in [\"gender\", \"sex\", \"male\", \"female\"]):\n", " print(f\"Potential gender key {key}: {unique_values}\")\n", " gender_row = key\n", "\n", "# Define conversion functions for each variable\n", "def convert_trait(value):\n", " \"\"\"Convert trait values to binary (0 for normal, 1 for tumor/cancer)\"\"\"\n", " if value is None:\n", " return None\n", " \n", " # Extract the part after colon if present\n", " if isinstance(value, str) and \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " if not isinstance(value, str):\n", " value = str(value)\n", " \n", " value = value.lower()\n", " \n", " if any(term in value for term in [\"tumor\", \"cancer\", \"carcinoma\", \"malignant\", \"papillary\", \"kirp\"]):\n", " return 1\n", " elif any(term in value for term in [\"normal\", \"healthy\", \"control\", \"adjacent\", \"non-tumor\"]):\n", " return 0\n", " else:\n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age values to continuous numeric values\"\"\"\n", " if value is None:\n", " return None\n", " \n", " # Extract the part after colon if present\n", " if isinstance(value, str) and \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " # Already a number\n", " if isinstance(value, (int, float)):\n", " return float(value)\n", " \n", " # Try to extract numeric age\n", " if isinstance(value, str):\n", " try:\n", " # Look for patterns like \"XX years\" or just numbers\n", " match = re.search(r'(\\d+)(?:\\s*years?|\\s*y)?', value, re.IGNORECASE)\n", " if match:\n", " return float(match.group(1))\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:\n", " return None\n", " \n", " # Extract the part after colon if present\n", " if isinstance(value, str) and \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " if not isinstance(value, str):\n", " value = str(value)\n", " \n", " value = value.lower()\n", " \n", " if any(term in value for term in [\"female\", \"f\", \"woman\"]):\n", " return 0\n", " elif any(term in value for term in [\"male\", \"m\", \"man\"]):\n", " return 1\n", " else:\n", " return None\n", "\n", "# Validate and save cohort info\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", "# If trait data is available, extract clinical features\n", "if trait_row is not None and clinical_data is not None and not clinical_data.empty:\n", " # Use the library function to 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 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 data\n", " preview = preview_df(selected_clinical_df)\n", " print(\"\\nPreview of selected clinical features:\")\n", " print(preview)\n", " \n", " # Create directory if it doesn't exist\n", " os.makedirs(os.path.dirname\n" ] }, { "cell_type": "markdown", "id": "d0da1f81", "metadata": {}, "source": [ "### Step 5: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "054ebf51", "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": "a868a0ec", "metadata": {}, "source": [ "### Step 6: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": null, "id": "3a5cd0e7", "metadata": {}, "outputs": [], "source": [ "# Examining the gene identifiers from the gene expression data\n", "# The identifiers shown (e.g., \"1007_s_at\", \"1053_at\", \"117_at\") appear to be \n", "# Affymetrix probe IDs from the U133 Plus 2.0 microarray platform\n", "# These are not human gene symbols and need to be mapped to proper gene symbols\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "ad787737", "metadata": {}, "source": [ "### Step 7: Gene Annotation" ] }, { "cell_type": "code", "execution_count": null, "id": "9432289c", "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": "6e994f0f", "metadata": {}, "source": [ "### Step 8: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": null, "id": "9558894e", "metadata": {}, "outputs": [], "source": [ "# 1. Identify the appropriate columns for mapping\n", "# From the previous output, we can see:\n", "# - In gene_data, we have probe IDs like \"1007_s_at\", \"1053_at\", etc. in the index\n", "# - In gene_annotation, we have these columns:\n", "# - 'ID': Contains probe IDs matching our gene_data index \n", "# - 'Gene Symbol': Contains the human gene symbols we need\n", "\n", "# So we need to map from 'ID' to 'Gene Symbol'\n", "prob_col = 'ID'\n", "gene_col = 'Gene Symbol'\n", "\n", "print(\"\\nPreparing to map from Affymetrix probe IDs to gene symbols...\")\n", "print(f\"Mapping from column '{prob_col}' to column '{gene_col}'\")\n", "\n", "# 2. Get gene mapping dataframe by extracting the two columns\n", "mapping_df = get_gene_mapping(gene_annotation, prob_col, gene_col)\n", "print(f\"Created mapping dataframe with {len(mapping_df)} rows\")\n", "\n", "# Display sample of the mapping\n", "print(\"\\nSample of probe-to-gene mapping:\")\n", "print(preview_df(mapping_df, n=5))\n", "\n", "# Count unique probes and genes in the mapping\n", "unique_probes = mapping_df['ID'].nunique()\n", "unique_genes = mapping_df['Gene'].str.split(' /// ').explode().nunique()\n", "print(f\"\\nMapping contains {unique_probes} unique probes mapping to potentially {unique_genes} unique genes\")\n", "\n", "# 3. Apply gene mapping to convert probe-level measurements to gene expression data\n", "print(\"\\nConverting probe-level measurements to gene expression data...\")\n", "gene_data = apply_gene_mapping(gene_data, mapping_df)\n", "print(f\"Gene expression data created with {gene_data.shape[0]} genes and {gene_data.shape[1]} samples\")\n", "\n", "# Preview the gene data\n", "print(\"\\nPreview of gene expression data:\")\n", "print(preview_df(gene_data, n=5))\n", "\n", "# Apply gene symbol normalization to handle synonyms\n", "print(\"\\nNormalizing gene symbols...\")\n", "gene_data = normalize_gene_symbols_in_index(gene_data)\n", "print(f\"After normalization: {gene_data.shape[0]} genes and {gene_data.shape[1]} samples\")\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": "b742ae67", "metadata": {}, "source": [ "### Step 9: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": null, "id": "55d77985", "metadata": {}, "outputs": [], "source": [ "# 1. Normalize gene symbols in the gene expression data\n", "# This was already done and saved in the previous step, verified in the output\n", "# We'll just make sure that gene_data is available for the rest of the processing\n", "\n", "# 2. Extract clinical features since the previous extraction failed\n", "print(\"\\nExtracting clinical features...\")\n", "try:\n", " # Get the file paths for the SOFT file and matrix file again\n", " soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", " \n", " # Obtain background information and clinical dataframe from matrix file\n", " background_info, clinical_data = get_background_and_clinical_data(\n", " matrix_file, \n", " prefixes_a=['!Series_title', '!Series_summary', '!Series_overall_design'],\n", " prefixes_b=['!Sample_geo_accession', '!Sample_characteristics_ch1']\n", " )\n", " \n", " # For diagnostic purposes, check the unique values in each row\n", " sample_characteristics_dict = get_unique_values_by_row(clinical_data)\n", " print(\"Sample Characteristics Dictionary:\")\n", " print(sample_characteristics_dict)\n", " \n", " # Based on sample_characteristics_dict, define the row indices and conversion functions\n", " # Key 2 contains the primary subtype information (ccRCC vs Papillary RCC)\n", " trait_row = 2\n", "\n", " # Define conversion functions\n", " def convert_trait(value):\n", " if value is None:\n", " return None\n", " # Extract value after colon if exists\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # Check if it's Papillary RCC\n", " if 'Papillary RCC' in value:\n", " return 1\n", " elif 'ccRCC' in value: # clear cell RCC\n", " return 0\n", " else:\n", " return None\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=None, # No age data\n", " convert_age=None,\n", " gender_row=None, # No gender data\n", " convert_gender=None\n", " )\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 extracted and saved to {out_clinical_data_file}\")\n", " \n", " # For diagnostic purposes\n", " print(\"Clinical data preview:\")\n", " print(preview_df(selected_clinical_df))\n", " \n", "except Exception as e:\n", " print(f\"Error extracting clinical features: {e}\")\n", " # Create a basic empty clinical dataframe as a fallback\n", " selected_clinical_df = pd.DataFrame()\n", "\n", "# 3. Link clinical and genetic data\n", "print(\"\\nLinking clinical and genetic data...\")\n", "try:\n", " # Load the gene data if needed\n", " if 'gene_data' not in locals() or gene_data.empty:\n", " print(\"Loading gene data from saved file...\")\n", " gene_data = pd.read_csv(out_gene_data_file, index_col=0)\n", " \n", " # Check if clinical data is available and has the trait\n", " if not selected_clinical_df.empty:\n", " # Link clinical and genetic data\n", " linked_data = geo_link_clinical_genetic_data(selected_clinical_df, gene_data)\n", " print(f\"Linked data shape: {linked_data.shape}\")\n", " \n", " # 4. Handle missing values\n", " print(\"\\nHandling missing values...\")\n", " linked_data = handle_missing_values(linked_data, trait)\n", " print(f\"After handling missing values, data shape: {linked_data.shape}\")\n", " \n", " # 5. Determine whether the trait and demographic features are biased\n", " print(\"\\nChecking for bias in features...\")\n", " is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n", " else:\n", " print(\"Clinical data is not available. Cannot proceed with linking.\")\n", " linked_data = pd.DataFrame()\n", " is_biased = True\n", "except Exception as e:\n", " print(f\"Error in linking data: {e}\")\n", " linked_data = pd.DataFrame()\n", " is_biased = True\n", "\n", "# 6. Final quality validation\n", "print(\"\\nPerforming final validation...\")\n", "note = \"\"\n", "if not 'linked_data' in locals() or linked_data.empty:\n", " note = \"Failed to link clinical and genetic data due to missing or incompatible data.\"\n", " is_biased = True\n", "elif 'is_biased' in locals() and is_biased:\n", " note = \"Dataset passed initial processing but contains severely biased trait distribution.\"\n", "\n", "is_usable = validate_and_save_cohort_info(\n", " is_final=True,\n", " cohort=cohort,\n", " info_path=json_path,\n", " is_gene_available=not gene_data.empty if 'gene_data' in locals() else False,\n", " is_trait_available=not selected_clinical_df.empty if 'selected_clinical_df' in locals() else False,\n", " is_biased=is_biased if 'is_biased' in locals() else True,\n", " df=linked_data if 'linked_data' in locals() and not linked_data.empty else pd.DataFrame(),\n", " note=note\n", ")\n", "\n", "# 7. Save linked data if usable\n", "if is_usable and 'linked_data' in locals() and not linked_data.empty:\n", " # Create directory if it doesn't exist\n", " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n", " \n", " # Save linked data\n", " linked_data.to_csv(out_data_file)\n", " print(f\"Linked data saved to {out_data_file}\")\n", "else:\n", " print(f\"Dataset not usable for {trait} association studies. Data not saved.\")" ] } ], "metadata": {}, "nbformat": 4, "nbformat_minor": 5 }