{ "cells": [ { "cell_type": "code", "execution_count": null, "id": "32b188ab", "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 = \"Obsessive-Compulsive_Disorder\"\n", "cohort = \"GSE60190\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Obsessive-Compulsive_Disorder\"\n", "in_cohort_dir = \"../../input/GEO/Obsessive-Compulsive_Disorder/GSE60190\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Obsessive-Compulsive_Disorder/GSE60190.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Obsessive-Compulsive_Disorder/gene_data/GSE60190.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Obsessive-Compulsive_Disorder/clinical_data/GSE60190.csv\"\n", "json_path = \"../../output/preprocess/Obsessive-Compulsive_Disorder/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "f04b8aa5", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": null, "id": "12b8c873", "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": "a900f0d5", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "8bb3cc11", "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "id": "41ac7f4a", "metadata": {}, "source": [ "### Step 3: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "165dffd2", "metadata": {}, "outputs": [], "source": [ "import pandas as pd\n", "import os\n", "import json\n", "from typing import Optional, Dict, Any, Callable\n", "\n", "# Load the necessary data to analyze\n", "# Check all files in the directory to find which ones might contain clinical data\n", "all_files = os.listdir(in_cohort_dir)\n", "print(f\"Files in directory: {all_files}\")\n", "\n", "# Check for gene data availability (look for files that might contain gene expression data)\n", "gene_data_files = [f for f in all_files if \"_gene\" in f or \"gene\" in f.lower() or \"expression\" in f.lower()]\n", "is_gene_available = len(gene_data_files) > 0\n", "print(f\"Gene data files: {gene_data_files}\")\n", "\n", "# Let's look for clinical data in any available text files\n", "clinical_data_files = [f for f in all_files if f.endswith('.txt')]\n", "print(f\"Potential clinical data files: {clinical_data_files}\")\n", "\n", "clinical_data = None\n", "if clinical_data_files:\n", " # Try to open each file to find clinical data\n", " for file in clinical_data_files:\n", " try:\n", " file_path = os.path.join(in_cohort_dir, file)\n", " df = pd.read_csv(file_path, sep='\\t', index_col=0)\n", " \n", " # If file has relevant data structure, it's likely our clinical data\n", " if df.shape[0] > 0 and df.shape[1] > 0:\n", " print(f\"Found potential clinical data in file: {file}\")\n", " print(f\"Data shape: {df.shape}\")\n", " print(f\"Sample columns: {list(df.columns)[:5]}\")\n", " print(f\"Sample index entries: {list(df.index)[:5]}\")\n", " \n", " # Display sample values to help identify trait and gender information\n", " for idx in df.index[:10]: # Look at first 10 rows\n", " unique_vals = df.loc[idx].unique()\n", " print(f\"Row {idx}: {unique_vals}\")\n", " \n", " clinical_data = df\n", " break\n", " except Exception as e:\n", " print(f\"Could not read {file} as a data file: {e}\")\n", "\n", "# Based on inspection of the clinical data, determine the correct rows and conversion functions\n", "if clinical_data is not None:\n", " # Determine trait row - look for information about OCD status\n", " trait_row = None\n", " gender_row = None\n", " \n", " # Look through the rows to find OCD and gender information\n", " for idx in clinical_data.index:\n", " row_values = [str(val).lower() for val in clinical_data.loc[idx].values if not pd.isna(val)]\n", " row_str = ' '.join(row_values)\n", " \n", " # Check for trait information\n", " if ('ocd' in row_str or 'obsessive' in row_str or 'control' in row_str or \n", " 'patient' in row_str or 'disorder' in row_str):\n", " trait_row = idx\n", " print(f\"Found potential trait row at index {idx}\")\n", " print(f\"Sample values: {clinical_data.loc[idx].head()}\")\n", " \n", " # Check for gender information\n", " if ('gender' in row_str or 'sex' in row_str or 'male' in row_str or 'female' in row_str):\n", " gender_row = idx\n", " print(f\"Found potential gender row at index {idx}\")\n", " print(f\"Sample values: {clinical_data.loc[idx].head()}\")\n", "else:\n", " print(\"No clinical data found in any of the files.\")\n", "\n", "# Define age row (assuming it's not available based on initial analysis)\n", "age_row = None\n", "\n", "# Define conversion functions for each variable\n", "def convert_trait(value):\n", " \"\"\"Convert OCD status to binary (0 for control, 1 for OCD).\"\"\"\n", " if pd.isna(value):\n", " return None\n", " \n", " # Extract value after the 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", " if 'control' in value or 'healthy' in value or 'normal' in value:\n", " return 0\n", " elif 'ocd' in value or 'obsessive' in value or 'patient' in value or 'disorder' in value:\n", " return 1\n", " else:\n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age to continuous value.\"\"\"\n", " # Function for completeness, but not used since age data is likely not available\n", " if pd.isna(value):\n", " return None\n", " \n", " if isinstance(value, str) and ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " try:\n", " return float(value)\n", " except:\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"Convert gender to binary (0 for female, 1 for male).\"\"\"\n", " if pd.isna(value):\n", " return None\n", " \n", " # Extract value after the 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", " 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", "# Save metadata for initial filtering\n", "is_trait_available = trait_row is not None and clinical_data 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 trait data is available\n", "if is_trait_available:\n", " try:\n", " selected_clinical_df = geo_select_clinical_features(\n", " clinical_data, \n", " trait, \n", " trait_row, \n", " 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 data:\")\n", " print(preview)\n", " \n", " # Check if we have valid data (not all NaN)\n", " has_valid_data = selected_clinical_df.notna().any().any()\n", " if not has_valid_data:\n", " print(\"WARNING: Extracted clinical data contains only NaN values. Check row identifiers and conversion functions.\")\n", " \n", " # Create the directory if it doesn't exist\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " \n", " # Save the clinical data\n", " selected_clinical_df.to_csv(out_clinical_data_file)\n", " print(f\"Clinical data saved to {out_clinical_data_file}\")\n", " except Exception as e:\n", " print(f\"Error extracting clinical features: {e}\")\n", " # Update trait availability in case of extraction error\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=False\n", " )\n", "else:\n", " print(\"Clinical data extraction skipped: No trait data available.\")\n" ] }, { "cell_type": "markdown", "id": "9042b1a3", "metadata": {}, "source": [ "### Step 4: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "332d9bd1", "metadata": {}, "outputs": [], "source": [ "# 1. Get the SOFT and matrix file paths again \n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "print(f\"Matrix file found: {matrix_file}\")\n", "\n", "# 2. Use the get_genetic_data function from the library to get the gene_data\n", "try:\n", " gene_data = get_genetic_data(matrix_file)\n", " print(f\"Gene data shape: {gene_data.shape}\")\n", " \n", " # 3. Print the first 20 row IDs (gene or probe identifiers)\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" ] }, { "cell_type": "markdown", "id": "e0601fbb", "metadata": {}, "source": [ "### Step 5: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": null, "id": "576bc374", "metadata": {}, "outputs": [], "source": [ "# The gene identifiers start with \"ILMN_\" which indicates they are Illumina probe IDs \n", "# rather than human gene symbols. Illumina probes need to be mapped to gene symbols.\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "c4bf772e", "metadata": {}, "source": [ "### Step 6: Gene Annotation" ] }, { "cell_type": "code", "execution_count": null, "id": "2c612021", "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", "# Check if there are any platforms defined in the SOFT file that might contain annotation data\n", "with gzip.open(soft_file, 'rt') as f:\n", " soft_content = f.read()\n", "\n", "# Look for platform sections in the SOFT file\n", "platform_sections = re.findall(r'^!Platform_title\\s*=\\s*(.+)$', soft_content, re.MULTILINE)\n", "if platform_sections:\n", " print(f\"Platform title found: {platform_sections[0]}\")\n", "\n", "# Try to extract more annotation data by reading directly from the SOFT file\n", "# Look for lines that might contain gene symbol mappings\n", "symbol_pattern = re.compile(r'ID_REF\\s+Symbol|ID\\s+Gene Symbol', re.IGNORECASE)\n", "annotation_lines = []\n", "with gzip.open(soft_file, 'rt') as f:\n", " for line in f:\n", " if symbol_pattern.search(line):\n", " annotation_lines.append(line)\n", " # Collect the next few lines to see the annotation structure\n", " for _ in range(10):\n", " annotation_lines.append(next(f, ''))\n", "\n", "if annotation_lines:\n", " print(\"Found potential gene symbol mappings:\")\n", " for line in annotation_lines:\n", " print(line.strip())\n", "\n", "# 2. Use the 'preview_df' function from the library to preview the data and print out the results.\n", "print(\"\\nGene annotation preview:\")\n", "print(preview_df(gene_annotation, n=10))\n", "\n", "# If we need an alternative source of mapping, check if there are any other annotation files in the cohort directory\n", "cohort_files = os.listdir(in_cohort_dir)\n", "annotation_files = [f for f in cohort_files if 'annotation' in f.lower() or 'platform' in f.lower()]\n", "if annotation_files:\n", " print(\"\\nAdditional annotation files found in the cohort directory:\")\n", " for file in annotation_files:\n", " print(file)" ] } ], "metadata": {}, "nbformat": 4, "nbformat_minor": 5 }