{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "a4feec58", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:44:23.089297Z", "iopub.status.busy": "2025-03-25T05:44:23.089070Z", "iopub.status.idle": "2025-03-25T05:44:23.257284Z", "shell.execute_reply": "2025-03-25T05:44:23.256839Z" } }, "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 = \"HIV_Resistance\"\n", "cohort = \"GSE46599\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/HIV_Resistance\"\n", "in_cohort_dir = \"../../input/GEO/HIV_Resistance/GSE46599\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/HIV_Resistance/GSE46599.csv\"\n", "out_gene_data_file = \"../../output/preprocess/HIV_Resistance/gene_data/GSE46599.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/HIV_Resistance/clinical_data/GSE46599.csv\"\n", "json_path = \"../../output/preprocess/HIV_Resistance/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "f8e34cec", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "1665ff3a", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:44:23.258776Z", "iopub.status.busy": "2025-03-25T05:44:23.258622Z", "iopub.status.idle": "2025-03-25T05:44:23.420546Z", "shell.execute_reply": "2025-03-25T05:44:23.420178Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Genome-wide analysis of interferon-stimulated genes in primary cells and immortalized cell lines\"\n", "!Series_summary\t\"Analysis of interferon-stimulated genes (ISGs) in various primary cells and immortalized cell lines, following type 1 interferon (IFN) treatment. Some cell types become resistant to HIV-1 infection following type 1 interferon treatment (such as macrophages, THP-1, PMA-THP-1, U87-MG cells and to a lesser extent, primary CD4+ T cells) while others either become only partially resistant (e.g., HT1080, PMA-U937) or remain permissive (e.g., CEM, CEM-SS, Jurkat T cell lines and U937); for more information see (Goujon and Malim, Journal of Virology 2010) and (Goujon and Schaller et al., Retrovirology 2013). We hypothesized that the anti-HIV-1 ISGs are differentially induced and expressed in restrictive cells compared to permissive cells and performed a whole genome analysis following type 1 IFN treatment in cell types exhibiting different HIV-1 resistance phenotypes.\"\n", "!Series_overall_design\t\"48 samples; design: 9 cell lines, primary CD4+ T cells and primary macrophages, untreated and IFN-treated; 2 replicate experiments per cell line; 3 replicate experiments per primary cell type\"\n", "Sample Characteristics Dictionary:\n", "{0: ['cell line: CEM (T cell line)', 'cell line: CEM-SS (T cell line)', 'cell line: HT1080 (fibrosarcoma cell line)', 'cell line: Jurkat (T cell line)', 'cell line: PMA-THP-1 (PMA-treated monocytic cell line)', 'cell line: PMA-U937 (PMA-treated monocytic cell line)', 'primary cell type: primary macrophages (derived from blood monocytes)', 'primary cell type: primary CD4+ T cells (total CD4+ T cells from blood activated with IL2 / PHA)', 'cell line: THP-1 (monocytic cell line)', 'cell line: U87-MG (glioblastoma-astrocytoma, epithelial-like cell line)', 'cell line: U937 (monocytic cell line)'], 1: ['treatment: type 1 IFN', 'treatment: None'], 2: ['donor: CEM', 'donor: CEM-SS', 'donor: HT1080', 'donor: Jurkat', 'donor: THP-1', 'donor: U937', 'donor: A', 'donor: B', 'donor: C', 'donor: D', 'donor: U87-MG'], 3: ['replicate: 1', 'replicate: 2', 'replicate: 3'], 4: ['resistance to hiv-1 following ifn treatment: permissive', 'resistance to hiv-1 following ifn treatment: untreated', 'resistance to hiv-1 following ifn treatment: partially resistant', 'resistance to hiv-1 following ifn treatment: resistant']}\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": "541fa371", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "268be6bc", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:44:23.421697Z", "iopub.status.busy": "2025-03-25T05:44:23.421583Z", "iopub.status.idle": "2025-03-25T05:44:23.428479Z", "shell.execute_reply": "2025-03-25T05:44:23.428120Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "No clinical data file found. Creating minimal DataFrame for trait information only.\n", "Warning: Using placeholder clinical data. Real analysis requires actual sample data.\n", "Error during clinical feature extraction: Length mismatch: Expected axis has 0 elements, new values have 1 elements\n", "Skipping clinical feature extraction due to data structure issues.\n", "Note: This cohort has trait information but couldn't be processed in standard format.\n" ] } ], "source": [ "# 1. Gene Expression Data Availability\n", "# Based on the background information, this dataset contains gene expression data for interferon-stimulated genes\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "# For HIV_Resistance: identified in key 4 \"resistance to hiv-1 following ifn treatment\"\n", "trait_row = 4\n", "\n", "# Age is not available in the sample characteristics\n", "age_row = None\n", "\n", "# Gender is not available in the sample characteristics\n", "gender_row = None\n", "\n", "# 2.2 Data Type Conversion\n", "def convert_trait(value):\n", " \"\"\"\n", " Convert HIV resistance trait to binary:\n", " 1 = resistant\n", " 0 = not resistant (permissive or partially resistant)\n", " None = untreated or unknown\n", " \"\"\"\n", " if value is None:\n", " return None\n", " \n", " if isinstance(value, str) and \":\" in value:\n", " value = value.split(\":\", 1)[1].strip().lower()\n", " \n", " if value == \"resistant\":\n", " return 1\n", " elif value in [\"permissive\", \"partially resistant\"]:\n", " return 0\n", " elif value == \"untreated\":\n", " return None\n", " else:\n", " return None\n", "\n", "# Since age and gender data are not available, define basic converter functions\n", "def convert_age(value):\n", " return None\n", "\n", "def convert_gender(value):\n", " return None\n", "\n", "# 3. Save Metadata\n", "# Conduct initial filtering on the usability of the dataset\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 not None, we need to extract clinical features\n", "if trait_row is not None:\n", " try:\n", " # Try loading from standard location first\n", " clinical_data = pd.read_csv(os.path.join(in_cohort_dir, \"clinical_data.csv\"), index_col=0)\n", " except FileNotFoundError:\n", " # If not found, try to find or construct the data from available sources\n", " # Get all files in the cohort directory\n", " files = os.listdir(in_cohort_dir)\n", " \n", " # Look for any files that might contain clinical information\n", " clinical_files = [f for f in files if \"characteristic\" in f.lower() or \"clinical\" in f.lower() or \"phenotype\" in f.lower()]\n", " \n", " if clinical_files:\n", " # Try to load the first matching file\n", " clinical_data = pd.read_csv(os.path.join(in_cohort_dir, clinical_files[0]), index_col=0)\n", " else:\n", " # If no suitable file is found, create a placeholder DataFrame\n", " # with the structure expected by geo_select_clinical_features\n", " # This should have one column per sample and rows for each characteristic\n", " print(\"No clinical data file found. Creating minimal DataFrame for trait information only.\")\n", " \n", " # Create a simple DataFrame with just the trait information\n", " # Minimal structure with trait row and sample columns\n", " sample_data = {\n", " \"sample1\": \"resistance to hiv-1 following ifn treatment: resistant\",\n", " \"sample2\": \"resistance to hiv-1 following ifn treatment: permissive\",\n", " \"sample3\": \"resistance to hiv-1 following ifn treatment: partially resistant\",\n", " \"sample4\": \"resistance to hiv-1 following ifn treatment: untreated\"\n", " }\n", " clinical_data = pd.DataFrame({\n", " trait_row: [sample_data[s] for s in sample_data]\n", " }, index=sample_data.keys())\n", " \n", " # We're only creating a placeholder to demonstrate the structure\n", " print(\"Warning: Using placeholder clinical data. Real analysis requires actual sample data.\")\n", " \n", " try:\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 clinical features\n", " print(\"Preview of selected clinical features:\")\n", " print(preview_df(selected_clinical_df))\n", " \n", " # Save the clinical data\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " selected_clinical_df.to_csv(out_clinical_data_file)\n", " print(f\"Clinical data saved to {out_clinical_data_file}\")\n", " except Exception as e:\n", " print(f\"Error during clinical feature extraction: {str(e)}\")\n", " print(\"Skipping clinical feature extraction due to data structure issues.\")\n", " print(\"Note: This cohort has trait information but couldn't be processed in standard format.\")\n" ] }, { "cell_type": "markdown", "id": "27838c3a", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "bc48ce7a", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:44:23.429584Z", "iopub.status.busy": "2025-03-25T05:44:23.429474Z", "iopub.status.idle": "2025-03-25T05:44:23.625264Z", "shell.execute_reply": "2025-03-25T05:44:23.624731Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Found data marker at line 69\n", "Header line: \"ID_REF\"\t\"GSM1133032\"\t\"GSM1133033\"\t\"GSM1133034\"\t\"GSM1133035\"\t\"GSM1133036\"\t\"GSM1133037\"\t\"GSM1133038\"\t\"GSM1133039\"\t\"GSM1133040\"\t\"GSM1133041\"\t\"GSM1133042\"\t\"GSM1133043\"\t\"GSM1133044\"\t\"GSM1133045\"\t\"GSM1133046\"\t\"GSM1133047\"\t\"GSM1133048\"\t\"GSM1133049\"\t\"GSM1133050\"\t\"GSM1133051\"\t\"GSM1133052\"\t\"GSM1133053\"\t\"GSM1133054\"\t\"GSM1133055\"\t\"GSM1133056\"\t\"GSM1133057\"\t\"GSM1133058\"\t\"GSM1133059\"\t\"GSM1133060\"\t\"GSM1133061\"\t\"GSM1133062\"\t\"GSM1133063\"\t\"GSM1133064\"\t\"GSM1133065\"\t\"GSM1133066\"\t\"GSM1133067\"\t\"GSM1133068\"\t\"GSM1133069\"\t\"GSM1133070\"\t\"GSM1133071\"\t\"GSM1133072\"\t\"GSM1133073\"\t\"GSM1133074\"\t\"GSM1133075\"\t\"GSM1133076\"\t\"GSM1133077\"\t\"GSM1133078\"\t\"GSM1133079\"\n", "First data line: \"ILMN_1343291\"\t15.19802012\t15.11333259\t15.20127512\t15.1206348\t15.20127512\t15.21882761\t15.22919968\t15.12717254\t15.19802012\t15.21882761\t15.04530416\t15.20127512\t15.0085115\t15.18504016\t15.04367475\t15.26469393\t15.1436849\t15.15197724\t15.23978664\t15.11794106\t15.04875307\t15.33007355\t15.01588861\t14.96164359\t15.17472608\t15.34340311\t15.21505253\t15.30269515\t15.12717254\t15.16542976\t15.12717254\t15.20127512\t15.13718939\t15.23978664\t15.2256302\t15.12553169\t15.16112168\t14.96642919\t15.20588675\t15.13007484\t15.25052604\t15.35782563\t15.21882761\t15.16331926\t14.97473574\t15.19035669\t15.11129152\t15.13007484\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Index(['ILMN_1343291', 'ILMN_1343295', 'ILMN_1651209', 'ILMN_1651228',\n", " 'ILMN_1651229', 'ILMN_1651230', 'ILMN_1651232', 'ILMN_1651236',\n", " 'ILMN_1651238', 'ILMN_1651253', 'ILMN_1651254', 'ILMN_1651259',\n", " 'ILMN_1651260', 'ILMN_1651262', 'ILMN_1651268', 'ILMN_1651278',\n", " 'ILMN_1651281', 'ILMN_1651282', 'ILMN_1651285', 'ILMN_1651286'],\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": "50934e15", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "bf8f65b4", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:44:23.626767Z", "iopub.status.busy": "2025-03-25T05:44:23.626638Z", "iopub.status.idle": "2025-03-25T05:44:23.628834Z", "shell.execute_reply": "2025-03-25T05:44:23.628452Z" } }, "outputs": [], "source": [ "# Analyzing the gene identifiers from the previous step output\n", "\n", "# The identifiers starting with \"ILMN_\" indicate Illumina probe IDs, not human gene symbols\n", "# These are microarray probe identifiers from Illumina platform that need to be mapped to gene symbols\n", "# For example, ILMN_1343291 is an Illumina probe ID, not a standard human gene symbol\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "92314683", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "1c17a2e1", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:44:23.630274Z", "iopub.status.busy": "2025-03-25T05:44:23.630163Z", "iopub.status.idle": "2025-03-25T05:44:24.534772Z", "shell.execute_reply": "2025-03-25T05:44:24.534240Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Examining SOFT file structure:\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "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 = GSE46599\n", "Line 6: !Series_title = Genome-wide analysis of interferon-stimulated genes in primary cells and immortalized cell lines\n", "Line 7: !Series_geo_accession = GSE46599\n", "Line 8: !Series_status = Public on Sep 13 2013\n", "Line 9: !Series_submission_date = May 02 2013\n", "Line 10: !Series_last_update_date = Dec 01 2022\n", "Line 11: !Series_pubmed_id = 24048477\n", "Line 12: !Series_pubmed_id = 36161446\n", "Line 13: !Series_summary = Analysis of interferon-stimulated genes (ISGs) in various primary cells and immortalized cell lines, following type 1 interferon (IFN) treatment. Some cell types become resistant to HIV-1 infection following type 1 interferon treatment (such as macrophages, THP-1, PMA-THP-1, U87-MG cells and to a lesser extent, primary CD4+ T cells) while others either become only partially resistant (e.g., HT1080, PMA-U937) or remain permissive (e.g., CEM, CEM-SS, Jurkat T cell lines and U937); for more information see (Goujon and Malim, Journal of Virology 2010) and (Goujon and Schaller et al., Retrovirology 2013). We hypothesized that the anti-HIV-1 ISGs are differentially induced and expressed in restrictive cells compared to permissive cells and performed a whole genome analysis following type 1 IFN treatment in cell types exhibiting different HIV-1 resistance phenotypes.\n", "Line 14: !Series_overall_design = 48 samples; design: 9 cell lines, primary CD4+ T cells and primary macrophages, untreated and IFN-treated; 2 replicate experiments per cell line; 3 replicate experiments per primary cell type\n", "Line 15: !Series_type = Expression profiling by array\n", "Line 16: !Series_contributor = Caroline,,Goujon\n", "Line 17: !Series_contributor = Reiner,,Schulz\n", "Line 18: !Series_contributor = Muddassar,,Mirza\n", "Line 19: !Series_contributor = Michael,H,Malim\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": "dda55456", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "6f8c17fc", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:44:24.536249Z", "iopub.status.busy": "2025-03-25T05:44:24.536119Z", "iopub.status.idle": "2025-03-25T05:44:25.238257Z", "shell.execute_reply": "2025-03-25T05:44:25.237709Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Number of mappable probes: 44837\n", "Preview of 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 data shape: (19428, 48)\n", "Preview of gene expression data:\n", " GSM1133032 GSM1133033 GSM1133034 GSM1133035 GSM1133036 GSM1133037 \\\n", "Gene \n", "A1BG 5.662013 5.323517 6.473583 5.874020 5.736427 5.818472 \n", "A1CF 16.273260 17.492853 15.699672 15.778524 15.830556 15.665282 \n", "A26C3 16.724024 15.905628 16.344077 16.558834 15.962810 16.514401 \n", "A2BP1 20.912821 20.809613 21.722912 21.300184 20.866304 21.050868 \n", "A2LD1 8.259530 8.040645 8.182764 7.862223 8.172796 7.544583 \n", "\n", " GSM1133038 GSM1133039 GSM1133040 GSM1133041 ... GSM1133070 \\\n", "Gene ... \n", "A1BG 5.902604 5.989310 5.487193 5.567038 ... 5.471597 \n", "A1CF 16.896836 16.012218 16.666459 15.863367 ... 15.828178 \n", "A26C3 16.859979 16.552442 17.460900 16.886041 ... 16.370953 \n", "A2BP1 21.208208 20.968385 20.689202 21.703173 ... 21.800751 \n", "A2LD1 7.522025 7.002201 7.982514 7.873129 ... 10.886817 \n", "\n", " GSM1133071 GSM1133072 GSM1133073 GSM1133074 GSM1133075 GSM1133076 \\\n", "Gene \n", "A1BG 5.477688 5.503762 6.004427 5.227777 5.116045 5.150343 \n", "A1CF 17.093878 16.644442 16.435789 17.057774 16.987197 15.814903 \n", "A26C3 16.886450 16.590772 16.337387 16.386970 16.704457 16.520139 \n", "A2BP1 20.243312 20.807097 21.586094 20.612806 20.877664 21.241529 \n", "A2LD1 10.788143 5.100891 5.476115 5.158076 5.441909 9.043675 \n", "\n", " GSM1133077 GSM1133078 GSM1133079 \n", "Gene \n", "A1BG 5.192986 5.235030 5.125745 \n", "A1CF 16.036059 15.977838 16.982119 \n", "A26C3 16.881729 16.236574 16.991791 \n", "A2BP1 20.577717 20.577334 20.771981 \n", "A2LD1 7.815352 9.055605 8.122923 \n", "\n", "[5 rows x 48 columns]\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene expression data saved to ../../output/preprocess/HIV_Resistance/gene_data/GSE46599.csv\n" ] } ], "source": [ "# Step 1: Identify which columns in gene annotation contain probe IDs and gene symbols\n", "# From the preview, we can see:\n", "# - \"ID\" column contains Illumina probe IDs like \"ILMN_1343048\"\n", "# - \"Symbol\" column contains gene symbols like \"phage_lambda_genome\", \"thrB\"\n", "\n", "# Step 2: Extract mapping between probe IDs and gene symbols\n", "# Create a mapping dataframe with only the relevant columns\n", "mapping_df = gene_annotation[['ID', 'Symbol']].copy()\n", "mapping_df = mapping_df.dropna(subset=['Symbol']) # Remove rows without 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\"Number of mappable probes: {len(mapping_df)}\")\n", "print(\"Preview of mapping dataframe:\")\n", "print(mapping_df.head())\n", "\n", "# Step 3: Apply gene mapping to convert probe-level data to gene expression data\n", "try:\n", " gene_data = apply_gene_mapping(gene_data, mapping_df)\n", " \n", " # Check the result\n", " print(f\"Resulting gene expression data shape: {gene_data.shape}\")\n", " print(\"Preview of gene expression data:\")\n", " print(gene_data.head())\n", " \n", " # Save the gene expression data\n", " os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n", " gene_data.to_csv(out_gene_data_file)\n", " print(f\"Gene expression data saved to {out_gene_data_file}\")\n", "except Exception as e:\n", " print(f\"Error during gene mapping: {str(e)}\")\n", " print(\"Gene mapping failed. Check the structure of your mapping dataframe and gene expression data.\")\n" ] }, { "cell_type": "markdown", "id": "c8d55baa", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "7abf16b3", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:44:25.239873Z", "iopub.status.busy": "2025-03-25T05:44:25.239741Z", "iopub.status.idle": "2025-03-25T05:44:32.946327Z", "shell.execute_reply": "2025-03-25T05:44:32.945652Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene data shape after normalization: (18626, 48)\n", "Sample gene symbols after normalization: ['A1BG', 'A1BG-AS1', 'A1CF', 'A2M', 'A3GALT2', 'A4GALT', 'A4GNT', 'AAA1', 'AAAS', 'AACS']\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene data saved to ../../output/preprocess/HIV_Resistance/gene_data/GSE46599.csv\n", "Selected clinical features:\n", " GSM1133032 GSM1133033 GSM1133034 GSM1133035 GSM1133036 \\\n", "HIV_Resistance 0.0 0.0 NaN NaN 0.0 \n", "\n", " GSM1133037 GSM1133038 GSM1133039 GSM1133040 GSM1133041 \\\n", "HIV_Resistance 0.0 NaN NaN 0.0 0.0 \n", "\n", " ... GSM1133070 GSM1133071 GSM1133072 GSM1133073 \\\n", "HIV_Resistance ... NaN NaN 1.0 1.0 \n", "\n", " GSM1133074 GSM1133075 GSM1133076 GSM1133077 GSM1133078 \\\n", "HIV_Resistance NaN NaN 0.0 0.0 NaN \n", "\n", " GSM1133079 \n", "HIV_Resistance NaN \n", "\n", "[1 rows x 48 columns]\n", "Clinical data saved to ../../output/preprocess/HIV_Resistance/clinical_data/GSE46599.csv\n", "Linked data shape: (48, 18627)\n", "Linked data columns preview:\n", "['HIV_Resistance', 'A1BG', 'A1BG-AS1', 'A1CF', 'A2M', 'A3GALT2', 'A4GALT', 'A4GNT', 'AAA1', 'AAAS']\n", "\n", "Missing values before handling:\n", " Trait (HIV_Resistance) missing: 24 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: (24, 18627)\n", "For the feature 'HIV_Resistance', the least common label is '0.0' with 12 occurrences. This represents 50.00% of the dataset.\n", "The distribution of the feature 'HIV_Resistance' in this dataset is fine.\n", "\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Linked data saved to ../../output/preprocess/HIV_Resistance/GSE46599.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. Since we didn't successfully save clinical data in previous steps, let's extract it again\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "background_info, clinical_df = get_background_and_clinical_data(matrix_file)\n", "\n", "# Define conversion functions based on Step 2's correct implementation\n", "def convert_trait(value):\n", " \"\"\"\n", " Convert HIV resistance trait to binary:\n", " 1 = resistant\n", " 0 = not resistant (permissive or partially resistant)\n", " None = untreated or unknown\n", " \"\"\"\n", " if value is None:\n", " return None\n", " \n", " if isinstance(value, str) and \":\" in value:\n", " value = value.split(\":\", 1)[1].strip().lower()\n", " \n", " if value == \"resistant\":\n", " return 1\n", " elif value in [\"permissive\", \"partially resistant\"]:\n", " return 0\n", " elif value == \"untreated\":\n", " return None\n", " else:\n", " return None\n", "\n", "def convert_age(value):\n", " return None\n", "\n", "def convert_gender(value):\n", " return None\n", "\n", "# Extract clinical features with the correct row indices from Step 2\n", "trait_row = 4 # Correct row for HIV resistance from Step 2\n", "age_row = None # From Step 2\n", "gender_row = None # From Step 2\n", "\n", "# Extract clinical features\n", "try:\n", " selected_clinical_df = geo_select_clinical_features(\n", " clinical_df=clinical_df,\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(\"Selected clinical features:\")\n", " print(selected_clinical_df)\n", "\n", " # Save clinical data for future reference\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " selected_clinical_df.to_csv(out_clinical_data_file)\n", " print(f\"Clinical data saved to {out_clinical_data_file}\")\n", "\n", " # 3. Link clinical and genetic data\n", " linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)\n", " print(f\"Linked data shape: {linked_data.shape}\")\n", " print(\"Linked data columns preview:\")\n", " print(list(linked_data.columns[:10])) # Show first 10 column names\n", "\n", " # Check if we have any valid trait values before proceeding\n", " if linked_data[trait].notna().sum() == 0:\n", " print(\"Warning: No valid trait values found in the linked data.\")\n", " print(\"This may indicate an issue with the trait extraction or mapping.\")\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=False, # No usable trait data\n", " is_biased=True, # Mark as biased as we have no trait data\n", " df=linked_data,\n", " note=\"No valid trait values were found in the clinical data after extraction.\"\n", " )\n", " print(\"Data was determined to be unusable due to missing trait values and was not saved\")\n", " else:\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", " # Only proceed with further evaluation if we have data left\n", " if len(cleaned_data) > 0:\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 HIV resistance 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\")\n", " else:\n", " print(\"After handling missing values, no samples remained. Data is unusable.\")\n", " is_gene_available = len(normalized_gene_data) > 0\n", " 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=True, # Mark as biased since no samples survived processing\n", " df=pd.DataFrame(), # Empty dataframe\n", " note=\"No samples remained after handling missing values.\"\n", " )\n", "except Exception as e:\n", " print(f\"Error during processing: {str(e)}\")\n", " # Record failure information\n", " validate_and_save_cohort_info(\n", " is_final=True, \n", " cohort=cohort, \n", " info_path=json_path, \n", " is_gene_available=len(normalized_gene_data) > 0, \n", " is_trait_available=False,\n", " is_biased=True,\n", " df=pd.DataFrame(), # Empty dataframe\n", " note=f\"Processing failed with error: {str(e)}\"\n", " )\n", " print(\"Data processing failed 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 }