{ "cells": [ { "cell_type": "code", "execution_count": null, "id": "4d449993", "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 = \"Insomnia\"\n", "cohort = \"GSE208668\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Insomnia\"\n", "in_cohort_dir = \"../../input/GEO/Insomnia/GSE208668\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Insomnia/GSE208668.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Insomnia/gene_data/GSE208668.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Insomnia/clinical_data/GSE208668.csv\"\n", "json_path = \"../../output/preprocess/Insomnia/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "6dc0a7ac", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": null, "id": "ad054e14", "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": "33476faa", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "9fd1a005", "metadata": {}, "outputs": [], "source": [ "# 1. Gene Expression Data Availability\n", "# Based on background information, this dataset contains genome-wide transcriptional profiling data from PBMCs\n", "# Note: Raw data was lost but processed data should be available for analysis\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "\n", "# Trait (Insomnia)\n", "trait_row = 0 # Key 0 contains 'insomnia: yes', 'insomnia: no'\n", "\n", "# Age\n", "age_row = 1 # Key 1 contains age information with multiple values (60-80)\n", "\n", "# Gender\n", "gender_row = 2 # Key 2 contains 'gender: female', 'gender: male'\n", "\n", "# 2.2 Data Type Conversion Functions\n", "\n", "def convert_trait(value):\n", " \"\"\"Convert insomnia status to binary format (0 for No, 1 for Yes).\"\"\"\n", " if not isinstance(value, str):\n", " return None\n", " \n", " # Extract value after colon and strip whitespace\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip().lower()\n", " \n", " if value == 'yes':\n", " return 1\n", " elif value == 'no':\n", " return 0\n", " else:\n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age to continuous format.\"\"\"\n", " if not isinstance(value, str):\n", " return None\n", " \n", " # Extract value after colon and strip whitespace\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " try:\n", " return float(value)\n", " except (ValueError, TypeError):\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"Convert gender to binary format (0 for female, 1 for male).\"\"\"\n", " if not isinstance(value, str):\n", " return None\n", " \n", " # Extract value after colon and strip whitespace\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip().lower()\n", " \n", " if value == 'female':\n", " return 0\n", " elif value == 'male':\n", " return 1\n", " else:\n", " return None\n", "\n", "# 3. Save Metadata\n", "# Conduct initial filtering on dataset usability\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", " clinical_features = 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 features\n", " preview = preview_df(clinical_features)\n", " print(\"Clinical Features Preview:\")\n", " print(preview)\n", " \n", " # Save the clinical data to CSV\n", " clinical_features.to_csv(out_clinical_data_file)\n", " print(f\"Clinical data saved to {out_clinical_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "f79a21e6", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "7a0791a9", "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": "4a5cb6ae", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": null, "id": "0329a2d3", "metadata": {}, "outputs": [], "source": [ "# Looking at the gene identifiers in the gene expression data\n", "# The identifiers appear to be human gene symbols (like A1BG, A2M, etc.)\n", "# These are standard gene symbols and not probe identifiers that would need mapping\n", "\n", "requires_gene_mapping = False\n" ] }, { "cell_type": "markdown", "id": "6e90ef74", "metadata": {}, "source": [ "### Step 5: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": null, "id": "9efa52ce", "metadata": {}, "outputs": [], "source": [ "# 1. Normalize gene symbols in the gene expression data - already done in previous step\n", "print(f\"Gene data shape after normalization: {gene_data.shape}\")\n", "\n", "# Save the normalized gene data to file - already done in previous step\n", "print(f\"Normalized gene expression data saved to {out_gene_data_file}\")\n", "\n", "# 2. Link the clinical and genetic data\n", "# Load the clinical features from the previous step\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", "print(f\"Selected clinical data shape: {selected_clinical_df.shape}\")\n", "print(\"Clinical data preview:\")\n", "print(selected_clinical_df.head())\n", "\n", "# Link the clinical and genetic data directly using the properly encoded clinical data\n", "linked_data = geo_link_clinical_genetic_data(selected_clinical_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])\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", "print(f\"Data shape after removing biased features: {linked_data.shape}\")\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 related to alcohol dependence but was evaluated for Schizophrenia.\"\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 }