{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "717659e8", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:08:06.544748Z", "iopub.status.busy": "2025-03-25T04:08:06.544522Z", "iopub.status.idle": "2025-03-25T04:08:06.712120Z", "shell.execute_reply": "2025-03-25T04:08:06.711762Z" } }, "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 = \"Substance_Use_Disorder\"\n", "cohort = \"GSE273630\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Substance_Use_Disorder\"\n", "in_cohort_dir = \"../../input/GEO/Substance_Use_Disorder/GSE273630\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Substance_Use_Disorder/GSE273630.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Substance_Use_Disorder/gene_data/GSE273630.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Substance_Use_Disorder/clinical_data/GSE273630.csv\"\n", "json_path = \"../../output/preprocess/Substance_Use_Disorder/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "817b3bce", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "d5afb807", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:08:06.713698Z", "iopub.status.busy": "2025-03-25T04:08:06.713557Z", "iopub.status.idle": "2025-03-25T04:08:06.722720Z", "shell.execute_reply": "2025-03-25T04:08:06.722436Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Dopamine-regulated biomarkers in peripheral blood of HIV+ Methamphetamine users\"\n", "!Series_summary\t\"HIV and Methamphetamine study - Translational Methamphetamine AIDS Research Center - Dopamine-regulated inflammatory biomarkers\"\n", "!Series_summary\t\"A digital transcript panel was custom-made based on Hs_NeuroPath_v1 (Nanostring) to accommodate dopamine-regulated inflammatory genes that were previously identified in vitro, and hypothesized to cluster HIV+ Methamphetamine users.\"\n", "!Series_overall_design\t\"Specimens were peripheral blood leukocytes isolated from participants that included adults enrolled by NIH-funded studies at the University of California San Diego’s HIV Neurobehavioral Research Program (HNRP) and Translational Methamphetamine Research Center (TMARC) under informed consent and approved protocols. The subset of PWH and PWoH selected for this study were by design males, between 35 – 44 years old, due to cohort characteristics and to increase statistical power. The participants were divided based on HIV serostatus (HIV+/-) and Meth use (METH+/-). METH+ was defined as meeting lifetime DSM-IV criteria for methamphetamine use or dependence, and METH dependence or abuse within 18 months (LT Methamphetamine Dx), with 8.2% urine toxicology positive/current METH users. A cross-sectional design assembled the following groups: HIV-METH- , HIV+METH- , HIV-METH+ , and HIV+METH+. Exclusion criteria were a history of non-HIV-related neurological, medical, or psychiatric disorders that affect brain function (e.g., schizophrenia, traumatic brain injury, epilepsy), learning disabilities, or dementia.\"\n", "Sample Characteristics Dictionary:\n", "{0: ['tissue: Peripheral blood cells']}\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": "10a7fda4", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "d197fdb9", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:08:06.723788Z", "iopub.status.busy": "2025-03-25T04:08:06.723682Z", "iopub.status.idle": "2025-03-25T04:08:06.730680Z", "shell.execute_reply": "2025-03-25T04:08:06.730385Z" } }, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 1. Analyze gene expression data availability\n", "is_gene_available = True # Based on the background, this is a gene expression panel\n", "\n", "# 2.1 Data Availability Analysis\n", "# This dataset appears to study HIV+ methamphetamine users\n", "# From the background information, we can infer:\n", "# - The trait is Substance Use Disorder (methamphetamine use/dependence)\n", "# - Age is controlled (all participants are 35-44 years old)\n", "# - Gender is controlled (all participants are males)\n", "\n", "# Since the sample characteristics don't show trait/age/gender explicitly,\n", "# but the background information mentions HIV+/- and METH+/- groups,\n", "# we need to infer these values from the overall design.\n", "\n", "# The key for trait (METH use) doesn't exist in sample characteristics\n", "trait_row = None # Not directly available in the sample characteristics\n", "\n", "# Age and gender are controlled variables (all males, 35-44 years)\n", "age_row = None # Not available as a variable (all subjects are 35-44 years)\n", "gender_row = None # Not available as a variable (all subjects are males)\n", "\n", "# 2.2 Data Type Conversion Functions\n", "# Although we don't have actual data for these variables, we'll define \n", "# conversion functions that would be used if the data were available\n", "\n", "def convert_trait(value):\n", " \"\"\"Convert methamphetamine use status to binary.\"\"\"\n", " if value is None:\n", " return None\n", " value = value.lower() if isinstance(value, str) else str(value).lower()\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " if 'meth+' in value or 'methamphetamine+' in value or 'yes' in value:\n", " return 1\n", " elif 'meth-' in value or 'methamphetamine-' in value or 'no' in value:\n", " return 0\n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age to continuous value.\"\"\"\n", " if value is None:\n", " return None\n", " value = str(value)\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " try:\n", " age = float(value)\n", " return age\n", " except:\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"Convert gender to binary (0=female, 1=male).\"\"\"\n", " if value is None:\n", " return None\n", " value = value.lower() if isinstance(value, str) else str(value).lower()\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " if 'male' in value or 'm' == value:\n", " return 1\n", " elif 'female' in value or 'f' == value:\n", " return 0\n", " return None\n", "\n", "# 3. Save metadata\n", "# Trait data is not available as a variable in the sample characteristics\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", "# Since trait_row is None, we skip this step\n" ] }, { "cell_type": "markdown", "id": "bfad6eab", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "cd54ef63", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:08:06.731844Z", "iopub.status.busy": "2025-03-25T04:08:06.731744Z", "iopub.status.idle": "2025-03-25T04:08:06.751923Z", "shell.execute_reply": "2025-03-25T04:08:06.751629Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Found data marker at line 61\n", "Header line: \"ID_REF\"\t\"GSM8434091\"\t\"GSM8434092\"\t\"GSM8434093\"\t\"GSM8434094\"\t\"GSM8434095\"\t\"GSM8434096\"\t\"GSM8434097\"\t\"GSM8434098\"\t\"GSM8434099\"\t\"GSM8434100\"\t\"GSM8434101\"\t\"GSM8434102\"\t\"GSM8434103\"\t\"GSM8434104\"\t\"GSM8434105\"\t\"GSM8434106\"\t\"GSM8434107\"\t\"GSM8434108\"\t\"GSM8434109\"\t\"GSM8434110\"\t\"GSM8434111\"\t\"GSM8434112\"\t\"GSM8434113\"\t\"GSM8434114\"\t\"GSM8434115\"\t\"GSM8434116\"\t\"GSM8434117\"\t\"GSM8434118\"\t\"GSM8434119\"\t\"GSM8434120\"\t\"GSM8434121\"\t\"GSM8434122\"\t\"GSM8434123\"\t\"GSM8434124\"\t\"GSM8434125\"\t\"GSM8434126\"\t\"GSM8434127\"\t\"GSM8434128\"\t\"GSM8434129\"\t\"GSM8434130\"\t\"GSM8434131\"\t\"GSM8434132\"\t\"GSM8434133\"\t\"GSM8434134\"\t\"GSM8434135\"\t\"GSM8434136\"\t\"GSM8434137\"\t\"GSM8434138\"\t\"GSM8434139\"\t\"GSM8434140\"\t\"GSM8434141\"\t\"GSM8434142\"\t\"GSM8434143\"\t\"GSM8434144\"\t\"GSM8434145\"\t\"GSM8434146\"\t\"GSM8434147\"\t\"GSM8434148\"\t\"GSM8434149\"\t\"GSM8434150\"\t\"GSM8434151\"\t\"GSM8434152\"\t\"GSM8434153\"\t\"GSM8434154\"\t\"GSM8434155\"\t\"GSM8434156\"\t\"GSM8434157\"\t\"GSM8434158\"\t\"GSM8434159\"\t\"GSM8434160\"\t\"GSM8434161\"\t\"GSM8434162\"\t\"GSM8434163\"\t\"GSM8434164\"\t\"GSM8434165\"\t\"GSM8434166\"\t\"GSM8434167\"\t\"GSM8434168\"\t\"GSM8434169\"\t\"GSM8434170\"\t\"GSM8434171\"\t\"GSM8434172\"\t\"GSM8434173\"\t\"GSM8434174\"\t\"GSM8434175\"\t\"GSM8434176\"\t\"GSM8434177\"\t\"GSM8434178\"\t\"GSM8434179\"\t\"GSM8434180\"\t\"GSM8434181\"\t\"GSM8434182\"\t\"GSM8434183\"\t\"GSM8434184\"\t\"GSM8434185\"\t\"GSM8434186\"\t\"GSM8434187\"\t\"GSM8434188\"\t\"GSM8434189\"\n", "First data line: \"ABAT\"\t119\t0\t2.666666667\t0.666666667\t1.333333333\t-3.333333333\t0\t-1\t-2.333333333\t8.666666667\t-3\t-8.333333333\t18.33333333\t1.666666667\t8.333333333\t25.33333333\t-2\t-24.66666667\t-10.66666667\t3.333333333\t1\t6\t-42.33333333\t-1\t8\t7.666666667\t6.333333333\t3\t4.333333333\t0.666666667\t0.666666667\t-173.6666667\t-2\t-2\t-26.33333333\t-10.33333333\t1.666666667\t431.6666667\t-17\t35\t2.333333333\t-32\t-57.66666667\t3\t347\t-8\t-22.33333333\t4.333333333\t122.3333333\t-307\t128.6666667\t269.6666667\t238\t-3.666666667\t82\t-32.66666667\t-6.333333333\t-21.33333333\t0.666666667\t-119\t2\t-280.3333333\t0.666666667\t-30.66666667\t25\t3.666666667\t-331.3333333\t-27.66666667\t-24.33333333\t126.3333333\t100.3333333\t4\t-2.333333333\t9.666666667\t-1.666666667\t61.33333333\t5.333333333\t19.66666667\t-58.33333333\t-4.333333333\t-36.66666667\t7.666666667\t-16.33333333\t3\t0.666666667\t-18.66666667\t-98.66666667\t-31.66666667\t-1\t-1\t-52.33333333\t1.333333333\t16.66666667\t-0.666666667\t6\t6\t-38.66666667\t7.666666667\t1.666666667\n", "Index(['ABAT', 'ABL1', 'ACAA1', 'ACHE', 'ACIN1', 'ACTN1', 'ACVRL1', 'ADAM10',\n", " 'ADCY5', 'ADCY8', 'ADCY9', 'ADCYAP1', 'ADORA1', 'ADORA2A', 'ADRA2A',\n", " 'ADRB2', 'AGER', 'AIF1', 'AKT1', 'AKT1S1'],\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": "415d4c56", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "ef753ba2", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:08:06.752943Z", "iopub.status.busy": "2025-03-25T04:08:06.752843Z", "iopub.status.idle": "2025-03-25T04:08:06.754622Z", "shell.execute_reply": "2025-03-25T04:08:06.754315Z" } }, "outputs": [], "source": [ "# I need to analyze the gene identifiers in the data\n", "# Looking at the first data line, I see identifiers like \"ABAT\", \"ABL1\", \"ACAA1\", \"ACHE\", etc.\n", "# These appear to be standard human gene symbols rather than probe IDs or other identifiers\n", "\n", "# Based on the sample data, I can see that the identifiers are already in the form of standard \n", "# human gene symbols (e.g., ABAT, ABL1, ACAA1, etc.). These are the official gene symbols \n", "# used in human genomics and do not require mapping.\n", "\n", "requires_gene_mapping = False\n" ] }, { "cell_type": "markdown", "id": "8bbd9605", "metadata": {}, "source": [ "### Step 5: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 6, "id": "042458d4", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:08:06.755792Z", "iopub.status.busy": "2025-03-25T04:08:06.755694Z", "iopub.status.idle": "2025-03-25T04:08:06.881041Z", "shell.execute_reply": "2025-03-25T04:08:06.880664Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene data shape before normalization: (780, 99)\n", "Gene data shape after normalization: (780, 99)\n", "Normalized gene data saved to ../../output/preprocess/Substance_Use_Disorder/gene_data/GSE273630.csv\n", "Trait row is None. Cannot extract trait information from clinical data.\n", "Abnormality detected in the cohort: GSE273630. Preprocessing failed.\n", "Data was determined to be unusable due to missing trait indicators and was not saved\n" ] } ], "source": [ "# 1. Normalize gene symbols in the obtained gene expression data\n", "print(f\"Gene data shape before normalization: {gene_data.shape}\")\n", "\n", "# Normalize gene symbols using NCBI Gene database\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\n", "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n", "normalized_gene_data.to_csv(out_gene_data_file)\n", "print(f\"Normalized gene data saved to {out_gene_data_file}\")\n", "\n", "# 2. Check if trait data is available before proceeding with clinical data extraction\n", "if trait_row is None:\n", " print(\"Trait row is None. Cannot extract trait information from clinical data.\")\n", " # Create an empty dataframe for clinical features\n", " clinical_features = pd.DataFrame()\n", " \n", " # Create an empty dataframe for linked data\n", " linked_data = pd.DataFrame()\n", " \n", " # Validate and save cohort info\n", " 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=False, # Trait data is not available\n", " is_biased=True, # Not applicable but required\n", " df=pd.DataFrame(), # Empty dataframe\n", " note=f\"Dataset contains gene expression data but lacks clear trait indicators for {trait} status.\"\n", " )\n", " print(\"Data was determined to be unusable due to missing trait indicators and was not saved\")\n", "else:\n", " try:\n", " # Get the file paths for the matrix file to extract clinical data\n", " _, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", " \n", " # Get raw clinical data from the matrix file\n", " _, clinical_raw = get_background_and_clinical_data(matrix_file)\n", " \n", " # Verify clinical data structure\n", " print(\"Raw clinical data shape:\", clinical_raw.shape)\n", " \n", " # Extract clinical features using the defined conversion functions\n", " clinical_features = geo_select_clinical_features(\n", " clinical_df=clinical_raw,\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 features:\")\n", " print(clinical_features)\n", " \n", " # Save clinical features to file\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " clinical_features.to_csv(out_clinical_data_file)\n", " print(f\"Clinical features saved to {out_clinical_data_file}\")\n", " \n", " # 3. Link clinical and genetic data\n", " linked_data = geo_link_clinical_genetic_data(clinical_features, normalized_gene_data)\n", " print(f\"Linked data shape: {linked_data.shape}\")\n", " print(\"Linked data preview (first 5 rows, first 5 columns):\")\n", " print(linked_data.iloc[:5, :5])\n", " \n", " # 4. Handle missing values\n", " print(\"Missing values before handling:\")\n", " print(f\" Trait ({trait}) missing: {linked_data[trait].isna().sum()} out of {len(linked_data)}\")\n", " if 'Age' in linked_data.columns:\n", " print(f\" Age missing: {linked_data['Age'].isna().sum()} out of {len(linked_data)}\")\n", " if 'Gender' in linked_data.columns:\n", " print(f\" Gender missing: {linked_data['Gender'].isna().sum()} out of {len(linked_data)}\")\n", " \n", " gene_cols = [col for col in linked_data.columns if col not in [trait, 'Age', 'Gender']]\n", " print(f\" Genes with >20% missing: {sum(linked_data[gene_cols].isna().mean() > 0.2)}\")\n", " print(f\" Samples with >5% missing genes: {sum(linked_data[gene_cols].isna().mean(axis=1) > 0.05)}\")\n", " \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", " is_trait_biased = False\n", " if len(cleaned_data) > 0:\n", " trait_biased, cleaned_data = judge_and_remove_biased_features(cleaned_data, trait)\n", " is_trait_biased = trait_biased\n", " else:\n", " print(\"No data remains after handling missing values.\")\n", " is_trait_biased = True\n", " \n", " # 6. Final validation and save\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_trait_biased, \n", " df=cleaned_data,\n", " note=f\"Dataset contains gene expression data for {trait} analysis.\"\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\")\n", " \n", " except Exception as e:\n", " print(f\"Error processing data: {e}\")\n", " # Handle the error case by still recording cohort info\n", " 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=False, # Mark as not available due to processing issues\n", " is_biased=True, \n", " df=pd.DataFrame(), # Empty dataframe\n", " note=f\"Error processing data for {trait}: {str(e)}\"\n", " )\n", " print(\"Data was determined to be unusable 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 }