{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "81ca93cf", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:07:05.148476Z", "iopub.status.busy": "2025-03-25T04:07:05.148375Z", "iopub.status.idle": "2025-03-25T04:07:05.336412Z", "shell.execute_reply": "2025-03-25T04:07:05.336074Z" } }, "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 = \"GSE116833\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Substance_Use_Disorder\"\n", "in_cohort_dir = \"../../input/GEO/Substance_Use_Disorder/GSE116833\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Substance_Use_Disorder/GSE116833.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Substance_Use_Disorder/gene_data/GSE116833.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Substance_Use_Disorder/clinical_data/GSE116833.csv\"\n", "json_path = \"../../output/preprocess/Substance_Use_Disorder/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "ddd3767c", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "499d9989", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:07:05.337839Z", "iopub.status.busy": "2025-03-25T04:07:05.337703Z", "iopub.status.idle": "2025-03-25T04:07:05.442454Z", "shell.execute_reply": "2025-03-25T04:07:05.442102Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Peripheral gene expression in cocaine use disorders with low and high anhedonia\"\n", "!Series_summary\t\"Treatments for Cocaine Use Disorder (CUD) are variably effective, and there are no FDA-approved medications. One approach to developing new treatments for CUD may be to investigate and target poor prognostic signs. One such sign is anhedonia (i.e. a loss of pleasure or interest in non-drug rewards), which predicts worse outcomes in existing CUD treatments. Inflammation is thought to underlie anhedonia in many other disorders, but the relationship between anhedonia and inflammation has not been investigated in CUD. Therefore, we assessed peripheral genome-wide gene expression in n = 48 individuals with CUD with high (n=24) vs. low (n = 24) levels of anhedonia, defined by a median split of self-reported anhedonia. Our hypothesis was that individuals with high anhedonia would show differential gene expression in inflammatory pathways. No individual genes were significantly different between the low and high anhedonia groups when using t-tests with a stringent false discovery rate correction. However, an exploratory analysis identified 166 loci where t-tests suggested group differences at a nominal p < 0.05. We used DAVID, a bioinformatics tool that provides functional interpretations of complex lists of genes, to examine representation of this gene list in known pathways. It confirmed that mechanisms related to immunity were the top significant associations with anhedonia in the sample. Further, the two top differentially expressed genes in our sample, IRF1 and GBP5, both have primary inflammation and immune functions, and were significantly negatively correlated with total scores on our self-report of anhedonia across all 48 subjects. These results suggest that prioritizing development of anti-inflammatory medications for CUD may pay dividends, particularly in combination with treatment-matching strategies using either phenotypic measures of anhedonia or biomarkers of inflammatory gene expression to individualize treatment.\"\n", "!Series_overall_design\t\"HumanHT-12 v4.0 Gene Expression BeadChip (Illumina) was used to assess peripheral genome-wide gene expression in n = 48 individuals with CUD with high (n=24) vs. low (n = 24) levels of anhedonia, defined by a median split of self-reported anhedonia.\"\n", "Sample Characteristics Dictionary:\n", "{0: ['anhedonia: low', 'anhedonia: high'], 1: ['gender: female', 'gender: male'], 2: ['age: 40', 'age: 50', 'age: 46', 'age: 38', 'age: 52', 'age: 51', 'age: 33', 'age: 49', 'age: 44', 'age: 34', 'age: 53', 'age: 45', 'age: 56', 'age: 36', 'age: 57', 'age: 48', 'age: 30', 'age: 28', 'age: 35', 'age: 55', 'age: 59', 'age: 39', 'age: 24', 'age: 41', 'age: 31', 'age: 47', 'age: 37'], 3: ['shaps_total: 8', 'shaps_total: 0', 'shaps_total: 9', 'shaps_total: 4', 'shaps_total: 10', 'shaps_total: 6', 'shaps_total: 11', 'shaps_total: 16', 'shaps_total: 15', 'shaps_total: 14', 'shaps_total: 7', 'shaps_total: 5', 'shaps_total: 3', 'shaps_total: 12', 'shaps_total: 20', 'shaps_total: 17', 'shaps_total: 34', 'shaps_total: 38', 'shaps_total: 18', 'shaps_total: 29'], 4: ['race: More than one race', 'race: Black/AA', 'race: White', 'race: Unknown/Not Reported']}\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": "a8c2043b", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "b9577dc3", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:07:05.443643Z", "iopub.status.busy": "2025-03-25T04:07:05.443530Z", "iopub.status.idle": "2025-03-25T04:07:05.454894Z", "shell.execute_reply": "2025-03-25T04:07:05.454614Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Preview of extracted clinical features:\n", "{'GSM3262437': [0.0, 40.0, 0.0], 'GSM3262438': [0.0, 50.0, 1.0], 'GSM3262439': [0.0, 46.0, 1.0], 'GSM3262440': [0.0, 38.0, 1.0], 'GSM3262441': [0.0, 52.0, 1.0], 'GSM3262442': [0.0, 51.0, 1.0], 'GSM3262443': [0.0, 33.0, 0.0], 'GSM3262444': [0.0, 49.0, 1.0], 'GSM3262445': [1.0, 52.0, 1.0], 'GSM3262446': [1.0, 52.0, 1.0], 'GSM3262447': [0.0, 44.0, 1.0], 'GSM3262448': [0.0, 49.0, 1.0], 'GSM3262449': [1.0, 51.0, 0.0], 'GSM3262450': [0.0, 40.0, 0.0], 'GSM3262451': [0.0, 34.0, 0.0], 'GSM3262452': [0.0, 53.0, 1.0], 'GSM3262453': [1.0, 45.0, 1.0], 'GSM3262454': [1.0, 56.0, 1.0], 'GSM3262455': [0.0, 36.0, 0.0], 'GSM3262456': [0.0, 52.0, 1.0], 'GSM3262457': [1.0, 57.0, 1.0], 'GSM3262458': [0.0, 48.0, 1.0], 'GSM3262459': [0.0, 52.0, 1.0], 'GSM3262460': [0.0, 30.0, 1.0], 'GSM3262461': [0.0, 28.0, 1.0], 'GSM3262462': [1.0, 53.0, 1.0], 'GSM3262463': [1.0, 46.0, 1.0], 'GSM3262464': [1.0, 35.0, 0.0], 'GSM3262465': [0.0, 55.0, 1.0], 'GSM3262466': [0.0, 57.0, 1.0], 'GSM3262467': [1.0, 59.0, 1.0], 'GSM3262468': [1.0, 48.0, 1.0], 'GSM3262469': [1.0, 39.0, 0.0], 'GSM3262470': [0.0, 38.0, 1.0], 'GSM3262471': [1.0, 24.0, 1.0], 'GSM3262472': [1.0, 38.0, 0.0], 'GSM3262473': [1.0, 53.0, 0.0], 'GSM3262474': [1.0, 51.0, 1.0], 'GSM3262475': [1.0, 41.0, 0.0], 'GSM3262476': [0.0, 31.0, 1.0], 'GSM3262477': [1.0, 47.0, 1.0], 'GSM3262478': [0.0, 53.0, 1.0], 'GSM3262479': [1.0, 56.0, 1.0], 'GSM3262480': [1.0, 45.0, 1.0], 'GSM3262481': [1.0, 50.0, 1.0], 'GSM3262482': [1.0, 46.0, 1.0], 'GSM3262483': [1.0, 59.0, 1.0], 'GSM3262484': [1.0, 37.0, 1.0]}\n", "Clinical data saved to: ../../output/preprocess/Substance_Use_Disorder/clinical_data/GSE116833.csv\n" ] } ], "source": [ "import pandas as pd\n", "import os\n", "\n", "# 1. Gene Expression Data Availability\n", "# Based on the background information, this dataset uses \"HumanHT-12 v4.0 Gene Expression BeadChip\" \n", "# which indicates it contains gene expression data\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "# For trait (Substance Use Disorder), we can use the anhedonia level as a proxy\n", "# since this study is about Cocaine Use Disorder with high vs low anhedonia\n", "trait_row = 0 # anhedonia level (high/low)\n", "age_row = 2 # age data is available\n", "gender_row = 1 # gender data is available\n", "\n", "# 2.2 Data Type Conversion\n", "def convert_trait(value):\n", " \"\"\"Convert anhedonia level to binary representation.\"\"\"\n", " if pd.isna(value):\n", " return None\n", " if \":\" in value:\n", " value = value.split(\":\")[1].strip()\n", " if value.lower() == \"low\":\n", " return 0\n", " elif value.lower() == \"high\":\n", " return 1\n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age string to numeric value.\"\"\"\n", " if pd.isna(value):\n", " return None\n", " if \":\" in value:\n", " value = value.split(\":\")[1].strip()\n", " try:\n", " return float(value)\n", " except:\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"Convert gender to binary representation (female=0, male=1).\"\"\"\n", " if pd.isna(value):\n", " return None\n", " if \":\" in value:\n", " value = value.split(\":\")[1].strip()\n", " if value.lower() == \"female\":\n", " return 0\n", " elif value.lower() == \"male\":\n", " return 1\n", " return None\n", "\n", "# 3. Save Metadata\n", "# Determine if trait data is available\n", "is_trait_available = trait_row is not None\n", "\n", "# Conduct initial filtering and save metadata\n", "validate_and_save_cohort_info(\n", " is_final=False,\n", " cohort=cohort,\n", " info_path=json_path,\n", " is_gene_available=is_gene_available,\n", " is_trait_available=is_trait_available\n", ")\n", "\n", "# 4. Clinical Feature Extraction\n", "if trait_row is not None:\n", " try:\n", " # Extract clinical features from the clinical_data that was already loaded\n", " # in a previous step and is available in the environment\n", " selected_clinical_df = geo_select_clinical_features(\n", " clinical_df=clinical_data,\n", " trait=trait,\n", " trait_row=trait_row,\n", " convert_trait=convert_trait,\n", " age_row=age_row,\n", " convert_age=convert_age,\n", " gender_row=gender_row,\n", " convert_gender=convert_gender\n", " )\n", " \n", " # Preview the extracted clinical features\n", " preview = preview_df(selected_clinical_df)\n", " print(\"Preview of extracted clinical features:\")\n", " print(preview)\n", " \n", " # Save the extracted clinical features 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", " \n", " except Exception as e:\n", " print(f\"Error in clinical feature extraction: {e}\")\n" ] }, { "cell_type": "markdown", "id": "eace1e8b", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "fa011fd0", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:07:05.455882Z", "iopub.status.busy": "2025-03-25T04:07:05.455781Z", "iopub.status.idle": "2025-03-25T04:07:05.621779Z", "shell.execute_reply": "2025-03-25T04:07:05.621416Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Found data marker at line 72\n", "Header line: \"ID_REF\"\t\"GSM3262437\"\t\"GSM3262438\"\t\"GSM3262439\"\t\"GSM3262440\"\t\"GSM3262441\"\t\"GSM3262442\"\t\"GSM3262443\"\t\"GSM3262444\"\t\"GSM3262445\"\t\"GSM3262446\"\t\"GSM3262447\"\t\"GSM3262448\"\t\"GSM3262449\"\t\"GSM3262450\"\t\"GSM3262451\"\t\"GSM3262452\"\t\"GSM3262453\"\t\"GSM3262454\"\t\"GSM3262455\"\t\"GSM3262456\"\t\"GSM3262457\"\t\"GSM3262458\"\t\"GSM3262459\"\t\"GSM3262460\"\t\"GSM3262461\"\t\"GSM3262462\"\t\"GSM3262463\"\t\"GSM3262464\"\t\"GSM3262465\"\t\"GSM3262466\"\t\"GSM3262467\"\t\"GSM3262468\"\t\"GSM3262469\"\t\"GSM3262470\"\t\"GSM3262471\"\t\"GSM3262472\"\t\"GSM3262473\"\t\"GSM3262474\"\t\"GSM3262475\"\t\"GSM3262476\"\t\"GSM3262477\"\t\"GSM3262478\"\t\"GSM3262479\"\t\"GSM3262480\"\t\"GSM3262481\"\t\"GSM3262482\"\t\"GSM3262483\"\t\"GSM3262484\"\n", "First data line: \"ILMN_1343291\"\t24685.7\t24733.9\t28152.7\t24733.9\t29971.7\t24595.2\t20213.5\t24473.2\t23915.6\t23099\t28882.2\t29971.7\t29239.2\t28882.2\t25456.1\t24922.5\t23915.6\t29239.2\t27115\t19761.6\t27637.4\t28552.7\t27988\t27492.2\t25378.4\t22610.7\t25623.6\t27355.8\t24272.2\t26606.5\t27816.5\t27988\t23723.4\t20329.9\t21227.4\t22996.8\t24874.5\t24021.3\t26690.2\t28882.2\t28152.7\t20947.1\t27637.4\t24140.9\t27007.6\t27492.2\t29239.2\t27115\n", "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": "0acd56b0", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "f4e08b78", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:07:05.622926Z", "iopub.status.busy": "2025-03-25T04:07:05.622811Z", "iopub.status.idle": "2025-03-25T04:07:05.624659Z", "shell.execute_reply": "2025-03-25T04:07:05.624384Z" } }, "outputs": [], "source": [ "# Looking at the identifiers, these are Illumina probe IDs (starting with \"ILMN_\") \n", "# rather than standard human gene symbols.\n", "# These identifiers need to be mapped to human gene symbols.\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "287dc9cc", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "3968cf9a", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:07:05.625780Z", "iopub.status.busy": "2025-03-25T04:07:05.625670Z", "iopub.status.idle": "2025-03-25T04:07:06.525955Z", "shell.execute_reply": "2025-03-25T04:07:06.525515Z" } }, "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 = GSE116833\n", "Line 6: !Series_title = Peripheral gene expression in cocaine use disorders with low and high anhedonia\n", "Line 7: !Series_geo_accession = GSE116833\n", "Line 8: !Series_status = Public on Nov 02 2018\n", "Line 9: !Series_submission_date = Jul 09 2018\n", "Line 10: !Series_last_update_date = Nov 30 2018\n", "Line 11: !Series_pubmed_id = 30408130\n", "Line 12: !Series_summary = Treatments for Cocaine Use Disorder (CUD) are variably effective, and there are no FDA-approved medications. One approach to developing new treatments for CUD may be to investigate and target poor prognostic signs. One such sign is anhedonia (i.e. a loss of pleasure or interest in non-drug rewards), which predicts worse outcomes in existing CUD treatments. Inflammation is thought to underlie anhedonia in many other disorders, but the relationship between anhedonia and inflammation has not been investigated in CUD. Therefore, we assessed peripheral genome-wide gene expression in n = 48 individuals with CUD with high (n=24) vs. low (n = 24) levels of anhedonia, defined by a median split of self-reported anhedonia. Our hypothesis was that individuals with high anhedonia would show differential gene expression in inflammatory pathways. No individual genes were significantly different between the low and high anhedonia groups when using t-tests with a stringent false discovery rate correction. However, an exploratory analysis identified 166 loci where t-tests suggested group differences at a nominal p < 0.05. We used DAVID, a bioinformatics tool that provides functional interpretations of complex lists of genes, to examine representation of this gene list in known pathways. It confirmed that mechanisms related to immunity were the top significant associations with anhedonia in the sample. Further, the two top differentially expressed genes in our sample, IRF1 and GBP5, both have primary inflammation and immune functions, and were significantly negatively correlated with total scores on our self-report of anhedonia across all 48 subjects. These results suggest that prioritizing development of anti-inflammatory medications for CUD may pay dividends, particularly in combination with treatment-matching strategies using either phenotypic measures of anhedonia or biomarkers of inflammatory gene expression to individualize treatment.\n", "Line 13: !Series_overall_design = HumanHT-12 v4.0 Gene Expression BeadChip (Illumina) was used to assess peripheral genome-wide gene expression in n = 48 individuals with CUD with high (n=24) vs. low (n = 24) levels of anhedonia, defined by a median split of self-reported anhedonia.\n", "Line 14: !Series_type = Expression profiling by array\n", "Line 15: !Series_contributor = Gabriel,,Fries\n", "Line 16: !Series_contributor = Sarwar,,Khan\n", "Line 17: !Series_contributor = Sydney,,Stamatovich\n", "Line 18: !Series_contributor = Elena,,Dyukova\n", "Line 19: !Series_contributor = Consuelo,,Walss-Bass\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": "7e089799", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "c6e60772", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:07:06.527615Z", "iopub.status.busy": "2025-03-25T04:07:06.527506Z", "iopub.status.idle": "2025-03-25T04:07:07.102545Z", "shell.execute_reply": "2025-03-25T04:07:07.102169Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "Gene mapping preview (first 5 rows):\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", "\n", "Gene expression data preview (first 5 genes):\n", " GSM3262437 GSM3262438 GSM3262439 GSM3262440 GSM3262441 GSM3262442 \\\n", "Gene \n", "A1BG 238.2 263.3 264.4 247.0 262.2 274.6 \n", "A1CF 354.6 344.1 354.7 363.3 381.6 364.4 \n", "A26C3 365.0 330.3 354.6 340.1 356.3 328.8 \n", "A2BP1 455.3 452.7 452.7 450.8 468.0 438.1 \n", "A2LD1 208.9 227.4 242.2 214.2 239.1 229.1 \n", "\n", " GSM3262443 GSM3262444 GSM3262445 GSM3262446 ... GSM3262475 \\\n", "Gene ... \n", "A1BG 245.4 263.5 252.9 268.6 ... 259.1 \n", "A1CF 375.3 353.0 352.6 340.5 ... 353.8 \n", "A26C3 361.1 347.5 354.3 356.8 ... 347.9 \n", "A2BP1 462.0 460.5 446.2 446.4 ... 452.0 \n", "A2LD1 208.4 254.8 193.9 201.1 ... 225.6 \n", "\n", " GSM3262476 GSM3262477 GSM3262478 GSM3262479 GSM3262480 GSM3262481 \\\n", "Gene \n", "A1BG 272.3 257.3 836.8 269.9 235.5 255.4 \n", "A1CF 354.0 358.4 436.5 363.2 364.8 360.3 \n", "A26C3 332.7 348.9 394.3 355.0 352.3 375.5 \n", "A2BP1 456.0 472.2 608.2 443.7 452.9 448.9 \n", "A2LD1 213.3 252.6 120.3 208.2 213.6 240.0 \n", "\n", " GSM3262482 GSM3262483 GSM3262484 \n", "Gene \n", "A1BG 282.0 267.3 248.1 \n", "A1CF 362.5 366.1 357.4 \n", "A26C3 378.6 353.6 352.5 \n", "A2BP1 474.0 460.2 459.3 \n", "A2LD1 241.0 251.0 208.5 \n", "\n", "[5 rows x 48 columns]\n", "\n", "Number of genes after mapping: 21464\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene expression data saved to: ../../output/preprocess/Substance_Use_Disorder/gene_data/GSE116833.csv\n" ] } ], "source": [ "# From inspecting the gene annotation preview, we need to use ID for probe identifiers\n", "# and Symbol for gene symbols\n", "\n", "# 1. Define the columns for probe IDs and gene symbols in the gene annotation dataframe\n", "id_column = 'ID'\n", "symbol_column = 'Symbol'\n", "\n", "# 2. Get the gene mapping dataframe\n", "gene_mapping = get_gene_mapping(gene_annotation, id_column, symbol_column)\n", "print(\"\\nGene mapping preview (first 5 rows):\")\n", "print(gene_mapping.head())\n", "\n", "# 3. Apply the gene mapping to convert probe-level data to gene-level data\n", "gene_data = apply_gene_mapping(gene_data, gene_mapping)\n", "print(\"\\nGene expression data preview (first 5 genes):\")\n", "print(gene_data.head())\n", "\n", "# Check the number of genes after mapping\n", "print(f\"\\nNumber of genes after mapping: {len(gene_data)}\")\n", "\n", "# Save the gene expression data to CSV\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": "29e8b5e5", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "0cd1eace", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:07:07.103804Z", "iopub.status.busy": "2025-03-25T04:07:07.103686Z", "iopub.status.idle": "2025-03-25T04:07:18.123696Z", "shell.execute_reply": "2025-03-25T04:07:18.123348Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene data shape before normalization: (21464, 48)\n", "Gene data shape after normalization: (20259, 48)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene data saved to ../../output/preprocess/Substance_Use_Disorder/gene_data/GSE116833.csv\n", "Raw clinical data shape: (5, 49)\n", "Clinical features:\n", " GSM3262437 GSM3262438 GSM3262439 GSM3262440 \\\n", "Substance_Use_Disorder 0.0 0.0 0.0 0.0 \n", "Age 40.0 50.0 46.0 38.0 \n", "Gender 0.0 1.0 1.0 1.0 \n", "\n", " GSM3262441 GSM3262442 GSM3262443 GSM3262444 \\\n", "Substance_Use_Disorder 0.0 0.0 0.0 0.0 \n", "Age 52.0 51.0 33.0 49.0 \n", "Gender 1.0 1.0 0.0 1.0 \n", "\n", " GSM3262445 GSM3262446 ... GSM3262475 GSM3262476 \\\n", "Substance_Use_Disorder 1.0 1.0 ... 1.0 0.0 \n", "Age 52.0 52.0 ... 41.0 31.0 \n", "Gender 1.0 1.0 ... 0.0 1.0 \n", "\n", " GSM3262477 GSM3262478 GSM3262479 GSM3262480 \\\n", "Substance_Use_Disorder 1.0 0.0 1.0 1.0 \n", "Age 47.0 53.0 56.0 45.0 \n", "Gender 1.0 1.0 1.0 1.0 \n", "\n", " GSM3262481 GSM3262482 GSM3262483 GSM3262484 \n", "Substance_Use_Disorder 1.0 1.0 1.0 1.0 \n", "Age 50.0 46.0 59.0 37.0 \n", "Gender 1.0 1.0 1.0 1.0 \n", "\n", "[3 rows x 48 columns]\n", "Clinical features saved to ../../output/preprocess/Substance_Use_Disorder/clinical_data/GSE116833.csv\n", "Linked data shape: (48, 20262)\n", "Linked data preview (first 5 rows, first 5 columns):\n", " Substance_Use_Disorder Age Gender A1BG A1BG-AS1\n", "GSM3262437 0.0 40.0 0.0 238.2 119.7\n", "GSM3262438 0.0 50.0 1.0 263.3 114.9\n", "GSM3262439 0.0 46.0 1.0 264.4 117.8\n", "GSM3262440 0.0 38.0 1.0 247.0 117.2\n", "GSM3262441 0.0 52.0 1.0 262.2 109.6\n", "Missing values before handling:\n", " Trait (Substance_Use_Disorder) missing: 0 out of 48\n", " Age missing: 0 out of 48\n", " Gender missing: 0 out of 48\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: (48, 20262)\n", "For the feature 'Substance_Use_Disorder', the least common label is '0.0' with 24 occurrences. This represents 50.00% of the dataset.\n", "The distribution of the feature 'Substance_Use_Disorder' in this dataset is fine.\n", "\n", "Quartiles for 'Age':\n", " 25%: 38.75\n", " 50% (Median): 48.0\n", " 75%: 52.0\n", "Min: 24.0\n", "Max: 59.0\n", "The distribution of the feature 'Age' in this dataset is fine.\n", "\n", "For the feature 'Gender', the least common label is '0.0' with 11 occurrences. This represents 22.92% of the dataset.\n", "The distribution of the feature 'Gender' in this dataset is fine.\n", "\n", "A new JSON file was created at: ../../output/preprocess/Substance_Use_Disorder/cohort_info.json\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Linked data saved to ../../output/preprocess/Substance_Use_Disorder/GSE116833.csv\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 }