{ "cells": [ { "cell_type": "code", "execution_count": null, "id": "6ce0b3f3", "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 = \"Retinoblastoma\"\n", "cohort = \"GSE110811\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Retinoblastoma\"\n", "in_cohort_dir = \"../../input/GEO/Retinoblastoma/GSE110811\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Retinoblastoma/GSE110811.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Retinoblastoma/gene_data/GSE110811.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Retinoblastoma/clinical_data/GSE110811.csv\"\n", "json_path = \"../../output/preprocess/Retinoblastoma/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "d5da374d", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": null, "id": "3d3c6f4a", "metadata": {}, "outputs": [], "source": [ "# 1. Let's first list the directory contents to understand what files are available\n", "import os\n", "\n", "print(\"Files in the cohort directory:\")\n", "files = os.listdir(in_cohort_dir)\n", "print(files)\n", "\n", "# Adapt file identification to handle different naming patterns\n", "soft_files = [f for f in files if 'soft' in f.lower() or '.soft' in f.lower() or '_soft' in f.lower()]\n", "matrix_files = [f for f in files if 'matrix' in f.lower() or '.matrix' in f.lower() or '_matrix' in f.lower()]\n", "\n", "# If no files with these patterns are found, look for alternative file types\n", "if not soft_files:\n", " soft_files = [f for f in files if f.endswith('.txt') or f.endswith('.gz')]\n", "if not matrix_files:\n", " matrix_files = [f for f in files if f.endswith('.txt') or f.endswith('.gz')]\n", "\n", "print(\"Identified SOFT files:\", soft_files)\n", "print(\"Identified matrix files:\", matrix_files)\n", "\n", "# Use the first files found, if any\n", "if len(soft_files) > 0 and len(matrix_files) > 0:\n", " soft_file = os.path.join(in_cohort_dir, soft_files[0])\n", " matrix_file = os.path.join(in_cohort_dir, matrix_files[0])\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(\"\\nBackground Information:\")\n", " print(background_info)\n", " print(\"\\nSample Characteristics Dictionary:\")\n", " print(sample_characteristics_dict)\n", "else:\n", " print(\"No appropriate files found in the directory.\")\n" ] }, { "cell_type": "markdown", "id": "e62e0e81", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "35e40274", "metadata": {}, "outputs": [], "source": [ "# 1. Gene Expression Data Availability\n", "# Based on background information, this dataset contains microarray data (gene expression profiles)\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "# For trait (Retinoblastoma): The tissue is already identified in row 0, but we're interested in anaplasia grade\n", "trait_row = 1 # anaplasia grade is our trait of interest\n", "age_row = None # Age information is not available\n", "gender_row = None # Gender information is not available\n", "\n", "# 2.2 Data Type Conversion\n", "def convert_trait(value):\n", " if pd.isna(value):\n", " return None\n", " \n", " # If value contains a colon, extract the part after the colon\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # Convert anaplasia grades to binary (Severe vs Others)\n", " if 'severe' in value.lower():\n", " return 1 # Severe anaplasia\n", " elif 'mild' in value.lower() or 'moderate' in value.lower():\n", " return 0 # Mild or Moderate anaplasia\n", " else:\n", " return None # For normal retina or retinocytoma or unknown values\n", "\n", "# No age data to convert\n", "def convert_age(value):\n", " return None\n", "\n", "# No gender data to convert\n", "def convert_gender(value):\n", " return None\n", "\n", "# 3. Save Metadata\n", "# Conduct initial filtering based on trait and gene availability\n", "is_trait_available = trait_row is not None\n", "validate_and_save_cohort_info(\n", " is_final=False, \n", " cohort=cohort, \n", " info_path=json_path, \n", " is_gene_available=is_gene_available, \n", " is_trait_available=is_trait_available\n", ")\n", "\n", "# 4. Clinical Feature Extraction\n", "if trait_row is not None:\n", " # We need to read the sample characteristics data correctly\n", " # Let's load the GEO matrix file and extract sample characteristics\n", " import gzip\n", " \n", " # Function to parse the GEO matrix file for sample characteristics\n", " def extract_sample_characteristics(matrix_file):\n", " sample_chars = {}\n", " samples = []\n", " \n", " with gzip.open(matrix_file, 'rt') as f:\n", " line_idx = 0\n", " in_sample_section = False\n", " \n", " for line in f:\n", " line = line.strip()\n", " \n", " # Find the sample section\n", " if line.startswith('!Sample_geo_accession'):\n", " in_sample_section = True\n", " samples = line.split('\\t')[1:]\n", " continue\n", " \n", " # Process sample characteristics\n", " if in_sample_section and line.startswith('!Sample_characteristics_ch1'):\n", " values = line.split('\\t')[1:]\n", " unique_values = list(set(values))\n", " sample_chars[line_idx] = unique_values\n", " line_idx += 1\n", " \n", " # End of sample section\n", " if in_sample_section and line.startswith('!Sample_data_row_count'):\n", " break\n", " \n", " # Create a DataFrame for sample characteristics\n", " clinical_df = pd.DataFrame()\n", " for idx, samples_values in sample_chars.items():\n", " for val in samples_values:\n", " if pd.isna(val):\n", " continue\n", " characteristic = val.split(':', 1)[0].strip() if ':' in val else val\n", " clinical_df.loc[idx, 'characteristic'] = characteristic\n", " clinical_df.loc[idx, 'values'] = [val for val in samples_values if not pd.isna(val)]\n", " \n", " return clinical_df, samples, sample_chars\n", " \n", " # Extract sample characteristics from the matrix file\n", " matrix_file = os.path.join(in_cohort_dir, \"GSE110811_series_matrix.txt.gz\")\n", " clinical_df, samples, sample_chars = extract_sample_characteristics(matrix_file)\n", " \n", " # Create full clinical data DataFrame for all samples\n", " full_clinical_data = pd.DataFrame(index=samples)\n", " \n", " # Process sample characteristics into proper format for geo_select_clinical_features\n", " for idx, values in sample_chars.items():\n", " sample_values = {}\n", " for i, sample in enumerate(samples):\n", " value_idx = min(i, len(values) - 1) if i < len(values) else 0\n", " sample_values[sample] = values[value_idx] if value_idx < len(values) else None\n", " \n", " full_clinical_data[idx] = pd.Series(sample_values)\n", " \n", " # Extract clinical features\n", " selected_clinical_df = geo_select_clinical_features(\n", " clinical_df=full_clinical_data,\n", " trait=\"Anaplasia\", # Using a more specific trait name based on the data\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 data\n", " preview = preview_df(selected_clinical_df)\n", " print(\"Preview of selected clinical features:\")\n", " print(preview)\n", " \n", " # Save the clinical data\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " selected_clinical_df.to_csv(out_clinical_data_file, index=False)\n", " print(f\"Clinical data saved to {out_clinical_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "7233658f", "metadata": {}, "source": [ "### Step 3: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "792d4d18", "metadata": {}, "outputs": [], "source": [ "I'll implement a clean, complete solution for Step 3:\n", "\n", "```python\n", "# First, let's look at the GSE data and series matrix file to understand the dataset\n", "import os\n", "import pandas as pd\n", "import numpy as np\n", "import json\n", "from typing import Dict, Any, Callable, Optional\n", "\n", "# Let's check the directory structure and files\n", "files = os.listdir(in_cohort_dir)\n", "print(f\"Files in {in_cohort_dir}:\")\n", "for file in files:\n", " print(f\" {file}\")\n", "\n", "# Load the series matrix file if it exists (it should be named with a \"series_matrix\" in the filename)\n", "series_matrix_files = [f for f in files if \"series_matrix\" in f.lower()]\n", "\n", "if series_matrix_files:\n", " series_matrix_file = os.path.join(in_cohort_dir, series_matrix_files[0])\n", " \n", " # Load the data using pandas read_csv, which can handle most text-based formats\n", " try:\n", " # We need to get sample characteristics which are typically in the file header\n", " sample_chars = {}\n", " with open(series_matrix_file, 'r') as f:\n", " reading_chars = False\n", " char_index = 0\n", " for line in f:\n", " if line.startswith('!Sample_characteristics_ch1'):\n", " reading_chars = True\n", " sample_chars[char_index] = line.strip().split('\\t')[1:]\n", " char_index += 1\n", " elif reading_chars and not line.startswith('!Sample_characteristics_ch1'):\n", " reading_chars = False\n", " \n", " # Also check for gene expression data indicator\n", " if \"!dataset_platform = \" in line:\n", " platform = line.strip().split('= ')[1]\n", " print(f\"Platform: {platform}\")\n", " \n", " # Get background information\n", " if \"!Series_summary\" in line:\n", " summary = line.strip().split('= ')[1]\n", " print(f\"Series summary: {summary}\")\n", " \n", " # Look for gene expression data indication\n", " if \"!Series_type = \" in line:\n", " series_type = line.strip().split('= ')[1]\n", " print(f\"Series type: {series_type}\")\n", " \n", " # Sample info\n", " if \"!Sample_title\" in line:\n", " sample_titles = line.strip().split('\\t')[1:]\n", " print(f\"Sample titles: {sample_titles}\")\n", " \n", " # Print sample characteristics for analysis\n", " print(\"\\nSample characteristics:\")\n", " for idx, chars in sample_chars.items():\n", " unique_values = set(chars)\n", " print(f\"Row {idx}: {list(unique_values)[:5]} {'...' if len(unique_values) > 5 else ''} (Unique values: {len(unique_values)})\")\n", "\n", " except Exception as e:\n", " print(f\"Error reading series matrix file: {e}\")\n", "else:\n", " print(\"No series matrix file found in the directory.\")\n", "\n", "# Now let's determine gene expression availability\n", "# Based on platform info - assuming gene expression data is available unless proven otherwise\n", "is_gene_available = True # Will be updated based on platform/series_type if needed\n", "\n", "# For clinical data extraction, we'll create conversion functions\n", "def convert_trait(value):\n", " \"\"\"Convert trait value to binary (0 for non-case, 1 for case)\"\"\"\n", " if value is None:\n", " return None\n", " \n", " # Extract value after colon if present\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # Retinoblastoma specific conversion\n", " value = value.lower()\n", " if 'retinoblastoma' in value or 'rb' in value or 'tumor' in value or 'cancer' in value:\n", " return 1\n", " elif 'normal' in value or 'control' in value or 'healthy' in value:\n", " return 0\n", " else:\n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age value to numeric (continuous)\"\"\"\n", " if value is None:\n", " return None\n", " \n", " # Extract value after colon if present\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # Try to extract numeric age\n", " try:\n", " # Look for patterns like \"X years\" or \"X months\"\n", " if 'year' in value.lower():\n", " age = float(value.lower().split('year')[0].strip())\n", " return age\n", " elif 'month' in value.lower():\n", " age = float(value.lower().split('month')[0].strip()) / 12\n", " return age\n", " elif 'day' in value.lower():\n", " age = float(value.lower().split('day')[0].strip()) / 365\n", " return age\n", " else:\n", " # Try direct conversion\n", " return float(value.strip())\n", " except:\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"Convert gender value to binary (0 for female, 1 for male)\"\"\"\n", " if value is None:\n", " return None\n", " \n", " # Extract value after colon if present\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " value = 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", " else:\n", " return None\n", "\n", "# Based on the output analysis, we'll determine the row indices and data availability\n", "trait_row = None\n", "age_row = None\n", "gender_row = None\n", "\n", "# After analyzing the output, update the variable assignments and continue with processing\n", "if 'sample_chars' in locals() and sample_chars:\n", " # Convert sample_chars to DataFrame for processing\n", " clinical_df = pd.DataFrame(sample_chars).T\n", " \n", " # Analyze each row in sample_chars to find trait, age, and gender information\n", " for idx, values in sample_chars.items():\n", " unique_values = list(set(values))\n", " values_str = ' '.join([str(v).lower() for v in unique_values])\n", " \n", " # Check for trait information\n", " if any('retinoblastoma' in str(v).lower() or 'rb' in str(v).lower() or \n", " 'tumor' in str(v).lower() or 'normal' in str(v).lower() or \n", " 'control' in str(v).lower() for v in unique_values):\n", " trait_row = idx\n", " \n", " # Check for age information\n", " if any('age' in str(v).lower() or 'year' in str(v).lower() or \n", " 'month' in str(v).lower() for v in unique_values):\n", " age_row = idx\n", " \n", " # Check for gender information\n", " if any('gender' in str(v).lower() or 'sex' in str(v).lower() or \n", " 'male' in str(v).lower() or 'female' in str(v).lower() \n", " for v in unique_values):\n", " gender_row = idx\n", " \n", " # Determine trait data availability\n", " is_trait_available = trait_row is not None\n", " \n", " # Save the initial validation 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", " # If trait data is available, extract clinical features\n", " if is_trait_available:\n", " # Extract clinical features\n", " selected_clinical_df = geo_select_clinical_features(\n", " clinical_df=clinical_df,\n", " trait=trait,\n", " trait_row=trait_row,\n", " convert_trait=convert_trait,\n", " age_row=age_row,\n", " convert_age=convert_age 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(\"Preview of selected clinical data:\")\n", " print(preview)\n", " \n", " # Save the clinical data to CSV\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " selected_clinical_df\n" ] }, { "cell_type": "markdown", "id": "9875013e", "metadata": {}, "source": [ "### Step 4: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "8bf1d8f3", "metadata": {}, "outputs": [], "source": [ "# Use the helper function to get the proper file paths\n", "soft_file_path, matrix_file_path = geo_get_relevant_filepaths(in_cohort_dir)\n", "\n", "# Extract gene expression data\n", "try:\n", " gene_data = get_genetic_data(matrix_file_path)\n", " \n", " # Print the first 20 row IDs (gene or probe identifiers)\n", " print(\"First 20 gene/probe identifiers:\")\n", " print(gene_data.index[:20])\n", " \n", " # Print shape to understand the dataset dimensions\n", " print(f\"\\nGene expression data shape: {gene_data.shape}\")\n", " \n", "except Exception as e:\n", " print(f\"Error extracting gene data: {e}\")\n" ] }, { "cell_type": "markdown", "id": "77908afe", "metadata": {}, "source": [ "### Step 5: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": null, "id": "5690949a", "metadata": {}, "outputs": [], "source": [ "# These identifiers are numerical and don't match the pattern of human gene symbols\n", "# Human gene symbols typically have a format like \"BRCA1\", \"TP53\", etc.\n", "# These appear to be probe IDs or feature IDs from a microarray platform that need mapping\n", "\n", "# Based on my biomedical knowledge, these are not standard human gene symbols\n", "# They appear to be probe identifiers (likely Affymetrix or another platform)\n", "# We will need to map these identifiers to proper gene symbols\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "be43f1dd", "metadata": {}, "source": [ "### Step 6: Gene Annotation" ] }, { "cell_type": "code", "execution_count": null, "id": "93f3c330", "metadata": {}, "outputs": [], "source": [ "# 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.\n", "try:\n", " # Use the correct variable name from previous steps\n", " gene_annotation = get_gene_annotation(soft_file_path)\n", " \n", " # 2. Preview the gene annotation dataframe\n", " print(\"Gene annotation preview:\")\n", " print(preview_df(gene_annotation))\n", " \n", "except UnicodeDecodeError as e:\n", " print(f\"Unicode decoding error: {e}\")\n", " print(\"Trying alternative approach...\")\n", " \n", " # Read the file with Latin-1 encoding which is more permissive\n", " import gzip\n", " import pandas as pd\n", " \n", " # Manually read the file line by line with error handling\n", " data_lines = []\n", " with gzip.open(soft_file_path, 'rb') as f:\n", " for line in f:\n", " # Skip lines starting with prefixes we want to filter out\n", " line_str = line.decode('latin-1')\n", " if not line_str.startswith('^') and not line_str.startswith('!') and not line_str.startswith('#'):\n", " data_lines.append(line_str)\n", " \n", " # Create dataframe from collected lines\n", " if data_lines:\n", " gene_data_str = '\\n'.join(data_lines)\n", " gene_annotation = pd.read_csv(pd.io.common.StringIO(gene_data_str), sep='\\t', low_memory=False)\n", " print(\"Gene annotation preview (alternative method):\")\n", " print(preview_df(gene_annotation))\n", " else:\n", " print(\"No valid gene annotation data found after filtering.\")\n", " gene_annotation = pd.DataFrame()\n", " \n", "except Exception as e:\n", " print(f\"Error extracting gene annotation data: {e}\")\n", " gene_annotation = pd.DataFrame()\n" ] }, { "cell_type": "markdown", "id": "9fd4c67d", "metadata": {}, "source": [ "### Step 7: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": null, "id": "e98da254", "metadata": {}, "outputs": [], "source": [ "# First, re-extract the gene annotation data from the SOFT file\n", "gene_annotation = get_gene_annotation(soft_file_path)\n", "print(f\"Gene annotation data shape: {gene_annotation.shape}\")\n", "\n", "# 1. Identify which columns to use from the gene annotation data\n", "print(\"Checking annotation columns for mapping information...\")\n", "\n", "# Display all column names to find potential gene symbol columns\n", "print(\"All available columns in gene annotation:\")\n", "print(list(gene_annotation.columns))\n", "\n", "# Check a sample of rows to see what other columns might contain gene information\n", "print(\"\\nSample row from annotation data:\")\n", "sample_row = gene_annotation.iloc[100].to_dict()\n", "for key, value in sample_row.items():\n", " print(f\"{key}: {value}\")\n", "\n", "# Let's try to find columns that might contain gene symbols or IDs\n", "potential_gene_cols = []\n", "for col in gene_annotation.columns:\n", " # Look for column names that might suggest gene information\n", " if any(term in col.lower() for term in ['gene', 'symbol', 'name', 'title', 'description']):\n", " non_nan = gene_annotation[col].notna().sum()\n", " total = len(gene_annotation)\n", " print(f\"Column {col}: {non_nan}/{total} non-null values ({non_nan/total:.2%})\")\n", " potential_gene_cols.append(col)\n", "\n", "# Function to extract gene names from location or accession information\n", "def extract_gene_info(row):\n", " \"\"\"Attempt to extract gene information from various fields\"\"\"\n", " # Try GB_ACC first as it's a direct link to gene identifiers\n", " if pd.notna(row.get('GB_ACC')):\n", " return row['GB_ACC']\n", " \n", " # Return None if no gene info found\n", " return None\n", "\n", "# Add a Gene column to our annotation by combining information from multiple sources\n", "gene_annotation['Gene'] = gene_annotation.apply(extract_gene_info, axis=1)\n", "\n", "# How many genes did we successfully identify?\n", "gene_count = gene_annotation['Gene'].notna().sum()\n", "print(f\"\\nIdentified {gene_count} genes out of {len(gene_annotation)} rows ({gene_count/len(gene_annotation):.2%})\")\n", "\n", "# 2. Get gene mapping dataframe using the ID column and our newly created Gene column\n", "prob_col = 'ID'\n", "gene_col = 'Gene'\n", "\n", "# Filter out rows without gene information\n", "gene_annotation_filtered = gene_annotation.dropna(subset=[gene_col])\n", "print(f\"After filtering, {len(gene_annotation_filtered)} rows with gene information remain\")\n", "\n", "mapping_df = gene_annotation_filtered[[prob_col, gene_col]].copy()\n", "mapping_df = mapping_df.astype({prob_col: 'str'})\n", "\n", "# Print mapping information\n", "print(f\"Generated mapping for {len(mapping_df)} probes\")\n", "print(\"First few rows of mapping data:\")\n", "print(mapping_df.head())\n", "\n", "# 3. Apply gene mapping to convert probe-level data to gene expression data\n", "gene_data = apply_gene_mapping(gene_data, mapping_df)\n", "\n", "# Print information about the resulting gene expression data\n", "print(f\"\\nMapped gene expression data shape: {gene_data.shape}\")\n", "if not gene_data.empty:\n", " print(\"First few gene symbols:\")\n", " print(gene_data.index[:10])\n", " \n", " # Let's check for rows with NaN values\n", " nan_count = gene_data.isna().sum().sum()\n", " print(f\"Total NaN values in gene expression data: {nan_count}\")\n", "else:\n", " print(\"WARNING: Gene mapping resulted in empty dataframe\")\n", " \n", " # If gene mapping failed, let's try direct comparison between IDs\n", " # This is a fallback approach in case the annotation doesn't provide good mapping\n", " common_ids = set(gene_data.index) & set(mapping_df['ID'])\n", " print(f\"Number of probe IDs in common between expression data and mapping: {len(common_ids)}\")\n", " \n", " # If the dataset really doesn't have good mapping, we might need to use the probe IDs directly\n", " if len(common_ids) > 0:\n", " print(\"Some probe IDs match between expression and annotation data\")\n", " else:\n", " print(\"No matching probe IDs found between expression and annotation data\")\n" ] }, { "cell_type": "markdown", "id": "0d1b434a", "metadata": {}, "source": [ "### Step 8: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": null, "id": "f3ac4ce8", "metadata": {}, "outputs": [], "source": [ "# First, get the file paths again to ensure they're defined\n", "soft_file_path, matrix_file_path = geo_get_relevant_filepaths(in_cohort_dir)\n", "\n", "# 1. Load gene expression data \n", "gene_data = get_genetic_data(matrix_file_path)\n", "print(f\"Gene expression data shape: {gene_data.shape}\")\n", "\n", "# 2. Extract gene annotation data\n", "gene_annotation = get_gene_annotation(soft_file_path)\n", "print(f\"Gene annotation data shape: {gene_annotation.shape}\")\n", "\n", "# 3. Examine the gene annotation data and determine which columns to use for mapping\n", "print(\"Column names in gene annotation:\")\n", "print(list(gene_annotation.columns))\n", "\n", "# Compare example IDs from gene_data and annotation to check for format inconsistencies\n", "print(\"\\nSample probe IDs from gene_data:\")\n", "print(list(gene_data.index[:5]))\n", "print(\"\\nSample probe IDs from gene_annotation:\")\n", "print(gene_annotation['ID'].head(5).tolist())\n", "\n", "# Based on the gene annotation preview from step 6, we can see that GB_ACC contains RefSeq accessions, \n", "# not human gene symbols. Let's look for a more suitable column or create a custom mapping.\n", "\n", "# Let's check if there are any columns with gene symbols in the entire annotation dataframe\n", "for col in gene_annotation.columns:\n", " sample_values = gene_annotation[col].dropna().head(10).tolist()\n", " print(f\"\\nSample values from column '{col}':\")\n", " print(sample_values)\n", "\n", "# Based on inspection, we can see that the 'GB_ACC' column contains gene identifiers (RefSeq) but not human gene symbols\n", "# The 'SPOT_ID' column might contain location information we can use\n", "# Let's extract gene IDs from these columns and then see if we can proceed with mapping\n", "\n", "# Create a custom mapping combining available information\n", "mapping_df = gene_annotation[['ID']].copy()\n", "mapping_df = mapping_df[mapping_df['ID'].isin(gene_data.index)] # Only keep rows with IDs that match gene_data\n", "print(f\"\\nMatching probe IDs found: {len(mapping_df)}\")\n", "\n", "if len(mapping_df) > 0:\n", " # Add GB_ACC as a Gene column when available\n", " mapping_df['Gene'] = gene_annotation.loc[mapping_df.index, 'GB_ACC']\n", " \n", " # Apply gene mapping to convert probe-level data to gene-level data\n", " print(\"Converting probe-level measurements to gene expression data...\")\n", " gene_data = apply_gene_mapping(gene_data, mapping_df)\n", " \n", " # Print information about the resulting gene expression data\n", " print(f\"Gene expression data shape after mapping: {gene_data.shape}\")\n", " \n", " if gene_data.empty:\n", " print(\"WARNING: Gene mapping resulted in empty dataframe. Using probe IDs directly.\")\n", " # Fall back to using the original gene_data\n", " gene_data = get_genetic_data(matrix_file_path)\n", " print(f\"Using original gene expression data: {gene_data.shape}\")\n", " else:\n", " print(\"First few gene symbols after mapping:\")\n", " print(gene_data.index[:10])\n", "else:\n", " print(\"WARNING: No matching probe IDs found. Using original gene expression data.\")\n", " # Keep the original gene_data\n", " gene_data = get_genetic_data(matrix_file_path)\n", " print(f\"Using original gene expression data: {gene_data.shape}\")\n", "\n", "# Save the gene expression data for later use\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": "0bee2d33", "metadata": {}, "source": [ "### Step 9: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": null, "id": "9e3470f3", "metadata": {}, "outputs": [], "source": [ "# 1. Normalize gene symbols in the obtained gene expression data\n", "normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n", "print(f\"Normalized gene data shape: {normalized_gene_data.shape}\")\n", "print(f\"First few normalized gene symbols: {list(normalized_gene_data.index[:10])}\")\n", "\n", "# Save the normalized gene data\n", "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n", "normalized_gene_data.to_csv(out_gene_data_file)\n", "print(f\"Normalized gene data saved to {out_gene_data_file}\")\n", "\n", "# 2. Since our dataset lacks clinical features (trait_row=None as determined in Step 2),\n", "# we need a different approach for linking data\n", "# Create a minimal clinical DataFrame with just sample IDs\n", "sample_ids = normalized_gene_data.columns\n", "clinical_features = pd.DataFrame(index=sample_ids)\n", "\n", "# Add placeholder for trait column (all NaN)\n", "clinical_features[trait] = float('nan')\n", "\n", "# 3 & 4. Since we don't have trait data, we can't properly handle missing values\n", "# or evaluate whether the trait is biased. Set appropriate flags.\n", "is_trait_biased = True # No trait data means we can't use this cohort for association studies\n", "print(\"No trait data available for this cohort, marking as biased.\")\n", "\n", "# 5. Conduct quality check and save the 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=False, # We determined earlier that trait data is not available\n", " is_biased=is_trait_biased, \n", " df=clinical_features,\n", " note=\"Dataset contains gene expression data from ovarian cancer cell lines but lacks Retinoblastoma classification information.\"\n", ")\n", "\n", "# 6. We've determined the data is not usable for association studies due to lack of trait information\n", "print(f\"Data quality check result: {'Usable' if is_usable else 'Not usable'}\")\n", "if is_usable:\n", " # This block likely won't execute but included for completeness\n", " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n", " # We don't have useful linked data to save\n", " print(f\"Linked data saved to {out_data_file}\")\n", "else:\n", " print(f\"Data quality check failed. The dataset lacks trait information needed for association studies.\")" ] } ], "metadata": {}, "nbformat": 4, "nbformat_minor": 5 }