{ "cells": [ { "cell_type": "code", "execution_count": null, "id": "1a94e06c", "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 = \"Mitochondrial_Disorders\"\n", "cohort = \"GSE30933\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Mitochondrial_Disorders\"\n", "in_cohort_dir = \"../../input/GEO/Mitochondrial_Disorders/GSE30933\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Mitochondrial_Disorders/GSE30933.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Mitochondrial_Disorders/gene_data/GSE30933.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Mitochondrial_Disorders/clinical_data/GSE30933.csv\"\n", "json_path = \"../../output/preprocess/Mitochondrial_Disorders/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "80c30409", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": null, "id": "53abbc08", "metadata": {}, "outputs": [], "source": [ "# 1. Check what files are actually in the directory\n", "import os\n", "print(\"Files in the directory:\")\n", "files = os.listdir(in_cohort_dir)\n", "print(files)\n", "\n", "# 2. Find appropriate files with more flexible pattern matching\n", "soft_file = None\n", "matrix_file = None\n", "\n", "for file in files:\n", " file_path = os.path.join(in_cohort_dir, file)\n", " # Look for files that might contain SOFT or matrix data with various possible extensions\n", " if 'soft' in file.lower() or 'family' in file.lower() or file.endswith('.soft.gz'):\n", " soft_file = file_path\n", " if 'matrix' in file.lower() or file.endswith('.txt.gz') or file.endswith('.tsv.gz'):\n", " matrix_file = file_path\n", "\n", "if not soft_file:\n", " print(\"Warning: Could not find a SOFT file. Using the first .gz file as fallback.\")\n", " gz_files = [f for f in files if f.endswith('.gz')]\n", " if gz_files:\n", " soft_file = os.path.join(in_cohort_dir, gz_files[0])\n", "\n", "if not matrix_file:\n", " print(\"Warning: Could not find a matrix file. Using the second .gz file as fallback if available.\")\n", " gz_files = [f for f in files if f.endswith('.gz')]\n", " if len(gz_files) > 1 and soft_file != os.path.join(in_cohort_dir, gz_files[1]):\n", " matrix_file = os.path.join(in_cohort_dir, gz_files[1])\n", " elif len(gz_files) == 1 and not soft_file:\n", " matrix_file = os.path.join(in_cohort_dir, gz_files[0])\n", "\n", "print(f\"SOFT file: {soft_file}\")\n", "print(f\"Matrix file: {matrix_file}\")\n", "\n", "# 3. Read files if found\n", "if soft_file and matrix_file:\n", " # 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", " \n", " try:\n", " background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)\n", " \n", " # Obtain the sample characteristics dictionary from the clinical dataframe\n", " sample_characteristics_dict = get_unique_values_by_row(clinical_data)\n", " \n", " # 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", " except Exception as e:\n", " print(f\"Error processing files: {e}\")\n", " # Try swapping files if first attempt fails\n", " print(\"Trying to swap SOFT and matrix files...\")\n", " temp = soft_file\n", " soft_file = matrix_file\n", " matrix_file = temp\n", " try:\n", " background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)\n", " sample_characteristics_dict = get_unique_values_by_row(clinical_data)\n", " print(\"Background Information:\")\n", " print(background_info)\n", " print(\"Sample Characteristics Dictionary:\")\n", " print(sample_characteristics_dict)\n", " except Exception as e:\n", " print(f\"Still error after swapping: {e}\")\n", "else:\n", " print(\"Could not find necessary files for processing.\")\n" ] }, { "cell_type": "markdown", "id": "ac93bd90", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "921f5728", "metadata": {}, "outputs": [], "source": [ "# 1. Gene expression data availability assessment\n", "# Based on the background information, this study focuses on gene expression profiling in PBMCs from FRDA patients.\n", "# The series title mentions \"A Gene Expression Phenotype In Lymphocytes From Friedreich's Ataxia Patients\"\n", "is_gene_available = True\n", "\n", "# 2.1 Data Availability\n", "# Reviewing sample characteristics dictionary:\n", "# Row 0: 'disease status' contains information about FRDA (a type of mitochondrial disorder), Carrier, or Normal status\n", "trait_row = 0 # This contains the disease status information which matches our trait (Mitochondrial_Disorders)\n", "\n", "# Age and gender information are not provided in the sample characteristics\n", "age_row = None\n", "gender_row = None\n", "\n", "# 2.2 Data Type Conversion Functions\n", "def convert_trait(value):\n", " \"\"\"Convert disease status to binary format (1 for disease, 0 for non-disease).\"\"\"\n", " if value is None:\n", " return None\n", " # Extract value after colon if present\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # Convert to binary: FRDA (disease) = 1, Normal/Carrier = 0\n", " if value.lower() == \"frda\":\n", " return 1\n", " elif value.lower() in [\"normal\", \"carrier\"]:\n", " return 0\n", " else:\n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age to numerical value.\"\"\"\n", " # Function defined but not used since age data is not available\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"Convert gender to binary (0 for female, 1 for male).\"\"\"\n", " # Function defined but not used since gender data is not available\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", " # Load the matrix file\n", " matrix_file = os.path.join(in_cohort_dir, \"GSE30933_series_matrix.txt.gz\")\n", " \n", " # Parse the clinical data from the matrix file\n", " # Since the tools module is already imported, we can directly access its functions\n", " clinical_data = get_geo_clinical_data(matrix_file)\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=age_row,\n", " convert_age=convert_age,\n", " gender_row=gender_row,\n", " convert_gender=convert_gender\n", " )\n", " \n", " # Preview the extracted clinical data\n", " print(\"Preview of selected clinical features:\")\n", " print(preview_df(selected_clinical_df))\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 saved to {out_clinical_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "d8b30929", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "fa4a67ce", "metadata": {}, "outputs": [], "source": [ "# 1. First get the path to the soft and matrix files\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "\n", "# 2. Looking more carefully at the background information\n", "# This is a SuperSeries which doesn't contain direct gene expression data\n", "# Need to investigate the soft file to find the subseries\n", "print(\"This appears to be a SuperSeries. Looking at the SOFT file to find potential subseries:\")\n", "\n", "# Open the SOFT file to try to identify subseries\n", "with gzip.open(soft_file, 'rt') as f:\n", " subseries_lines = []\n", " for i, line in enumerate(f):\n", " if 'Series_relation' in line and 'SuperSeries of' in line:\n", " subseries_lines.append(line.strip())\n", " if i > 1000: # Limit search to first 1000 lines\n", " break\n", "\n", "# Display the subseries found\n", "if subseries_lines:\n", " print(\"Found potential subseries references:\")\n", " for line in subseries_lines:\n", " print(line)\n", "else:\n", " print(\"No subseries references found in the first 1000 lines of the SOFT file.\")\n", "\n", "# Despite trying to extract gene data, we expect it might fail because this is a SuperSeries\n", "try:\n", " gene_data = get_genetic_data(matrix_file)\n", " print(\"\\nGene data extraction result:\")\n", " print(\"Number of rows:\", len(gene_data))\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", " print(\"This confirms the dataset is a SuperSeries without direct gene expression data.\")\n" ] }, { "cell_type": "markdown", "id": "438811ea", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": null, "id": "9ee60ce6", "metadata": {}, "outputs": [], "source": [ "# Based on the identifiers, these are Illumina probes (ILMN_*) and not human gene symbols\n", "# These probe IDs need to be mapped to standard gene symbols\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "6512cb3c", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": null, "id": "f5cb92af", "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", "# 2. Use the 'preview_df' function from the library to preview the data and print out the results.\n", "print(\"Gene annotation preview:\")\n", "print(preview_df(gene_annotation))\n" ] }, { "cell_type": "markdown", "id": "77e92ed6", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": null, "id": "1c05bebd", "metadata": {}, "outputs": [], "source": [ "# 1. Identify the relevant columns for mapping\n", "# Based on the preview, we can see:\n", "# - Gene identifiers in expression data are in the 'ID' column (ILMN_* format)\n", "# - Gene symbols are in the 'SYMBOL' column\n", "\n", "# 2. Get the gene mapping dataframe\n", "gene_mapping = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='SYMBOL')\n", "print(\"Gene mapping preview:\")\n", "print(preview_df(gene_mapping))\n", "\n", "# 3. Apply gene mapping to convert probe-level measurements to gene expression data\n", "gene_data = apply_gene_mapping(gene_data, gene_mapping)\n", "print(\"\\nGene data after mapping:\")\n", "print(f\"Number of genes: {len(gene_data)}\")\n", "print(\"First few genes:\")\n", "print(gene_data.index[:10])\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": "828f1b29", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": null, "id": "d3d21613", "metadata": {}, "outputs": [], "source": [ "# 1. Re-load the gene expression data that was saved in a previous step\n", "try:\n", " gene_data = pd.read_csv(out_gene_data_file, index_col=0)\n", " print(f\"Successfully loaded gene data from {out_gene_data_file}\")\n", "except Exception as e:\n", " print(f\"Error loading gene data: {e}\")\n", " raise\n", "\n", "# 2. Normalize gene symbols in the gene expression data\n", "gene_data = normalize_gene_symbols_in_index(gene_data)\n", "print(f\"Shape of gene data after normalization: {gene_data.shape}\")\n", "\n", "# 3. Extract clinical data from the matrix file again to be sure we have the correct data\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "background_info, clinical_data = get_background_and_clinical_data(matrix_file)\n", "\n", "# Based on the sample characteristics dictionary, the trait information is in row 0 (disease status)\n", "# Define conversion functions for the clinical features based on the actual data\n", "def convert_trait(value):\n", " \"\"\"Convert FRDA disease status to binary (1 = FRDA, 0 = Normal or Carrier)\"\"\"\n", " if not isinstance(value, str):\n", " return None\n", " \n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " if value.lower() == \"frda\":\n", " return 1\n", " elif value.lower() in [\"normal\", \"carrier\"]:\n", " return 0\n", " else:\n", " return None\n", "\n", "# Create the clinical dataframe using the correct trait row\n", "trait_row = 0 # Row for disease status (FRDA)\n", "is_trait_available = True\n", "\n", "try:\n", " clinical_df = geo_select_clinical_features(\n", " clinical_data,\n", " trait=trait, # Using the predefined trait variable\n", " trait_row=trait_row,\n", " convert_trait=convert_trait,\n", " age_row=None, # Age information not available\n", " convert_age=None,\n", " gender_row=None, # Gender information not available\n", " convert_gender=None\n", " )\n", " \n", " print(\"Clinical data preview:\")\n", " print(preview_df(clinical_df.T)) # Transpose for better viewing\n", " \n", " # Save the clinical data\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " clinical_df.to_csv(out_clinical_data_file)\n", " print(f\"Saved clinical data to {out_clinical_data_file}\")\n", " \n", " # 3. Link clinical and genetic data\n", " linked_data = geo_link_clinical_genetic_data(clinical_df, gene_data)\n", " print(f\"Shape of linked data: {linked_data.shape}\")\n", " \n", " # 4. Handle missing values in the linked data\n", " linked_data_cleaned = handle_missing_values(linked_data, trait)\n", " print(f\"Shape of linked data after handling missing values: {linked_data_cleaned.shape}\")\n", " \n", " # 5. Check if the trait is biased\n", " is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data_cleaned, trait)\n", " \n", " # 6. Validate the dataset and save cohort information\n", " note = \"Dataset contains gene expression data from human samples with Friedreich's Ataxia (FRDA). The trait variable indicates FRDA status (1=FRDA, 0=Normal/Carrier).\"\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=is_trait_available,\n", " is_biased=is_trait_biased,\n", " df=unbiased_linked_data,\n", " note=note\n", " )\n", " \n", " # 7. Save the linked data if it's usable\n", " if is_usable:\n", " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n", " unbiased_linked_data.to_csv(out_data_file)\n", " print(f\"Saved processed linked data to {out_data_file}\")\n", " else:\n", " print(\"Dataset validation failed. Final linked data not saved.\")\n", " \n", "except Exception as e:\n", " print(f\"Error in processing clinical data: {e}\")\n", " # Make sure to properly handle validation in the exception case\n", " df_empty = pd.DataFrame()\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,\n", " is_biased=None,\n", " df=df_empty, # Empty DataFrame\n", " note=\"Failed to extract or process clinical data, but gene expression data is available.\"\n", " )\n", " print(\"Dataset validation failed due to clinical data processing errors. Gene data was saved.\")" ] } ], "metadata": {}, "nbformat": 4, "nbformat_minor": 5 }