{ "cells": [ { "cell_type": "code", "execution_count": null, "id": "790e948d", "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 = \"Vitamin_D_Levels\"\n", "cohort = \"GSE86406\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Vitamin_D_Levels\"\n", "in_cohort_dir = \"../../input/GEO/Vitamin_D_Levels/GSE86406\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Vitamin_D_Levels/GSE86406.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Vitamin_D_Levels/gene_data/GSE86406.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Vitamin_D_Levels/clinical_data/GSE86406.csv\"\n", "json_path = \"../../output/preprocess/Vitamin_D_Levels/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "0e2d780d", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": null, "id": "da382985", "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": "fdb6d15e", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "263d1a33", "metadata": {}, "outputs": [], "source": [ "# 1. Assess gene expression data availability\n", "is_gene_available = True # Based on series_matrix file and the study design using skin biopsies with transcriptome analysis\n", "\n", "# 2.1 Identify data availability and row indices\n", "# This is a vitamin D intervention study with different doses as described in Series_overall_design\n", "# While not directly in the sample characteristics, we can infer the trait is studied through the intervention design\n", "trait_row = None # Cannot directly extract from sample characteristics, but study is about vitamin D intervention\n", "age_row = 1 # Age data is available at index 1\n", "gender_row = 2 # Gender data is available at index 2\n", "\n", "# 2.2 Define conversion functions\n", "def convert_trait(value_str):\n", " # No direct vitamin D level measurements available in sample characteristics\n", " # The study uses different doses (0/placebo, 50k IU, 100k IU, 200k IU) but this info isn't in the sample characteristics\n", " return None\n", "\n", "def convert_age(value_str):\n", " try:\n", " # Extract age value from the format \"age: XX\"\n", " age_value = value_str.split(\": \")[1]\n", " return float(age_value) # Convert to float for continuous variable\n", " except (ValueError, IndexError):\n", " return None\n", "\n", "def convert_gender(value_str):\n", " try:\n", " gender = value_str.split(\": \")[1]\n", " if gender.upper() == 'F':\n", " return 0 # Female\n", " elif gender.upper() == 'M':\n", " return 1 # Male\n", " else:\n", " return None\n", " except (ValueError, IndexError):\n", " return None\n", "\n", "# 3. Save metadata about dataset availability\n", "# While this is a vitamin D study, we can't extract the exact vitamin D levels or treatment groups\n", "# from the sample characteristics dictionary, so we mark trait as unavailable for our analysis\n", "is_trait_available = False # Cannot extract vitamin D levels or treatment groups from sample characteristics\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 is skipped since trait_row is None\n" ] }, { "cell_type": "markdown", "id": "0aed3d25", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "8e5eda66", "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": "90189218", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": null, "id": "7291b8c4", "metadata": {}, "outputs": [], "source": [ "# This previous output shows gene identifiers that appear to be probe IDs or microarray feature IDs\n", "# (starting with 1665xxxx), not standard human gene symbols.\n", "# Standard human gene symbols would typically be letters or letter-number combinations like \"BRCA1\", \"TP53\", etc.\n", "# These numeric identifiers need to be mapped to actual gene symbols for meaningful biological interpretation.\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "38fae357", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": null, "id": "352cf81d", "metadata": {}, "outputs": [], "source": [ "# 1. This part examines the data more thoroughly to determine what type of data it contains\n", "try:\n", " # First, let's check a few rows of the gene_data we extracted in Step 3\n", " print(\"Sample of gene expression data (first 5 rows, first 5 columns):\")\n", " print(gene_data.iloc[:5, :5])\n", " \n", " # Analyze the SOFT file to identify the data type and mapping information\n", " platform_info = []\n", " with gzip.open(soft_file_path, 'rt', encoding='latin-1') as f:\n", " for line in f:\n", " if line.startswith(\"!Platform_title\") or line.startswith(\"!Series_title\") or \"description\" in line.lower():\n", " platform_info.append(line.strip())\n", " \n", " print(\"\\nPlatform information:\")\n", " for line in platform_info:\n", " print(line)\n", " \n", " # Extract the gene annotation using the library function\n", " gene_annotation = get_gene_annotation(soft_file_path)\n", " \n", " # Display column names of the annotation dataframe\n", " print(\"\\nGene annotation columns:\")\n", " print(gene_annotation.columns.tolist())\n", " \n", " # Preview the annotation dataframe\n", " print(\"\\nGene annotation preview:\")\n", " annotation_preview = preview_df(gene_annotation)\n", " print(annotation_preview)\n", " \n", " # Check if ID column exists in the gene_annotation dataframe\n", " if 'ID' in gene_annotation.columns:\n", " # Check if any of the IDs in gene_annotation match those in gene_data\n", " sample_ids = list(gene_data.index[:10])\n", " matching_rows = gene_annotation[gene_annotation['ID'].isin(sample_ids)]\n", " print(f\"\\nMatching rows in annotation for sample IDs: {len(matching_rows)}\")\n", " \n", " # Look for gene symbol column\n", " gene_symbol_candidates = [col for col in gene_annotation.columns if 'gene' in col.lower() or 'symbol' in col.lower() or 'name' in col.lower()]\n", " print(f\"\\nPotential gene symbol columns: {gene_symbol_candidates}\")\n", " \n", "except Exception as e:\n", " print(f\"Error analyzing gene annotation data: {e}\")\n", " gene_annotation = pd.DataFrame()\n", "\n", "# Based on our analysis, determine if this is really gene expression data\n", "# Check the platform description and match with the data we've extracted\n", "is_gene_expression = False\n", "for info in platform_info:\n", " if 'expression' in info.lower() or 'transcript' in info.lower() or 'mrna' in info.lower():\n", " is_gene_expression = True\n", " break\n", "\n", "print(f\"\\nIs this dataset likely to contain gene expression data? {is_gene_expression}\")\n", "\n", "# If this isn't gene expression data, we need to update our metadata\n", "if not is_gene_expression:\n", " print(\"\\nNOTE: Based on our analysis, this dataset doesn't appear to contain gene expression data.\")\n", " print(\"It appears to be a different type of data (possibly SNP array or other genomic data).\")\n", " # Update is_gene_available for metadata\n", " is_gene_available = False\n", " \n", " # Save the updated 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" ] }, { "cell_type": "markdown", "id": "41f51e55", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": null, "id": "6f6802f0", "metadata": {}, "outputs": [], "source": [ "# 1. Let's try a different approach with the existing data\n", "# The problem is that we need to map probe IDs to gene symbols more effectively\n", "\n", "# First, let's check the ID formats more carefully\n", "print(\"Gene expression data ID format:\", gene_data.index[0])\n", "print(\"Gene annotation ID format:\", gene_annotation['ID'].iloc[0])\n", "\n", "# Let's create a better mapping approach by:\n", "# 1. Ensuring the IDs are in the same format\n", "# 2. Using both GB_ACC and SPOT_ID for potential gene information\n", "# 3. Creating a fallback mapping when needed\n", "\n", "# Convert annotation IDs to the same format as expression data IDs\n", "gene_annotation['ID'] = gene_annotation['ID'].astype(str)\n", "gene_data.index = gene_data.index.astype(str)\n", "\n", "# Create a mapping dataframe with gene information from multiple sources\n", "gene_mapping = pd.DataFrame({'ID': gene_data.index})\n", "\n", "# Match gene annotation to our data\n", "annotation_lookup = gene_annotation.set_index('ID')\n", "\n", "# Map accession IDs to our data\n", "gene_mapping['Gene'] = gene_mapping['ID'].map(lambda x: annotation_lookup.loc[x, 'GB_ACC'] if x in annotation_lookup.index else None)\n", "\n", "# Check how many valid gene mappings we have\n", "valid_mappings = gene_mapping['Gene'].notna().sum()\n", "print(f\"\\nValid gene mappings found: {valid_mappings} out of {len(gene_mapping)}\")\n", "\n", "# If very few valid mappings, create temporary gene symbols based on probe IDs\n", "if valid_mappings < 1000: # Arbitrary threshold\n", " print(\"Insufficient gene mappings. Creating temporary gene symbols.\")\n", " gene_mapping['Gene'] = gene_mapping['ID'].map(lambda x: f\"PROBE_{x}\")\n", "\n", "# Ensure the Gene column doesn't have null values\n", "gene_mapping = gene_mapping.fillna({'Gene': lambda x: f\"PROBE_{x['ID']}\"})\n", "\n", "print(\"\\nGene mapping sample:\")\n", "print(gene_mapping.head())\n", "\n", "# Apply the mapping to get gene-level data\n", "gene_data_mapped = gene_data.copy()\n", "gene_data_mapped.index = gene_mapping.set_index('ID')['Gene']\n", "\n", "# Group by the new gene index to handle duplicates\n", "gene_data_mapped = gene_data_mapped.groupby(level=0).mean()\n", "\n", "print(\"\\nMapped gene expression data:\")\n", "print(f\"Shape: {gene_data_mapped.shape}\")\n", "print(gene_data_mapped.head())\n", "\n", "# Assign the mapped data to gene_data for downstream processing\n", "gene_data = gene_data_mapped\n", "\n", "# Update the is_gene_available flag based on whether we have gene expression data\n", "is_gene_available = gene_data.shape[0] > 0 and gene_data.shape[1] > 0\n", "print(f\"\\nIs gene expression data available after mapping: {is_gene_available}\")\n", "\n", "# Check gene symbol format to detect if we're using temporary IDs\n", "using_temp_ids = gene_data.index.str.contains('PROBE_').any()\n", "print(f\"Using temporary gene IDs: {using_temp_ids}\")" ] } ], "metadata": {}, "nbformat": 4, "nbformat_minor": 5 }