{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "ddb735cf", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:42:08.952169Z", "iopub.status.busy": "2025-03-25T06:42:08.952059Z", "iopub.status.idle": "2025-03-25T06:42:09.113877Z", "shell.execute_reply": "2025-03-25T06:42:09.113516Z" } }, "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 = \"Asthma\"\n", "cohort = \"GSE270312\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Asthma\"\n", "in_cohort_dir = \"../../input/GEO/Asthma/GSE270312\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Asthma/GSE270312.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Asthma/gene_data/GSE270312.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Asthma/clinical_data/GSE270312.csv\"\n", "json_path = \"../../output/preprocess/Asthma/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "887a66e0", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "36cd3016", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:42:09.115317Z", "iopub.status.busy": "2025-03-25T06:42:09.115177Z", "iopub.status.idle": "2025-03-25T06:42:09.146945Z", "shell.execute_reply": "2025-03-25T06:42:09.146640Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"The rs6967330 minor allele in CDHR3 increased CRS exacerbations and is associated with an exaggerated interferon response to RV-A and RV-C infections\"\n", "!Series_summary\t\"Background: Adults with at least one copy of the minor allele in the rs6967330 SNP (AA/AG) in the rhinovirus (RV) receptor Cadherin related family member 3 gene (CDHR3), have a higher risk for CRS than those with two copies of the major allele (GG).\"\n", "!Series_summary\t\"Objective: To determine if the rs6967330 SNP increased the risk for acute exacerbations of chronic rhinosinusitis (AECRS) in adults and identify if their nasal cells showed a distinct pathophysiologic process activated by RV infection.\"\n", "!Series_summary\t\"Methods: We recruited adults with CRS (AG/AA,n=17; GG,n=37) and at baseline collected sinonasal outcome tests (SNOT-22), objective endoscopy scores, and nasal brushings for cells and RV viral detection. Subjects were contacted every two weeks for AECRS over one year, and if symptomatic this data was re-collected. To determine the effect of the rs6967330 SNP, air-liquid-interface (ALI) cultures were derived from nasal samples (AG/AA,n=19; GG,n=19). Cytokines and RNA transcriptome responses were measured 48 hours-post viral challenge with RV-A, RV-B, and RV-C.\"\n", "!Series_summary\t\"Results: During AECRS, adults with the AA/AG allele had 1.6x higher SNOT-22 scores, 2x higher endoscopic scores, and were 4x more likely to have RV infections during AECRS than those with the GG allele. (AA/AG) ALI cultures had significantly greater virus replication of RV-A (2.4x) and RV-C (3.5x) but not RV-B, higher levels of inflammatory cytokines, and significantly increased interferon-related pathways compared to (GG) ALI cultures.\"\n", "!Series_summary\t\"Conclusions: The minor allele in the rs6967330 SNP increases the risk for AECRS disease severity and is associated with an aberrant interferon-mediated inflammatory response to both RV-A and RV-C infections.\"\n", "!Series_overall_design\t\"To determine the effect of the rs6967330 SNP, air-liquid-interface (ALI) cultures were derived from nasal samples. RNA transcriptome responses were measured 48 hours-post viral challenge with RV-A and RV-C. A total of 90 samples were submitted for nanostring analyses.\"\n", "Sample Characteristics Dictionary:\n", "{0: ['cell type: Sinonasal Epithelial Cells'], 1: ['cdhr3 genotype: GG', 'cdhr3 genotype: AA/AG'], 2: ['gender: Female', 'gender: Male'], 3: ['asthma status: No', 'asthma status: Yes'], 4: ['presence of polyps: Yes', 'presence of polyps: No'], 5: ['allergic rhinitis status: No', 'allergic rhinitis status: Yes']}\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": "bdedf5ff", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "9fd8abde", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:42:09.148018Z", "iopub.status.busy": "2025-03-25T06:42:09.147905Z", "iopub.status.idle": "2025-03-25T06:42:09.153459Z", "shell.execute_reply": "2025-03-25T06:42:09.153166Z" } }, "outputs": [], "source": [ "# 1. Gene Expression Data Availability\n", "# Based on the background, the study involves RNA transcriptome analysis,\n", "# so this dataset should contain gene expression data\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "# For the trait (Asthma), we find it in row 3\n", "trait_row = 3\n", "\n", "# For age, there's no information in the sample characteristics\n", "age_row = None\n", "\n", "# For gender, we find it in row 2\n", "gender_row = 2\n", "\n", "# 2.2 Data Type Conversion Functions\n", "def convert_trait(value):\n", " \"\"\"Convert asthma status to binary: 1 for Yes, 0 for No.\"\"\"\n", " if pd.isna(value) or value is None:\n", " return None\n", " \n", " # Extract value after colon if present\n", " if isinstance(value, str) and ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " if isinstance(value, str):\n", " if value.lower() == 'yes':\n", " return 1\n", " elif value.lower() == 'no':\n", " return 0\n", " \n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age to continuous value.\"\"\"\n", " # This function is defined but not used since age data is not available\n", " if pd.isna(value) or value is None:\n", " return None\n", " \n", " # Extract value after colon if present\n", " if isinstance(value, str) and ':' 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: 0 for Female, 1 for Male.\"\"\"\n", " if pd.isna(value) or value is None:\n", " return None\n", " \n", " # Extract value after colon if present\n", " if isinstance(value, str) and ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " if isinstance(value, str):\n", " if value.lower() == 'female':\n", " return 0\n", " elif value.lower() == 'male':\n", " return 1\n", " \n", " return None\n", "\n", "# 3. Save Metadata for initial filtering\n", "# 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", "# Only if trait_row is not None\n", "if trait_row is not None:\n", " # Assuming clinical_data is the input DataFrame\n", " # We need to read it first from the cohort directory\n", " clinical_data_path = os.path.join(in_cohort_dir, \"clinical_data.csv\")\n", " if os.path.exists(clinical_data_path):\n", " clinical_data = pd.read_csv(clinical_data_path)\n", " \n", " # Extract clinical features\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", " # Preview the DataFrame\n", " print(\"Preview of selected clinical features:\")\n", " print(preview_df(selected_clinical_df))\n", " \n", " # Save to CSV\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " selected_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": "d1dfe8c7", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "e5a9952d", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:42:09.154461Z", "iopub.status.busy": "2025-03-25T06:42:09.154354Z", "iopub.status.idle": "2025-03-25T06:42:09.171508Z", "shell.execute_reply": "2025-03-25T06:42:09.171212Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Matrix file found: ../../input/GEO/Asthma/GSE270312/GSE270312_series_matrix.txt.gz\n", "Gene data shape: (832, 90)\n", "First 20 gene/probe identifiers:\n", "Index(['ABCF1', 'ACE', 'ACKR2', 'ACKR3', 'ACKR4', 'ACOX1', 'ACSL1', 'ACSL3',\n", " 'ACSL4', 'ACVR1', 'ADAM17', 'ADAR', 'ADGRE5', 'ADGRG3', 'ADORA2A',\n", " 'AGT', 'AHR', 'AIF1', 'AIM2', 'AKT1'],\n", " dtype='object', name='ID')\n" ] } ], "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": "23648a58", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "5aae6233", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:42:09.172518Z", "iopub.status.busy": "2025-03-25T06:42:09.172410Z", "iopub.status.idle": "2025-03-25T06:42:09.174163Z", "shell.execute_reply": "2025-03-25T06:42:09.173847Z" } }, "outputs": [], "source": [ "# Looking at the gene identifiers in the gene expression data\n", "# These identifiers (ABCF1, ACE, ACKR2, etc.) are standard human gene symbols\n", "# They match official HGNC gene symbols and do not need mapping\n", "\n", "requires_gene_mapping = False\n" ] }, { "cell_type": "markdown", "id": "87c001fc", "metadata": {}, "source": [ "### Step 5: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 6, "id": "31e04f6c", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:42:09.175142Z", "iopub.status.busy": "2025-03-25T06:42:09.175038Z", "iopub.status.idle": "2025-03-25T06:42:09.447557Z", "shell.execute_reply": "2025-03-25T06:42:09.447255Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene data saved to ../../output/preprocess/Asthma/gene_data/GSE270312.csv\n", "Clinical data saved to ../../output/preprocess/Asthma/clinical_data/GSE270312.csv\n", "Linked data shape: (90, 834)\n", "Linked data preview (first 5 rows, 5 columns):\n", " Asthma Gender ABCF1 ACE ACKR2\n", "GSM8339381 0.0 1.0 9.57557 5.71144 5.79512\n", "GSM8339382 0.0 1.0 9.05703 5.50984 5.42685\n", "GSM8339383 0.0 1.0 9.07081 5.17455 5.68615\n", "GSM8339384 0.0 1.0 9.56418 5.68938 5.53547\n", "GSM8339385 0.0 1.0 9.19873 5.16993 4.88070\n", "Data shape after handling missing values: (90, 834)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "For the feature 'Asthma', the least common label is '0.0' with 39 occurrences. This represents 43.33% of the dataset.\n", "The distribution of the feature 'Asthma' in this dataset is fine.\n", "\n", "For the feature 'Gender', the least common label is '1.0' with 90 occurrences. This represents 100.00% of the dataset.\n", "The distribution of the feature 'Gender' in this dataset is severely biased.\n", "\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Linked data saved to ../../output/preprocess/Asthma/GSE270312.csv\n" ] } ], "source": [ "# First, re-extract the necessary files from the cohort directory\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "\n", "# Read background information and clinical data again to ensure we have the correct 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", "# Get the gene data again\n", "gene_data = get_genetic_data(matrix_file)\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", "# Using the correct trait_row and gender_row identified in step 2\n", "# Extract clinical features using the appropriate conversion functions\n", "selected_clinical_data = geo_select_clinical_features(\n", " clinical_df=clinical_data,\n", " trait=trait,\n", " trait_row=3, # Using trait_row = 3 for asthma status\n", " convert_trait=lambda value: 1 if isinstance(value, str) and 'yes' in value.lower().split(':')[-1].strip() else 0,\n", " age_row=None, # No age data available\n", " convert_age=None,\n", " gender_row=2, # Using gender_row = 2\n", " convert_gender=lambda value: 1 if isinstance(value, str) and 'male' in value.lower().split(':')[-1].strip() else 0\n", ")\n", "\n", "# Save the processed clinical data\n", "os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", "selected_clinical_data.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", "linked_data = geo_link_clinical_genetic_data(selected_clinical_data, 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", "# 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", "# Check for bias in features\n", "is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n", "\n", "# 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 sinonasal epithelial cells with Asthma status information.\"\n", ")\n", "\n", "# 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": { "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 }