{ "cells": [ { "cell_type": "code", "execution_count": null, "id": "a9077b62", "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 = \"Celiac_Disease\"\n", "cohort = \"GSE112102\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Celiac_Disease\"\n", "in_cohort_dir = \"../../input/GEO/Celiac_Disease/GSE112102\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Celiac_Disease/GSE112102.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Celiac_Disease/gene_data/GSE112102.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Celiac_Disease/clinical_data/GSE112102.csv\"\n", "json_path = \"../../output/preprocess/Celiac_Disease/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "ea494e7c", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": null, "id": "f33c9d95", "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": "fc79e0b1", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "4c871202", "metadata": {}, "outputs": [], "source": [ "# 1. Analyze gene expression data availability\n", "is_gene_available = True # Based on the Series_summary, this dataset contains gene expression data\n", "\n", "# 2. Analyze variable availability and conversion functions\n", "# 2.1 Identify rows for trait, age, and gender\n", "trait_row = 1 # The trait information is in row 1 (group: CeD, control, FDR)\n", "age_row = 2 # Age information is in row 2\n", "gender_row = 4 # Gender information is in row 4\n", "\n", "# 2.2 Define conversion functions\n", "def convert_trait(value):\n", " \"\"\"Convert trait values to binary (1 for CeD, 0 for control, None for FDR)\"\"\"\n", " if not isinstance(value, str):\n", " return None\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " if value.lower() == 'ced':\n", " return 1 # Celiac Disease\n", " elif value.lower() == 'control':\n", " return 0 # Control\n", " else:\n", " return None # FDR (First Degree Relatives) are neither cases nor controls\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age values to continuous numeric values\"\"\"\n", " if not isinstance(value, str):\n", " return None\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " try:\n", " return float(value)\n", " except (ValueError, TypeError):\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"Convert gender values to binary (0 for Female, 1 for Male)\"\"\"\n", " if not isinstance(value, str):\n", " return None\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " if value.lower() == 'female':\n", " return 0\n", " elif value.lower() == 'male':\n", " return 1\n", " else:\n", " return None\n", "\n", "# 3. Save metadata for 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. Extract clinical features if trait data is available\n", "if trait_row is not None:\n", " # Get the clinical data by filtering and processing\n", " 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 extracted clinical data:\")\n", " print(preview_df(clinical_df))\n", " \n", " # Save clinical data to CSV file\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " 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": "a9bf6594", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "0f0e6d5e", "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": "2f7c9c58", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": null, "id": "9e69d07b", "metadata": {}, "outputs": [], "source": [ "# These identifiers begin with \"ILMN_\" which indicates they are Illumina probe IDs,\n", "# specifically from an Illumina BeadArray microarray platform.\n", "# These are not human gene symbols but rather probe identifiers that need to be\n", "# mapped to gene symbols for biological interpretation.\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "a615f808", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": null, "id": "f9bb14b3", "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": "c119e2c7", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": null, "id": "58e2c871", "metadata": {}, "outputs": [], "source": [ "# 1. Identify the columns for mapping\n", "# From the gene annotation preview, we can see that 'ID' contains the probe identifiers (ILMN_*) \n", "# and 'Symbol' contains the gene symbols\n", "prob_col = 'ID' # Column with probe IDs matching the gene expression data index\n", "gene_col = 'Symbol' # Column with gene symbols\n", "\n", "# 2. Create the gene mapping dataframe\n", "gene_mapping = get_gene_mapping(gene_annotation, prob_col, gene_col)\n", "print(f\"Gene mapping dataframe shape: {gene_mapping.shape}\")\n", "print(\"Gene mapping preview:\")\n", "print(preview_df(gene_mapping))\n", "\n", "# 3. Apply the gene mapping to convert probe-level data to gene-level data\n", "gene_data = apply_gene_mapping(gene_data, gene_mapping)\n", "print(f\"Gene expression data after mapping - shape: {gene_data.shape}\")\n", "print(\"First 5 genes in the mapped data:\")\n", "print(gene_data.index[:5])\n", "\n", "# Save the gene expression data to CSV\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": "1cea372c", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": null, "id": "052096f6", "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", "print(\"First 10 normalized gene symbols:\")\n", "print(gene_data.index[:10])\n", "\n", "# Save the normalized gene 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\"Normalized gene data saved to {out_gene_data_file}\")\n", "\n", "# 2. Load the clinical data that was saved in Step 2\n", "clinical_data = pd.read_csv(out_clinical_data_file)\n", "\n", "# Convert to proper format for linking\n", "clinical_df = pd.DataFrame()\n", "sample_ids = clinical_data.columns\n", "\n", "# Create proper clinical dataframe with samples as columns and features as rows\n", "clinical_df[trait] = clinical_data.iloc[0]\n", "clinical_df['Age'] = clinical_data.iloc[1]\n", "clinical_df['Gender'] = clinical_data.iloc[2]\n", "clinical_df.index = [trait, 'Age', 'Gender']\n", "clinical_df.columns = sample_ids\n", "\n", "print(f\"Clinical data shape: {clinical_df.shape}\")\n", "print(\"Clinical data preview:\")\n", "print(preview_df(clinical_df))\n", "\n", "# 3. Link clinical and genetic data\n", "linked_data = geo_link_clinical_genetic_data(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", "# Transpose linked data to have samples as rows and features as columns\n", "linked_data = linked_data.T\n", "\n", "print(\"After transposing:\")\n", "print(f\"Linked data shape: {linked_data.shape}\")\n", "print(\"Actual column names in linked_data:\", linked_data.columns.tolist()[:10]) # Show first 10 columns\n", "\n", "# 4. 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", "# 5. Check for bias in features\n", "is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n", "\n", "# 6. 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 Celiac Disease patients and controls.\"\n", ")\n", "\n", "# 7. 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": "d7d49f29", "metadata": {}, "source": [ "### Step 8: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": null, "id": "2a897ffd", "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", "print(\"First 10 normalized gene symbols:\")\n", "print(gene_data.index[:10])\n", "\n", "# Save the normalized gene 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\"Normalized gene data saved to {out_gene_data_file}\")\n", "\n", "# 2. Load the clinical data from Step 2\n", "clinical_data_path = out_clinical_data_file\n", "clinical_data = pd.read_csv(clinical_data_path)\n", "print(f\"Loaded clinical data from {clinical_data_path}\")\n", "\n", "# Create a proper clinical DataFrame with rows as features and columns as samples\n", "# First, get column names from the CSV (these are the sample IDs)\n", "sample_ids = clinical_data.columns.tolist()\n", "# Extract and prepare the clinical features\n", "trait_values = clinical_data.iloc[0].values\n", "age_values = clinical_data.iloc[1].values\n", "gender_values = clinical_data.iloc[2].values\n", "\n", "# Create DataFrame with correct format for linking\n", "clinical_df = pd.DataFrame({\n", " trait: trait_values,\n", " 'Age': age_values,\n", " 'Gender': gender_values\n", "}, index=sample_ids).T\n", "\n", "print(f\"Clinical data shape: {clinical_df.shape}\")\n", "print(\"Clinical data preview:\")\n", "print(clinical_df.iloc[:, :5]) # Show first 5 columns\n", "\n", "# 3. Link clinical and genetic data\n", "linked_data = pd.concat([clinical_df, gene_data], axis=0)\n", "print(f\"Linked data shape after concatenation: {linked_data.shape}\")\n", "\n", "# Transpose to have samples as rows and features as columns\n", "linked_data = linked_data.T\n", "print(f\"Linked data shape after transpose: {linked_data.shape}\")\n", "print(\"Linked data preview (first 5 rows, 5 columns):\")\n", "print(linked_data.iloc[:5, :5])\n", "\n", "# 4. 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", "# 5. Check for bias in features\n", "is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n", "\n", "# 6. 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 Celiac Disease patients and controls. FDR samples were excluded from the trait analysis.\"\n", ")\n", "\n", "# 7. 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 }