{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "5240718c", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:41:54.882163Z", "iopub.status.busy": "2025-03-25T06:41:54.881977Z", "iopub.status.idle": "2025-03-25T06:41:55.050315Z", "shell.execute_reply": "2025-03-25T06:41:55.049910Z" } }, "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 = \"GSE205151\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Asthma\"\n", "in_cohort_dir = \"../../input/GEO/Asthma/GSE205151\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Asthma/GSE205151.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Asthma/gene_data/GSE205151.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Asthma/clinical_data/GSE205151.csv\"\n", "json_path = \"../../output/preprocess/Asthma/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "3140b43f", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "0ad75ca0", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:41:55.051845Z", "iopub.status.busy": "2025-03-25T06:41:55.051686Z", "iopub.status.idle": "2025-03-25T06:41:55.075598Z", "shell.execute_reply": "2025-03-25T06:41:55.075265Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Functional Immunophenotyping of Children with Critical Status Asthmaticus Identifies Differential Gene Expression Responses in Neutrophils Exposed to a Poly(I:C) Stimulus\"\n", "!Series_summary\t\"We determined whether we could identify clusters of children with critical asthma by functional immunophenotyping using an intracellular viral analog stimulus.\"\n", "!Series_summary\t\"We performed a single-center, prospective, observational cohort study of 43 children ages 6 – 17 years admitted to a pediatric intensive care unit for an asthma attack between July 2019 to February 2021.\"\n", "!Series_overall_design\t\"Neutrophils were isolated from children, stimulated overnight with LyoVec poly(I:C), and mRNA was analyzed using a targeted Nanostring immunology array. Network analysis of the differentially expressed transcripts for the paired LyoVec poly(I:C) samples was performed.\"\n", "Sample Characteristics Dictionary:\n", "{0: ['polyic_stimulation: Unstimulated', 'polyic_stimulation: Stimulated', 'polyic_stimulation: No'], 1: ['cluster: 1', 'cluster: 2', nan]}\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": "63102b45", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "59e2a46c", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:41:55.076753Z", "iopub.status.busy": "2025-03-25T06:41:55.076636Z", "iopub.status.idle": "2025-03-25T06:41:55.109649Z", "shell.execute_reply": "2025-03-25T06:41:55.109314Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Available files in ../../input/GEO/Asthma/GSE205151: ['GSE205151_family.soft.gz', 'GSE205151_series_matrix.txt.gz']\n", "Found series matrix file: ../../input/GEO/Asthma/GSE205151/GSE205151_series_matrix.txt.gz\n", "Extracted sample characteristics:\n", "Row 0: ['\"polyic_stimulation: Stimulated\"', '\"polyic_stimulation: Unstimulated\"', '\"polyic_stimulation: No\"']\n", "Row 1: ['\"\"', '\"cluster: 1\"', '\"cluster: 2\"']\n", "Preview of selected clinical features:\n", "{'\"GSM6205808\"': [nan], '\"GSM6205809\"': [nan], '\"GSM6205810\"': [nan], '\"GSM6205811\"': [nan], '\"GSM6205812\"': [nan], '\"GSM6205813\"': [nan], '\"GSM6205814\"': [nan], '\"GSM6205815\"': [nan], '\"GSM6205816\"': [nan], '\"GSM6205817\"': [nan], '\"GSM6205818\"': [nan], '\"GSM6205819\"': [nan], '\"GSM6205820\"': [nan], '\"GSM6205821\"': [nan], '\"GSM6205822\"': [nan], '\"GSM6205823\"': [nan], '\"GSM6205824\"': [nan], '\"GSM6205825\"': [nan], '\"GSM6205826\"': [nan], '\"GSM6205827\"': [nan], '\"GSM6205828\"': [nan], '\"GSM6205829\"': [nan], '\"GSM6205830\"': [nan], '\"GSM6205831\"': [nan], '\"GSM6205832\"': [nan], '\"GSM6205833\"': [nan], '\"GSM6205834\"': [nan], '\"GSM6205835\"': [nan], '\"GSM6205836\"': [nan], '\"GSM6205837\"': [nan], '\"GSM6205838\"': [nan], '\"GSM6205839\"': [nan], '\"GSM6205840\"': [nan], '\"GSM6205841\"': [nan], '\"GSM6205842\"': [nan], '\"GSM6205843\"': [nan], '\"GSM6205844\"': [nan], '\"GSM6205845\"': [nan], '\"GSM6205846\"': [nan], '\"GSM6205847\"': [nan], '\"GSM6205848\"': [nan], '\"GSM6205849\"': [nan], '\"GSM6205850\"': [nan], '\"GSM6205851\"': [nan], '\"GSM6205852\"': [nan], '\"GSM6205853\"': [nan], '\"GSM6205854\"': [nan], '\"GSM6205855\"': [nan], '\"GSM6205856\"': [nan], '\"GSM6205857\"': [nan], '\"GSM6205858\"': [nan], '\"GSM6205859\"': [nan], '\"GSM6205860\"': [nan], '\"GSM6205861\"': [nan], '\"GSM6205862\"': [nan], '\"GSM6205863\"': [nan], '\"GSM6205864\"': [nan], '\"GSM6205865\"': [nan], '\"GSM6205866\"': [nan], '\"GSM6205867\"': [nan], '\"GSM6205868\"': [nan], '\"GSM6205869\"': [nan], '\"GSM6205870\"': [nan], '\"GSM6205871\"': [nan], '\"GSM6205872\"': [nan], '\"GSM6205873\"': [nan], '\"GSM6205874\"': [nan], '\"GSM6205875\"': [nan], '\"GSM6205876\"': [nan], '\"GSM6205877\"': [nan], '\"GSM6205878\"': [nan], '\"GSM6205879\"': [nan], '\"GSM6205880\"': [nan], '\"GSM6205881\"': [nan], '\"GSM6205882\"': [nan], '\"GSM6205883\"': [nan], '\"GSM6205884\"': [nan], '\"GSM6205885\"': [nan], '\"GSM6205886\"': [nan], '\"GSM6205887\"': [nan], '\"GSM6205888\"': [nan], '\"GSM6205889\"': [nan], '\"GSM6205890\"': [nan], '\"GSM6205891\"': [nan], '\"GSM6205892\"': [nan], '\"GSM6205893\"': [nan], '\"GSM6205894\"': [nan], '\"GSM6205895\"': [nan], '\"GSM6205896\"': [nan], '\"GSM6205897\"': [nan], '\"GSM6205898\"': [nan], '\"GSM6205899\"': [nan], '\"GSM6205900\"': [nan], '\"GSM6205901\"': [nan], '\"GSM6205902\"': [nan], '\"GSM6205903\"': [nan], '\"GSM6205904\"': [nan], '\"GSM6205905\"': [nan], '\"GSM6205906\"': [nan], '\"GSM6205907\"': [nan], '\"GSM6205908\"': [nan], '\"GSM6205909\"': [nan], '\"GSM6205910\"': [nan], '\"GSM6205911\"': [nan], '\"GSM6205912\"': [nan], '\"GSM6205913\"': [nan], '\"GSM6205914\"': [nan], '\"GSM6205915\"': [nan], '\"GSM6205916\"': [nan], '\"GSM6205917\"': [nan], '\"GSM6205918\"': [nan], '\"GSM6205919\"': [nan], '\"GSM6205920\"': [nan], '\"GSM6205921\"': [nan], '\"GSM6205922\"': [nan], '\"GSM6205923\"': [nan], '\"GSM6205924\"': [nan], '\"GSM6205925\"': [nan], '\"GSM6205926\"': [nan], '\"GSM6205927\"': [nan], '\"GSM6205928\"': [nan], '\"GSM6205929\"': [nan], '\"GSM6205930\"': [nan], '\"GSM6205931\"': [nan], '\"GSM6205932\"': [nan], '\"GSM6205933\"': [nan], '\"GSM6205934\"': [nan], '\"GSM6205935\"': [nan], '\"GSM6205936\"': [nan], '\"GSM6205937\"': [nan], '\"GSM6205938\"': [nan], '\"GSM6205939\"': [nan], '\"GSM6205940\"': [nan], '\"GSM6205941\"': [nan], '\"GSM6205942\"': [nan], '\"GSM6205943\"': [nan], '\"GSM6205944\"': [nan], '\"GSM6205945\"': [nan], '\"GSM6205946\"': [nan], '\"GSM6205947\"': [nan], '\"GSM6205948\"': [nan], '\"GSM6205949\"': [nan], '\"GSM6205950\"': [nan], '\"GSM6205951\"': [nan]}\n", "Clinical data saved to ../../output/preprocess/Asthma/clinical_data/GSE205151.csv\n" ] } ], "source": [ "import gzip\n", "import io\n", "\n", "# Analyze the available information\n", "# From the background information, we can determine this is a gene expression dataset (Nanostring immunology array)\n", "is_gene_available = True\n", "\n", "# Look at what files are available in the input directory\n", "available_files = os.listdir(in_cohort_dir)\n", "print(f\"Available files in {in_cohort_dir}: {available_files}\")\n", "\n", "# For trait - using 'cluster' as a potential proxy for asthma severity/subtypes\n", "trait_row = 1 # The row with 'cluster' information\n", "def convert_trait(value):\n", " if pd.isna(value):\n", " return None\n", " # Extract value after colon\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " # Convert to binary (0 for cluster 1, 1 for cluster 2)\n", " if value == '1':\n", " return 0\n", " elif value == '2':\n", " return 1\n", " else:\n", " return None\n", "\n", "# Age data is not available in the provided information\n", "age_row = None\n", "def convert_age(value):\n", " return None\n", "\n", "# Gender data is not available in the provided information\n", "gender_row = None\n", "def convert_gender(value):\n", " return None\n", "\n", "# Initial validation to see if we should continue processing this dataset\n", "is_trait_available = (trait_row is not None)\n", "validated = 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", "# If clinical data is available, extract and save it\n", "if trait_row is not None:\n", " try:\n", " # Find and extract the series matrix file which should contain clinical information\n", " series_matrix_file = None\n", " for file in available_files:\n", " if \"series_matrix\" in file.lower():\n", " series_matrix_file = os.path.join(in_cohort_dir, file)\n", " break\n", " \n", " if series_matrix_file:\n", " print(f\"Found series matrix file: {series_matrix_file}\")\n", " \n", " # Read and parse the gzipped series matrix file\n", " clinical_data = None\n", " sample_ids = []\n", " sample_characteristics = {}\n", " \n", " with gzip.open(series_matrix_file, 'rt') as f:\n", " lines = f.readlines()\n", " \n", " # Extract sample IDs\n", " for line in lines:\n", " if line.startswith('!Sample_geo_accession'):\n", " sample_ids = line.strip().split('\\t')[1:]\n", " break\n", " \n", " # Extract sample characteristics\n", " row_idx = 0\n", " for line in lines:\n", " if line.startswith('!Sample_characteristics_ch1'):\n", " char_values = line.strip().split('\\t')[1:]\n", " sample_characteristics[row_idx] = char_values\n", " row_idx += 1\n", " \n", " # Create a DataFrame from the extracted sample characteristics\n", " clinical_data = pd.DataFrame(sample_characteristics, index=sample_ids).T\n", " \n", " # Display what we've extracted\n", " print(\"Extracted sample characteristics:\")\n", " for row_idx, values in sample_characteristics.items():\n", " unique_values = list(set([v for v in values if pd.notna(v)]))\n", " print(f\"Row {row_idx}: {unique_values[:5]}{'...' if len(unique_values) > 5 else ''}\")\n", " \n", " # Select and process 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,\n", " gender_row=gender_row,\n", " convert_gender=convert_gender\n", " )\n", " \n", " # Preview the processed clinical data\n", " preview = preview_df(selected_clinical_df)\n", " print(\"Preview of selected clinical features:\")\n", " print(preview)\n", " \n", " # Save the processed 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", " else:\n", " print(\"No series matrix file found. Cannot extract clinical features.\")\n", " except Exception as e:\n", " print(f\"Error processing clinical data: {e}\")\n", " print(f\"Error traceback: {traceback.format_exc()}\")\n", " print(\"Unable to extract clinical features.\")\n" ] }, { "cell_type": "markdown", "id": "8b4b343d", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "963cf8f7", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:41:55.110728Z", "iopub.status.busy": "2025-03-25T06:41:55.110612Z", "iopub.status.idle": "2025-03-25T06:41:55.129973Z", "shell.execute_reply": "2025-03-25T06:41:55.129641Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Matrix file found: ../../input/GEO/Asthma/GSE205151/GSE205151_series_matrix.txt.gz\n", "Gene data shape: (608, 144)\n", "First 20 gene/probe identifiers:\n", "Index(['ABCB1', 'ABCF1', 'ABL1', 'ADA', 'AHR', 'AICDA', 'AIRE', 'ALAS1', 'APP',\n", " 'ARG1', 'ARG2', 'ARHGDIB', 'ATG10', 'ATG12', 'ATG16L1', 'ATG5', 'ATG7',\n", " 'ATM', 'B2M', 'B3GAT1'],\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": "5b7f040e", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "a38c2ef5", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:41:55.131038Z", "iopub.status.busy": "2025-03-25T06:41:55.130915Z", "iopub.status.idle": "2025-03-25T06:41:55.132776Z", "shell.execute_reply": "2025-03-25T06:41:55.132450Z" } }, "outputs": [], "source": [ "# Examining the gene identifiers from the previous step\n", "# The identifiers appear to be official human gene symbols (e.g., ABCB1, ABCF1, ABL1)\n", "# These are proper human gene symbols that don't require further mapping\n", "\n", "requires_gene_mapping = False\n" ] }, { "cell_type": "markdown", "id": "9af17d3b", "metadata": {}, "source": [ "### Step 5: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 6, "id": "1ed1cbde", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:41:55.133861Z", "iopub.status.busy": "2025-03-25T06:41:55.133748Z", "iopub.status.idle": "2025-03-25T06:41:55.321489Z", "shell.execute_reply": "2025-03-25T06:41:55.321142Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene data saved to ../../output/preprocess/Asthma/gene_data/GSE205151.csv\n", "Clinical data saved to ../../output/preprocess/Asthma/clinical_data/GSE205151.csv\n", "Linked data shape: (144, 609)\n", "Linked data preview (first 5 rows, 5 columns):\n", " Asthma ABCB1 ABCF1 ABL1 ADA\n", "GSM6205808 0.0 5.0 21.0 49.0 27.0\n", "GSM6205809 0.0 3.0 16.0 5.0 3.0\n", "GSM6205810 1.0 3.0 15.0 3.0 15.0\n", "GSM6205811 1.0 5.0 15.0 7.0 19.0\n", "GSM6205812 0.0 5.0 17.0 2.0 8.0\n", "Data shape after handling missing values: (143, 609)\n", "For the feature 'Asthma', the least common label is '0.0' with 69 occurrences. This represents 48.25% of the dataset.\n", "The distribution of the feature 'Asthma' in this dataset is fine.\n", "\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Linked data saved to ../../output/preprocess/Asthma/GSE205151.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", "# Get the gene data again\n", "gene_data = get_genetic_data(matrix_file)\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", "# Save the gene data (no normalization needed as the gene symbols are already standard)\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 data saved to {out_gene_data_file}\")\n", "\n", "# Using the correct trait_row identified in step 2\n", "# Using the correct convert_trait function from step 2\n", "def convert_trait(value):\n", " if pd.isna(value):\n", " return None\n", " # Extract value after colon\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " # Convert to binary (0 for cluster 1, 1 for cluster 2)\n", " if value == '1':\n", " return 0\n", " elif value == '2':\n", " return 1\n", " else:\n", " return None\n", "\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=1, # Using trait_row = 1 for cluster as identified in step 2\n", " convert_trait=convert_trait,\n", " age_row=None, # No age data available\n", " convert_age=None,\n", " gender_row=None, # No gender data available\n", " convert_gender=None\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] if not linked_data.empty else \"Linked data is empty\")\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 neutrophils with cluster information indicating response patterns to viral stimuli in children with critical asthma.\"\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 }