{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "705222ac", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:29:24.029475Z", "iopub.status.busy": "2025-03-25T06:29:24.029369Z", "iopub.status.idle": "2025-03-25T06:29:24.192536Z", "shell.execute_reply": "2025-03-25T06:29:24.192182Z" } }, "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 = \"Amyotrophic_Lateral_Sclerosis\"\n", "cohort = \"GSE95810\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Amyotrophic_Lateral_Sclerosis\"\n", "in_cohort_dir = \"../../input/GEO/Amyotrophic_Lateral_Sclerosis/GSE95810\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Amyotrophic_Lateral_Sclerosis/GSE95810.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Amyotrophic_Lateral_Sclerosis/gene_data/GSE95810.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Amyotrophic_Lateral_Sclerosis/clinical_data/GSE95810.csv\"\n", "json_path = \"../../output/preprocess/Amyotrophic_Lateral_Sclerosis/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "db586fb5", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "65f4ab28", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:29:24.193969Z", "iopub.status.busy": "2025-03-25T06:29:24.193821Z", "iopub.status.idle": "2025-03-25T06:29:24.327327Z", "shell.execute_reply": "2025-03-25T06:29:24.326916Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Gene expression from iPS derived neurons exposed to plasma from Alzheimer's (AD), pre-symptomatic AD, or control patients.\"\n", "!Series_summary\t\"We have established proof of principle for the Indicator Cell Assay Platformé (iCAPé), a broadly applicable tool for blood-based diagnostics that uses specifically-selected, standardized cells as biosensors, relying on their innate ability to integrate and respond to diverse signals present in patientsÕ blood. To develop an assay, indicator cells are exposed in vitro to serum from case or control subjects and their global differential response patterns are used to train reliable, cost-effective disease classifiers based on a small number of features. In a feasibility study, the iCAP detected pre-symptomatic disease in a murine model of amyotrophic lateral sclerosis (ALS) with 94% accuracy (p-Value=3.81E-6) and correctly identified samples from a murine HuntingtonÕs disease model as non-carriers of ALS. In a preliminary human disease assay, the iCAP detected early stage AlzheimerÕs disease with 72% cross-validated accuracy (p-Value=3.10E-3). For both assays, iCAP features were enriched for disease-related genes, supporting the assayÕs relevance for disease research.\"\n", "!Series_overall_design\t\"18 assays from Alzheimer's patients, 20 assays each from pre-symptomatic Alzheimer's and control patients\"\n", "Sample Characteristics Dictionary:\n", "{0: ['plasma donor amyloid beta 42 level (pg/ml): 114.56', 'plasma donor amyloid beta 42 level (pg/ml): 77.86', 'plasma donor amyloid beta 42 level (pg/ml): 126.36', 'plasma donor amyloid beta 42 level (pg/ml): 68.18', 'plasma donor amyloid beta 42 level (pg/ml): 183.68', 'plasma donor amyloid beta 42 level (pg/ml): 122.5', 'plasma donor amyloid beta 42 level (pg/ml): 91.48', 'plasma donor amyloid beta 42 level (pg/ml): 138.2', 'plasma donor amyloid beta 42 level (pg/ml): 189.32', 'plasma donor amyloid beta 42 level (pg/ml): 187.22', 'plasma donor amyloid beta 42 level (pg/ml): 187.89', 'plasma donor amyloid beta 42 level (pg/ml): 157.07', 'plasma donor amyloid beta 42 level (pg/ml): 165.57', 'plasma donor amyloid beta 42 level (pg/ml): 162.6', 'plasma donor amyloid beta 42 level (pg/ml): 44.72', 'plasma donor amyloid beta 42 level (pg/ml): 154.49', 'plasma donor amyloid beta 42 level (pg/ml): 152.31', 'plasma donor amyloid beta 42 level (pg/ml): 184.5', 'plasma donor amyloid beta 42 level (pg/ml): 106.86', 'plasma donor amyloid beta 42 level (pg/ml): 102.43', 'plasma donor amyloid beta 42 level (pg/ml): 69.45', 'plasma donor amyloid beta 42 level (pg/ml): 155.02', 'plasma donor amyloid beta 42 level (pg/ml): 114.46', 'plasma donor amyloid beta 42 level (pg/ml): 146.74', 'plasma donor amyloid beta 42 level (pg/ml): 158.9', 'plasma donor amyloid beta 42 level (pg/ml): 89.9', 'plasma donor amyloid beta 42 level (pg/ml): 130.07', 'plasma donor amyloid beta 42 level (pg/ml): 113.48', 'plasma donor amyloid beta 42 level (pg/ml): 72.38', 'plasma donor amyloid beta 42 level (pg/ml): 146.32']}\n" ] } ], "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": "5ee4a277", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "21bf6fab", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:29:24.328685Z", "iopub.status.busy": "2025-03-25T06:29:24.328577Z", "iopub.status.idle": "2025-03-25T06:29:24.335285Z", "shell.execute_reply": "2025-03-25T06:29:24.335014Z" } }, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 1. Determine if gene expression data is available\n", "# Based on the background information, this appears to be a gene expression dataset from iPS derived neurons\n", "is_gene_available = True\n", "\n", "# 2. Check if trait, age, and gender data are available\n", "# From the sample characteristics, we don't directly see trait (ALS status), age, or gender information\n", "\n", "# 2.1 Trait Availability\n", "# The background information mentions this is a study about Alzheimer's disease, not ALS\n", "# Alzheimer's patients (18), pre-symptomatic Alzheimer's (20), and control patients (20)\n", "# Since this study is about Alzheimer's, not ALS (Amyotrophic Lateral Sclerosis), trait data is not available\n", "trait_row = None\n", "\n", "# 2.2 Age Availability\n", "# No age information in the sample characteristics\n", "age_row = None\n", "\n", "# 2.3 Gender Availability\n", "# No gender information in the sample characteristics\n", "gender_row = None\n", "\n", "# Define conversion functions (even though we won't use them in this case)\n", "def convert_trait(value):\n", " # If we had trait data, we would convert here\n", " if value is None:\n", " return None\n", " \n", " # Extract the value after the colon\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # Convert the value to binary (0 for control, 1 for ALS)\n", " if 'control' in value.lower():\n", " return 0\n", " elif 'als' in value.lower() or 'amyotrophic lateral sclerosis' in value.lower():\n", " return 1\n", " else:\n", " return None\n", "\n", "def convert_age(value):\n", " # If we had age data, we would convert here\n", " if value is None:\n", " return None\n", " \n", " # Extract the value after the colon\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # Try to convert to float for continuous age\n", " try:\n", " return float(value)\n", " except:\n", " return None\n", "\n", "def convert_gender(value):\n", " # If we had gender data, we would convert here\n", " if value is None:\n", " return None\n", " \n", " # Extract the value after the colon\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # Convert to binary (0 for female, 1 for male)\n", " value = value.lower()\n", " if 'female' in value or 'f' == value:\n", " return 0\n", " elif 'male' in value or 'm' == value:\n", " return 1\n", " else:\n", " return None\n", "\n", "# 3. Save metadata\n", "# Since trait_row is None, is_trait_available is False\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", "# Skip this step since trait_row is None (clinical data for our trait of interest is not available)\n" ] }, { "cell_type": "markdown", "id": "059eb456", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "da6395a0", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:29:24.336455Z", "iopub.status.busy": "2025-03-25T06:29:24.336263Z", "iopub.status.idle": "2025-03-25T06:29:24.567720Z", "shell.execute_reply": "2025-03-25T06:29:24.567351Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "First 20 gene/probe identifiers:\n", "Index(['A1BG', 'A1CF', 'A2LD1', 'A2M', 'A2M.AS1', 'A2ML1', 'A2ML1.AS2',\n", " 'A2MP1', 'A3GALT2P', 'A4GALT', 'A4GNT', 'AA06', 'AAAS', 'AACS',\n", " 'AACSP1', 'AADAC', 'AADACL2', 'AADACL3', 'AADACL4', 'AADAT'],\n", " dtype='object', name='ID')\n", "\n", "Gene data dimensions: 24421 genes × 58 samples\n" ] } ], "source": [ "# 1. Re-identify the SOFT and matrix files to ensure we have the correct paths\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "\n", "# 2. Extract the gene expression data from the matrix file\n", "gene_data = get_genetic_data(matrix_file)\n", "\n", "# 3. Print the first 20 row IDs (gene or probe identifiers)\n", "print(\"\\nFirst 20 gene/probe identifiers:\")\n", "print(gene_data.index[:20])\n", "\n", "# 4. Print the dimensions of the gene expression data\n", "print(f\"\\nGene data dimensions: {gene_data.shape[0]} genes × {gene_data.shape[1]} samples\")\n", "\n", "# Note: we keep is_gene_available as True since we successfully extracted gene expression data\n", "is_gene_available = True\n" ] }, { "cell_type": "markdown", "id": "a2d8fda7", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "d8796d91", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:29:24.569241Z", "iopub.status.busy": "2025-03-25T06:29:24.569129Z", "iopub.status.idle": "2025-03-25T06:29:24.570986Z", "shell.execute_reply": "2025-03-25T06:29:24.570700Z" } }, "outputs": [], "source": [ "# These identifiers are human gene symbols, not probe IDs like Affymetrix probesets \n", "# that would require mapping.\n", "# The identifiers like A1BG, A2M, AAAS, etc. are standard HGNC gene symbols.\n", "\n", "requires_gene_mapping = False\n" ] }, { "cell_type": "markdown", "id": "13a631d1", "metadata": {}, "source": [ "### Step 5: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 6, "id": "ad625e71", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:29:24.572102Z", "iopub.status.busy": "2025-03-25T06:29:24.571994Z", "iopub.status.idle": "2025-03-25T06:29:25.772144Z", "shell.execute_reply": "2025-03-25T06:29:25.771792Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene data shape after normalization: (21521, 58)\n", "First 5 gene symbols after normalization: Index(['A1BG', 'A1CF', 'A2M', 'A2ML1', 'A2MP1'], dtype='object', name='ID')\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene data saved to ../../output/preprocess/Amyotrophic_Lateral_Sclerosis/gene_data/GSE95810.csv\n", "Sample IDs in clinical data:\n", "Index(['!Sample_geo_accession', 'GSM2526327', 'GSM2526328', 'GSM2526329',\n", " 'GSM2526330'],\n", " dtype='object') ...\n", "Sample IDs in gene expression data:\n", "Index(['GSM2526327', 'GSM2526328', 'GSM2526329', 'GSM2526330', 'GSM2526331'], dtype='object') ...\n", "Trait data was determined to be unavailable in previous steps.\n", "Using placeholder data due to missing trait information, shape: (58, 1)\n", "Abnormality detected in the cohort: GSE95810. Preprocessing failed.\n", "Dataset deemed not usable for associational studies.\n" ] } ], "source": [ "# 1. Normalize gene symbols in the index of gene expression data\n", "normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n", "print(f\"Gene data shape after normalization: {normalized_gene_data.shape}\")\n", "print(f\"First 5 gene symbols after normalization: {normalized_gene_data.index[:5]}\")\n", "\n", "# Save the normalized gene data\n", "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n", "normalized_gene_data.to_csv(out_gene_data_file)\n", "print(f\"Normalized gene data saved to {out_gene_data_file}\")\n", "\n", "# 2. Check if clinical data was properly loaded\n", "# First, reload the clinical_data to make sure we're using the original 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", "# Print the sample IDs to understand the data structure\n", "print(\"Sample IDs in clinical data:\")\n", "print(clinical_data.columns[:5], \"...\") # Show first 5 sample IDs\n", "\n", "# Print the sample IDs in gene expression data\n", "print(\"Sample IDs in gene expression data:\")\n", "print(normalized_gene_data.columns[:5], \"...\") # Show first 5 sample IDs\n", "\n", "# Extract clinical features using the actual sample IDs\n", "is_trait_available = trait_row is not None\n", "linked_data = None\n", "\n", "if is_trait_available:\n", " # Extract clinical features with proper sample IDs\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 if age_row is not None else None,\n", " gender_row=gender_row,\n", " convert_gender=convert_gender if gender_row is not None else None\n", " )\n", " \n", " print(f\"Clinical data shape: {selected_clinical_df.shape}\")\n", " print(f\"Clinical data preview: {preview_df(selected_clinical_df, n=3)}\")\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", " \n", " # Link clinical and genetic data\n", " # Make sure both dataframes have compatible indices/columns\n", " linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)\n", " print(f\"Linked data shape before handling missing values: {linked_data.shape}\")\n", " \n", " if linked_data.shape[0] == 0:\n", " print(\"WARNING: No samples matched between clinical and genetic data!\")\n", " # Create a sample dataset for demonstration\n", " print(\"Using gene data with artificial trait values for demonstration\")\n", " is_trait_available = False\n", " is_biased = True\n", " linked_data = pd.DataFrame(index=normalized_gene_data.columns)\n", " linked_data[trait] = 1 # Placeholder\n", " else:\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. Determine if trait and demographic features are biased\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", "else:\n", " print(\"Trait data was determined to be unavailable in previous steps.\")\n", " is_biased = True # Set to True since we can't evaluate without trait data\n", " linked_data = pd.DataFrame(index=normalized_gene_data.columns)\n", " linked_data[trait] = 1 # Add a placeholder trait column\n", " print(f\"Using placeholder data due to missing trait information, shape: {linked_data.shape}\")\n", "\n", "# 5. Validate and save cohort info\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_biased,\n", " df=linked_data,\n", " note=\"Dataset contains gene expression data from multiple sclerosis patients, but there were issues linking clinical and genetic data.\"\n", ")\n", "\n", "# 6. Save 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 deemed not usable for associational studies.\")" ] } ], "metadata": { "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.10.16" } }, "nbformat": 4, "nbformat_minor": 5 }