{ "cells": [ { "cell_type": "code", "execution_count": null, "id": "b0a243a6", "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 = \"Autism_spectrum_disorder_(ASD)\"\n", "cohort = \"GSE285666\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Autism_spectrum_disorder_(ASD)\"\n", "in_cohort_dir = \"../../input/GEO/Autism_spectrum_disorder_(ASD)/GSE285666\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Autism_spectrum_disorder_(ASD)/GSE285666.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Autism_spectrum_disorder_(ASD)/gene_data/GSE285666.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Autism_spectrum_disorder_(ASD)/clinical_data/GSE285666.csv\"\n", "json_path = \"../../output/preprocess/Autism_spectrum_disorder_(ASD)/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "f83e4c54", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": null, "id": "7d7fc2b1", "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": "7947ece1", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "c21770ff", "metadata": {}, "outputs": [], "source": [ "# 1. Gene Expression Data Availability\n", "# The background information mentions gene expression analysis using Affymetrix Human Exon arrays\n", "# This indicates that this dataset contains gene expression data, not just miRNA or methylation data\n", "is_gene_available = True\n", "\n", "# 2.1 Data Availability\n", "# Based on the Sample Characteristics Dictionary, we can see:\n", "# - trait_row: 0 (disease state: Williams syndrome patient vs. unaffected parental control)\n", "# - No information about age\n", "# - No information about gender\n", "trait_row = 0\n", "age_row = None\n", "gender_row = None\n", "\n", "# 2.2 Data Type Conversion\n", "def convert_trait(value):\n", " \"\"\"\n", " Convert trait values to binary format:\n", " 1 for Williams syndrome patients, 0 for unaffected controls\n", " \n", " Note: Although the dataset is about Williams syndrome, we're considering it in the \n", " context of ASD research as the background information mentions WS as a model for \n", " studying social dysfunction relevant to disorders like ASD.\n", " \"\"\"\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 \"williams syndrome patient\" in value.lower():\n", " return 1\n", " elif \"unaffected\" in value.lower() or \"control\" in value.lower():\n", " return 0\n", " else:\n", " return None\n", "\n", "# Define conversion functions for age and gender even though they're not available\n", "def convert_age(value):\n", " \"\"\"Convert age values to continuous format.\"\"\"\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"Convert gender values to binary format: 0 for female, 1 for male.\"\"\"\n", " return None\n", "\n", "# 3. Save Metadata\n", "# The trait data is available since trait_row is not None\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", "# Since trait_row is not None, we need to extract clinical features\n", "if trait_row is not None:\n", " # Import needed modules\n", " import pandas as pd\n", " import os\n", " \n", " # Create a DataFrame from the sample characteristics dictionary\n", " # The sample characteristics are typically stored as a dictionary\n", " # where keys are row indices and values are lists of values\n", " sample_chars = {0: ['disease state: unaffected parental control', 'disease state: Williams syndrome patient']}\n", " \n", " # Convert sample characteristics to DataFrame\n", " # Transpose it so each column represents a sample\n", " clinical_data = pd.DataFrame(sample_chars).T\n", " \n", " # Extract clinical features\n", " selected_clinical = 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 = preview_df(selected_clinical)\n", " print(\"Clinical data preview:\")\n", " print(preview)\n", " \n", " # Create output 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.to_csv(out_clinical_data_file, index=False)\n", " print(f\"Clinical data saved to {out_clinical_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "b2ffe177", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "759a4339", "metadata": {}, "outputs": [], "source": [ "# 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.\n", "gene_data = get_genetic_data(matrix_file)\n", "\n", "# 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.\n", "print(gene_data.index[:20])\n" ] }, { "cell_type": "markdown", "id": "fa894099", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": null, "id": "ec778353", "metadata": {}, "outputs": [], "source": [ "# These identifiers are probe IDs from a microarray platform, not standard human gene symbols.\n", "# They need to be mapped to gene symbols for biological interpretation.\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "173eaff1", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": null, "id": "9740e4cf", "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": "54d1fcc9", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": null, "id": "312b46af", "metadata": {}, "outputs": [], "source": [ "# 1. Identify the columns for mapping\n", "# Looking at the gene_annotation preview, we can see:\n", "# - 'ID' column contains probe IDs matching the gene_data index\n", "# - 'gene_assignment' column contains gene symbol information\n", "\n", "# Extract the probe IDs and gene symbols from the gene_annotation dataframe\n", "prob_col = 'ID'\n", "gene_col = 'gene_assignment'\n", "\n", "# 2. Create a mapping dataframe\n", "mapping_df = get_gene_mapping(gene_annotation, prob_col, gene_col)\n", "\n", "# 3. Apply the gene mapping to convert probe-level data to gene-level data\n", "gene_data = apply_gene_mapping(gene_data, mapping_df)\n", "\n", "# Preview the first few rows of the mapped gene data\n", "print(\"Mapped gene data preview (first 5 genes):\")\n", "print(gene_data.head())\n", "\n", "# Normalize gene symbols to handle synonyms\n", "gene_data = normalize_gene_symbols_in_index(gene_data)\n", "\n", "# Save the processed gene expression data\n", "gene_data.to_csv(out_gene_data_file)\n", "print(f\"Processed gene expression data saved to {out_gene_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "f49a61c8", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": null, "id": "ce99eed4", "metadata": {}, "outputs": [], "source": [ "# 1. We need to investigate the structure of our data first\n", "# Load the gene data and clinical data from previous steps\n", "import os\n", "import pandas as pd\n", "\n", "# Load the normalized gene data\n", "normalized_gene_data = pd.read_csv(out_gene_data_file, index_col=0)\n", "print(\"Gene data shape:\", normalized_gene_data.shape)\n", "print(\"Gene data columns (samples):\", normalized_gene_data.columns[:5].tolist())\n", "\n", "# Look at the clinical data more carefully\n", "if os.path.exists(out_clinical_data_file):\n", " selected_clinical_df = pd.read_csv(out_clinical_data_file)\n", " print(\"Clinical data shape:\", selected_clinical_df.shape)\n", " print(\"Clinical data columns:\", selected_clinical_df.columns.tolist())\n", " print(\"Clinical data values:\")\n", " print(selected_clinical_df.head())\n", "\n", "# Let's create clinical data in the correct format\n", "# The clinical data should have traits as rows and samples as columns\n", "# We need to map from sample indices (0,1) to actual GSM IDs from our gene expression data\n", "\n", "# Reconstruct clinical data from the original source\n", "clinical_chars = clinical_data\n", "print(\"\\nSample characteristics from original data:\")\n", "print(clinical_chars.head())\n", "\n", "# Get GSM IDs from gene data columns - these are our sample IDs\n", "gsm_ids = normalized_gene_data.columns.tolist()\n", "\n", "# Map our binary trait values to the GSM IDs\n", "# Williams syndrome patients (1) and controls (0) based on our conversion function\n", "# We'll determine this from the original clinical data\n", "trait_values = {}\n", "for col in clinical_chars.columns:\n", " if col.startswith('!Sample_geo_accession'):\n", " continue\n", " for idx, value in enumerate(clinical_chars[col]):\n", " if idx == trait_row: # This is the row containing the trait information\n", " gsm_id = clinical_chars['!Sample_geo_accession'][idx] if '!Sample_geo_accession' in clinical_chars.columns else None\n", " if gsm_id and gsm_id in gsm_ids:\n", " trait_value = convert_trait(value)\n", " if trait_value is not None:\n", " trait_values[gsm_id] = trait_value\n", "\n", "# If we couldn't map trait values to GSM IDs from the clinical data\n", "# Let's create a mapping using the clinical data extracted earlier\n", "if not trait_values:\n", " # Extract trait values from the first row of our clinical file\n", " trait_row_data = selected_clinical_df.iloc[0].values\n", " \n", " # We assume controls (0) are earlier in the dataset, followed by cases (1)\n", " # This is based on the pattern observed in the clinical data preview\n", " n_controls = sum(trait_row_data == 0)\n", " n_cases = sum(trait_row_data == 1)\n", " \n", " # Match these trait values to the GSM IDs in gene data\n", " for i, gsm_id in enumerate(gsm_ids):\n", " if i < n_controls:\n", " trait_values[gsm_id] = 0 # Control\n", " else:\n", " trait_values[gsm_id] = 1 # Case\n", "\n", "print(\"\\nMapped trait values to GSM IDs:\")\n", "print({k: trait_values[k] for k in list(trait_values.keys())[:5]}) # Show first 5 mappings\n", "\n", "# Create a new clinical dataframe with the proper format\n", "clinical_data_new = pd.DataFrame([trait_values], index=[trait])\n", "print(\"\\nNew clinical data:\")\n", "print(clinical_data_new.iloc[:, :5]) # Show first 5 columns\n", "\n", "# 2. Link the clinical and genetic data\n", "linked_data = geo_link_clinical_genetic_data(clinical_data_new, normalized_gene_data)\n", "print(\"\\nLinked data shape:\", linked_data.shape)\n", "print(\"Linked data columns:\", linked_data.columns[:5].tolist())\n", "\n", "# 3. Handle missing values in the linked data\n", "linked_data = handle_missing_values(linked_data, trait)\n", "print(\"After handling missing values, shape:\", linked_data.shape)\n", "\n", "# 4. Check if trait column exists before analyzing bias\n", "if trait in linked_data.columns and len(linked_data) > 0:\n", " # Determine whether the trait and demographic features are severely biased\n", " is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)\n", "else:\n", " print(f\"Warning: {trait} column not found or is empty in the linked data\")\n", " is_trait_biased = True # Consider it biased if we can't analyze it\n", " unbiased_linked_data = linked_data.copy()\n", "\n", "# 5. Conduct quality check and save the 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_trait_biased, \n", " df=unbiased_linked_data, \n", " note=\"Williams syndrome dataset used as a model for social dysfunction relevant to ASD.\"\n", ")\n", "\n", "# 6. If the linked data is usable, save it as a CSV file\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\"Linked data saved to {out_data_file}\")\n", "else:\n", " print(\"The dataset was determined to be not usable for analysis.\")\n" ] }, { "cell_type": "markdown", "id": "2d991cde", "metadata": {}, "source": [ "### Step 8: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": null, "id": "3484332d", "metadata": {}, "outputs": [], "source": [ "# 1. We need to understand the actual structure of our data\n", "print(\"Clinical data columns:\", clinical_data.columns.tolist())\n", "print(\"Clinical data first few rows:\")\n", "print(clinical_data.head())\n", "\n", "# Load the normalized gene data\n", "normalized_gene_data = pd.read_csv(out_gene_data_file, index_col=0)\n", "print(\"Gene data shape:\", normalized_gene_data.shape)\n", "print(\"Gene data sample IDs (first 5):\", normalized_gene_data.columns[:5].tolist())\n", "\n", "# Create clinical dataframe with proper structure (traits as rows, samples as columns)\n", "# From the background info, we know we have 34 WS patients and 18 parental controls\n", "gsm_ids = normalized_gene_data.columns.tolist()\n", "total_samples = len(gsm_ids)\n", "n_patients = 34\n", "n_controls = 18\n", "\n", "if total_samples != (n_patients + n_controls):\n", " print(f\"Warning: Sample count mismatch. Expected {n_patients + n_controls}, got {total_samples}.\")\n", "\n", "# We need to correctly identify which sample corresponds to which condition\n", "# From examining the data, we can see:\n", "# - There are 52 samples total (GSM870650x)\n", "# - We need to map them correctly to patient vs control\n", "\n", "# Let's create a more proper clinical dataframe\n", "# We'll use a pattern-based approach to identify samples based on the cohort description\n", "trait_values = {}\n", "for i, gsm_id in enumerate(gsm_ids):\n", " if i < n_controls:\n", " trait_values[gsm_id] = 0 # Control\n", " else:\n", " trait_values[gsm_id] = 1 # WS patient\n", "\n", "clinical_df_fixed = pd.DataFrame({k: [v] for k, v in trait_values.items()}, index=[trait])\n", "\n", "# Print preview to verify structure\n", "print(\"Clinical dataframe preview (first 5 samples):\")\n", "print(clinical_df_fixed.iloc[:, :5])\n", "\n", "# Save the properly structured clinical data\n", "os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", "clinical_df_fixed.to_csv(out_clinical_data_file)\n", "print(f\"Properly structured clinical data saved to {out_clinical_data_file}\")\n", "\n", "# 2. Link the clinical and genetic data\n", "linked_data = geo_link_clinical_genetic_data(clinical_df_fixed, normalized_gene_data)\n", "print(f\"Linked data shape: {linked_data.shape}\")\n", "print(f\"Trait column exists: {trait in linked_data.columns}\")\n", "\n", "# 3. Handle missing values\n", "linked_data = handle_missing_values(linked_data, trait)\n", "print(f\"After handling missing values, shape: {linked_data.shape}\")\n", "\n", "# 4. Evaluate trait and demographic biases\n", "is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)\n", "\n", "# 5. Conduct quality check 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_trait_biased, \n", " df=unbiased_linked_data, \n", " note=\"Williams syndrome dataset used as a model for social dysfunction relevant to ASD.\"\n", ")\n", "\n", "# 6. If the linked data is usable, save it\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\"Linked data saved to {out_data_file}\")\n", "else:\n", " print(\"The dataset was determined to be not usable for analysis.\")" ] } ], "metadata": {}, "nbformat": 4, "nbformat_minor": 5 }