{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "9f9503cd", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:08:07.521242Z", "iopub.status.busy": "2025-03-25T04:08:07.521066Z", "iopub.status.idle": "2025-03-25T04:08:07.686331Z", "shell.execute_reply": "2025-03-25T04:08:07.685857Z" } }, "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 = \"GSE94399\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Substance_Use_Disorder\"\n", "in_cohort_dir = \"../../input/GEO/Substance_Use_Disorder/GSE94399\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Substance_Use_Disorder/GSE94399.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Substance_Use_Disorder/gene_data/GSE94399.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Substance_Use_Disorder/clinical_data/GSE94399.csv\"\n", "json_path = \"../../output/preprocess/Substance_Use_Disorder/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "3b547a80", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "7f4e2dfe", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:08:07.687888Z", "iopub.status.busy": "2025-03-25T04:08:07.687742Z", "iopub.status.idle": "2025-03-25T04:08:07.827725Z", "shell.execute_reply": "2025-03-25T04:08:07.827265Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Transcriptome profiles of liver biopsy tissues from sever alcoholic hepatitis patients (validation cohort, Brussels)\"\n", "!Series_summary\t\"Corticosteroids are the current standard of care to improve short_term mortality in severe alcoholic hepatitis (AH), although nearly 40% of the patients do not respond and accurate pre_treatment predictors are lacking. We developed 123_gene prognostic score based on molecular and clinical variables before initiation of corticosteroids. Furthermore, The gene signature was implemented in an FDA_approved platform (NanoString), and verified for technical validity and prognostic capability. Here we demonstrated that a Nanostring_based gene expressoin risk classificatoin is useful to predict mortality in patients with severe alcoholic hepatitis who were treated by corticosteroid\"\n", "!Series_overall_design\t\"Gene expression profiling of formalin-fixed paraffin-embedded liver biopsy tissues obtained at the time of enrollment.\"\n", "Sample Characteristics Dictionary:\n", "{0: ['cohort: Validation cohort (BRAH)'], 1: ['outcome at 6 months: Alive', 'outcome at 6 months: Dead or liver transplantation']}\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": "792f9dbc", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "4eca19b5", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:08:07.829157Z", "iopub.status.busy": "2025-03-25T04:08:07.829041Z", "iopub.status.idle": "2025-03-25T04:08:07.837152Z", "shell.execute_reply": "2025-03-25T04:08:07.836780Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Preview of selected clinical features:\n", "{0: [nan], 1: [1.0]}\n", "Clinical data saved to ../../output/preprocess/Substance_Use_Disorder/clinical_data/GSE94399.csv\n" ] } ], "source": [ "# 1. Gene Expression Data Availability\n", "# Based on the background information, this dataset contains gene expression data\n", "# specifically from liver biopsy tissues as mentioned in \"Series_overall_design\"\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Looking at the Sample Characteristics Dictionary\n", "# For trait (Substance Use Disorder): The dictionary shows outcome in row 1,\n", "# which relates to alcoholic hepatitis (a substance use disorder from background info)\n", "# For age and gender: Not explicitly available in the sample characteristics\n", "\n", "# Trait is available in row 1 (outcome at 6 months)\n", "trait_row = 1\n", "# Age and gender are not available in the sample characteristics\n", "age_row = None\n", "gender_row = None\n", "\n", "# 2.2 Data Type Conversion Functions\n", "def convert_trait(value):\n", " \"\"\"Convert outcome data to binary trait value for Substance Use Disorder\"\"\"\n", " if value is None or not isinstance(value, str):\n", " return None\n", " \n", " # Extract the value after colon if present\n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " # Convert to binary: 1 for negative outcome (dead/transplant), 0 for alive\n", " if \"alive\" in value.lower():\n", " return 0\n", " elif \"dead\" in value.lower() or \"transplantation\" in value.lower():\n", " return 1\n", " else:\n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age data to continuous values\"\"\"\n", " # Not used as age is not available\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"Convert gender data to binary values (0 for female, 1 for male)\"\"\"\n", " # Not used as gender is not available\n", " return None\n", "\n", "# 3. Save Metadata\n", "# Determine trait data availability and conduct initial filtering\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 (Only if trait_row is not None)\n", "if trait_row is not None:\n", " # Create a DataFrame from the sample characteristics dictionary\n", " # The dictionary from the previous output has keys as rows and values as lists of characteristics\n", " sample_chars = {\n", " 0: ['cohort: Validation cohort (BRAH)'], \n", " 1: ['outcome at 6 months: Alive', 'outcome at 6 months: Dead or liver transplantation']\n", " }\n", " \n", " # Build a matrix-like structure that mimics the expected clinical data format\n", " # First determine all sample IDs based on the data available in row 1\n", " sample_ids = []\n", " for i in range(len(sample_chars[1])):\n", " sample_ids.append(f\"GSM{i+1}\")\n", " \n", " # Create a dictionary to build our DataFrame\n", " data_dict = {'Sample': sample_ids}\n", " \n", " # Add the characteristic values for each row\n", " for row, values in sample_chars.items():\n", " # Check if there's one value per sample or just one value for all samples\n", " if len(values) == len(sample_ids):\n", " # One value per sample\n", " data_dict[row] = values\n", " else:\n", " # Repeat the same value for all samples or handle differently if needed\n", " # For simplicity, we'll just use the first value for all samples if there's a mismatch\n", " data_dict[row] = [values[0]] * len(sample_ids)\n", " \n", " # Create DataFrame\n", " clinical_data = pd.DataFrame(data_dict)\n", " clinical_data.set_index('Sample', inplace=True)\n", " \n", " # Use geo_select_clinical_features to extract 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 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)\n", " print(f\"Clinical data saved to {out_clinical_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "5ccb0606", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "8c680a62", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:08:07.838128Z", "iopub.status.busy": "2025-03-25T04:08:07.837996Z", "iopub.status.idle": "2025-03-25T04:08:08.063106Z", "shell.execute_reply": "2025-03-25T04:08:08.062629Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Found data marker at line 58\n", "Header line: \"ID_REF\"\t\"GSM2474751\"\t\"GSM2474752\"\t\"GSM2474753\"\t\"GSM2474754\"\t\"GSM2474755\"\t\"GSM2474756\"\t\"GSM2474757\"\t\"GSM2474758\"\t\"GSM2474759\"\t\"GSM2474760\"\t\"GSM2474761\"\t\"GSM2474762\"\t\"GSM2474763\"\t\"GSM2474764\"\t\"GSM2474765\"\t\"GSM2474766\"\t\"GSM2474767\"\t\"GSM2474768\"\t\"GSM2474769\"\t\"GSM2474770\"\t\"GSM2474771\"\t\"GSM2474772\"\t\"GSM2474773\"\t\"GSM2474774\"\t\"GSM2474775\"\t\"GSM2474776\"\t\"GSM2474777\"\t\"GSM2474778\"\t\"GSM2474779\"\t\"GSM2474780\"\t\"GSM2474781\"\t\"GSM2474782\"\t\"GSM2474783\"\t\"GSM2474784\"\t\"GSM2474785\"\t\"GSM2474786\"\t\"GSM2474787\"\t\"GSM2474788\"\n", "First data line: \"11715100_at\"\t14.61709571\t13.42065958\t19.6573113\t22.48539724\t52.65458339\t29.87886953\t15.64211321\t21.14364386\t37.30879312\t14.78742501\t17.08143895\t16.14591018\t13.26892829\t12.68560441\t13.18877976\t13.66343127\t15.88047304\t14.94092906\t11.28935481\t12.45280671\t10.92842639\t9.324238654\t18.42329466\t5.363407605\t18.08406026\t41.03262025\t30.92712002\t20.42521934\t16.11238155\t11.77488985\t15.73874147\t11.7609501\t15.12186329\t28.66298794\t12.07415117\t13.50058946\t8.107258143\t26.49587054\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Index(['11715100_at', '11715101_s_at', '11715102_x_at', '11715103_x_at',\n", " '11715104_s_at', '11715105_at', '11715106_x_at', '11715107_s_at',\n", " '11715108_x_at', '11715109_at', '11715110_at', '11715111_s_at',\n", " '11715112_at', '11715113_x_at', '11715114_x_at', '11715115_s_at',\n", " '11715116_s_at', '11715117_x_at', '11715118_s_at', '11715119_s_at'],\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": "89e128b1", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "d0ef15fa", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:08:08.064378Z", "iopub.status.busy": "2025-03-25T04:08:08.064261Z", "iopub.status.idle": "2025-03-25T04:08:08.066381Z", "shell.execute_reply": "2025-03-25T04:08:08.066013Z" } }, "outputs": [], "source": [ "# Analyzing gene identifiers\n", "# The IDs are in the format \"11715100_at\", which appears to be Affymetrix probe IDs \n", "# from an Affymetrix microarray chip rather than standard human gene symbols\n", "# These probe IDs need to be mapped to gene symbols\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "7c51821d", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "290f2b4a", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:08:08.067581Z", "iopub.status.busy": "2025-03-25T04:08:08.067480Z", "iopub.status.idle": "2025-03-25T04:08:09.791467Z", "shell.execute_reply": "2025-03-25T04:08:09.790919Z" } }, "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 = GSE94399\n", "Line 6: !Series_title = Transcriptome profiles of liver biopsy tissues from sever alcoholic hepatitis patients (validation cohort, Brussels)\n", "Line 7: !Series_geo_accession = GSE94399\n", "Line 8: !Series_status = Public on Feb 18 2018\n", "Line 9: !Series_submission_date = Feb 01 2017\n", "Line 10: !Series_last_update_date = Mar 21 2019\n", "Line 11: !Series_pubmed_id = 29158192\n", "Line 12: !Series_summary = Corticosteroids are the current standard of care to improve short_term mortality in severe alcoholic hepatitis (AH), although nearly 40% of the patients do not respond and accurate pre_treatment predictors are lacking. We developed 123_gene prognostic score based on molecular and clinical variables before initiation of corticosteroids. Furthermore, The gene signature was implemented in an FDA_approved platform (NanoString), and verified for technical validity and prognostic capability. Here we demonstrated that a Nanostring_based gene expressoin risk classificatoin is useful to predict mortality in patients with severe alcoholic hepatitis who were treated by corticosteroid\n", "Line 13: !Series_overall_design = Gene expression profiling of formalin-fixed paraffin-embedded liver biopsy tissues obtained at the time of enrollment.\n", "Line 14: !Series_type = Expression profiling by array\n", "Line 15: !Series_contributor = Eric,,Trépo\n", "Line 16: !Series_contributor = Nicolas,,Goossens\n", "Line 17: !Series_contributor = Naoto,,Fujiwara\n", "Line 18: !Series_contributor = Yujin,,Hoshida\n", "Line 19: !Series_contributor = Denis,,Franchimont\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Gene annotation preview:\n", "{'ID': ['11715100_at', '11715101_s_at', '11715102_x_at', '11715103_x_at', '11715104_s_at'], 'GeneChip Array': ['Human Genome HG-U219 Array', 'Human Genome HG-U219 Array', 'Human Genome HG-U219 Array', 'Human Genome HG-U219 Array', 'Human Genome HG-U219 Array'], 'Species Scientific Name': ['Homo sapiens', 'Homo sapiens', 'Homo sapiens', 'Homo sapiens', 'Homo sapiens'], 'Annotation Date': ['20-Aug-10', '20-Aug-10', '20-Aug-10', '20-Aug-10', '20-Aug-10'], 'Sequence Type': ['Consensus sequence', 'Consensus sequence', 'Consensus sequence', 'Consensus sequence', 'Consensus sequence'], 'Sequence Source': ['Affymetrix Proprietary Database', 'Affymetrix Proprietary Database', 'Affymetrix Proprietary Database', 'Affymetrix Proprietary Database', 'Affymetrix Proprietary Database'], 'Transcript ID(Array Design)': ['g21264570', 'g21264570', 'g21264570', 'g22748780', 'g30039713'], 'Target Description': ['g21264570 /TID=g21264570 /CNT=1 /FEA=FLmRNA /TIER=FL /STK=0 /DEF=g21264570 /REP_ORG=Homo sapiens', 'g21264570 /TID=g21264570 /CNT=1 /FEA=FLmRNA /TIER=FL /STK=0 /DEF=g21264570 /REP_ORG=Homo sapiens', 'g21264570 /TID=g21264570 /CNT=1 /FEA=FLmRNA /TIER=FL /STK=0 /DEF=g21264570 /REP_ORG=Homo sapiens', 'g22748780 /TID=g22748780 /CNT=1 /FEA=FLmRNA /TIER=FL /STK=0 /DEF=g22748780 /REP_ORG=Homo sapiens', 'g30039713 /TID=g30039713 /CNT=1 /FEA=FLmRNA /TIER=FL /STK=0 /DEF=g30039713 /REP_ORG=Homo sapiens'], 'Representative Public ID': ['g21264570', 'g21264570', 'g21264570', 'g22748780', 'g30039713'], 'Archival UniGene Cluster': ['---', '---', '---', '---', '---'], 'UniGene ID': ['Hs.247813', 'Hs.247813', 'Hs.247813', 'Hs.465643', 'Hs.352515'], 'Genome Version': ['February 2009 (Genome Reference Consortium GRCh37)', 'February 2009 (Genome Reference Consortium GRCh37)', 'February 2009 (Genome Reference Consortium GRCh37)', 'February 2009 (Genome Reference Consortium GRCh37)', 'February 2009 (Genome Reference Consortium GRCh37)'], 'Alignments': ['chr6:26271145-26271612 (-) // 100.0 // p22.2', 'chr6:26271145-26271612 (-) // 100.0 // p22.2', 'chr6:26271145-26271612 (-) // 100.0 // p22.2', 'chr19:4639529-5145579 (+) // 48.53 // p13.3', 'chr17:72920369-72929640 (+) // 100.0 // q25.1'], 'Gene Title': ['histone cluster 1, H3g', 'histone cluster 1, H3g', 'histone cluster 1, H3g', 'tumor necrosis factor, alpha-induced protein 8-like 1', 'otopetrin 2'], 'Gene Symbol': ['HIST1H3G', 'HIST1H3G', 'HIST1H3G', 'TNFAIP8L1', 'OTOP2'], 'Chromosomal Location': ['chr6p21.3', 'chr6p21.3', 'chr6p21.3', 'chr19p13.3', 'chr17q25.1'], 'GB_LIST': ['NM_003534', 'NM_003534', 'NM_003534', 'NM_001167942,NM_152362', 'NM_178160'], 'SPOT_ID': [nan, nan, nan, nan, nan], 'Unigene Cluster Type': ['full length', 'full length', 'full length', 'full length', 'full length'], 'Ensembl': ['---', 'ENSG00000178458', '---', 'ENSG00000185361', 'ENSG00000183034'], 'Entrez Gene': ['8355', '8355', '8355', '126282', '92736'], 'SwissProt': ['P68431', 'P68431', 'P68431', 'Q8WVP5', 'Q7RTS6'], 'EC': ['---', '---', '---', '---', '---'], 'OMIM': ['602815', '602815', '602815', '---', '607827'], 'RefSeq Protein ID': ['NP_003525', 'NP_003525', 'NP_003525', 'NP_001161414 /// NP_689575', 'NP_835454'], 'RefSeq Transcript ID': ['NM_003534', 'NM_003534', 'NM_003534', 'NM_001167942 /// NM_152362', 'NM_178160'], 'FlyBase': ['---', '---', '---', '---', '---'], 'AGI': ['---', '---', '---', '---', '---'], 'WormBase': ['---', '---', '---', '---', '---'], 'MGI Name': ['---', '---', '---', '---', '---'], 'RGD Name': ['---', '---', '---', '---', '---'], 'SGD accession number': ['---', '---', '---', '---', '---'], 'Gene Ontology Biological Process': ['0006334 // nucleosome assembly // inferred from electronic annotation', '0006334 // nucleosome assembly // inferred from electronic annotation', '0006334 // nucleosome assembly // inferred from electronic annotation', '---', '---'], 'Gene Ontology Cellular Component': ['0000786 // nucleosome // inferred from electronic annotation /// 0005634 // nucleus // inferred from electronic annotation /// 0005694 // chromosome // inferred from electronic annotation', '0000786 // nucleosome // inferred from electronic annotation /// 0005634 // nucleus // inferred from electronic annotation /// 0005694 // chromosome // inferred from electronic annotation', '0000786 // nucleosome // inferred from electronic annotation /// 0005634 // nucleus // inferred from electronic annotation /// 0005694 // chromosome // inferred from electronic annotation', '---', '0016020 // membrane // inferred from electronic annotation /// 0016021 // integral to membrane // inferred from electronic annotation'], 'Gene Ontology Molecular Function': ['0003677 // DNA binding // inferred from electronic annotation /// 0005515 // protein binding // inferred from physical interaction', '0003677 // DNA binding // inferred from electronic annotation /// 0005515 // protein binding // inferred from physical interaction', '0003677 // DNA binding // inferred from electronic annotation /// 0005515 // protein binding // inferred from physical interaction', '---', '---'], 'Pathway': ['---', '---', '---', '---', '---'], 'InterPro': ['---', '---', '---', '---', 'IPR004878 // Protein of unknown function DUF270 // 1.0E-6 /// IPR004878 // Protein of unknown function DUF270 // 1.0E-13'], 'Trans Membrane': ['---', '---', '---', '---', 'NP_835454.1 // span:30-52,62-81,101-120,135-157,240-262,288-310,327-349,369-391,496-515,525-547 // numtm:10'], 'QTL': ['---', '---', '---', '---', '---'], 'Annotation Description': ['This probe set was annotated using the Matching Probes based pipeline to a Entrez Gene identifier using 1 transcripts. // false // Matching Probes // A', 'This probe set was annotated using the Matching Probes based pipeline to a Entrez Gene identifier using 2 transcripts. // false // Matching Probes // A', 'This probe set was annotated using the Matching Probes based pipeline to a Entrez Gene identifier using 1 transcripts. // false // Matching Probes // A', 'This probe set was annotated using the Matching Probes based pipeline to a Entrez Gene identifier using 5 transcripts. // false // Matching Probes // A', 'This probe set was annotated using the Matching Probes based pipeline to a Entrez Gene identifier using 3 transcripts. // false // Matching Probes // A'], 'Annotation Transcript Cluster': ['NM_003534(11)', 'BC079835(11),NM_003534(11)', 'NM_003534(11)', 'BC017672(11),BC044250(9),ENST00000327473(11),NM_001167942(11),NM_152362(11)', 'ENST00000331427(11),ENST00000426069(11),NM_178160(11)'], 'Transcript Assignments': ['NM_003534 // Homo sapiens histone cluster 1, H3g (HIST1H3G), mRNA. // refseq // 11 // ---', 'BC079835 // Homo sapiens histone cluster 1, H3g, mRNA (cDNA clone IMAGE:5935692). // gb_htc // 11 // --- /// ENST00000321285 // cdna:known chromosome:GRCh37:6:26271202:26271612:-1 gene:ENSG00000178458 // ensembl // 11 // --- /// GENSCAN00000044911 // cdna:Genscan chromosome:GRCh37:6:26271202:26271612:-1 // ensembl // 11 // --- /// NM_003534 // Homo sapiens histone cluster 1, H3g (HIST1H3G), mRNA. // refseq // 11 // ---', 'NM_003534 // Homo sapiens histone cluster 1, H3g (HIST1H3G), mRNA. // refseq // 11 // ---', 'BC017672 // Homo sapiens tumor necrosis factor, alpha-induced protein 8-like 1, mRNA (cDNA clone MGC:17791 IMAGE:3885999), complete cds. // gb // 11 // --- /// BC044250 // Homo sapiens tumor necrosis factor, alpha-induced protein 8-like 1, mRNA (cDNA clone IMAGE:5784807). // gb // 9 // --- /// ENST00000327473 // cdna:known chromosome:GRCh37:19:4639530:4653952:1 gene:ENSG00000185361 // ensembl // 11 // --- /// NM_001167942 // Homo sapiens tumor necrosis factor, alpha-induced protein 8-like 1 (TNFAIP8L1), transcript variant 1, mRNA. // refseq // 11 // --- /// NM_152362 // Homo sapiens tumor necrosis factor, alpha-induced protein 8-like 1 (TNFAIP8L1), transcript variant 2, mRNA. // refseq // 11 // ---', 'ENST00000331427 // cdna:known chromosome:GRCh37:17:72920370:72929640:1 gene:ENSG00000183034 // ensembl // 11 // --- /// ENST00000426069 // cdna:known chromosome:GRCh37:17:72920370:72929640:1 gene:ENSG00000183034 // ensembl // 11 // --- /// NM_178160 // Homo sapiens otopetrin 2 (OTOP2), mRNA. // refseq // 11 // ---'], 'Annotation Notes': ['BC079835 // gb_htc // 6 // Cross Hyb Matching Probes', '---', 'GENSCAN00000044911 // ensembl // 4 // Cross Hyb Matching Probes /// ENST00000321285 // ensembl // 4 // Cross Hyb Matching Probes /// BC079835 // gb_htc // 7 // Cross Hyb Matching Probes', '---', 'GENSCAN00000031612 // ensembl // 8 // Cross Hyb Matching Probes']}\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": "fcfc7021", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "5f9126ac", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:08:09.792926Z", "iopub.status.busy": "2025-03-25T04:08:09.792816Z", "iopub.status.idle": "2025-03-25T04:08:09.939981Z", "shell.execute_reply": "2025-03-25T04:08:09.939493Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene mapping preview (first 5 rows):\n", "{'ID': ['11715100_at', '11715101_s_at', '11715102_x_at', '11715103_x_at', '11715104_s_at'], 'Gene': ['HIST1H3G', 'HIST1H3G', 'HIST1H3G', 'TNFAIP8L1', 'OTOP2']}\n", "\n", "Gene expression data after mapping (first 5 rows, 3 columns):\n", " GSM2474751 GSM2474752 GSM2474753\n", "Gene \n", "A1BG 235.239452 166.162065 139.648057\n", "A1CF 357.729179 296.125841 233.119900\n", "A2BP1 29.494727 34.639537 44.718189\n", "A2LD1 4.900975 4.134265 4.364917\n", "A2M 570.793025 799.633007 616.235048\n", "\n", "Shape of gene expression data: (19521, 38)\n" ] } ], "source": [ "# Identify which columns in the gene annotation dataframe correspond to gene identifiers and gene symbols\n", "# From the previous output, we can see:\n", "# - The gene expression data uses IDs like \"11715100_at\"\n", "# - The gene annotation has an \"ID\" column with these probe IDs\n", "# - The \"Gene Symbol\" column contains the gene symbols we want to map to\n", "\n", "# 1. Extract the gene identifier and gene symbol columns for mapping\n", "prob_col = 'ID' # Column with probe IDs matching gene expression data\n", "gene_col = 'Gene Symbol' # Column with gene symbols\n", "\n", "# 2. Get the gene mapping dataframe\n", "gene_mapping = get_gene_mapping(gene_annotation, prob_col, gene_col)\n", "print(f\"Gene mapping preview (first 5 rows):\")\n", "print(preview_df(gene_mapping))\n", "\n", "# 3. Apply the gene mapping to convert probe-level measurements to gene expression data\n", "gene_data = apply_gene_mapping(gene_data, gene_mapping)\n", "print(f\"\\nGene expression data after mapping (first 5 rows, 3 columns):\")\n", "print(gene_data.head(5)[gene_data.columns[:3]])\n", "\n", "# 4. Get the shape of the resulting gene expression dataframe\n", "print(f\"\\nShape of gene expression data: {gene_data.shape}\")\n" ] }, { "cell_type": "markdown", "id": "29516c49", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "2d5d0800", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:08:09.941455Z", "iopub.status.busy": "2025-03-25T04:08:09.941344Z", "iopub.status.idle": "2025-03-25T04:08:19.088737Z", "shell.execute_reply": "2025-03-25T04:08:19.088288Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene data shape before normalization: (19521, 38)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene data shape after normalization: (19298, 38)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene data saved to ../../output/preprocess/Substance_Use_Disorder/gene_data/GSE94399.csv\n", "Raw clinical data shape: (2, 39)\n", "Clinical features:\n", " GSM2474751 GSM2474752 GSM2474753 GSM2474754 \\\n", "Substance_Use_Disorder 0.0 0.0 0.0 1.0 \n", "\n", " GSM2474755 GSM2474756 GSM2474757 GSM2474758 \\\n", "Substance_Use_Disorder 0.0 1.0 1.0 1.0 \n", "\n", " GSM2474759 GSM2474760 ... GSM2474779 GSM2474780 \\\n", "Substance_Use_Disorder 1.0 1.0 ... 1.0 1.0 \n", "\n", " GSM2474781 GSM2474782 GSM2474783 GSM2474784 \\\n", "Substance_Use_Disorder 0.0 0.0 0.0 1.0 \n", "\n", " GSM2474785 GSM2474786 GSM2474787 GSM2474788 \n", "Substance_Use_Disorder 0.0 0.0 1.0 1.0 \n", "\n", "[1 rows x 38 columns]\n", "Clinical features saved to ../../output/preprocess/Substance_Use_Disorder/clinical_data/GSE94399.csv\n", "Linked data shape: (38, 19299)\n", "Linked data preview (first 5 rows, first 5 columns):\n", " Substance_Use_Disorder A1BG A1CF A2M \\\n", "GSM2474751 0.0 235.239452 357.729179 570.793025 \n", "GSM2474752 0.0 166.162065 296.125841 799.633007 \n", "GSM2474753 0.0 139.648057 233.119900 616.235048 \n", "GSM2474754 1.0 190.601163 154.386343 831.861973 \n", "GSM2474755 0.0 44.600586 43.266344 40.096098 \n", "\n", " A2ML1 \n", "GSM2474751 6.674990 \n", "GSM2474752 5.175807 \n", "GSM2474753 6.422781 \n", "GSM2474754 4.089858 \n", "GSM2474755 5.738373 \n", "Missing values before handling:\n", " Trait (Substance_Use_Disorder) missing: 0 out of 38\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: (38, 19299)\n", "For the feature 'Substance_Use_Disorder', the least common label is '1.0' with 15 occurrences. This represents 39.47% of the dataset.\n", "The distribution of the feature 'Substance_Use_Disorder' in this dataset is fine.\n", "\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Linked data saved to ../../output/preprocess/Substance_Use_Disorder/GSE94399.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 }