{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "21ad5882", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:25:04.700950Z", "iopub.status.busy": "2025-03-25T05:25:04.700846Z", "iopub.status.idle": "2025-03-25T05:25:04.861322Z", "shell.execute_reply": "2025-03-25T05:25:04.860952Z" } }, "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 = \"Glucocorticoid_Sensitivity\"\n", "cohort = \"GSE33649\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Glucocorticoid_Sensitivity\"\n", "in_cohort_dir = \"../../input/GEO/Glucocorticoid_Sensitivity/GSE33649\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Glucocorticoid_Sensitivity/GSE33649.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Glucocorticoid_Sensitivity/gene_data/GSE33649.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Glucocorticoid_Sensitivity/clinical_data/GSE33649.csv\"\n", "json_path = \"../../output/preprocess/Glucocorticoid_Sensitivity/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "38ccdf99", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "a98bbc32", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:25:04.862726Z", "iopub.status.busy": "2025-03-25T05:25:04.862590Z", "iopub.status.idle": "2025-03-25T05:25:05.028321Z", "shell.execute_reply": "2025-03-25T05:25:05.028014Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Inter-ethnic differences in lymphocyte sensitivity to glucocorticoids reflect variation in transcriptional response\"\n", "!Series_summary\t\"Glucocorticoids (GCs) are steroid hormones widely used as pharmaceutical interventions, which act mainly by regulating gene expression levels. A large fraction of patients (~30%), especially those of African descent, show a weak response to treatment. To interrogate the contribution of variable transcriptional response to inter-ethnic differences, we measured in vitro lymphocyte GC sensitivity (LGS) and transcriptome-wide response to GCs in peripheral blood mononuclear cells (PBMCs) from African-American and European-American healthy donors. We found that transcriptional response after 8hrs treatment was significantly correlated with variation in LGS within and between populations. We found that NFKB1, a gene previously found to predict LGS within populations, was more strongly downregulated in European-Americans on average. NFKB1 could not completely explain population differences, however, and we found an additional 177 genes with population differences in the average log2 fold change (FDR<0.05), most of which also showed a weaker transcriptional response in AfricanAmericans. These results suggest that inter-ethnic differences in GC sensitivity reflect variation in transcriptional response at many genes, including regulators with large effects (e.g. NFKB1) and numerous other genes with smaller effects.\"\n", "!Series_overall_design\t\"Total RNA was obtained from paired aliquots of peripheral blood mononuclear cells treated with dexamethasone or vehicle (EtOH) for 8 and 24 hours.\"\n", "Sample Characteristics Dictionary:\n", "{0: ['cell type: peripheral blood mononuclear cells'], 1: ['population: African-American', 'population: European-American'], 2: ['treatment: dexamethasone', 'treatment: vehicle (EtOH)'], 3: ['in vitro lymphocyte gc sensitivity (lgs - %inhibition by dex): 89.43486', 'in vitro lymphocyte gc sensitivity (lgs - %inhibition by dex): 95.88507', 'in vitro lymphocyte gc sensitivity (lgs - %inhibition by dex): 95.22036', 'in vitro lymphocyte gc sensitivity (lgs - %inhibition by dex): 92.86704', 'in vitro lymphocyte gc sensitivity (lgs - %inhibition by dex): 93.71633', 'in vitro lymphocyte gc sensitivity (lgs - %inhibition by dex): 96.76962', 'in vitro lymphocyte gc sensitivity (lgs - %inhibition by dex): 88.55031', 'in vitro lymphocyte gc sensitivity (lgs - %inhibition by dex): 90.09957', 'in vitro lymphocyte gc sensitivity (lgs - %inhibition by dex): 94.17097', 'in vitro lymphocyte gc sensitivity (lgs - %inhibition by dex): 86.97089', 'in vitro lymphocyte gc sensitivity (lgs - %inhibition by dex): 98.34904', 'in vitro lymphocyte gc sensitivity (lgs - %inhibition by dex): 91.14896'], 4: ['duration of treatment (hours): 8', 'duration of treatment (hours): 24'], 5: ['gender: female', 'gender: male'], 6: ['age (years): 44.15342', 'age (years): 24.72329', 'age (years): 32.37808', 'age (years): 20.38082', 'age (years): 21.2411', 'age (years): 22.54247', 'age (years): 26.13973', 'age (years): 21.5616', 'age (years): 21.9863', 'age (years): 26.76712', 'age (years): 23.59452', 'age (years): 23.47945']}\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": "55dcfbbb", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "c5fd5567", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:25:05.029542Z", "iopub.status.busy": "2025-03-25T05:25:05.029435Z", "iopub.status.idle": "2025-03-25T05:25:05.041621Z", "shell.execute_reply": "2025-03-25T05:25:05.041326Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Clinical data preview: {0: [89.43486, 44.15342, 0.0], 1: [95.88507, 24.72329, 1.0], 2: [95.22036, 32.37808, nan], 3: [92.86704, 20.38082, nan], 4: [93.71633, 21.2411, nan], 5: [96.76962, 22.54247, nan], 6: [88.55031, 26.13973, nan], 7: [90.09957, 21.5616, nan], 8: [94.17097, 21.9863, nan], 9: [86.97089, 26.76712, nan], 10: [98.34904, 23.59452, nan], 11: [91.14896, 23.47945, nan]}\n", "Clinical data saved to ../../output/preprocess/Glucocorticoid_Sensitivity/clinical_data/GSE33649.csv\n" ] } ], "source": [ "import pandas as pd\n", "import re\n", "import os\n", "import json\n", "from typing import Dict, Any, Optional, Callable\n", "\n", "# 1. Gene Expression Data Availability\n", "# Based on the background information, this dataset contains mRNA expression data from PBMCs\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "\n", "# For Glucocorticoid_Sensitivity trait\n", "# Key 3 contains \"in vitro lymphocyte gc sensitivity (lgs - %inhibition by dex)\" with various values\n", "trait_row = 3\n", "\n", "# For age\n", "# Key 6 contains \"age (years)\" with various values\n", "age_row = 6\n", "\n", "# For gender\n", "# Key 5 contains \"gender\" with values female and male\n", "gender_row = 5\n", "\n", "# 2.2 Data Type Conversion Functions\n", "\n", "def convert_trait(value):\n", " \"\"\"Convert trait data (GC sensitivity) to continuous value.\"\"\"\n", " if value is None:\n", " return None\n", " if isinstance(value, (int, float)):\n", " return float(value)\n", " if not isinstance(value, str):\n", " return None\n", " \n", " if 'in vitro lymphocyte gc sensitivity' not in value.lower():\n", " return None\n", " \n", " # Extract numeric value using regex\n", " match = re.search(r'(\\d+\\.\\d+)', value)\n", " if match:\n", " return float(match.group(1))\n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age data to continuous value.\"\"\"\n", " if value is None:\n", " return None\n", " if isinstance(value, (int, float)):\n", " return float(value)\n", " if not isinstance(value, str):\n", " return None\n", " \n", " if 'age' not in value.lower():\n", " return None\n", " \n", " # Extract numeric value using regex\n", " match = re.search(r'(\\d+\\.\\d+)', value)\n", " if match:\n", " return float(match.group(1))\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"Convert gender data to binary (0: female, 1: male).\"\"\"\n", " if value is None:\n", " return None\n", " if isinstance(value, (int, float)):\n", " return float(value)\n", " if not isinstance(value, str):\n", " return None\n", " \n", " if 'gender' not in value.lower():\n", " return None\n", " \n", " if 'female' in value.lower():\n", " return 0\n", " elif 'male' in value.lower():\n", " return 1\n", " return None\n", "\n", "# 3. Save Metadata\n", "# Trait data is available (trait_row is not None)\n", "is_trait_available = trait_row is not None\n", "\n", "# Save the cohort info\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 proceed with clinical feature extraction\n", "if trait_row is not None:\n", " # Create a DataFrame from the sample characteristics dictionary provided in previous output\n", " # Sample characteristics dictionary structure is {row_index: [values]}\n", " # We need to transform it into a DataFrame with columns being sample IDs\n", " \n", " # Example sample characteristics dictionary from previous output\n", " sample_chars = {\n", " 0: ['cell type: peripheral blood mononuclear cells'],\n", " 1: ['population: African-American', 'population: European-American'],\n", " 2: ['treatment: dexamethasone', 'treatment: vehicle (EtOH)'],\n", " 3: ['in vitro lymphocyte gc sensitivity (lgs - %inhibition by dex): 89.43486', 'in vitro lymphocyte gc sensitivity (lgs - %inhibition by dex): 95.88507',\n", " 'in vitro lymphocyte gc sensitivity (lgs - %inhibition by dex): 95.22036', 'in vitro lymphocyte gc sensitivity (lgs - %inhibition by dex): 92.86704',\n", " 'in vitro lymphocyte gc sensitivity (lgs - %inhibition by dex): 93.71633', 'in vitro lymphocyte gc sensitivity (lgs - %inhibition by dex): 96.76962',\n", " 'in vitro lymphocyte gc sensitivity (lgs - %inhibition by dex): 88.55031', 'in vitro lymphocyte gc sensitivity (lgs - %inhibition by dex): 90.09957',\n", " 'in vitro lymphocyte gc sensitivity (lgs - %inhibition by dex): 94.17097', 'in vitro lymphocyte gc sensitivity (lgs - %inhibition by dex): 86.97089',\n", " 'in vitro lymphocyte gc sensitivity (lgs - %inhibition by dex): 98.34904', 'in vitro lymphocyte gc sensitivity (lgs - %inhibition by dex): 91.14896'],\n", " 4: ['duration of treatment (hours): 8', 'duration of treatment (hours): 24'],\n", " 5: ['gender: female', 'gender: male'],\n", " 6: ['age (years): 44.15342', 'age (years): 24.72329', 'age (years): 32.37808', 'age (years): 20.38082',\n", " 'age (years): 21.2411', 'age (years): 22.54247', 'age (years): 26.13973', 'age (years): 21.5616',\n", " 'age (years): 21.9863', 'age (years): 26.76712', 'age (years): 23.59452', 'age (years): 23.47945']\n", " }\n", " \n", " # Determine number of samples\n", " max_samples = max(len(values) for values in sample_chars.values())\n", " \n", " # Create a DataFrame where each column is a sample\n", " clinical_data = pd.DataFrame(index=sample_chars.keys(), columns=range(max_samples))\n", " \n", " # Fill in values\n", " for row_idx, values in sample_chars.items():\n", " for col_idx, value in enumerate(values):\n", " clinical_data.loc[row_idx, col_idx] = value\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,\n", " gender_row=gender_row,\n", " convert_gender=convert_gender\n", " )\n", " \n", " # Preview the extracted data\n", " preview = preview_df(selected_clinical_df)\n", " print(\"Clinical data preview:\", preview)\n", " \n", " # Save clinical data 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": "45de0a23", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "5ed775ff", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:25:05.042739Z", "iopub.status.busy": "2025-03-25T05:25:05.042640Z", "iopub.status.idle": "2025-03-25T05:25:05.291804Z", "shell.execute_reply": "2025-03-25T05:25:05.291434Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Found data marker at line 67\n", "Header line: \"ID_REF\"\t\"GSM832137\"\t\"GSM832138\"\t\"GSM832139\"\t\"GSM832140\"\t\"GSM832141\"\t\"GSM832142\"\t\"GSM832143\"\t\"GSM832144\"\t\"GSM832145\"\t\"GSM832146\"\t\"GSM832147\"\t\"GSM832148\"\t\"GSM832149\"\t\"GSM832150\"\t\"GSM832151\"\t\"GSM832152\"\t\"GSM832153\"\t\"GSM832154\"\t\"GSM832155\"\t\"GSM832156\"\t\"GSM832157\"\t\"GSM832158\"\t\"GSM832159\"\t\"GSM832160\"\t\"GSM832161\"\t\"GSM832162\"\t\"GSM832163\"\t\"GSM832164\"\t\"GSM832165\"\t\"GSM832166\"\t\"GSM832167\"\t\"GSM832168\"\t\"GSM832169\"\t\"GSM832170\"\t\"GSM832171\"\t\"GSM832172\"\t\"GSM832173\"\t\"GSM832174\"\t\"GSM832175\"\t\"GSM832176\"\t\"GSM832177\"\t\"GSM832178\"\t\"GSM832179\"\t\"GSM832180\"\t\"GSM832181\"\t\"GSM832182\"\t\"GSM832183\"\t\"GSM832184\"\n", "First data line: \"ILMN_1343291\"\t14.12073024\t14.1847953\t14.3271103\t14.21074679\t14.35649097\t14.21573196\t14.25949372\t14.26541254\t14.36153392\t14.25490712\t14.28494604\t14.21327393\t14.37099787\t14.37099787\t14.32494472\t14.32079848\t14.26699913\t14.08661628\t14.33650015\t14.33877929\t14.24410318\t14.21573196\t14.34573164\t14.38961689\t14.32959504\t14.31869455\t14.37099787\t14.4243792\t14.31077135\t14.24773914\t14.20496391\t14.29628828\t14.27520624\t14.16802087\t14.22209016\t14.32288942\t14.32079848\t14.29628828\t14.27674846\t14.31077135\t14.20610208\t14.11111632\t14.10822775\t14.40216307\t14.25657841\t14.24534098\t14.21675287\t14.21074679\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Index(['ILMN_1343291', 'ILMN_1343295', 'ILMN_1651199', 'ILMN_1651209',\n", " 'ILMN_1651210', 'ILMN_1651221', 'ILMN_1651228', 'ILMN_1651229',\n", " 'ILMN_1651230', 'ILMN_1651232', 'ILMN_1651235', 'ILMN_1651236',\n", " 'ILMN_1651237', 'ILMN_1651238', 'ILMN_1651249', 'ILMN_1651253',\n", " 'ILMN_1651254', 'ILMN_1651259', 'ILMN_1651260', 'ILMN_1651262'],\n", " dtype='object', name='ID')\n" ] } ], "source": [ "# 1. Get the file paths for the SOFT file and matrix file\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "\n", "# 2. First, let's examine the structure of the matrix file to understand its format\n", "import gzip\n", "\n", "# Peek at the first few lines of the file to understand its structure\n", "with gzip.open(matrix_file, 'rt') as file:\n", " # Read first 100 lines to find the header structure\n", " for i, line in enumerate(file):\n", " if '!series_matrix_table_begin' in line:\n", " print(f\"Found data marker at line {i}\")\n", " # Read the next line which should be the header\n", " header_line = next(file)\n", " print(f\"Header line: {header_line.strip()}\")\n", " # And the first data line\n", " first_data_line = next(file)\n", " print(f\"First data line: {first_data_line.strip()}\")\n", " break\n", " if i > 100: # Limit search to first 100 lines\n", " print(\"Matrix table marker not found in first 100 lines\")\n", " break\n", "\n", "# 3. Now try to get the genetic data with better error handling\n", "try:\n", " gene_data = get_genetic_data(matrix_file)\n", " print(gene_data.index[:20])\n", "except KeyError as e:\n", " print(f\"KeyError: {e}\")\n", " \n", " # Alternative approach: manually extract the data\n", " print(\"\\nTrying alternative approach to read the gene data:\")\n", " with gzip.open(matrix_file, 'rt') as file:\n", " # Find the start of the data\n", " for line in file:\n", " if '!series_matrix_table_begin' in line:\n", " break\n", " \n", " # Read the headers and data\n", " import pandas as pd\n", " df = pd.read_csv(file, sep='\\t', index_col=0)\n", " print(f\"Column names: {df.columns[:5]}\")\n", " print(f\"First 20 row IDs: {df.index[:20]}\")\n", " gene_data = df\n" ] }, { "cell_type": "markdown", "id": "4f194a8b", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "ad1e7d2f", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:25:05.293012Z", "iopub.status.busy": "2025-03-25T05:25:05.292901Z", "iopub.status.idle": "2025-03-25T05:25:05.294719Z", "shell.execute_reply": "2025-03-25T05:25:05.294449Z" } }, "outputs": [], "source": [ "# Analyzing the gene identifiers from the provided output\n", "# The identifiers follow the pattern \"ILMN_xxxxxxx\", which are Illumina probe IDs\n", "# These are not direct human gene symbols and will need to be mapped to gene symbols\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "8c55c25a", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "973bade0", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:25:05.295805Z", "iopub.status.busy": "2025-03-25T05:25:05.295710Z", "iopub.status.idle": "2025-03-25T05:25:06.208087Z", "shell.execute_reply": "2025-03-25T05:25:06.207559Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Examining SOFT file structure:\n", "Line 0: ^DATABASE = GeoMiame\n", "Line 1: !Database_name = Gene Expression Omnibus (GEO)\n", "Line 2: !Database_institute = NCBI NLM NIH\n", "Line 3: !Database_web_link = http://www.ncbi.nlm.nih.gov/geo\n", "Line 4: !Database_email = geo@ncbi.nlm.nih.gov\n", "Line 5: ^SERIES = GSE33649\n", "Line 6: !Series_title = Inter-ethnic differences in lymphocyte sensitivity to glucocorticoids reflect variation in transcriptional response\n", "Line 7: !Series_geo_accession = GSE33649\n", "Line 8: !Series_status = Public on Feb 01 2012\n", "Line 9: !Series_submission_date = Nov 12 2011\n", "Line 10: !Series_last_update_date = Aug 13 2018\n", "Line 11: !Series_pubmed_id = 22158329\n", "Line 12: !Series_summary = Glucocorticoids (GCs) are steroid hormones widely used as pharmaceutical interventions, which act mainly by regulating gene expression levels. A large fraction of patients (~30%), especially those of African descent, show a weak response to treatment. To interrogate the contribution of variable transcriptional response to inter-ethnic differences, we measured in vitro lymphocyte GC sensitivity (LGS) and transcriptome-wide response to GCs in peripheral blood mononuclear cells (PBMCs) from African-American and European-American healthy donors. We found that transcriptional response after 8hrs treatment was significantly correlated with variation in LGS within and between populations. We found that NFKB1, a gene previously found to predict LGS within populations, was more strongly downregulated in European-Americans on average. NFKB1 could not completely explain population differences, however, and we found an additional 177 genes with population differences in the average log2 fold change (FDR<0.05), most of which also showed a weaker transcriptional response in AfricanAmericans. These results suggest that inter-ethnic differences in GC sensitivity reflect variation in transcriptional response at many genes, including regulators with large effects (e.g. NFKB1) and numerous other genes with smaller effects.\n", "Line 13: !Series_overall_design = Total RNA was obtained from paired aliquots of peripheral blood mononuclear cells treated with dexamethasone or vehicle (EtOH) for 8 and 24 hours.\n", "Line 14: !Series_type = Expression profiling by array\n", "Line 15: !Series_contributor = Joseph,C,Maranville\n", "Line 16: !Series_contributor = Shaneen,S,Baxter\n", "Line 17: !Series_contributor = Jason,M,Torres\n", "Line 18: !Series_contributor = Anna,,Di Rienzo\n", "Line 19: !Series_sample_id = GSM832137\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Gene annotation preview:\n", "{'ID': ['ILMN_1343048', 'ILMN_1343049', 'ILMN_1343050', 'ILMN_1343052', 'ILMN_1343059'], 'Species': [nan, nan, nan, nan, nan], 'Source': [nan, nan, nan, nan, nan], 'Search_Key': [nan, nan, nan, nan, nan], 'Transcript': [nan, nan, nan, nan, nan], 'ILMN_Gene': [nan, nan, nan, nan, nan], 'Source_Reference_ID': [nan, nan, nan, nan, nan], 'RefSeq_ID': [nan, nan, nan, nan, nan], 'Unigene_ID': [nan, nan, nan, nan, nan], 'Entrez_Gene_ID': [nan, nan, nan, nan, nan], 'GI': [nan, nan, nan, nan, nan], 'Accession': [nan, nan, nan, nan, nan], 'Symbol': ['phage_lambda_genome', 'phage_lambda_genome', 'phage_lambda_genome:low', 'phage_lambda_genome:low', 'thrB'], 'Protein_Product': [nan, nan, nan, nan, 'thrB'], 'Probe_Id': [nan, nan, nan, nan, nan], 'Array_Address_Id': [5090180, 6510136, 7560739, 1450438, 1240647], 'Probe_Type': [nan, nan, nan, nan, nan], 'Probe_Start': [nan, nan, nan, nan, nan], 'SEQUENCE': ['GAATAAAGAACAATCTGCTGATGATCCCTCCGTGGATCTGATTCGTGTAA', 'CCATGTGATACGAGGGCGCGTAGTTTGCATTATCGTTTTTATCGTTTCAA', 'CCGACAGATGTATGTAAGGCCAACGTGCTCAAATCTTCATACAGAAAGAT', 'TCTGTCACTGTCAGGAAAGTGGTAAAACTGCAACTCAATTACTGCAATGC', 'CTTGTGCCTGAGCTGTCAAAAGTAGAGCACGTCGCCGAGATGAAGGGCGC'], 'Chromosome': [nan, nan, nan, nan, nan], 'Probe_Chr_Orientation': [nan, nan, nan, nan, nan], 'Probe_Coordinates': [nan, nan, nan, nan, nan], 'Cytoband': [nan, nan, nan, nan, nan], 'Definition': [nan, nan, nan, nan, nan], 'Ontology_Component': [nan, nan, nan, nan, nan], 'Ontology_Process': [nan, nan, nan, nan, nan], 'Ontology_Function': [nan, nan, nan, nan, nan], 'Synonyms': [nan, nan, nan, nan, nan], 'Obsolete_Probe_Id': [nan, nan, nan, nan, nan], 'GB_ACC': [nan, nan, nan, nan, nan]}\n" ] } ], "source": [ "# 1. Let's first examine the structure of the SOFT file before trying to parse it\n", "import gzip\n", "\n", "# Look at the first few lines of the SOFT file to understand its structure\n", "print(\"Examining SOFT file structure:\")\n", "try:\n", " with gzip.open(soft_file, 'rt') as file:\n", " # Read first 20 lines to understand the file structure\n", " for i, line in enumerate(file):\n", " if i < 20:\n", " print(f\"Line {i}: {line.strip()}\")\n", " else:\n", " break\n", "except Exception as e:\n", " print(f\"Error reading SOFT file: {e}\")\n", "\n", "# 2. Now let's try a more robust approach to extract the gene annotation\n", "# Instead of using the library function which failed, we'll implement a custom approach\n", "try:\n", " # First, look for the platform section which contains gene annotation\n", " platform_data = []\n", " with gzip.open(soft_file, 'rt') as file:\n", " in_platform_section = False\n", " for line in file:\n", " if line.startswith('^PLATFORM'):\n", " in_platform_section = True\n", " continue\n", " if in_platform_section and line.startswith('!platform_table_begin'):\n", " # Next line should be the header\n", " header = next(file).strip()\n", " platform_data.append(header)\n", " # Read until the end of the platform table\n", " for table_line in file:\n", " if table_line.startswith('!platform_table_end'):\n", " break\n", " platform_data.append(table_line.strip())\n", " break\n", " \n", " # If we found platform data, convert it to a DataFrame\n", " if platform_data:\n", " import pandas as pd\n", " import io\n", " platform_text = '\\n'.join(platform_data)\n", " gene_annotation = pd.read_csv(io.StringIO(platform_text), delimiter='\\t', \n", " low_memory=False, on_bad_lines='skip')\n", " print(\"\\nGene annotation preview:\")\n", " print(preview_df(gene_annotation))\n", " else:\n", " print(\"Could not find platform table in SOFT file\")\n", " \n", " # Try an alternative approach - extract mapping from other sections\n", " with gzip.open(soft_file, 'rt') as file:\n", " for line in file:\n", " if 'ANNOTATION information' in line or 'annotation information' in line:\n", " print(f\"Found annotation information: {line.strip()}\")\n", " if line.startswith('!Platform_title') or line.startswith('!platform_title'):\n", " print(f\"Platform title: {line.strip()}\")\n", " \n", "except Exception as e:\n", " print(f\"Error processing gene annotation: {e}\")\n" ] }, { "cell_type": "markdown", "id": "93da10c3", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "26f69cf5", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:25:06.209535Z", "iopub.status.busy": "2025-03-25T05:25:06.209407Z", "iopub.status.idle": "2025-03-25T05:25:07.069559Z", "shell.execute_reply": "2025-03-25T05:25:07.069104Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene mapping dataframe shape: (44837, 2)\n", "First few rows of the mapping dataframe:\n", " ID Gene\n", "0 ILMN_1343048 phage_lambda_genome\n", "1 ILMN_1343049 phage_lambda_genome\n", "2 ILMN_1343050 phage_lambda_genome:low\n", "3 ILMN_1343052 phage_lambda_genome:low\n", "4 ILMN_1343059 thrB\n", "Resulting gene expression dataframe shape: (21372, 48)\n", "First few gene symbols and their expression values:\n", " GSM832137 GSM832138 GSM832139 GSM832140 GSM832141 GSM832142 \\\n", "Gene \n", "A1BG 15.956246 15.847209 15.781695 15.764754 15.795053 15.643423 \n", "A1CF 23.307923 23.242826 23.307606 23.256966 23.446269 23.527114 \n", "A26C3 23.488414 23.404135 23.448766 23.626364 23.472122 23.514723 \n", "A2BP1 31.002495 30.914475 30.992848 30.959287 30.961103 30.967724 \n", "A2LD1 9.334543 9.229682 9.447489 9.405594 8.231067 8.343261 \n", "\n", " GSM832143 GSM832144 GSM832145 GSM832146 ... GSM832175 GSM832176 \\\n", "Gene ... \n", "A1BG 15.779660 15.824818 15.775725 15.661611 ... 15.779389 15.899487 \n", "A1CF 23.417477 23.278243 23.424897 23.350377 ... 23.494204 23.336486 \n", "A26C3 23.367502 23.373383 23.247039 23.337216 ... 23.331750 23.540398 \n", "A2BP1 31.059999 31.080621 30.867032 30.947630 ... 30.923782 31.084773 \n", "A2LD1 8.626896 8.569864 8.123200 8.306151 ... 8.527398 8.355871 \n", "\n", " GSM832177 GSM832178 GSM832179 GSM832180 GSM832181 GSM832182 \\\n", "Gene \n", "A1BG 15.731616 15.700666 15.967220 15.941457 15.762920 15.839891 \n", "A1CF 23.365456 23.390428 23.312633 23.476120 23.600806 23.263504 \n", "A26C3 23.319503 23.403601 23.346071 23.377054 23.469911 23.276766 \n", "A2BP1 30.961476 31.005755 30.854040 30.983793 31.071695 30.864837 \n", "A2LD1 8.437386 8.439186 8.235688 8.179967 8.512047 8.283219 \n", "\n", " GSM832183 GSM832184 \n", "Gene \n", "A1BG 15.769117 15.699262 \n", "A1CF 23.529575 23.227141 \n", "A26C3 23.283627 23.547305 \n", "A2BP1 30.958008 30.820436 \n", "A2LD1 8.307083 8.299852 \n", "\n", "[5 rows x 48 columns]\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "After normalization, gene expression dataframe shape: (20259, 48)" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "First few normalized gene symbols:\n", "Index(['A1BG', 'A1BG-AS1', 'A1CF', 'A2M', 'A2ML1', 'A3GALT2', 'A4GALT',\n", " 'A4GNT', 'AAA1', 'AAAS'],\n", " dtype='object', name='Gene')\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene expression data saved to ../../output/preprocess/Glucocorticoid_Sensitivity/gene_data/GSE33649.csv\n" ] } ], "source": [ "# 1. Identify the relevant columns in the gene annotation dataframe\n", "# Based on examining the annotation preview, we need:\n", "# - \"ID\" column which contains the same Illumina probe IDs seen in the gene expression data (ILMN_*)\n", "# - \"Symbol\" column which contains the gene symbols we want to map to\n", "\n", "# 2. Extract the mapping between probe IDs and gene symbols\n", "mapping_df = gene_annotation[['ID', 'Symbol']]\n", "mapping_df = mapping_df.dropna() # Remove rows with missing gene symbols\n", "# Rename 'Symbol' to 'Gene' to match the expected column name in apply_gene_mapping function\n", "mapping_df = mapping_df.rename(columns={'Symbol': 'Gene'})\n", "print(f\"Gene mapping dataframe shape: {mapping_df.shape}\")\n", "print(\"First few rows of the mapping dataframe:\")\n", "print(mapping_df.head())\n", "\n", "# 3. Apply the gene mapping to convert probe-level measurements to gene-level expression\n", "# This will handle the many-to-many relationship between probes and genes\n", "gene_data = apply_gene_mapping(gene_data, mapping_df)\n", "print(f\"Resulting gene expression dataframe shape: {gene_data.shape}\")\n", "print(\"First few gene symbols and their expression values:\")\n", "print(gene_data.head())\n", "\n", "# Normalize gene symbols to standard format\n", "gene_data = normalize_gene_symbols_in_index(gene_data)\n", "print(f\"After normalization, gene expression dataframe shape: {gene_data.shape}\")\n", "print(\"First few normalized gene symbols:\")\n", "print(gene_data.index[:10])\n", "\n", "# Save gene expression data to CSV\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 expression data saved to {out_gene_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "298a5ce7", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "f113153a", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:25:07.071101Z", "iopub.status.busy": "2025-03-25T05:25:07.070812Z", "iopub.status.idle": "2025-03-25T05:25:14.550724Z", "shell.execute_reply": "2025-03-25T05:25:14.550335Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene data shape after normalization: (20259, 48)\n", "Sample gene symbols after normalization: ['A1BG', 'A1BG-AS1', 'A1CF', 'A2M', 'A2ML1', 'A3GALT2', 'A4GALT', 'A4GNT', 'AAA1', 'AAAS']\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene data saved to ../../output/preprocess/Glucocorticoid_Sensitivity/gene_data/GSE33649.csv\n", "Clinical data shape: (3, 12)\n", "Clinical data preview:\n", " 0 1 2 3 4 5 6 \\\n", "0 89.43486 95.88507 95.22036 92.86704 93.71633 96.76962 88.55031 \n", "1 44.15342 24.72329 32.37808 20.38082 21.24110 22.54247 26.13973 \n", "2 0.00000 1.00000 NaN NaN NaN NaN NaN \n", "\n", " 7 8 9 10 11 \n", "0 90.09957 94.17097 86.97089 98.34904 91.14896 \n", "1 21.56160 21.98630 26.76712 23.59452 23.47945 \n", "2 NaN NaN NaN NaN NaN \n", "\n", "Sample ID diagnostics:\n", "Gene data sample IDs: ['GSM832137', 'GSM832138', 'GSM832139', 'GSM832140', 'GSM832141']\n", "Clinical data columns: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11']\n", "Identified trait column: 0\n", "Sample mapping (first 5): {'GSM832137': 1, 'GSM832138': 2, 'GSM832139': 3}\n", "\n", "Clinical data transposed:\n", " 0 1 2\n", "0 89.43486 44.15342 0.0\n", "1 95.88507 24.72329 1.0\n", "2 95.22036 32.37808 NaN\n", "3 92.86704 20.38082 NaN\n", "4 93.71633 21.24110 NaN\n", "\n", "Gene data with mapped IDs:\n", "Gene A1BG A1BG-AS1 A1CF A2M A2ML1 A3GALT2 \\\n", "numeric_id \n", "1 15.956246 7.895359 23.307923 7.757711 7.719816 15.655539 \n", "2 15.847209 7.873267 23.242826 8.065421 7.581164 15.738909 \n", "3 15.781695 7.835743 23.307606 8.099250 7.684101 15.570464 \n", "\n", "Gene A4GALT A4GNT AAA1 AAAS ... ZWILCH \\\n", "numeric_id ... \n", "1 7.747972 8.088589 38.925349 8.014077 ... 25.110930 \n", "2 7.703107 8.049581 38.907990 7.954776 ... 25.311686 \n", "3 7.658285 8.014558 39.025544 8.254025 ... 25.818622 \n", "\n", "Gene ZWINT ZXDA ZXDB ZXDC ZYG11A ZYG11B \\\n", "numeric_id \n", "1 31.221308 39.490740 8.356400 16.352819 15.514534 10.778422 \n", "2 31.161810 39.626308 8.514483 16.318253 15.410154 10.334427 \n", "3 31.451772 39.367885 8.333304 16.330052 15.482203 11.164723 \n", "\n", "Gene ZYX ZZEF1 ZZZ3 \n", "numeric_id \n", "1 23.019915 9.489551 19.923810 \n", "2 22.556829 9.239643 20.133535 \n", "3 23.649310 9.667609 19.674565 \n", "\n", "[3 rows x 20259 columns]\n", "\n", "Linked data shape: (3, 20262)\n", "Linked data preview (first 5 rows, first 5 columns):\n", " Glucocorticoid_Sensitivity Age Gender A1BG A1BG-AS1\n", "1 95.88507 24.72329 1.0 15.956246 7.895359\n", "2 95.22036 32.37808 NaN 15.847209 7.873267\n", "3 92.86704 20.38082 NaN 15.781695 7.835743\n", "\n", "Missing values before handling:\n", " Trait (Glucocorticoid_Sensitivity) missing: 0 out of 3\n", " Genes with >20% missing: 0\n", " Samples with >5% missing genes: 0\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Data shape after handling missing values: (3, 20262)\n", "Quartiles for 'Glucocorticoid_Sensitivity':\n", " 25%: 94.0437\n", " 50% (Median): 95.22036\n", " 75%: 95.552715\n", "Min: 92.86704\n", "Max: 95.88507\n", "The distribution of the feature 'Glucocorticoid_Sensitivity' in this dataset is fine.\n", "\n", "Quartiles for 'Age':\n", " 25%: 22.552055\n", " 50% (Median): 24.72329\n", " 75%: 28.550684999999998\n", "Min: 20.38082\n", "Max: 32.37808\n", "The distribution of the feature 'Age' in this dataset is fine.\n", "\n", "For the feature 'Gender', the least common label is '1.0' with 3 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/Glucocorticoid_Sensitivity/GSE33649.csv\n" ] } ], "source": [ "# 1. Normalize gene symbols in the obtained 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\"Sample gene symbols after normalization: {list(normalized_gene_data.index[:10])}\")\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\"Gene data saved to {out_gene_data_file}\")\n", "\n", "# 2. Load the previously saved clinical data\n", "clinical_data = pd.read_csv(out_clinical_data_file)\n", "print(f\"Clinical data shape: {clinical_data.shape}\")\n", "print(\"Clinical data preview:\")\n", "print(clinical_data.head())\n", "\n", "# 3. Link clinical and genetic data\n", "# First, transpose gene expression data to have samples as rows\n", "gene_data_t = normalized_gene_data.T\n", "\n", "# Print sample IDs from both datasets to debug the mismatch\n", "print(\"\\nSample ID diagnostics:\")\n", "print(f\"Gene data sample IDs: {list(gene_data_t.index)[:5]}\")\n", "print(f\"Clinical data columns: {list(clinical_data.columns)}\")\n", "\n", "# The clinical data has the trait, age, and gender values for each sample\n", "# Gene expression data uses GSM IDs for samples (GSM832137, etc.)\n", "# We need to map the sample IDs properly\n", "\n", "# Transform sample IDs in gene_data to match clinical data indices\n", "# Extract actual trait and demographic columns from clinical data\n", "clinical_columns = clinical_data.columns.tolist()\n", "trait_col = clinical_columns[0] # First column should be the trait\n", "print(f\"Identified trait column: {trait_col}\")\n", "\n", "# Prepare gene expression data to be merged with clinical data\n", "gene_data_t = gene_data_t.reset_index().rename(columns={'index': 'Sample_ID'})\n", "\n", "# Construct a mapping between GSM IDs and numeric indices\n", "# Get the unique IDs from the matrix file header\n", "with gzip.open(matrix_file, 'rt') as file:\n", " for line in file:\n", " if '!series_matrix_table_begin' in line:\n", " # Next line is the header with GSM IDs\n", " header_line = next(file).strip()\n", " header_items = header_line.split('\\t')\n", " gsm_ids = [id.strip('\"') for id in header_items[1:]] # Skip first column which is ID_REF\n", " break\n", "\n", "# Map between GSM IDs and clinical data indices (1-based)\n", "sample_mapping = {}\n", "for i, gsm_id in enumerate(gsm_ids[:clinical_data.shape[0]]):\n", " sample_mapping[gsm_id] = i + 1 # 1-based index for clinical data\n", "\n", "print(f\"Sample mapping (first 5): {dict(list(sample_mapping.items())[:5])}\")\n", "\n", "# Apply the mapping to gene_data_t\n", "gene_data_t['numeric_id'] = gene_data_t['Sample_ID'].map(sample_mapping)\n", "gene_data_t = gene_data_t.dropna(subset=['numeric_id']) # Keep only mapped samples\n", "gene_data_t['numeric_id'] = gene_data_t['numeric_id'].astype(int)\n", "\n", "# Set numeric_id as index to prepare for merge\n", "gene_data_t = gene_data_t.set_index('numeric_id')\n", "gene_data_t = gene_data_t.drop(columns=['Sample_ID'])\n", "\n", "# Create the linked data by combining clinical and gene expression data\n", "# First, get clinical data with samples as rows\n", "clinical_data_t = clinical_data.T\n", "clinical_data_t.index = pd.to_numeric(clinical_data_t.index, errors='coerce')\n", "clinical_data_t = clinical_data_t.dropna(subset=[0]) # Keep samples with trait value\n", "\n", "print(\"\\nClinical data transposed:\")\n", "print(clinical_data_t.head())\n", "print(\"\\nGene data with mapped IDs:\")\n", "print(gene_data_t.head())\n", "\n", "# Merge the datasets based on the index (numeric_id)\n", "linked_data = clinical_data_t.merge(gene_data_t, \n", " left_index=True, \n", " right_index=True,\n", " how='inner')\n", "\n", "# Rename the clinical columns to descriptive names\n", "linked_data = linked_data.rename(columns={0: trait, 1: 'Age', 2: 'Gender'})\n", "\n", "print(f\"\\nLinked data shape: {linked_data.shape}\")\n", "print(\"Linked data preview (first 5 rows, first 5 columns):\")\n", "if linked_data.shape[1] >= 5:\n", " print(linked_data.iloc[:5, :5])\n", "else:\n", " print(linked_data.head())\n", "\n", "# 4. Handle missing values\n", "print(\"\\nMissing values before handling:\")\n", "print(f\" Trait ({trait}) missing: {linked_data[trait].isna().sum()} out of {len(linked_data)}\")\n", "gene_cols = [col for col in linked_data.columns if col not in [trait, 'Age', 'Gender']]\n", "if gene_cols:\n", " missing_genes_pct = linked_data[gene_cols].isna().mean()\n", " genes_with_high_missing = sum(missing_genes_pct > 0.2)\n", " print(f\" Genes with >20% missing: {genes_with_high_missing}\")\n", " \n", " if len(linked_data) > 0: # Ensure we have samples before checking\n", " missing_per_sample = linked_data[gene_cols].isna().mean(axis=1)\n", " samples_with_high_missing = sum(missing_per_sample > 0.05)\n", " print(f\" Samples with >5% missing genes: {samples_with_high_missing}\")\n", "\n", "# Handle missing values\n", "cleaned_data = handle_missing_values(linked_data, trait)\n", "print(f\"Data shape after handling missing values: {cleaned_data.shape}\")\n", "\n", "# 5. Evaluate bias in trait and demographic features\n", "trait_biased, cleaned_data = judge_and_remove_biased_features(cleaned_data, trait)\n", "\n", "# 6. Final validation and save\n", "note = \"Dataset contains gene expression data from glucocorticoid sensitivity studies. \"\n", "if 'Age' in cleaned_data.columns:\n", " note += \"Age data is available. \"\n", "if 'Gender' in cleaned_data.columns:\n", " note += \"Gender data is available. \"\n", "\n", "is_gene_available = len(normalized_gene_data) > 0\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=True, \n", " is_biased=trait_biased, \n", " df=cleaned_data,\n", " note=note\n", ")\n", "\n", "# 7. Save if usable\n", "if is_usable and len(cleaned_data) > 0:\n", " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n", " cleaned_data.to_csv(out_data_file)\n", " print(f\"Linked data saved to {out_data_file}\")\n", "else:\n", " print(\"Data was determined to be unusable or empty and was not 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 }