{ "cells": [ { "cell_type": "code", "execution_count": null, "id": "08f3d535", "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 = \"GSE78104\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Obsessive-Compulsive_Disorder\"\n", "in_cohort_dir = \"../../input/GEO/Obsessive-Compulsive_Disorder/GSE78104\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Obsessive-Compulsive_Disorder/GSE78104.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Obsessive-Compulsive_Disorder/gene_data/GSE78104.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Obsessive-Compulsive_Disorder/clinical_data/GSE78104.csv\"\n", "json_path = \"../../output/preprocess/Obsessive-Compulsive_Disorder/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "b6f65344", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": null, "id": "b36c11cd", "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": "7eed811b", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "f9fe7312", "metadata": {}, "outputs": [], "source": [ "# 1. Gene Expression Data Availability\n", "# This dataset mentions mRNA expression data in the title and design,\n", "# so it likely contains gene expression data\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Identifying rows\n", "trait_row = 1 # disease state\n", "age_row = 3 # age\n", "gender_row = 2 # gender\n", "\n", "# 2.2 Data Type Conversion Functions\n", "def convert_trait(value):\n", " \"\"\"Convert trait data to binary format (0 for control, 1 for OCD)\"\"\"\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", " if 'obsessive' in value.lower() or 'ocd' in value.lower():\n", " return 1\n", " elif 'normal' in value.lower() or 'control' in value.lower():\n", " return 0\n", " else:\n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age data to continuous format\"\"\"\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", " # Extract numeric age from format like \"25y\"\n", " if 'y' in value:\n", " try:\n", " return float(value.replace('y', '').strip())\n", " except ValueError:\n", " return None\n", " \n", " try:\n", " return float(value)\n", " except ValueError:\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"Convert gender data to binary format (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", " 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", "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", " # 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,\n", " gender_row=gender_row,\n", " convert_gender=convert_gender\n", " )\n", " \n", " # Preview the data\n", " preview_data = preview_df(selected_clinical_df)\n", " print(\"Preview of clinical data:\")\n", " print(preview_data)\n", " \n", " # Save as CSV\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": "58c7452b", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "c1bf40e1", "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": "06e43958", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": null, "id": "13d15d23", "metadata": {}, "outputs": [], "source": [ "# Examining gene identifiers in data\n", "# The identifiers look like microarray probe IDs rather than gene symbols\n", "# The format is consistent with Agilent microarray designations (e.g., \"A_19_P00315459\")\n", "# These are not standard human gene symbols and will need to be mapped\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "735df700", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": null, "id": "9e6da8fa", "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)\n" ] }, { "cell_type": "markdown", "id": "45e09dff", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": null, "id": "2e4e071e", "metadata": {}, "outputs": [], "source": [ "# 1. Identify which columns in the gene annotation contain probe IDs and gene symbols\n", "# From the preview, 'ID' contains probe identifiers that match expression data\n", "# 'GeneSymbol' appears to contain gene symbols, but we should check for nulls\n", "probe_col = 'ID'\n", "gene_col = 'GeneSymbol'\n", "\n", "print(f\"Mapping probes using columns: {probe_col} → {gene_col}\")\n", "print(f\"Number of probes in annotation: {len(gene_annotation)}\")\n", "print(f\"Number of non-null gene symbols: {gene_annotation[gene_col].notna().sum()}\")\n", "\n", "# 2. Get the gene mapping dataframe\n", "mapping_df = get_gene_mapping(gene_annotation, prob_col=probe_col, gene_col=gene_col)\n", "print(f\"Mapping dataframe shape: {mapping_df.shape}\")\n", "print(\"First few rows of mapping:\")\n", "print(mapping_df.head())\n", "\n", "# 3. Apply gene mapping to convert probe-level measurements to gene-level expression\n", "# This will handle the many-to-many relationship properly\n", "gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)\n", "print(f\"Gene expression data shape after mapping: {gene_data.shape}\")\n", "print(\"First few gene symbols:\")\n", "print(gene_data.index[:10])\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\"Gene expression data saved to {out_gene_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "7ff76b3b", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": null, "id": "5df04557", "metadata": {}, "outputs": [], "source": [ "# 1. Normalize gene symbols in the gene expression data\n", "gene_data = normalize_gene_symbols_in_index(gene_data)\n", "print(f\"Gene data shape after normalization: {gene_data.shape}\")\n", "gene_data.to_csv(out_gene_data_file)\n", "print(f\"Normalized gene data saved to {out_gene_data_file}\")\n", "\n", "# 2. Load clinical data that was already saved in Step 2\n", "clinical_data_df = pd.read_csv(out_clinical_data_file)\n", "# Set proper index for clinical data \n", "clinical_data_df.set_index(clinical_data_df.columns[0], inplace=True)\n", "print(f\"Loaded clinical data shape: {clinical_data_df.shape}\")\n", "print(clinical_data_df.head())\n", "\n", "# Link clinical and genetic data\n", "linked_data = geo_link_clinical_genetic_data(clinical_data_df, gene_data)\n", "print(f\"Linked data shape: {linked_data.shape}\")\n", "print(\"Linked data preview (first 5 rows, 5 columns):\")\n", "print(linked_data.iloc[:5, :5] if not linked_data.empty else \"Linked data is empty\")\n", "\n", "# 3. Handle missing values\n", "# Identify trait column - it's the first column in the linked data\n", "trait_col = linked_data.columns[0] # This gets the actual column name where trait values are stored\n", "linked_data = handle_missing_values(linked_data, trait_col)\n", "print(f\"Data shape after handling missing values: {linked_data.shape}\")\n", "\n", "# 4. Check for bias in features\n", "is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait_col)\n", "\n", "# 5. Validate and save 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=True,\n", " is_biased=is_biased,\n", " df=linked_data,\n", " note=\"Dataset contains gene expression data from peripheral blood of patients with Obsessive-Compulsive Disorder.\"\n", ")\n", "\n", "# 6. Save the linked data if usable\n", "if is_usable:\n", " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n", " linked_data.to_csv(out_data_file)\n", " print(f\"Linked data saved to {out_data_file}\")\n", "else:\n", " print(\"Dataset is not usable for analysis. No linked data file saved.\")\n" ] }, { "cell_type": "markdown", "id": "d409082f", "metadata": {}, "source": [ "### Step 8: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": null, "id": "33b827d3", "metadata": {}, "outputs": [], "source": [ "# 1. Normalize gene symbols in the gene expression data - we already did this in step 6\n", "# No need to do it again\n", "print(f\"Gene data already normalized and saved to {out_gene_data_file}\")\n", "\n", "# 2. Load clinical data that was already saved in Step 2\n", "clinical_data_df = pd.read_csv(out_clinical_data_file, index_col=0)\n", "print(f\"Loaded clinical data shape: {clinical_data_df.shape}\")\n", "print(clinical_data_df.head())\n", "\n", "# 2. Link clinical and genetic data\n", "linked_data = geo_link_clinical_genetic_data(clinical_data_df, gene_data)\n", "print(f\"Linked data shape: {linked_data.shape}\")\n", "print(\"Linked data preview (first 5 rows, 5 columns):\")\n", "print(linked_data.iloc[:5, :5] if not linked_data.empty else \"Linked data is empty\")\n", "\n", "# 3. Handle missing values\n", "linked_data = handle_missing_values(linked_data, trait)\n", "print(f\"Data shape after handling missing values: {linked_data.shape}\")\n", "\n", "# 4. Check for bias in features\n", "is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n", "\n", "# 5. Validate and save 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=True,\n", " is_biased=is_biased,\n", " df=linked_data,\n", " note=\"Dataset contains gene expression data from dorsolateral prefrontal cortex of postmortem tissue with Eating Disorders.\"\n", ")\n", "\n", "# 6. Save the linked data if usable\n", "if is_usable:\n", " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n", " linked_data.to_csv(out_data_file)\n", " print(f\"Linked data saved to {out_data_file}\")\n", "else:\n", " print(\"Dataset is not usable for analysis. No linked data file saved.\")" ] } ], "metadata": {}, "nbformat": 4, "nbformat_minor": 5 }