{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "4993ef44", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:23:10.163356Z", "iopub.status.busy": "2025-03-25T06:23:10.163136Z", "iopub.status.idle": "2025-03-25T06:23:10.328226Z", "shell.execute_reply": "2025-03-25T06:23:10.327910Z" } }, "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 = \"Allergies\"\n", "cohort = \"GSE169149\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Allergies\"\n", "in_cohort_dir = \"../../input/GEO/Allergies/GSE169149\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Allergies/GSE169149.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Allergies/gene_data/GSE169149.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Allergies/clinical_data/GSE169149.csv\"\n", "json_path = \"../../output/preprocess/Allergies/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "38b130e4", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "39a0275d", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:23:10.329627Z", "iopub.status.busy": "2025-03-25T06:23:10.329488Z", "iopub.status.idle": "2025-03-25T06:23:10.360515Z", "shell.execute_reply": "2025-03-25T06:23:10.360227Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Evaluation of tofacitinib in cutaneous sarcoidosis\"\n", "!Series_summary\t\"This SuperSeries is composed of the SubSeries listed below.\"\n", "!Series_overall_design\t\"Refer to individual Series\"\n", "Sample Characteristics Dictionary:\n", "{0: ['subject status: Sarcoidosis patient', 'subject status: healthy control'], 1: ['treatment: none', 'treatment: tofacitinib'], 2: ['tissue: Blood']}\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": "1ea8958d", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "24ee6f26", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:23:10.361524Z", "iopub.status.busy": "2025-03-25T06:23:10.361422Z", "iopub.status.idle": "2025-03-25T06:23:10.368296Z", "shell.execute_reply": "2025-03-25T06:23:10.368012Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Sample Characteristics Dictionary:\n", "{0: ['subject status: Sarcoidosis patient', 'subject status: healthy control'], 1: ['treatment: none', 'treatment: tofacitinib'], 2: ['tissue: Blood']}\n", "Preview of extracted clinical data:\n", "{'GSM5176932': [1.0], 'GSM5176933': [1.0], 'GSM5176934': [1.0], 'GSM5176935': [1.0], 'GSM5176936': [1.0], 'GSM5176937': [1.0], 'GSM5176938': [1.0], 'GSM5176939': [1.0], 'GSM5176940': [1.0], 'GSM5176941': [1.0], 'GSM5176942': [1.0], 'GSM5176943': [1.0], 'GSM5176944': [1.0], 'GSM5176945': [1.0], 'GSM5176946': [1.0], 'GSM5176947': [1.0], 'GSM5176948': [1.0], 'GSM5176949': [1.0], 'GSM5176950': [1.0], 'GSM5176951': [1.0], 'GSM5176952': [0.0], 'GSM5176953': [0.0], 'GSM5176954': [0.0], 'GSM5176955': [0.0], 'GSM5176956': [0.0], 'GSM5176957': [0.0], 'GSM5176958': [0.0], 'GSM5176959': [0.0], 'GSM5176960': [0.0], 'GSM5176961': [0.0], 'GSM5176962': [0.0]}\n", "Clinical data saved to ../../output/preprocess/Allergies/clinical_data/GSE169149.csv\n" ] } ], "source": [ "# Check the available data in the sample characteristics dictionary\n", "print(\"Sample Characteristics Dictionary:\")\n", "print({0: ['subject status: Sarcoidosis patient', 'subject status: healthy control'], \n", " 1: ['treatment: none', 'treatment: tofacitinib'], \n", " 2: ['tissue: Blood']})\n", "\n", "# 1. Gene Expression Data Availability\n", "# Based on the background information, this appears to be a blood gene expression dataset for sarcoidosis\n", "is_gene_available = True # Blood tissue samples likely contain gene expression data\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "trait_row = 0 # The trait (Allergies/Sarcoidosis status) is in row 0\n", "age_row = None # Age information is not available in the sample characteristics\n", "gender_row = None # Gender information is not available in the sample characteristics\n", "\n", "# 2.2 Data Type Conversion Functions\n", "def convert_trait(value):\n", " \"\"\"Convert trait data to binary format (0: control, 1: sarcoidosis)\"\"\"\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", " if \"sarcoidosis\" in value.lower() or \"patient\" in value.lower():\n", " return 1\n", " elif \"healthy\" in value.lower() or \"control\" in value.lower():\n", " return 0\n", " return None\n", "\n", "# Define convert_age and convert_gender as None since the data is not available\n", "convert_age = None\n", "convert_gender = None\n", "\n", "# 3. Save Metadata\n", "# Determine if trait data is available\n", "is_trait_available = trait_row is not None\n", "\n", "# Save initial metadata\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 data is available, extract clinical features\n", "if trait_row is not None:\n", " # Load clinical data (this variable should be provided from previous steps)\n", " # For this example, let's assume clinical_data is already defined\n", " \n", " # Make sure the clinical_data variable exists before using it\n", " try:\n", " # Extract clinical features using the library function\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 extracted clinical data:\")\n", " print(preview_df(selected_clinical_df))\n", " \n", " # Save the clinical data to a CSV file\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", " except NameError:\n", " print(\"Clinical data not available from previous steps\")\n" ] }, { "cell_type": "markdown", "id": "c4dfa7da", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "312018bb", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:23:10.369265Z", "iopub.status.busy": "2025-03-25T06:23:10.369164Z", "iopub.status.idle": "2025-03-25T06:23:10.379089Z", "shell.execute_reply": "2025-03-25T06:23:10.378817Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "First 20 gene/probe identifiers:\n", "Index(['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13',\n", " '14', '15', '16', '17', '18', '19', '20'],\n", " dtype='object', name='ID')\n" ] } ], "source": [ "# 1. First get the file paths again to access the matrix file\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "\n", "# 2. Use the get_genetic_data function from the library to get the gene_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) for future observation\n", "print(\"First 20 gene/probe identifiers:\")\n", "print(gene_data.index[:20])\n" ] }, { "cell_type": "markdown", "id": "de4da072", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "a3c18498", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:23:10.380019Z", "iopub.status.busy": "2025-03-25T06:23:10.379916Z", "iopub.status.idle": "2025-03-25T06:23:10.381605Z", "shell.execute_reply": "2025-03-25T06:23:10.381340Z" } }, "outputs": [], "source": [ "# Analyzing the identifiers provided\n", "\n", "# The observed identifiers are numeric (1, 2, 3, etc.) which are not standard human gene symbols\n", "# Standard human gene symbols would typically be alphanumeric strings like \"BRCA1\", \"TP53\", etc.\n", "# These appear to be just row indices or probe IDs that would need to be mapped to actual gene symbols\n", "\n", "# Therefore, gene mapping is required\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "a9738511", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "7e74b98c", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:23:10.382533Z", "iopub.status.busy": "2025-03-25T06:23:10.382438Z", "iopub.status.idle": "2025-03-25T06:23:10.435534Z", "shell.execute_reply": "2025-03-25T06:23:10.435244Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene annotation preview:\n", "{'ID': ['1', '2', '3', '4', '5'], 'Assay': ['AARSD1', 'ABHD14B', 'ABL1', 'ACAA1', 'ACAN'], 'OlinkID': ['OID21311', 'OID20921', 'OID21280', 'OID21269', 'OID20159'], 'PT_ACC': ['Q9BTE6', 'Q96IU4', 'P00519', 'P09110', 'P16112'], 'Panel': ['Oncology', 'Neurology', 'Oncology', 'Oncology', 'Cardiometabolic'], 'SPOT_ID': [nan, nan, nan, nan, nan]}\n" ] } ], "source": [ "# 1. First get the file paths using geo_get_relevant_filepaths function\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "\n", "# 2. 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", "# 3. 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": "bd2e3e44", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "44bdfd55", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:23:10.436663Z", "iopub.status.busy": "2025-03-25T06:23:10.436561Z", "iopub.status.idle": "2025-03-25T06:23:10.516724Z", "shell.execute_reply": "2025-03-25T06:23:10.516377Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "First few rows of gene-level expression data:\n", " GSM5176932 GSM5176933 GSM5176934 GSM5176935 GSM5176936 \\\n", "Gene \n", "AARSD1 3.4878 3.6728 4.1162 4.7169 3.6683 \n", "ABHD14B 1.7953 1.6497 3.0499 2.6048 1.9029 \n", "ABL1 2.6829 2.4827 3.3944 3.3331 2.6946 \n", "ACAA1 1.4306 0.9938 3.3866 2.7677 3.3732 \n", "ACAN 0.3385 0.2088 0.0150 -0.4124 -0.6523 \n", "\n", " GSM5176937 GSM5176938 GSM5176939 GSM5176940 GSM5176941 ... \\\n", "Gene ... \n", "AARSD1 3.6745 5.1706 3.0317 3.1368 4.8808 ... \n", "ABHD14B 1.4334 3.4131 2.1466 1.4771 4.1245 ... \n", "ABL1 3.1111 5.3688 2.6608 1.5761 4.6803 ... \n", "ACAA1 2.4944 3.2448 2.1226 0.4455 3.5292 ... \n", "ACAN -0.6931 -0.3421 0.2628 0.1606 0.0338 ... \n", "\n", " GSM5176953 GSM5176954 GSM5176955 GSM5176956 GSM5176957 \\\n", "Gene \n", "AARSD1 3.3435 4.4100 3.1226 4.9404 3.2793 \n", "ABHD14B 2.2767 3.1853 1.6759 4.4350 1.1119 \n", "ABL1 3.2717 4.5302 2.1446 2.8390 2.0160 \n", "ACAA1 1.8111 2.4088 0.5752 -0.2347 0.4655 \n", "ACAN -0.3127 -0.2813 0.5368 0.7278 -0.4408 \n", "\n", " GSM5176958 GSM5176959 GSM5176960 GSM5176961 GSM5176962 \n", "Gene \n", "AARSD1 2.8422 5.4656 5.1727 3.1816 3.7223 \n", "ABHD14B 1.2122 2.1448 4.0294 1.3713 1.6598 \n", "ABL1 1.8892 1.1338 4.7068 1.8993 2.3119 \n", "ACAA1 -0.0469 4.1731 3.2356 -0.2651 1.2224 \n", "ACAN 1.0610 0.0869 -0.0970 0.0715 0.8705 \n", "\n", "[5 rows x 31 columns]\n" ] } ], "source": [ "# 1. Observe gene identifiers and gene annotation data\n", "# From the output in steps 3 and 5, we can see:\n", "# - Gene identifiers in gene expression data are numeric strings ('1', '2', '3', etc.)\n", "# - In the gene annotation, the 'ID' column matches these identifiers, and 'Assay' column contains gene symbols\n", "\n", "# 2. Get a gene mapping dataframe by extracting the relevant columns\n", "prob_col = 'ID' # Column containing probe identifiers\n", "gene_col = 'Assay' # Column containing gene symbols\n", "gene_mapping = get_gene_mapping(gene_annotation, prob_col, gene_col)\n", "\n", "# 3. Apply gene mapping to convert probe-level measurements to gene-level expression data\n", "gene_data = apply_gene_mapping(gene_data, gene_mapping)\n", "\n", "# Print the first few rows of the resulting gene expression dataframe to verify the mapping\n", "print(\"First few rows of gene-level expression data:\")\n", "print(gene_data.head())\n" ] }, { "cell_type": "markdown", "id": "80c9d341", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "c0597054", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:23:10.518015Z", "iopub.status.busy": "2025-03-25T06:23:10.517897Z", "iopub.status.idle": "2025-03-25T06:23:10.893051Z", "shell.execute_reply": "2025-03-25T06:23:10.892675Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Normalizing gene symbols...\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene data shape after normalization: (1453, 31)\n", "Normalized gene data saved to ../../output/preprocess/Allergies/gene_data/GSE169149.csv\n", "Loading the original clinical data...\n", "Extracting clinical features...\n", "Clinical data preview:\n", "{'GSM5176932': [1.0], 'GSM5176933': [1.0], 'GSM5176934': [1.0], 'GSM5176935': [1.0], 'GSM5176936': [1.0], 'GSM5176937': [1.0], 'GSM5176938': [1.0], 'GSM5176939': [1.0], 'GSM5176940': [1.0], 'GSM5176941': [1.0], 'GSM5176942': [1.0], 'GSM5176943': [1.0], 'GSM5176944': [1.0], 'GSM5176945': [1.0], 'GSM5176946': [1.0], 'GSM5176947': [1.0], 'GSM5176948': [1.0], 'GSM5176949': [1.0], 'GSM5176950': [1.0], 'GSM5176951': [1.0], 'GSM5176952': [0.0], 'GSM5176953': [0.0], 'GSM5176954': [0.0], 'GSM5176955': [0.0], 'GSM5176956': [0.0], 'GSM5176957': [0.0], 'GSM5176958': [0.0], 'GSM5176959': [0.0], 'GSM5176960': [0.0], 'GSM5176961': [0.0], 'GSM5176962': [0.0]}\n", "Clinical data saved to ../../output/preprocess/Allergies/clinical_data/GSE169149.csv\n", "Linking clinical and genetic data...\n", "Linked data shape: (31, 1454)\n", "Handling missing values...\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Linked data shape after handling missing values: (31, 1454)\n", "Checking for bias in trait distribution...\n", "For the feature 'Allergies', the least common label is '0.0' with 11 occurrences. This represents 35.48% of the dataset.\n", "The distribution of the feature 'Allergies' in this dataset is fine.\n", "\n", "A new JSON file was created at: ../../output/preprocess/Allergies/cohort_info.json\n", "Dataset usability: True\n", "Linked data saved to ../../output/preprocess/Allergies/GSE169149.csv\n" ] } ], "source": [ "# 1. Normalize gene symbols in the gene expression data\n", "print(\"Normalizing gene symbols...\")\n", "normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n", "print(f\"Gene data shape after normalization: {normalized_gene_data.shape}\")\n", "\n", "# Save the normalized gene data to a CSV file\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. Link the clinical and genetic data\n", "print(\"Loading the original clinical data...\")\n", "# Get the matrix file again to ensure we have the proper 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(\"Extracting clinical features...\")\n", "# Use the clinical_data obtained directly from the matrix file\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(\"Clinical data preview:\")\n", "print(preview_df(selected_clinical_df))\n", "\n", "# Save the clinical data to a CSV file\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 using the normalized gene data\n", "print(\"Linking clinical and genetic data...\")\n", "linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)\n", "print(f\"Linked data shape: {linked_data.shape}\")\n", "\n", "# 3. Handle missing values in the linked data\n", "print(\"Handling missing values...\")\n", "linked_data = handle_missing_values(linked_data, trait)\n", "print(f\"Linked data shape after handling missing values: {linked_data.shape}\")\n", "\n", "# 4. Check if trait is biased\n", "print(\"Checking for bias in trait distribution...\")\n", "is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n", "\n", "# 5. Final validation\n", "note = \"Dataset contains gene expression data from bronchial brushings from control individuals and patients with asthma after rhinovirus infection in vivo, as described in the study 'Rhinovirus-induced epithelial RIG-I inflammasome suppresses antiviral immunity and promotes inflammation in asthma and COVID-19'.\"\n", "is_usable = validate_and_save_cohort_info(\n", " is_final=True,\n", " cohort=cohort,\n", " info_path=json_path,\n", " is_gene_available=is_gene_available,\n", " is_trait_available=is_trait_available,\n", " is_biased=is_biased,\n", " df=linked_data,\n", " note=note\n", ")\n", "\n", "print(f\"Dataset usability: {is_usable}\")\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 is not usable for trait-gene association studies due to bias or other issues.\")" ] } ], "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 }